]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlRpcServer.php
No tabs
[SourceForge/phpwiki.git] / lib / XmlRpcServer.php
1 <?php
2 // $Id$
3 /* Copyright (C) 2002, Lawrence Akka <lakka@users.sourceforge.net>
4  * Copyright (C) 2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
5  *
6  * LICENCE
7  * =======
8  * This file is part of PhpWiki.
9  *
10  * PhpWiki is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * PhpWiki is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with PhpWiki; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  *
24  * LIBRARY USED - POSSIBLE PROBLEMS
25  * ================================
26  *
27  * This file provides an XML-RPC interface for PhpWiki.
28  * It checks for the existence of the xmlrpc-epi c library by Dan Libby
29  * (see http://uk2.php.net/manual/en/ref.xmlrpc.php), and falls back to
30  * the slower PHP counterpart XML-RPC library by Edd Dumbill.
31  * See http://xmlrpc.usefulinc.com/php.html for details.
32  *
33  * INTERFACE SPECIFICTION
34  * ======================
35  *
36  * The interface specification is that discussed at
37  * http://www.ecyrd.com/JSPWiki/Wiki.jsp?page=WikiRPCInterface
38  *
39  * See also http://www.usemod.com/cgi-bin/mb.pl?XmlRpc
40  * or http://www.devshed.com/c/a/PHP/Using-XMLRPC-with-PHP/
41  *
42  * Note: All XMLRPC methods are automatically prefixed with "wiki."
43  *       eg. "wiki.getAllPages"
44 */
45
46 /*
47 ToDo:
48     * Change to unit tests: XmlRpcTest v1, v2 and private
49     * Return list of external links in listLinks
50     * Support RSS2 cloud subscription: wiki.rssPleaseNotify, pingback.ping
51
52     * API v2 http://www.jspwiki.org/wiki/WikiRPCInterface2 :
53
54     * array listAttachments( utf8 page ) - Lists attachments on a given page.
55             The array consists of utf8 attachment names that can be fed to getAttachment (or putAttachment).
56     * base64 getAttachment( utf8 attachmentName ) - returns the content of an attachment.
57     * putAttachment( utf8 attachmentName, base64 content ) - (over)writes an attachment.
58     * array system.listMethods()
59     * string system.methodHelp (string methodName)
60     * array system.methodSignature (string methodName)
61
62 Done:
63         Test hwiki.jar xmlrpc interface (java visualization plugin)
64          Make use of the xmlrpc extension if found. http://xmlrpc-epi.sourceforge.net/
65     Resolved namespace conflicts
66     Added various phpwiki specific methods (mailPasswordToUser, getUploadedFileInfo,
67     putPage, titleSearch, listPlugins, getPluginSynopsis, listRelations)
68     Use client methods in inter-phpwiki calls: SyncWiki, tests/xmlrpc/
69 */
70
71 // Intercept GET requests from confused users.  Only POST is allowed here!
72 if (empty($GLOBALS['HTTP_SERVER_VARS']))
73     $GLOBALS['HTTP_SERVER_VARS']  =& $_SERVER;
74 if ($GLOBALS['HTTP_SERVER_VARS']['REQUEST_METHOD'] != "POST")
75 {
76     die('This is the address of the XML-RPC interface.' .
77         '  You must use XML-RPC calls to access information here.');
78 }
79
80 require_once("lib/XmlRpcClient.php");
81 if (loadPhpExtension('xmlrpc')) { // fast c lib
82     require_once("lib/XMLRPC/xmlrpcs_emu.inc");
83 } else { // slow php lib
84     global $_xmlrpcs_dmap;
85     require_once("lib/XMLRPC/xmlrpcs.inc");
86 }
87
88
89 /**
90  * Helper function:  Looks up a page revision (most recent by default) in the wiki database
91  *
92  * @param xmlrpcmsg $params :  string pagename [int version]
93  * @return WikiDB _PageRevision object, or false if no such page
94  */
95
96 function _getPageRevision ($params)
97 {
98     global $request;
99     $ParamPageName = $params->getParam(0);
100     $ParamVersion = $params->getParam(1);
101     $pagename = short_string_decode($ParamPageName->scalarval());
102     $version =  ($ParamVersion) ? ($ParamVersion->scalarval()):(0);
103     // FIXME:  test for version <=0 ??
104     $dbh = $request->getDbh();
105     if ($dbh->isWikiPage($pagename)) {
106         $page = $dbh->getPage($pagename);
107         if (!$version) {
108             $revision = $page->getCurrentRevision();
109         } else {
110             $revision = $page->getRevision($version);
111         }
112         return $revision;
113     }
114     return false;
115 }
116
117 /**
118  * Get an xmlrpc "No such page" error message
119  */
120 function NoSuchPage ($pagename='')
121 {
122     global $xmlrpcerruser;
123     return new xmlrpcresp(0, $xmlrpcerruser + 1, "No such page ".$pagename);
124 }
125
126
127 // ****************************************************************************
128 // Main API functions follow
129 // ****************************************************************************
130 global $wiki_dmap;
131
132 /**
133  * int getRPCVersionSupported(): Returns 1 for this version of the API
134  */
135 $wiki_dmap['getRPCVersionSupported']
136 = array('signature'    => array(array($xmlrpcInt)),
137         'documentation' => 'Get the version of the wiki API',
138         'function'    => 'getRPCVersionSupported');
139
140 // The function must be a function in the global scope which services the XML-RPC
141 // method.
142 function getRPCVersionSupported($params)
143 {
144     return new xmlrpcresp(new xmlrpcval((integer)WIKI_XMLRPC_VERSION, "int"));
145 }
146
147 /**
148  * array getRecentChanges(Date timestamp) : Get list of changed pages since
149  * timestamp, which should be in UTC. The result is an array, where each element
150  * is a struct:
151  *     name (string)       : Name of the page. The name is UTF-8 with URL encoding to make it ASCII.
152  *     lastModified (date) : Date of last modification, in UTC.
153  *     author (string)     : Name of the author (if available). Again, name is UTF-8 with URL encoding.
154  *     version (int)       : Current version.
155  *     summary (string)    : UTF-8 with URL encoding.
156  * A page MAY be specified multiple times. A page MAY NOT be specified multiple
157  * times with the same modification date.
158  * Additionally to API version 1 and 2 we added the summary field.
159  */
160 $wiki_dmap['getRecentChanges']
161 = array('signature'    => array(array($xmlrpcArray, $xmlrpcDateTime)),
162         'documentation' => 'Get a list of changed pages since [timestamp]',
163         'function'    => 'getRecentChanges');
164
165 function getRecentChanges($params)
166 {
167     global $request;
168     // Get the first parameter as an ISO 8601 date. Assume UTC
169     $encoded_date = $params->getParam(0);
170     $datetime = iso8601_decode($encoded_date->scalarval(), 1);
171     $dbh = $request->getDbh();
172     $pages = array();
173     $iterator = $dbh->mostRecent(array('since' => $datetime));
174     while ($page = $iterator->next()) {
175         // $page contains a WikiDB_PageRevision object
176         // no need to url encode $name, because it is already stored in that format ???
177         $name = short_string($page->getPageName());
178         $lastmodified = new xmlrpcval(iso8601_encode($page->get('mtime')), "dateTime.iso8601");
179         $author = short_string($page->get('author'));
180         $version = new xmlrpcval($page->getVersion(), 'int');
181
182         // Build an array of xmlrpc structs
183         $pages[] = new xmlrpcval(array('name' => $name,
184                                        'lastModified' => $lastmodified,
185                                        'author' => $author,
186                        'summary' => short_string($page->get('summary')),
187                                        'version' => $version),
188                                  'struct');
189     }
190     return new xmlrpcresp(new xmlrpcval($pages, "array"));
191 }
192
193
194 /**
195  * base64 getPage( String pagename ): Get the raw Wiki text of page, latest version.
196  * Page name must be UTF-8, with URL encoding. Returned value is a binary object,
197  * with UTF-8 encoded page data.
198  */
199 $wiki_dmap['getPage']
200 = array('signature'    => array(array($xmlrpcBase64, $xmlrpcString)),
201         'documentation' => 'Get the raw Wiki text of the current version of a page',
202         'function'    => 'getPage');
203
204 function getPage($params)
205 {
206     $revision = _getPageRevision($params);
207
208     if (! $revision ) {
209         $ParamPageName = $params->getParam(0);
210         $pagename = short_string_decode($ParamPageName->scalarval());
211         return NoSuchPage($pagename);
212     }
213
214     return new xmlrpcresp(long_string($revision->getPackedContent()));
215 }
216
217
218 /**
219  * base64 getPageVersion( String pagename, int version ): Get the raw Wiki text of page.
220  * Returns UTF-8, expects UTF-8 with URL encoding.
221  */
222 $wiki_dmap['getPageVersion']
223 = array('signature'    => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
224         'documentation' => 'Get the raw Wiki text of a page version',
225         'function'    => 'getPageVersion');
226
227 function getPageVersion($params)
228 {
229     // error checking is done in getPage
230     return getPage($params);
231 }
232
233 /**
234  * base64 getPageHTML( String pagename ): Return page in rendered HTML.
235  * Returns UTF-8, expects UTF-8 with URL encoding.
236  */
237
238 $wiki_dmap['getPageHTML']
239 = array('signature'    => array(array($xmlrpcBase64, $xmlrpcString)),
240         'documentation' => 'Get the current version of a page rendered in HTML',
241         'function'    => 'getPageHTML');
242
243 function getPageHTML($params)
244 {
245     $revision = _getPageRevision($params);
246     if (!$revision)
247         return NoSuchPage();
248
249     $content = $revision->getTransformedContent();
250     $html = $content->asXML();
251     // HACK: Get rid of outer <div class="wikitext">
252     if (preg_match('/^\s*<div class="wikitext">/', $html, $m1)
253     && preg_match('@</div>\s*$@', $html, $m2)) {
254     $html = substr($html, strlen($m1[0]), -strlen($m2[0]));
255     }
256
257     return new xmlrpcresp(long_string($html));
258 }
259
260 /**
261  * base64 getPageHTMLVersion( String pagename, int version ): Return page in rendered HTML, UTF-8.
262  */
263 $wiki_dmap['getPageHTMLVersion']
264 = array('signature'    => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
265         'documentation' => 'Get a version of a page rendered in HTML',
266         'function'    => 'getPageHTMLVersion');
267
268 function getPageHTMLVersion($params)
269 {
270     return getPageHTML($params);
271 }
272
273 /**
274  * getAllPages(): Returns a list of all pages. The result is an array of strings.
275  */
276 $wiki_dmap['getAllPages']
277 = array('signature'    => array(array($xmlrpcArray)),
278         'documentation' => 'Returns a list of all pages as an array of strings',
279         'function'    => 'getAllPages');
280
281 function getAllPages($params)
282 {
283     global $request;
284     $dbh = $request->getDbh();
285     $iterator = $dbh->getAllPages();
286     $pages = array();
287     while ($page = $iterator->next()) {
288         $pages[] = short_string($page->getName());
289     }
290     return new xmlrpcresp(new xmlrpcval($pages, "array"));
291 }
292
293 /**
294  * struct getPageInfo( string pagename ) : returns a struct with elements:
295  *   name (string): the canonical page name
296  *   lastModified (date): Last modification date
297  *   version (int): current version
298  *   author (string): author name
299  */
300 $wiki_dmap['getPageInfo']
301 = array('signature'    => array(array($xmlrpcStruct, $xmlrpcString)),
302         'documentation' => 'Gets info about the current version of a page',
303         'function'    => 'getPageInfo');
304
305 function getPageInfo($params)
306 {
307     $revision = _getPageRevision($params);
308     if (!$revision)
309         return NoSuchPage();
310
311     $name = short_string($revision->getPageName());
312     $version = new xmlrpcval ($revision->getVersion(), "int");
313     $lastmodified = new xmlrpcval(iso8601_encode($revision->get('mtime'), 0),
314                                   "dateTime.iso8601");
315     $author = short_string($revision->get('author'));
316
317     return new xmlrpcresp(new xmlrpcval(array('name' => $name,
318                                               'lastModified' => $lastmodified,
319                                               'version' => $version,
320                                               'author' => $author),
321                                         "struct"));
322 }
323
324 /**
325  * struct getPageInfoVersion( string pagename, int version ) : returns
326  * a struct just like plain getPageInfo(), but this time for a
327  * specific version.
328  */
329 $wiki_dmap['getPageInfoVersion']
330 = array('signature'    => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcInt)),
331         'documentation' => 'Gets info about a page version',
332         'function'    => 'getPageInfoVersion');
333
334 function getPageInfoVersion($params)
335 {
336     return getPageInfo($params);
337 }
338
339
340 /*  array listLinks( string pagename ): Lists all links for a given page. The
341  *  returned array contains structs, with the following elements:
342  *        name (string) : The page name or URL the link is to.
343  *       type (int)    : The link type. Zero (0) for internal Wiki link,
344  *                        one (1) for external link (URL - image link, whatever).
345  */
346 $wiki_dmap['listLinks']
347 = array('signature'    => array(array($xmlrpcArray, $xmlrpcString)),
348         'documentation' => 'Lists all links for a given page',
349         'function'    => 'listLinks');
350
351 function listLinks($params)
352 {
353     global $request;
354
355     $ParamPageName = $params->getParam(0);
356     $pagename = short_string_decode($ParamPageName->scalarval());
357     $dbh = $request->getDbh();
358     if (! $dbh->isWikiPage($pagename))
359         return NoSuchPage($pagename);
360
361     $page = $dbh->getPage($pagename);
362
363     // The fast WikiDB method. below is the slow method which goes through the formatter
364     // NB no clean way to extract a list of external links yet, so
365     // only internal links returned.  i.e. all type 'local'.
366     $linkiterator = $page->getPageLinks();
367     $linkstruct = array();
368     while ($currentpage = $linkiterator->next()) {
369         $currentname = $currentpage->getName();
370         // Compute URL to page
371         $args = array();
372         // How to check external links?
373         if (!$currentpage->exists()) $args['action'] = 'edit';
374
375         // FIXME: Autodetected value of VIRTUAL_PATH wrong,
376         // this make absolute URLs constructed by WikiURL wrong.
377         // Also, if USE_PATH_INFO is false, WikiURL is wrong
378         // due to its use of SCRIPT_NAME.
379         //$use_abspath = USE_PATH_INFO && ! preg_match('/RPC2.php$/', VIRTUAL_PATH);
380
381         // USE_PATH_INFO must be defined in index.php or config.ini but not before,
382         // otherwise it is ignored and xmlrpc urls are wrong.
383         // SCRIPT_NAME here is always .../RPC2.php
384         if (USE_PATH_INFO and !$args) {
385             $url = preg_replace('/%2f/i', '/', rawurlencode($currentname));
386         } elseif (!USE_PATH_INFO) {
387             $url = str_replace("/RPC2.php","/index.php", WikiURL($currentname, $args, true));
388         } else {
389             $url = WikiURL($currentname, $args);
390         }
391         $linkstruct[] = new xmlrpcval(array('page'=> short_string($currentname),
392                                             'type'=> new xmlrpcval('local', 'string'),
393                                             'href' => short_string($url)),
394                                       "struct");
395     }
396
397     /*
398     $current = $page->getCurrentRevision();
399     $content = $current->getTransformedContent();
400     $links = $content->getLinkInfo();
401     foreach ($links as $link) {
402         // We used to give an href for unknown pages that
403         // included action=edit.  I think that's probably the
404         // wrong thing to do.
405         $linkstruct[] = new xmlrpcval(array('page'=> short_string($link->page),
406                                             'type'=> new xmlrpcval($link->type, 'string'),
407                                             'href' => short_string($link->href),
408                                             //'pageref' => short_string($link->pageref),
409                                             ),
410                                       "struct");
411     }
412     */
413     return new xmlrpcresp(new xmlrpcval ($linkstruct, "array"));
414 }
415
416 /* End of WikiXMLRpc API v1 */
417 /* ======================================================================== */
418 /* Start of partial WikiXMLRpc API v2 support */
419
420 /**
421  * struct putPage(String pagename, String content, [String author[, String password]})
422  * returns a struct with elements:
423  *   code (int): 200 on success, 400 or 401 on failure
424  *   message (string): success or failure message
425  *   version (int): version of new page
426  *
427  * @author: Arnaud Fontaine, Reini Urban
428  *
429  * API notes: Contrary to the API v2 specs we dropped attributes and added author + password
430  */
431 $wiki_dmap['putPage']
432 = array('signature'     => array(array($xmlrpcStruct, $xmlrpcString, $xmlrpcString, $xmlrpcString, $xmlrpcString)),
433         'documentation' => 'put the raw Wiki text into a page as new version',
434         'function'      => 'putPage');
435
436 function _getUser($userid='') {
437     global $request;
438
439     if (! $userid ) {
440         if (!isset($_SERVER))
441             $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
442         if (!isset($_ENV))
443             $_ENV =& $GLOBALS['HTTP_ENV_VARS'];
444         if (isset($_SERVER['REMOTE_USER']))
445             $userid = $_SERVER['REMOTE_USER'];
446         elseif (isset($_ENV['REMOTE_USER']))
447             $userid = $_ENV['REMOTE_USER'];
448         elseif (isset($_SERVER['REMOTE_ADDR']))
449             $userid = $_SERVER['REMOTE_ADDR'];
450         elseif (isset($_ENV['REMOTE_ADDR']))
451             $userid = $_ENV['REMOTE_ADDR'];
452         elseif (isset($GLOBALS['REMOTE_ADDR']))
453             $userid = $GLOBALS['REMOTE_ADDR'];
454     }
455
456     if (ENABLE_USER_NEW) {
457         return WikiUser($userid);
458     } else {
459         return new WikiUser($request, $userid);
460     }
461 }
462
463 function putPage($params) {
464     global $request;
465
466     $ParamPageName = $params->getParam(0);
467     $ParamContent = $params->getParam(1);
468     $pagename = short_string_decode($ParamPageName->scalarval());
469     $content = short_string_decode($ParamContent->scalarval());
470     $passwd = '';
471     if (count($params->params) > 2) {
472         $ParamAuthor = $params->getParam(2);
473         $userid = short_string_decode($ParamAuthor->scalarval());
474         if (count($params->params) > 3) {
475             $ParamPassword = $params->getParam(3);
476             $passwd = short_string_decode($ParamPassword->scalarval());
477         }
478     } else {
479         $userid = $request->_user->_userid;
480     }
481     $request->_user = _getUser($userid);
482     $request->_user->_group = $request->getGroup();
483     $request->_user->AuthCheck($userid, $passwd);
484
485     if (! mayAccessPage ('edit', $pagename)) {
486         return new xmlrpcresp(
487                               new xmlrpcval(
488                                             array('code' => new xmlrpcval(401, "int"),
489                                                   'version' => new xmlrpcval(0, "int"),
490                                                   'message' =>
491                                                   short_string("no permission for "
492                                                                .$request->_user->UserName())),
493                                             "struct"));
494     }
495
496     $now = time();
497     $dbh = $request->getDbh();
498     $page = $dbh->getPage($pagename);
499     $current = $page->getCurrentRevision();
500     $content = trim($content);
501     $version = $current->getVersion();
502     // $version = -1 will force create a new version
503     if ($current->getPackedContent() != $content) {
504         $init_meta = array('ctime' => $now,
505                            'creator' => $userid,
506                            'creator_id' => $userid,
507                            );
508         $version_meta = array('author' => $userid,
509                               'author_id' => $userid,
510                               'markup' => 2.0,
511                               'summary' => isset($summary) ? $summary : _("xml-rpc change"),
512                               'mtime' => $now,
513                               'pagetype' => 'wikitext',
514                               'wikitext' => $init_meta,
515                               );
516         $version++;
517         $res = $page->save($content, $version, $version_meta);
518         if ($res)
519             $message = "Page $pagename version $version created";
520         else
521             $message = "Problem creating version $version of page $pagename";
522     } else {
523         $res = 0;
524         $message = $message = "Page $pagename unchanged";
525     }
526     return new xmlrpcresp(new xmlrpcval(array('code'    => new xmlrpcval($res ? 200 : 400, "int"),
527                                               'version' => new xmlrpcval($version, "int"),
528                                               'message' => short_string($message)),
529                                         "struct"));
530 }
531
532 /* End of WikiXMLRpc API v2 */
533 /* ======================================================================== */
534 /* Start of private extensions */
535
536 /**
537  * struct getUploadedFileInfo( string localpath ) : returns a struct with elements:
538  *   lastModified (date): Last modification date
539  *   size (int): current version
540  * This is to sync uploaded files up to a remote master wiki. (SyncWiki)
541  * Not existing files return both 0.
542  *
543  * API notes: API v2 specs have array listAttachments( utf8 page ),
544  * base64 getAttachment( utf8 attachmentName ), putAttachment( utf8 attachmentName, base64 content )
545  */
546 $wiki_dmap['getUploadedFileInfo']
547 = array('signature'    => array(array($xmlrpcStruct, $xmlrpcString)),
548         'documentation' => 'Gets date and size about an uploaded local file',
549         'function'    => 'getUploadedFileInfo');
550
551 function getUploadedFileInfo($params)
552 {
553     // localpath is the relative part after "Upload:"
554     $ParamPath = $params->getParam(0);
555     $localpath = short_string_decode($ParamPath->scalarval());
556     preg_replace("/^[\\ \/ \.]/", "", $localpath); // strip hacks
557     $file = getUploadFilePath() . $localpath;
558     if (file_exists($file)) {
559         $size = filesize($file);
560         $lastmodified = filemtime($file);
561     } else {
562         $size = 0;
563         $lastmodified = 0;
564     }
565     return new xmlrpcresp(new xmlrpcval
566         (array('lastModified' => new xmlrpcval(iso8601_encode($lastmodified, 1),
567                                                "dateTime.iso8601"),
568                'size' => new xmlrpcval($size, "int")),
569         "struct"));
570 }
571
572 /**
573  * Publish-Subscribe (not yet implemented)
574  * Client subscribes to a RecentChanges-like channel, getting a short
575  * callback notification on every change. Like PageChangeNotification, just shorter
576  * and more complicated
577  * RSS2 support (not yet), since radio userland's rss-0.92. now called RSS2.
578  * BTW: Radio Userland deprecated this interface.
579  *
580  * boolean wiki.rssPleaseNotify ( notifyProcedure, port, path, protocol, urlList )
581  *   returns: true or false
582  *
583  * Check of the channel behind the rssurl has a cloud element,
584  * if the client has a direct IP connection (no NAT),
585  * register the client on the WikiDB notification handler
586  *
587  * http://backend.userland.com/publishSubscribeWalkthrough
588  * http://www.soapware.org/xmlStorageSystem#rssPleaseNotify
589  * http://www.thetwowayweb.com/soapmeetsrss#rsscloudInterface
590  */
591 $wiki_dmap['rssPleaseNotify']
592 = array('signature'    => array(array($xmlrpcBoolean, $xmlrpcStruct)),
593         'documentation' => 'RSS2 change notification subscriber channel',
594         'function'    => 'rssPleaseNotify');
595
596 function rssPleaseNotify($params)
597 {
598     // register the clients IP
599     return new xmlrpcresp(new xmlrpcval (0, "boolean"));
600 }
601
602 /*
603  *  boolean wiki.mailPasswordToUser ( username )
604  *  returns: true or false
605
606  */
607 $wiki_dmap['mailPasswordToUser']
608 = array('signature'    => array(array($xmlrpcBoolean, $xmlrpcString)),
609         'documentation' => 'RSS2 user management helper',
610         'function'    => 'mailPasswordToUser');
611
612 function mailPasswordToUser($params)
613 {
614     global $request;
615     $ParamUserid = $params->getParam(0);
616     $userid = short_string_decode($ParamUserid->scalarval());
617     $request->_user = _getUser($userid);
618     //$request->_prefs =& $request->_user->_prefs;
619     $email = $request->getPref('email');
620     $success = 0;
621     if ($email) {
622         $body = WikiURL('') . "\nPassword: " . $request->getPref('passwd');
623         $success = mail($email, "[".WIKI_NAME."} Password Request",
624                         $body);
625     }
626     return new xmlrpcresp(new xmlrpcval ($success, "boolean"));
627 }
628
629 /**
630  * array wiki.titleSearch(String substring [, String option = "0"])
631  * returns an array of matching pagenames.
632  * TODO: standardize options
633  *
634  * @author: Reini Urban
635  */
636 $wiki_dmap['titleSearch']
637 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)),
638         'documentation' => "Return matching pagenames.
639 Option 1: caseexact, 2: regex, 4: starts_with, 8: exact, 16: fallback",
640         'function'      => 'titleSearch');
641
642 function titleSearch($params)
643 {
644     global $request;
645     $ParamPageName = $params->getParam(0);
646     $searchstring = short_string_decode($ParamPageName->scalarval());
647     if (count($params->params) > 1) {
648         $ParamOption = $params->getParam(1);
649         $option = (int) $ParamOption->scalarval();
650     } else
651     $option = 0;
652         // default option: substring, case-inexact
653
654     $case_exact = $option & 1;
655     $regex      = $option & 2;
656     $fallback   = $option & 16;
657     if (!$regex) {
658         if ($option & 4) { // STARTS_WITH
659             $regex = true;
660             $searchstring = "^".$searchstring;
661         }
662         if ($option & 8) { // EXACT
663             $regex = true;
664             $searchstring = "^".$searchstring."$";
665         }
666     } else {
667         if ($option & 4 or $option & 8) {
668         global $xmlrpcerruser;
669             return new xmlrpcresp(0, $xmlrpcerruser + 1, "Invalid option");
670         }
671     }
672     include_once("lib/TextSearchQuery.php");
673     $query = new TextSearchQuery($searchstring, $case_exact, $regex ? 'auto' : 'none');
674     $dbh = $request->getDbh();
675     $iterator = $dbh->titleSearch($query);
676     $pages = array();
677     while ($page = $iterator->next()) {
678         $pages[] = short_string($page->getName());
679     }
680     // On failure try again broader (substring + case inexact)
681     if ($fallback and empty($pages)) {
682         $query = new TextSearchQuery(short_string_decode($ParamPageName->scalarval()), false,
683                                      $regex ? 'auto' : 'none');
684         $dbh = $request->getDbh();
685         $iterator = $dbh->titleSearch($query);
686         while ($page = $iterator->next()) {
687             $pages[] = short_string($page->getName());
688         }
689     }
690     return new xmlrpcresp(new xmlrpcval($pages, "array"));
691 }
692
693 /**
694  * array wiki.listPlugins()
695  *
696  * Returns an array of all available plugins.
697  * For EditToolbar pluginPulldown via AJAX
698  *
699  * @author: Reini Urban
700  */
701 $wiki_dmap['listPlugins']
702 = array('signature'     => array(array($xmlrpcArray)),
703         'documentation' => "Return names of all plugins",
704         'function'      => 'listPlugins');
705
706 function listPlugins($params)
707 {
708     $plugin_dir = 'lib/plugin';
709     if (defined('PHPWIKI_DIR'))
710         $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
711     $pd = new fileSet($plugin_dir, '*.php');
712     $plugins = $pd->getFiles();
713     unset($pd);
714     sort($plugins);
715     $RetArray = array();
716     if (!empty($plugins)) {
717         require_once("lib/WikiPlugin.php");
718         $w = new WikiPluginLoader;
719         foreach ($plugins as $plugin) {
720             $pluginName = str_replace(".php", "", $plugin);
721             $p = $w->getPlugin($pluginName, false); // second arg?
722             // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
723             if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
724                 $RetArray[] = short_string($pluginName);
725             }
726         }
727     }
728
729     return new xmlrpcresp(new xmlrpcval($RetArray, "array"));
730 }
731
732 /**
733  * String wiki.getPluginSynopsis(String plugin)
734  *
735  * For EditToolbar pluginPulldown via AJAX
736  *
737  * @author: Reini Urban
738  */
739 $wiki_dmap['getPluginSynopsis']
740 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString)),
741         'documentation' => "Return plugin synopsis",
742         'function'      => 'getPluginSynopsis');
743
744 function getPluginSynopsis($params)
745 {
746     $ParamPlugin = $params->getParam(0);
747     $pluginName = short_string_decode($ParamPlugin->scalarval());
748
749     require_once("lib/WikiPlugin.php");
750     $w = new WikiPluginLoader;
751     $synopsis = '';
752     $p = $w->getPlugin($pluginName, false); // second arg?
753     // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
754     if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
755         $plugin_args = '';
756         $desc = $p->getArgumentsDescription();
757         $src = array("\n",'"',"'",'|','[',']','\\');
758         $replace = array('%0A','%22','%27','%7C','%5B','%5D','%5C');
759         $desc = str_replace("<br />",' ',$desc->asXML());
760         if ($desc)
761             $plugin_args = '\n'.str_replace($src, $replace, $desc);
762         $synopsis = "<?plugin ".$pluginName.$plugin_args."?>"; // args?
763     }
764
765     return new xmlrpcresp(short_string($synopsis));
766 }
767
768 /**
769  * array wiki.callPlugin(String name, String args)
770  *
771  * Returns an array of pages as returned by the plugins PageList call.
772  * Only valid for plugins returning pagelists, e.g. BackLinks, AllPages, ...
773  * For various AJAX or WikiFormRich calls.
774  *
775  * @author: Reini Urban
776  */
777 $wiki_dmap['callPlugin']
778 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)),
779         'documentation' => "Returns an array of pages as returned by the plugins PageList call",
780         'function'      => 'callPlugin');
781
782 function callPlugin($params)
783 {
784     global $request;
785     $dbi = $request->getDbh();
786     $ParamPlugin = $params->getParam(0);
787     $pluginName = short_string_decode($ParamPlugin->scalarval());
788     $ParamArgs = $params->getParam(1);
789     $plugin_args = short_string_decode($ParamArgs->scalarval());
790
791     $basepage = ''; //$pluginName;
792     require_once("lib/WikiPlugin.php");
793     $w = new WikiPluginLoader;
794     $p = $w->getPlugin($pluginName, false); // second arg?
795     $pagelist = $p->run($dbi, $plugin_args, $request, $basepage);
796     $list = array();
797     if (is_object($pagelist) and isa($pagelist, 'PageList')) {
798     foreach ($pagelist->_pages as $page) {
799         $list[] = $page->getName();
800     }
801     }
802     return new xmlrpcresp(new xmlrpcval($list, "array"));
803 }
804
805 /**
806  * array wiki.listRelations([ Integer option = 1 ])
807  *
808  * Returns an array of all available relation names.
809  *   option: 1 relations only ( with 0 also )
810  *   option: 2 attributes only
811  *   option: 3 both, all names of relations and attributes
812  *   option: 4 unsorted, this might be added as bitvalue: 7 = 4+3. default: sorted
813  * For some semanticweb autofill methods.
814  *
815  * @author: Reini Urban
816  */
817 $wiki_dmap['listRelations']
818 = array('signature'     => array(array($xmlrpcArray, $xmlrpcInt)),
819         'documentation' => "Return names of all relations",
820         'function'      => 'listRelations');
821
822 function listRelations($params)
823 {
824     global $request;
825     $dbh = $request->getDbh();
826     if (count($params->params) > 0) {
827         $ParamOption = $params->getParam(0);
828         $option = (int) $ParamOption->scalarval();
829     } else
830     $option = 1;
831     $also_attributes = $option & 2;
832     $only_attributes = $option & 2 and !($option & 1);
833     $sorted = !($option & 4);
834     return new xmlrpcresp(new xmlrpcval($dbh->listRelations($also_attributes,
835                                 $only_attributes,
836                                 $sorted),
837                     "array"));
838 }
839
840 /**
841  * String pingback.ping(String sourceURI, String targetURI)
842
843 Spec: http://www.hixie.ch/specs/pingback/pingback
844
845 Parameters
846     sourceURI of type string
847         The absolute URI of the post on the source page containing the
848         link to the target site.
849     targetURI of type string
850         The absolute URI of the target of the link, as given on the source page.
851 Return Value
852     A string, as described below.
853 Faults
854     If an error condition occurs, then the appropriate fault code from
855     the following list should be used. Clients can quickly determine
856     the kind of error from bits 5-8. 0x001x fault codes are used for
857     problems with the source URI, 0x002x codes are for problems with
858     the target URI, and 0x003x codes are used when the URIs are fine
859     but the pingback cannot be acknowledged for some other reaon.
860
861     0
862         A generic fault code. Servers MAY use this error code instead
863         of any of the others if they do not have a way of determining
864         the correct fault code.
865     0x0010 (16)
866         The source URI does not exist.
867     0x0011 (17)
868         The source URI does not contain a link to the target URI, and
869         so cannot be used as a source.
870     0x0020 (32)
871         The specified target URI does not exist. This MUST only be
872         used when the target definitely does not exist, rather than
873         when the target may exist but is not recognised. See the next
874         error.
875     0x0021 (33)
876         The specified target URI cannot be used as a target. It either
877         doesn't exist, or it is not a pingback-enabled resource. For
878         example, on a blog, typically only permalinks are
879         pingback-enabled, and trying to pingback the home page, or a
880         set of posts, will fail with this error.
881     0x0030 (48)
882         The pingback has already been registered.
883     0x0031 (49)
884         Access denied.
885     0x0032 (50)
886         The server could not communicate with an upstream server, or
887         received an error from an upstream server, and therefore could
888         not complete the request. This is similar to HTTP's 402 Bad
889         Gateway error. This error SHOULD be used by pingback proxies
890         when propagating errors.
891
892     In addition, [FaultCodes] defines some standard fault codes that
893     servers MAY use to report higher level errors.
894
895 Servers MUST respond to this function call either with a single string
896 or with a fault code.
897
898 If the pingback request is successful, then the return value MUST be a
899 single string, containing as much information as the server deems
900 useful. This string is only expected to be used for debugging
901 purposes.
902
903 If the result is unsuccessful, then the server MUST respond with an
904 RPC fault value. The fault code should be either one of the codes
905 listed above, or the generic fault code zero if the server cannot
906 determine the correct fault code.
907
908 Clients MAY ignore the return value, whether the request was
909 successful or not. It is RECOMMENDED that clients do not show the
910 result of successful requests to the user.
911
912 Upon receiving a request, servers MAY do what they like. However, the
913 following steps are RECOMMENDED:
914
915    1. The server MAY attempt to fetch the source URI to verify that
916    the source does indeed link to the target.
917    2. The server MAY check its own data to ensure that the target
918    exists and is a valid entry.
919    3. The server MAY check that the pingback has not already been registered.
920    4. The server MAY record the pingback.
921    5. The server MAY regenerate the site's pages (if the pages are static).
922
923  * @author: Reini Urban
924  */
925 $wiki_dmap['pingback.ping']
926 = array('signature'     => array(array($xmlrpcString, $xmlrpcString, $xmlrpcString)),
927         'documentation' => "",
928         'function'      => 'pingBack');
929 function pingBack($params)
930 {
931     global $request;
932     $Param0 = $params->getParam(0);
933     $sourceURI = short_string_decode($Param0->scalarval());
934     $Param1 = $params->getParam(1);
935     $targetURI = short_string_decode($Param1->scalarval());
936     // TODO...
937 }
938
939 /* End of private WikiXMLRpc API extensions */
940 /* ======================================================================== */
941
942 /**
943  * Construct the server instance, and set up the dispatch map,
944  * which maps the XML-RPC methods on to the wiki functions.
945  * Provide the "wiki." prefix to each function. Besides
946  * the blog - pingback, ... - functions with a seperate namespace.
947  */
948 class XmlRpcServer extends xmlrpc_server
949 {
950     function XmlRpcServer ($request = false) {
951         global $wiki_dmap;
952         foreach ($wiki_dmap as $name => $val) {
953             if ($name == 'pingback.ping') // non-wiki methods
954                 $dmap[$name] = $val;
955             else
956                 $dmap['wiki.' . $name] = $val;
957         }
958
959         $this->xmlrpc_server($dmap, 0 /* delay service*/);
960     }
961
962     function service () {
963         global $ErrorManager;
964
965         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
966         xmlrpc_server::service();
967         $ErrorManager->popErrorHandler();
968     }
969
970     function _errorHandler ($e) {
971         $msg = htmlspecialchars($e->asString());
972         // '--' not allowed within xml comment
973         $msg = str_replace('--', '&#45;&#45;', $msg);
974         if (function_exists('xmlrpc_debugmsg'))
975             xmlrpc_debugmsg($msg);
976         return true;
977     }
978 }
979
980 // Local Variables:
981 // mode: php
982 // tab-width: 8
983 // c-basic-offset: 4
984 // c-hanging-comment-ender-p: nil
985 // indent-tabs-mode: nil
986 // End:
987 ?>