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