reset scroll position when setting selection FS#1707
[dokuwiki/radio.git] / inc / IXR_Library.php
blobb9e8052f21606c423244ba4ce2813ac2967acfe2
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 // The XML parser
140 var $_parser;
141 function IXR_Message ($message) {
142 $this->message = $message;
144 function parse() {
145 // first remove the XML declaration
146 $this->message = preg_replace('/<\?xml(.*)?\?'.'>/', '', $this->message);
147 // workaround for a bug in PHP/libxml2, see http://bugs.php.net/bug.php?id=45996
148 $this->message = str_replace('&lt;', '&#60;', $this->message);
149 $this->message = str_replace('&gt;', '&#62;', $this->message);
150 $this->message = str_replace('&amp;', '&#38;', $this->message);
151 $this->message = str_replace('&apos;', '&#39;', $this->message);
152 $this->message = str_replace('&quot;', '&#34;', $this->message);
153 if (trim($this->message) == '') {
154 return false;
156 $this->_parser = xml_parser_create();
157 // Set XML parser to take the case of tags in to account
158 xml_parser_set_option($this->_parser, XML_OPTION_CASE_FOLDING, false);
159 // Set XML parser callback functions
160 xml_set_object($this->_parser, $this);
161 xml_set_element_handler($this->_parser, 'tag_open', 'tag_close');
162 xml_set_character_data_handler($this->_parser, 'cdata');
163 if (!xml_parse($this->_parser, $this->message)) {
164 /* die(sprintf('XML error: %s at line %d',
165 xml_error_string(xml_get_error_code($this->_parser)),
166 xml_get_current_line_number($this->_parser))); */
167 return false;
169 xml_parser_free($this->_parser);
170 // Grab the error messages, if any
171 if ($this->messageType == 'fault') {
172 $this->faultCode = $this->params[0]['faultCode'];
173 $this->faultString = $this->params[0]['faultString'];
175 return true;
177 function tag_open($parser, $tag, $attr) {
178 $this->currentTag = $tag;
179 switch($tag) {
180 case 'methodCall':
181 case 'methodResponse':
182 case 'fault':
183 $this->messageType = $tag;
184 break;
185 /* Deal with stacks of arrays and structs */
186 case 'data': // data is to all intents and puposes more interesting than array
187 $this->_arraystructstypes[] = 'array';
188 $this->_arraystructs[] = array();
189 break;
190 case 'struct':
191 $this->_arraystructstypes[] = 'struct';
192 $this->_arraystructs[] = array();
193 break;
196 function cdata($parser, $cdata) {
197 $this->_currentTagContents .= $cdata;
199 function tag_close($parser, $tag) {
200 $valueFlag = false;
201 switch($tag) {
202 case 'int':
203 case 'i4':
204 $value = (int)trim($this->_currentTagContents);
205 $this->_currentTagContents = '';
206 $valueFlag = true;
207 break;
208 case 'double':
209 $value = (double)trim($this->_currentTagContents);
210 $this->_currentTagContents = '';
211 $valueFlag = true;
212 break;
213 case 'string':
214 $value = (string)trim($this->_currentTagContents);
215 $this->_currentTagContents = '';
216 $valueFlag = true;
217 break;
218 case 'dateTime.iso8601':
219 $value = new IXR_Date(trim($this->_currentTagContents));
220 // $value = $iso->getTimestamp();
221 $this->_currentTagContents = '';
222 $valueFlag = true;
223 break;
224 case 'value':
225 // "If no type is indicated, the type is string."
226 if (trim($this->_currentTagContents) != '') {
227 $value = (string)$this->_currentTagContents;
228 $this->_currentTagContents = '';
229 $valueFlag = true;
231 break;
232 case 'boolean':
233 $value = (boolean)trim($this->_currentTagContents);
234 $this->_currentTagContents = '';
235 $valueFlag = true;
236 break;
237 case 'base64':
238 $value = base64_decode($this->_currentTagContents);
239 $this->_currentTagContents = '';
240 $valueFlag = true;
241 break;
242 /* Deal with stacks of arrays and structs */
243 case 'data':
244 case 'struct':
245 $value = array_pop($this->_arraystructs);
246 array_pop($this->_arraystructstypes);
247 $valueFlag = true;
248 break;
249 case 'member':
250 array_pop($this->_currentStructName);
251 break;
252 case 'name':
253 $this->_currentStructName[] = trim($this->_currentTagContents);
254 $this->_currentTagContents = '';
255 break;
256 case 'methodName':
257 $this->methodName = trim($this->_currentTagContents);
258 $this->_currentTagContents = '';
259 break;
261 if ($valueFlag) {
263 if (!is_array($value) && !is_object($value)) {
264 $value = trim($value);
267 if (count($this->_arraystructs) > 0) {
268 // Add value to struct or array
269 if ($this->_arraystructstypes[count($this->_arraystructstypes)-1] == 'struct') {
270 // Add to struct
271 $this->_arraystructs[count($this->_arraystructs)-1][$this->_currentStructName[count($this->_currentStructName)-1]] = $value;
272 } else {
273 // Add to array
274 $this->_arraystructs[count($this->_arraystructs)-1][] = $value;
276 } else {
277 // Just add as a paramater
278 $this->params[] = $value;
285 class IXR_Server {
286 var $data;
287 var $callbacks = array();
288 var $message;
289 var $capabilities;
290 function IXR_Server($callbacks = false, $data = false) {
291 $this->setCapabilities();
292 if ($callbacks) {
293 $this->callbacks = $callbacks;
295 $this->setCallbacks();
296 $this->serve($data);
298 function serve($data = false) {
299 if (!$data) {
300 global $HTTP_RAW_POST_DATA;
301 if (!$HTTP_RAW_POST_DATA) {
302 die('XML-RPC server accepts POST requests only.');
304 $data = $HTTP_RAW_POST_DATA;
306 $this->message = new IXR_Message($data);
307 if (!$this->message->parse()) {
308 $this->error(-32700, 'parse error. not well formed');
310 if ($this->message->messageType != 'methodCall') {
311 $this->error(-32600, 'server error. invalid xml-rpc. not conforming to spec. Request must be a methodCall');
313 $result = $this->call($this->message->methodName, $this->message->params);
314 // Is the result an error?
315 if (is_a($result, 'IXR_Error')) {
316 $this->error($result);
318 // Encode the result
319 $r = new IXR_Value($result);
320 $resultxml = $r->getXml();
321 // Create the XML
322 $xml = <<<EOD
323 <methodResponse>
324 <params>
325 <param>
326 <value>
327 $resultxml
328 </value>
329 </param>
330 </params>
331 </methodResponse>
333 EOD;
334 // Send it
335 $this->output($xml);
337 function call($methodname, $args) {
338 if (!$this->hasMethod($methodname)) {
339 return new IXR_Error(-32601, 'server error. requested method '.$methodname.' does not exist.');
341 $method = $this->callbacks[$methodname];
342 // Perform the callback and send the response
344 # Removed for DokuWiki to have a more consistent interface
345 # if (count($args) == 1) {
346 # // If only one paramater just send that instead of the whole array
347 # $args = $args[0];
351 # Adjusted for DokuWiki to use call_user_func_array
353 // Are we dealing with a function or a method?
354 if (substr($method, 0, 5) == 'this:') {
355 // It's a class method - check it exists
356 $method = substr($method, 5);
357 if (!method_exists($this, $method)) {
358 return new IXR_Error(-32601, 'server error. requested class method "'.$method.'" does not exist.');
360 // Call the method
361 #$result = $this->$method($args);
362 $result = call_user_func_array(array(&$this,$method),$args);
363 } elseif (substr($method, 0, 7) == 'plugin:') {
364 require_once(DOKU_INC.'inc/pluginutils.php');
365 list($pluginname, $callback) = explode(':', substr($method, 7), 2);
366 if(!plugin_isdisabled($pluginname)) {
367 $plugin = plugin_load('action', $pluginname);
368 return call_user_func_array(array($plugin, $callback), $args);
369 } else {
370 return new IXR_Error(-99999, 'server error');
372 } else {
373 // It's a function - does it exist?
374 if (!function_exists($method)) {
375 return new IXR_Error(-32601, 'server error. requested function "'.$method.'" does not exist.');
377 // Call the function
378 #$result = $method($args);
379 $result = call_user_func_array($method,$args);
381 return $result;
384 function error($error, $message = false) {
385 // Accepts either an error object or an error code and message
386 if ($message && !is_object($error)) {
387 $error = new IXR_Error($error, $message);
389 $this->output($error->getXml());
391 function output($xml) {
392 $xml = '<?xml version="1.0"?>'."\n".$xml;
393 $length = strlen($xml);
394 header('Connection: close');
395 header('Content-Length: '.$length);
396 header('Content-Type: text/xml');
397 header('Date: '.date('r'));
398 echo $xml;
399 exit;
401 function hasMethod($method) {
402 return in_array($method, array_keys($this->callbacks));
404 function setCapabilities() {
405 // Initialises capabilities array
406 $this->capabilities = array(
407 'xmlrpc' => array(
408 'specUrl' => 'http://www.xmlrpc.com/spec',
409 'specVersion' => 1
411 'faults_interop' => array(
412 'specUrl' => 'http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php',
413 'specVersion' => 20010516
415 'system.multicall' => array(
416 'specUrl' => 'http://www.xmlrpc.com/discuss/msgReader$1208',
417 'specVersion' => 1
421 function getCapabilities() {
422 return $this->capabilities;
424 function setCallbacks() {
425 $this->callbacks['system.getCapabilities'] = 'this:getCapabilities';
426 $this->callbacks['system.listMethods'] = 'this:listMethods';
427 $this->callbacks['system.multicall'] = 'this:multiCall';
429 function listMethods() {
430 // Returns a list of methods - uses array_reverse to ensure user defined
431 // methods are listed before server defined methods
432 return array_reverse(array_keys($this->callbacks));
434 function multiCall($methodcalls) {
435 // See http://www.xmlrpc.com/discuss/msgReader$1208
436 $return = array();
437 foreach ($methodcalls as $call) {
438 $method = $call['methodName'];
439 $params = $call['params'];
440 if ($method == 'system.multicall') {
441 $result = new IXR_Error(-32600, 'Recursive calls to system.multicall are forbidden');
442 } else {
443 $result = $this->call($method, $params);
445 if (is_a($result, 'IXR_Error')) {
446 $return[] = array(
447 'faultCode' => $result->code,
448 'faultString' => $result->message
450 } else {
451 $return[] = array($result);
454 return $return;
458 class IXR_Request {
459 var $method;
460 var $args;
461 var $xml;
462 function IXR_Request($method, $args) {
463 $this->method = $method;
464 $this->args = $args;
465 $this->xml = <<<EOD
466 <?xml version="1.0"?>
467 <methodCall>
468 <methodName>{$this->method}</methodName>
469 <params>
471 EOD;
472 foreach ($this->args as $arg) {
473 $this->xml .= '<param><value>';
474 $v = new IXR_Value($arg);
475 $this->xml .= $v->getXml();
476 $this->xml .= "</value></param>\n";
478 $this->xml .= '</params></methodCall>';
480 function getLength() {
481 return strlen($this->xml);
483 function getXml() {
484 return $this->xml;
489 * Changed for DokuWiki to use DokuHTTPClient
491 * This should be compatible to the original class, but uses DokuWiki's
492 * HTTP client library which will respect proxy settings
494 * Because the XMLRPC client is not used in DokuWiki currently this is completely
495 * untested
497 class IXR_Client extends DokuHTTPClient {
498 var $posturl = '';
499 var $message = false;
500 var $xmlerror = false;
502 function IXR_Client($server, $path = false, $port = 80) {
503 $this->DokuHTTPClient();
504 if (!$path) {
505 // Assume we have been given a URL instead
506 $this->posturl = $server;
507 }else{
508 $this->posturl = 'http://'.$server.':'.$port.$path;
512 function query() {
513 $args = func_get_args();
514 $method = array_shift($args);
515 $request = new IXR_Request($method, $args);
516 $xml = $request->getXml();
518 $this->headers['Content-Type'] = 'text/xml';
519 if(!$this->sendRequest($this->posturl,$xml,'POST')){
520 $this->xmlerror = new IXR_Error(-32300, 'transport error - '.$this->error);
521 return false;
524 // Check HTTP Response code
525 if($this->status < 200 || $this->status > 206){
526 $this->xmlerror = new IXR_Error(-32300, 'transport error - HTTP status '.$this->status);
527 return false;
530 // Now parse what we've got back
531 $this->message = new IXR_Message($this->resp_body);
532 if (!$this->message->parse()) {
533 // XML error
534 $this->xmlerror = new IXR_Error(-32700, 'parse error. not well formed');
535 return false;
537 // Is the message a fault?
538 if ($this->message->messageType == 'fault') {
539 $this->xmlerror = new IXR_Error($this->message->faultCode, $this->message->faultString);
540 return false;
542 // Message must be OK
543 return true;
545 function getResponse() {
546 // methodResponses can only have one param - return that
547 return $this->message->params[0];
549 function isError() {
550 return (is_object($this->xmlerror));
552 function getErrorCode() {
553 return $this->xmlerror->code;
555 function getErrorMessage() {
556 return $this->xmlerror->message;
561 class IXR_Error {
562 var $code;
563 var $message;
564 function IXR_Error($code, $message) {
565 $this->code = $code;
566 $this->message = $message;
568 function getXml() {
569 $xml = <<<EOD
570 <methodResponse>
571 <fault>
572 <value>
573 <struct>
574 <member>
575 <name>faultCode</name>
576 <value><int>{$this->code}</int></value>
577 </member>
578 <member>
579 <name>faultString</name>
580 <value><string>{$this->message}</string></value>
581 </member>
582 </struct>
583 </value>
584 </fault>
585 </methodResponse>
587 EOD;
588 return $xml;
593 class IXR_Date {
594 var $year;
595 var $month;
596 var $day;
597 var $hour;
598 var $minute;
599 var $second;
600 function IXR_Date($time) {
601 // $time can be a PHP timestamp or an ISO one
602 if (is_numeric($time)) {
603 $this->parseTimestamp($time);
604 } else {
605 $this->parseIso($time);
608 function parseTimestamp($timestamp) {
609 $this->year = gmdate('Y', $timestamp);
610 $this->month = gmdate('m', $timestamp);
611 $this->day = gmdate('d', $timestamp);
612 $this->hour = gmdate('H', $timestamp);
613 $this->minute = gmdate('i', $timestamp);
614 $this->second = gmdate('s', $timestamp);
616 function parseIso($iso) {
617 $this->year = substr($iso, 0, 4);
618 $this->month = substr($iso, 5, 2);
619 $this->day = substr($iso, 8, 2);
620 $this->hour = substr($iso, 11, 2);
621 $this->minute = substr($iso, 14, 2);
622 $this->second = substr($iso, 17, 2);
624 function getIso() {
625 return $this->year.'-'.$this->month.'-'.$this->day.'T'.$this->hour.':'.$this->minute.':'.$this->second;
627 function getXml() {
628 return '<dateTime.iso8601>'.$this->getIso().'</dateTime.iso8601>';
630 function getTimestamp() {
631 return gmmktime($this->hour, $this->minute, $this->second, $this->month, $this->day, $this->year);
636 class IXR_Base64 {
637 var $data;
638 function IXR_Base64($data) {
639 $this->data = $data;
641 function getXml() {
642 return '<base64>'.base64_encode($this->data).'</base64>';
647 class IXR_IntrospectionServer extends IXR_Server {
648 var $signatures;
649 var $help;
650 function IXR_IntrospectionServer() {
651 $this->setCallbacks();
652 $this->setCapabilities();
653 $this->capabilities['introspection'] = array(
654 'specUrl' => 'http://xmlrpc.usefulinc.com/doc/reserved.html',
655 'specVersion' => 1
657 $this->addCallback(
658 'system.methodSignature',
659 'this:methodSignature',
660 array('array', 'string'),
661 'Returns an array describing the return type and required parameters of a method'
663 $this->addCallback(
664 'system.getCapabilities',
665 'this:getCapabilities',
666 array('struct'),
667 'Returns a struct describing the XML-RPC specifications supported by this server'
669 $this->addCallback(
670 'system.listMethods',
671 'this:listMethods',
672 array('array'),
673 'Returns an array of available methods on this server'
675 $this->addCallback(
676 'system.methodHelp',
677 'this:methodHelp',
678 array('string', 'string'),
679 'Returns a documentation string for the specified method'
682 function addCallback($method, $callback, $args, $help) {
683 $this->callbacks[$method] = $callback;
684 $this->signatures[$method] = $args;
685 $this->help[$method] = $help;
687 function call($methodname, $args) {
688 // Make sure it's in an array
689 if ($args && !is_array($args)) {
690 $args = array($args);
692 // Over-rides default call method, adds signature check
693 if (!$this->hasMethod($methodname)) {
694 return new IXR_Error(-32601, 'server error. requested method "'.$this->message->methodName.'" not specified.');
696 $method = $this->callbacks[$methodname];
697 $signature = $this->signatures[$methodname];
698 $returnType = array_shift($signature);
699 // Check the number of arguments. Check only, if the minimum count of parameters is specified. More parameters are possible.
700 // This is a hack to allow optional parameters...
701 if (count($args) < count($signature)) {
702 // print 'Num of args: '.count($args).' Num in signature: '.count($signature);
703 return new IXR_Error(-32602, 'server error. wrong number of method parameters');
705 // Check the argument types
706 $ok = true;
707 $argsbackup = $args;
708 for ($i = 0, $j = count($args); $i < $j; $i++) {
709 $arg = array_shift($args);
710 $type = array_shift($signature);
711 switch ($type) {
712 case 'int':
713 case 'i4':
714 if (is_array($arg) || !is_int($arg)) {
715 $ok = false;
717 break;
718 case 'base64':
719 case 'string':
720 if (!is_string($arg)) {
721 $ok = false;
723 break;
724 case 'boolean':
725 if ($arg !== false && $arg !== true) {
726 $ok = false;
728 break;
729 case 'float':
730 case 'double':
731 if (!is_float($arg)) {
732 $ok = false;
734 break;
735 case 'date':
736 case 'dateTime.iso8601':
737 if (!is_a($arg, 'IXR_Date')) {
738 $ok = false;
740 break;
742 if (!$ok) {
743 return new IXR_Error(-32602, 'server error. invalid method parameters');
746 // It passed the test - run the "real" method call
747 return parent::call($methodname, $argsbackup);
749 function methodSignature($method) {
750 if (!$this->hasMethod($method)) {
751 return new IXR_Error(-32601, 'server error. requested method "'.$method.'" not specified.');
753 // We should be returning an array of types
754 $types = $this->signatures[$method];
755 $return = array();
756 foreach ($types as $type) {
757 switch ($type) {
758 case 'string':
759 $return[] = 'string';
760 break;
761 case 'int':
762 case 'i4':
763 $return[] = 42;
764 break;
765 case 'double':
766 $return[] = 3.1415;
767 break;
768 case 'dateTime.iso8601':
769 $return[] = new IXR_Date(time());
770 break;
771 case 'boolean':
772 $return[] = true;
773 break;
774 case 'base64':
775 $return[] = new IXR_Base64('base64');
776 break;
777 case 'array':
778 $return[] = array('array');
779 break;
780 case 'struct':
781 $return[] = array('struct' => 'struct');
782 break;
785 return $return;
787 function methodHelp($method) {
788 return $this->help[$method];
793 class IXR_ClientMulticall extends IXR_Client {
794 var $calls = array();
795 function IXR_ClientMulticall($server, $path = false, $port = 80) {
796 parent::IXR_Client($server, $path, $port);
797 //$this->useragent = 'The Incutio XML-RPC PHP Library (multicall client)';
799 function addCall() {
800 $args = func_get_args();
801 $methodName = array_shift($args);
802 $struct = array(
803 'methodName' => $methodName,
804 'params' => $args
806 $this->calls[] = $struct;
808 function query() {
809 // Prepare multicall, then call the parent::query() method
810 return parent::query('system.multicall', $this->calls);