]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlRpcServer.php
The main script will now notice when you're directing and XML-RPC
[SourceForge/phpwiki.git] / lib / XmlRpcServer.php
1 <?php 
2 // $Id: XmlRpcServer.php,v 1.1 2002-09-14 22:28:33 dairiki 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).  This
32  * 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  * 
44  * NB:  All XMLRPC methods should be prefixed with "wiki."
45  * eg  wiki.getAllPages
46  * 
47 */
48
49 // ToDo:  
50 //        Remove all warnings from xmlrpc.inc 
51 //        Return list of external links in listLinks
52  
53
54 // Intercept GET requests from confused users.  Only POST is allowed here!
55 // There is some indication that $HTTP_SERVER_VARS is deprecated in php > 4.1.0
56 // in favour of $_Server, but as far as I know, it still works.
57 if ($GLOBALS['HTTP_SERVER_VARS']['REQUEST_METHOD'] != "POST")  
58 {
59     die('This is the address of the XML-RPC interface.' .
60         '  You must use XML-RPC calls to access information here');
61 }
62
63 // Include the php XML-RPC library
64
65 // All these global declarations make it so that this file
66 // (XmlRpcServer.php) can be included within a function body
67 // (not in global scope), and things will still work....
68
69 global $xmlrpcI4, $xmlrpcInt, $xmlrpcBoolean, $xmlrpcDouble, $xmlrpcString;
70 global $xmlrpcDateTime, $xmlrpcBase64, $xmlrpcArray, $xmlrpcStruct;
71 global $xmlrpcTypes;
72 global $xmlEntities;
73 global $xmlrpcerr, $xmlrpcstr;
74 global $xmlrpc_defencoding;
75 global $xmlrpcName, $xmlrpcVersion;
76 global $xmlrpcerruser, $xmlrpcerrxml;
77 global $xmlrpc_backslash;
78 global $_xh;
79 include_once("lib/XMLRPC/xmlrpc.inc");
80
81 global $_xmlrpcs_dmap;
82 global $_xmlrpcs_debug;
83 include_once("lib/XMLRPC/xmlrpcs.inc");
84
85 //  API version
86 define ("WIKI_XMLRPC_VERSION", 1);
87
88 /**
89  * Helper function:  Looks up a page revision (most recent by default) in the wiki database
90  * 
91  * @param xmlrpcmsg $params :  string pagename [int version]
92  * @return WikiDB _PageRevision object, or false if no such page
93  */
94
95 function _getPageRevision ($params)
96 {
97     global $request;
98     $ParamPageName = $params->getParam(0);
99     $ParamVersion = $params->getParam(1);
100     $pagename = short_string_decode($ParamPageName->scalarval());
101     $version =  ($ParamVersion) ? ($ParamVersion->scalarval()):(0);
102     // FIXME:  test for version <=0 ??
103     $dbh = $request->getDbh();
104     if ($dbh->isWikiPage($pagename)) {
105         $page = $dbh->getPage($pagename);
106         if (!$version) {
107             $revision = $page->getCurrentRevision();
108         } else {
109             $revision = $page->getRevision($version);
110         } 
111         return $revision;
112     } 
113     return false;
114
115
116 /*
117  * Helper functions for encoding/decoding strings.
118  *
119  * According to WikiRPC spec, all returned strings take one of either
120  * two forms.  Short strings (page names, and authors) are converted to
121  * UTF-8, then rawurlencode()d, and returned as XML-RPC <code>strings</code>.
122  * Long strings (page content) are converted to UTF-8 then returned as
123  * XML-RPC <code>base64</code> binary objects.
124  */
125
126 /**
127  * Convert a short string (page name, author) to xmlrpcval.
128  */
129 function short_string ($str) {
130     return new xmlrpcval(rawurlencode(utf8_encode($str)), 'string');
131 }
132
133 /**
134  * Convert a large string (page content) to xmlrpcval.
135  */
136 function long_string ($str) {
137     return new xmlrpcval(utf8_encode($str), 'base64');
138 }
139
140 /**
141  * Decode a short string (e.g. page name)
142  */
143 function short_string_decode ($str) {
144     return utf8_decode(urldecode($str));
145 }
146
147 /**
148  * Get an xmlrpc "No such page" error message
149  */
150 function NoSuchPage () 
151 {
152     global $xmlrpcerruser;
153     return new xmlrpcresp(0, $xmlrpcerruser + 1, "No such page");
154 }
155
156
157 // ****************************************************************************
158 // Main API functions follow
159 // ****************************************************************************
160 global $wiki_dmap;
161
162 /**
163  * int getRPCVersionSupported(): Returns 1 for this version of the API 
164  */
165 $wiki_dmap['getRPCVersionSupported']
166 = array('signature'     => array(array($xmlrpcInt)),
167         'documentation' => 'Get the version of the wiki API',
168         'function'      => 'getRPCVersionSupported');
169
170 // The function must be a function in the global scope which services the XML-RPC
171 // method.
172 function getRPCVersionSupported($params)
173 {
174     return new xmlrpcresp(new xmlrpcval(WIKI_XMLRPC_VERSION, "int"));
175 }
176
177 /**
178  * array getRecentChanges(Date timestamp) : Get list of changed pages since 
179  * timestamp, which should be in UTC. The result is an array, where each element
180  * is a struct: 
181  *     name (string) : Name of the page. The name is UTF-8 with URL encoding to make it ASCII. 
182  *     lastModified (date) : Date of last modification, in UTC. 
183  *     author (string) : Name of the author (if available). Again, name is UTF-8 with URL encoding. 
184  *         version (int) : Current version. 
185  * A page MAY be specified multiple times. A page MAY NOT be specified multiple 
186  * times with the same modification date.
187  */
188 $wiki_dmap['getRecentChanges']
189 = array('signature'     => array(array($xmlrpcArray, $xmlrpcDateTime)),
190         'documentation' => 'Get a list of changed pages since [timestamp]',
191         'function'      => 'getRecentChanges');
192
193 function getRecentChanges($params)
194 {
195     global $request;
196     // Get the first parameter as an ISO 8601 date.  Assume UTC
197     $encoded_date = $params->getParam(0);
198     $datetime = iso8601_decode($encoded_date->scalarval(), 1);
199     $dbh = $request->getDbh();
200     $pages = array();
201     $iterator = $dbh->mostRecent(array('since' => $datetime));
202     while ($page = $iterator->next()) {
203         // $page contains a WikiDB_PageRevision object
204         // no need to url encode $name, because it is already stored in that format ???
205         $name = short_string($page->getPageName());
206         $lastmodified = new xmlrpcval(iso8601_encode($page->get('mtime')), "dateTime.iso8601");
207         $author = short_string($page->get('author'));
208         $version = new xmlrpcval($page->getVersion(), 'int');
209
210         // Build an array of xmlrpc structs
211         $pages[] = new xmlrpcval(array('name'=>$name, 
212                                        'lastModified'=>$lastmodified,
213                                        'author'=>$author,
214                                        'version'=>$version),
215                                  'struct');
216     } 
217     return new xmlrpcresp(new xmlrpcval($pages, "array"));
218
219
220
221 /**
222  * base64 getPage( String pagename ): Get the raw Wiki text of page, latest version. 
223  * Page name must be UTF-8, with URL encoding. Returned value is a binary object,
224  * with UTF-8 encoded page data.
225  */
226 $wiki_dmap['getPage']
227 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString)),
228         'documentation' => 'Get the raw Wiki text of the current version of a page',
229         'function'      => 'getPage');
230
231 function getPage($params)
232 {
233     $revision = _getPageRevision($params);
234
235     if (! $revision)
236         return NoSuchPage();
237
238     return new xmlrpcresp(long_string($revision->getPackedContent()));
239 }
240  
241
242 /**
243  * base64 getPageVersion( String pagename, int version ): Get the raw Wiki text of page.
244  * Returns UTF-8, expects UTF-8 with URL encoding.
245  */
246 $wiki_dmap['getPageVersion']
247 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
248         'documentation' => 'Get the raw Wiki text of a page version',
249         'function'      => 'getPageVersion');
250
251 function getPageVersion($params)
252 {
253     // error checking is done in getPage
254     return getPage($params);
255
256
257 /**
258  * base64 getPageHTML( String pagename ): Return page in rendered HTML. 
259  * Returns UTF-8, expects UTF-8 with URL encoding.
260  */
261
262 $wiki_dmap['getPageHTML']
263 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString)),
264         'documentation' => 'Get the current version of a page rendered in HTML',
265         'function'      => 'getPageHTML');
266
267 function getPageHTML($params)
268 {
269     $revision = _getPageRevision($params);
270     if (!$revision)
271         return NoSuchPage();
272     
273     include_once('lib/PageType.php');
274     $content = array(PageType($revision));
275
276     // Get rid of outer <div class="wikitext">
277     while (count($content) == 1 && isa($content[0], 'XmlContent')) {
278         if (isa($content[0], 'XmlElement') && $content[0]->getTag() != 'div')
279             break;
280         $content = $content[0]->getContent();
281     }
282
283     return new xmlrpcresp(long_string(AsXML($content)));
284
285
286 /**
287  * base64 getPageHTMLVersion( String pagename, int version ): Return page in rendered HTML, UTF-8.
288  */
289 $wiki_dmap['getPageHTMLVersion']
290 = array('signature'     => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
291         'documentation' => 'Get a version of a page rendered in HTML',
292         'function'      => 'getPageHTMLVersion');
293
294 function getPageHTMLVersion($params)
295 {
296     return getPageHTML($params);
297
298
299 /**
300  * getAllPages(): Returns a list of all pages. The result is an array of strings.
301  */
302 $wiki_dmap['getAllPages']
303 = array('signature'     => array(array($xmlrpcArray)),
304         'documentation' => 'Returns a list of all pages as an array of strings', 
305         'function'      => 'getAllPages');
306
307 function getAllPages($params)
308 {
309     global $request;
310     $dbh = $request->getDbh();
311     $iterator = $dbh->getAllPages();
312     $pages = array();
313     while ($page = $iterator->next()) {
314         $pages[] = short_string($page->getName());
315     } 
316     return new xmlrpcresp(new xmlrpcval($pages, "array"));
317
318
319 /**
320  * struct getPageInfo( string pagename ) : returns a struct with elements: 
321  *   name (string): the canonical page name 
322  *   lastModified (date): Last modification date 
323  *   version (int): current version 
324  *       author (string): author name 
325  */
326 $wiki_dmap['getPageInfo']
327 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString)),
328         'documentation' => 'Gets info about the current version of a page',
329         'function'      => 'getPageInfo');
330
331 function getPageInfo($params)
332 {
333     $revision = _getPageRevision($params);
334     if (!$revision)
335         return NoSuchPage();
336     
337     $name = short_string($revision->getPageName());
338     $version = new xmlrpcval ($revision->getVersion(), "int");
339     $lastmodified = new xmlrpcval(iso8601_encode($revision->get('mtime'), 0),
340                                   "dateTime.iso8601");
341     $author = short_string($revision->get('author'));
342         
343     return new xmlrpcresp(new xmlrpcval(array('name' => $name, 
344                                               'lastModified' => $lastmodified,
345                                               'version' => $version, 
346                                               'author' => $author), 
347                                         "struct"));
348
349
350 /**
351  * struct getPageInfoVersion( string pagename, int version ) : returns
352  * a struct just like plain getPageInfo(), but this time for a
353  * specific version.
354  */
355 $wiki_dmap['getPageInfoVersion']
356 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcInt)),
357         'documentation' => 'Gets info about a page version',
358         'function'      => 'getPageInfoVersion');
359
360 function getPageInfoVersion($params)
361 {
362     return getPageInfo($params);
363 }
364
365  
366 /*  array listLinks( string pagename ): Lists all links for a given page. The
367  *  returned array contains structs, with the following elements: 
368  *       name (string) : The page name or URL the link is to. 
369  *       type (int) : The link type. Zero (0) for internal Wiki link,
370  *         one (1) for external link (URL - image link, whatever).
371  */
372 $wiki_dmap['listLinks']
373 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString)),
374         'documentation' => 'Lists all links for a given page',
375         'function'      => 'listLinks');
376
377 function listLinks($params)
378 {
379     global $request;
380     
381     $ParamPageName = $params->getParam(0);
382     $pagename = short_string_decode($ParamPageName->scalarval());
383     $dbh = $request->getDbh();
384     if (! $dbh->isWikiPage($pagename))
385         return NoSuchPage();
386     
387     $page = $dbh->getPage($pagename);
388     $linkiterator = $page->getLinks();
389     $linkstruct = array();
390     while ($currentpage = $linkiterator->next()) {
391         $currentname = $currentpage->getName();
392         $name = short_string($currentname);
393         // NB no clean way to extract a list of external links yet, so
394         // only internal links returned.  ie all type 'local'.
395         $type = new xmlrpcval('local');
396
397         // Compute URL to page
398         $args = array();
399         $currentrev = $currentpage->getCurrentRevision();
400         if ($currentrev->hasDefaultContents())
401             $args['action'] = 'edit';
402
403         // FIXME: Autodetected value of VIRTUAL_PATH wrong,
404         // this make absolute URLs contstructed by WikiURL wrong.
405         // Also, if USE_PATH_INFO is false, WikiURL is wrong
406         // due to its use of SCRIPT_NAME.
407         $use_abspath = USE_PATH_INFO && ! preg_match('/RPC2.php$/', VIRTUAL_PATH);
408         $href = new xmlrpcval(WikiURL($currentname, $args, $use_abspath));
409             
410         $linkstruct[] = new xmlrpcval(array('name'=> $name,
411                                             'type'=> $type,
412                                             'href' => $href),
413                                       "struct");
414     }
415     return new xmlrpcresp(new xmlrpcval ($linkstruct, "array"));
416
417  
418 // Construct the server instance, and set up the despatch map, which maps
419 // the XML-RPC methods onto the wiki functions
420 class XmlRpcServer extends xmlrpc_server
421 {
422     function XmlRpcServer ($request = false) {
423         global $wiki_dmap;
424         foreach ($wiki_dmap as $name => $val)
425             $dmap['wiki.' . $name] = $val;
426         
427         $this->xmlrpc_server($dmap, 0 /* delay service*/);
428     }
429
430     function service () {
431         global $ErrorManager;
432
433         $this->errbuf = '';
434         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
435
436         xmlrpc_server::service();
437
438         $ErrorManager->popErrorHandler();
439         print $this->errbuf;
440     }
441     
442     function _errorHandler ($e) {
443         $msg = htmlspecialchars($e->asString());
444         // '--' not allowed within xml comment
445         $msg = str_replace('--', '&#45;&#45;', $msg);
446         $this->errbuf .= sprintf("<!--\n%s\n-->", $msg);
447         return true;
448     }
449 }
450
451
452 // (c-file-style: "gnu")
453 // Local Variables:
454 // mode: php
455 // tab-width: 8
456 // c-basic-offset: 4
457 // c-hanging-comment-ender-p: nil
458 // indent-tabs-mode: nil
459 // End:   
460 ?>