]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlRpcServer.php
fix RPC for !USE_PATH_INFO, add debugging helper
[SourceForge/phpwiki.git] / lib / XmlRpcServer.php
1 <?php 
2 // $Id: XmlRpcServer.php,v 1.12 2004-12-18 16:49:29 rurban Exp $
3 /* Copyright (C) 2002, Lawrence Akka <lakka@users.sourceforge.net>
4  *
5  * LICENCE
6  * =======
7  * This file is part of PhpWiki.
8  * 
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  * 
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with PhpWiki; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  * LIBRARY USED - POSSIBLE PROBLEMS
24  * ================================
25  * 
26  * This file provides an XML-RPC interface for PhpWiki.  It uses the XML-RPC 
27  * library for PHP by Edd Dumbill - see http://xmlrpc.usefulinc.com/php.html 
28  * for details.
29  *
30  * PHP >= 4.1.0 includes experimental support for the xmlrpc-epi c library 
31  * written by Dan Libby (see http://uk2.php.net/manual/en/ref.xmlrpc.php).  
32  * This is not compiled into PHP by default.  If it *is* compiled into your installation
33  * (ie you have --with-xmlrpc) there may well be namespace conflicts with the xml-rpc
34  * library used by this code, and you will get errors.
35  * 
36  * INTERFACE SPECIFICTION
37  * ======================
38  *  
39  * The interface specification is that discussed at 
40  * http://www.ecyrd.com/JSPWiki/Wiki.jsp?page=WikiRPCInterface
41  * 
42  * See also http://www.usemod.com/cgi-bin/mb.pl?XmlRpc
43  * or http://www.devshed.com/c/a/PHP/Using-XMLRPC-with-PHP/
44  * 
45  * Note: All XMLRPC methods are automatically prefixed with "wiki."
46  *       eg. "wiki.getAllPages"
47 */
48
49 /*
50 ToDo:
51         Resolve namespace conflicts
52         Remove all warnings from xmlrpc.inc 
53         Return list of external links in listLinks
54         Support RSS2 cloud subscription
55         Test hwiki.jar xmlrpc interface (java visualization plugin)
56 Done:
57         Make use of the xmlrpc extension if found. http://xmlrpc-epi.sourceforge.net/
58 */
59
60 // Intercept GET requests from confused users.  Only POST is allowed here!
61 // There is some indication that $HTTP_SERVER_VARS is deprecated in php > 4.1.0
62 // in favour of $_Server, but as far as I know, it still works.
63 if ($GLOBALS['HTTP_SERVER_VARS']['REQUEST_METHOD'] != "POST")
64 {
65     die('This is the address of the XML-RPC interface.' .
66         '  You must use XML-RPC calls to access information here');
67 }
68
69 // All these global declarations make it so that this file
70 // (XmlRpcServer.php) can be included within a function body
71 // (not in global scope), and things will still work....
72
73 global $xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, $xmlrpcString;
74 global $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, $xmlrpcStruct;
75 global $xmlrpcTypes;
76 global $xmlEntities;
77 global $xmlrpcerr, $xmlrpcstr;
78 global $xmlrpc_defencoding;
79 global $xmlrpcName, $xmlrpcVersion;
80 global $xmlrpcerruser, $xmlrpcerrxml;
81 global $xmlrpc_backslash;
82 global $_xh;
83
84 if (loadPhpExtension('xmlrpc')) { // fast c lib
85     define('XMLRPC_EXT_LOADED', true);
86
87     global $xmlrpc_util_path;
88     $xmlrpc_util_path = dirname(__FILE__)."/XMLRPC/";
89     include_once("lib/XMLRPC/xmlrpc_emu.inc"); 
90     global $_xmlrpcs_debug;
91     include_once("lib/XMLRPC/xmlrpcs_emu.inc");
92
93  } else { // slow php lib
94     define('XMLRPC_EXT_LOADED', true);
95
96     // Include the php XML-RPC library
97     include_once("lib/XMLRPC/xmlrpc.inc");
98
99     global $_xmlrpcs_dmap;
100     global $_xmlrpcs_debug;
101     include_once("lib/XMLRPC/xmlrpcs.inc");
102 }
103  
104
105 //  API version
106 define ("WIKI_XMLRPC_VERSION", 2);
107
108 /**
109  * Helper function:  Looks up a page revision (most recent by default) in the wiki database
110  * 
111  * @param xmlrpcmsg $params :  string pagename [int version]
112  * @return WikiDB _PageRevision object, or false if no such page
113  */
114
115 function _getPageRevision ($params)
116 {
117     global $request;
118     $ParamPageName = $params->getParam(0);
119     $ParamVersion = $params->getParam(1);
120     $pagename = short_string_decode($ParamPageName->scalarval());
121     $version =  ($ParamVersion) ? ($ParamVersion->scalarval()):(0);
122     // FIXME:  test for version <=0 ??
123     $dbh = $request->getDbh();
124     if ($dbh->isWikiPage($pagename)) {
125         $page = $dbh->getPage($pagename);
126         if (!$version) {
127             $revision = $page->getCurrentRevision();
128         } else {
129             $revision = $page->getRevision($version);
130         } 
131         return $revision;
132     } 
133     return false;
134
135
136 /*
137  * Helper functions for encoding/decoding strings.
138  *
139  * According to WikiRPC spec, all returned strings take one of either
140  * two forms.  Short strings (page names, and authors) are converted to
141  * UTF-8, then rawurlencode()d, and returned as XML-RPC <code>strings</code>.
142  * Long strings (page content) are converted to UTF-8 then returned as
143  * XML-RPC <code>base64</code> binary objects.
144  */
145
146 /**
147  * Urlencode ASCII control characters.
148  *
149  * (And control characters...)
150  *
151  * @param string $str
152  * @return string
153  * @see urlencode
154  */
155 function UrlencodeControlCharacters($str) {
156     return preg_replace('/([\x00-\x1F])/e', "urlencode('\\1')", $str);
157 }
158
159 /**
160  * Convert a short string (page name, author) to xmlrpcval.
161  */
162 function short_string ($str) {
163     return new xmlrpcval(UrlencodeControlCharacters(utf8_encode($str)), 'string');
164 }
165
166 /**
167  * Convert a large string (page content) to xmlrpcval.
168  */
169 function long_string ($str) {
170     return new xmlrpcval(utf8_encode($str), 'base64');
171 }
172
173 /**
174  * Decode a short string (e.g. page name)
175  */
176 function short_string_decode ($str) {
177     return utf8_decode(urldecode($str));
178 }
179
180 /**
181  * Get an xmlrpc "No such page" error message
182  */
183 function NoSuchPage ($pagename='') 
184 {
185     global $xmlrpcerruser;
186     return new xmlrpcresp(0, $xmlrpcerruser + 1, "No such page ".$pagename);
187 }
188
189
190 // ****************************************************************************
191 // Main API functions follow
192 // ****************************************************************************
193 global $wiki_dmap;
194
195 /**
196  * int getRPCVersionSupported(): Returns 1 for this version of the API 
197  */
198 $wiki_dmap['getRPCVersionSupported']
199 = array('signature'     => array(array($xmlrpcInt)),
200         'documentation' => 'Get the version of the wiki API',
201         'function'      => 'getRPCVersionSupported');
202
203 // The function must be a function in the global scope which services the XML-RPC
204 // method.
205 function getRPCVersionSupported($params)
206 {
207     return new xmlrpcresp(new xmlrpcval((integer)WIKI_XMLRPC_VERSION, "int"));
208 }
209
210 /**
211  * array getRecentChanges(Date timestamp) : Get list of changed pages since 
212  * timestamp, which should be in UTC. The result is an array, where each element
213  * is a struct: 
214  *     name (string) : Name of the page. The name is UTF-8 with URL encoding to make it ASCII. 
215  *     lastModified (date) : Date of last modification, in UTC. 
216  *     author (string) : Name of the author (if available). Again, name is UTF-8 with URL encoding. 
217  *         version (int) : Current version. 
218  * A page MAY be specified multiple times. A page MAY NOT be specified multiple 
219  * times with the same modification date.
220  */
221 $wiki_dmap['getRecentChanges']
222 = array('signature'     => array(array($xmlrpcArray, $xmlrpcDateTime)),
223         'documentation' => 'Get a list of changed pages since [timestamp]',
224         'function'      => 'getRecentChanges');
225
226 function getRecentChanges($params)
227 {
228     global $request;
229     // Get the first parameter as an ISO 8601 date.  Assume UTC
230     $encoded_date = $params->getParam(0);
231     $datetime = iso8601_decode($encoded_date->scalarval(), 1);
232     $dbh = $request->getDbh();
233     $pages = array();
234     $iterator = $dbh->mostRecent(array('since' => $datetime));
235     while ($page = $iterator->next()) {
236         // $page contains a WikiDB_PageRevision object
237         // no need to url encode $name, because it is already stored in that format ???
238         $name = short_string($page->getPageName());
239         $lastmodified = new xmlrpcval(iso8601_encode($page->get('mtime')), "dateTime.iso8601");
240         $author = short_string($page->get('author'));
241         $version = new xmlrpcval($page->getVersion(), 'int');
242
243         // Build an array of xmlrpc structs
244         $pages[] = new xmlrpcval(array('name'=>$name, 
245                                        'lastModified'=>$lastmodified,
246                                        'author'=>$author,
247                                        'version'=>$version),
248                                  'struct');
249     } 
250     return new xmlrpcresp(new xmlrpcval($pages, "array"));
251
252
253
254 /**
255  * base64 getPage( String pagename ): Get the raw Wiki text of page, latest version. 
256  * Page name must be UTF-8, with URL encoding. Returned value is a binary object,
257  * with UTF-8 encoded page data.
258  */
259 $wiki_dmap['getPage']
260 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString)),
261         'documentation' => 'Get the raw Wiki text of the current version of a page',
262         'function'      => 'getPage');
263
264 function getPage($params)
265 {
266     $revision = _getPageRevision($params);
267
268     if (! $revision ) {
269         $ParamPageName = $params->getParam(0);
270         $pagename = short_string_decode($ParamPageName->scalarval());
271         return NoSuchPage($pagename);
272     }
273
274     return new xmlrpcresp(long_string($revision->getPackedContent()));
275 }
276  
277
278 /**
279  * base64 getPageVersion( String pagename, int version ): Get the raw Wiki text of page.
280  * Returns UTF-8, expects UTF-8 with URL encoding.
281  */
282 $wiki_dmap['getPageVersion']
283 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
284         'documentation' => 'Get the raw Wiki text of a page version',
285         'function'      => 'getPageVersion');
286
287 function getPageVersion($params)
288 {
289     // error checking is done in getPage
290     return getPage($params);
291
292
293 /**
294  * base64 getPageHTML( String pagename ): Return page in rendered HTML. 
295  * Returns UTF-8, expects UTF-8 with URL encoding.
296  */
297
298 $wiki_dmap['getPageHTML']
299 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString)),
300         'documentation' => 'Get the current version of a page rendered in HTML',
301         'function'      => 'getPageHTML');
302
303 function getPageHTML($params)
304 {
305     $revision = _getPageRevision($params);
306     if (!$revision)
307         return NoSuchPage();
308     
309     $content = $revision->getTransformedContent();
310     $html = $content->asXML();
311     // HACK: Get rid of outer <div class="wikitext">
312     if (preg_match('/^\s*<div class="wikitext">/', $html, $m1)
313         && preg_match('@</div>\s*$@', $html, $m2)) {
314         $html = substr($html, strlen($m1[0]), -strlen($m2[0]));
315     }
316
317     return new xmlrpcresp(long_string($html));
318
319
320 /**
321  * base64 getPageHTMLVersion( String pagename, int version ): Return page in rendered HTML, UTF-8.
322  */
323 $wiki_dmap['getPageHTMLVersion']
324 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
325         'documentation' => 'Get a version of a page rendered in HTML',
326         'function'      => 'getPageHTMLVersion');
327
328 function getPageHTMLVersion($params)
329 {
330     return getPageHTML($params);
331
332
333 /**
334  * getAllPages(): Returns a list of all pages. The result is an array of strings.
335  */
336 $wiki_dmap['getAllPages']
337 = array('signature'     => array(array($xmlrpcArray)),
338         'documentation' => 'Returns a list of all pages as an array of strings', 
339         'function'      => 'getAllPages');
340
341 function getAllPages($params)
342 {
343     global $request;
344     $dbh = $request->getDbh();
345     $iterator = $dbh->getAllPages();
346     $pages = array();
347     while ($page = $iterator->next()) {
348         $pages[] = short_string($page->getName());
349     } 
350     return new xmlrpcresp(new xmlrpcval($pages, "array"));
351
352
353 /**
354  * struct getPageInfo( string pagename ) : returns a struct with elements: 
355  *   name (string): the canonical page name 
356  *   lastModified (date): Last modification date 
357  *   version (int): current version 
358  *       author (string): author name 
359  */
360 $wiki_dmap['getPageInfo']
361 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString)),
362         'documentation' => 'Gets info about the current version of a page',
363         'function'      => 'getPageInfo');
364
365 function getPageInfo($params)
366 {
367     $revision = _getPageRevision($params);
368     if (!$revision)
369         return NoSuchPage();
370     
371     $name = short_string($revision->getPageName());
372     $version = new xmlrpcval ($revision->getVersion(), "int");
373     $lastmodified = new xmlrpcval(iso8601_encode($revision->get('mtime'), 0),
374                                   "dateTime.iso8601");
375     $author = short_string($revision->get('author'));
376         
377     return new xmlrpcresp(new xmlrpcval(array('name' => $name, 
378                                               'lastModified' => $lastmodified,
379                                               'version' => $version, 
380                                               'author' => $author), 
381                                         "struct"));
382
383
384 /**
385  * struct getPageInfoVersion( string pagename, int version ) : returns
386  * a struct just like plain getPageInfo(), but this time for a
387  * specific version.
388  */
389 $wiki_dmap['getPageInfoVersion']
390 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcInt)),
391         'documentation' => 'Gets info about a page version',
392         'function'      => 'getPageInfoVersion');
393
394 function getPageInfoVersion($params)
395 {
396     return getPageInfo($params);
397 }
398
399  
400 /*  array listLinks( string pagename ): Lists all links for a given page. The
401  *  returned array contains structs, with the following elements: 
402  *       name (string) : The page name or URL the link is to. 
403  *       type (int) : The link type. Zero (0) for internal Wiki link,
404  *         one (1) for external link (URL - image link, whatever).
405  */
406 $wiki_dmap['listLinks']
407 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString)),
408         'documentation' => 'Lists all links for a given page',
409         'function'      => 'listLinks');
410
411 function listLinks($params)
412 {
413     global $request;
414     
415     $ParamPageName = $params->getParam(0);
416     $pagename = short_string_decode($ParamPageName->scalarval());
417     $dbh = $request->getDbh();
418     if (! $dbh->isWikiPage($pagename))
419         return NoSuchPage($pagename);
420
421     $page = $dbh->getPage($pagename);
422     
423     // The fast WikiDB method. below is the slow method which goes through the formatter
424     // NB no clean way to extract a list of external links yet, so
425     // only internal links returned.  i.e. all type 'local'.
426     $linkiterator = $page->getPageLinks();
427     $linkstruct = array();
428     while ($currentpage = $linkiterator->next()) {
429         $currentname = $currentpage->getName();
430         // Compute URL to page
431         $args = array();
432         // How to check external links?
433         if (!$currentpage->exists()) $args['action'] = 'edit';
434
435         // FIXME: Autodetected value of VIRTUAL_PATH wrong,
436         // this make absolute URLs constructed by WikiURL wrong.
437         // Also, if USE_PATH_INFO is false, WikiURL is wrong
438         // due to its use of SCRIPT_NAME.
439         //$use_abspath = USE_PATH_INFO && ! preg_match('/RPC2.php$/', VIRTUAL_PATH);
440         
441         // USE_PATH_INFO must be defined in index.php or config.ini but not before, 
442         // otherwise it is ignored and xmlrpc urls are wrong.
443         // SCRIPT_NAME here is always .../RPC2.php
444         if (USE_PATH_INFO and !$args) {
445             $url = preg_replace('/%2f/i', '/', rawurlencode($currentname));
446         } elseif (!USE_PATH_INFO) {
447             $url = str_replace("/RPC2.php","/index.php", WikiURL($currentname, $args, true));
448         } else {
449             $url = WikiURL($currentname, $args);
450         }
451         $linkstruct[] = new xmlrpcval(array('page'=> short_string($currentname),
452                                             'type'=> new xmlrpcval('local', 'string'),
453                                             'href' => short_string($url)),
454                                       "struct");
455     }
456    
457     /*
458     $current = $page->getCurrentRevision();
459     $content = $current->getTransformedContent();
460     $links = $content->getLinkInfo();
461     foreach ($links as $link) {
462         // We used to give an href for unknown pages that
463         // included action=edit.  I think that's probably the
464         // wrong thing to do.
465         $linkstruct[] = new xmlrpcval(array('page'=> short_string($link->page),
466                                             'type'=> new xmlrpcval($link->type, 'string'),
467                                             'href' => short_string($link->href),
468                                             //'pageref' => short_string($link->pageref),
469                                             ),
470                                       "struct");
471     }
472     */
473     return new xmlrpcresp(new xmlrpcval ($linkstruct, "array"));
474
475
476 /**
477  * Publish-Subscribe
478  * Client subscribes to a RecentChanges-like channel, getting a short 
479  * callback notification on every change. Like PageChangeNotification, just shorter 
480  * and more complicated
481  * RSS2 support (not yet), since radio userland's rss-0.92. now called RSS2.
482  * BTW: Radio Userland deprecated this interface.
483  *
484  * boolean wiki.rssPleaseNotify ( notifyProcedure, port, path, protocol, urlList )
485  *   returns: true or false 
486  *
487  * Check of the channel behind the rssurl has a cloud element, 
488  * if the client has a direct IP connection (no NAT),
489  * register the client on the WikiDB notification handler
490  *
491  * http://backend.userland.com/publishSubscribeWalkthrough
492  * http://www.soapware.org/xmlStorageSystem#rssPleaseNotify
493  * http://www.thetwowayweb.com/soapmeetsrss#rsscloudInterface
494  */
495 $wiki_dmap['rssPleaseNotify']
496 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcBoolean)),
497         'documentation' => 'RSS2 change notification subscriber channel',
498         'function'      => 'rssPleaseNotify');
499
500 function rssPleaseNotify($params)
501 {
502     // register the clients IP
503     return new xmlrpcresp(new xmlrpcval (0, "boolean"));
504 }
505
506 $wiki_dmap['mailPasswordToUser']
507 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString)),
508         'documentation' => 'RSS2 change notification subscriber channel',
509         'function'      => 'mailPasswordToUser');
510
511 function mailPasswordToUser($params)
512 {
513     return new xmlrpcresp(new xmlrpcval (0, "boolean"));
514 }
515  
516 /** 
517  * Construct the server instance, and set up the dispatch map, 
518  * which maps the XML-RPC methods on to the wiki functions.
519  * Provide the "wiki." prefix to each function
520  */
521 class XmlRpcServer extends xmlrpc_server
522 {
523     function XmlRpcServer ($request = false) {
524         global $wiki_dmap;
525         foreach ($wiki_dmap as $name => $val)
526             $dmap['wiki.' . $name] = $val;
527
528         $this->xmlrpc_server($dmap, 0 /* delay service*/);
529     }
530
531     function service () {
532         global $ErrorManager;
533
534         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
535         xmlrpc_server::service();
536         $ErrorManager->popErrorHandler();
537     }
538     
539     function _errorHandler ($e) {
540         $msg = htmlspecialchars($e->asString());
541         // '--' not allowed within xml comment
542         $msg = str_replace('--', '&#45;&#45;', $msg);
543         if (function_exists('xmlrpc_debugmsg'))
544             xmlrpc_debugmsg($msg);
545         return true;
546     }
547 }
548
549
550 // (c-file-style: "gnu")
551 // Local Variables:
552 // mode: php
553 // tab-width: 8
554 // c-basic-offset: 4
555 // c-hanging-comment-ender-p: nil
556 // indent-tabs-mode: nil
557 // End:   
558 ?>