]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlRpcServer.php
Remove history
[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",
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     if (!$regex) {
657         if ($option & 4) { // STARTS_WITH
658             $regex = true;
659             $searchstring = "^".$searchstring;
660         }
661         if ($option & 8) { // EXACT
662             $regex = true;
663             $searchstring = "^".$searchstring."$";
664         }
665     } else {
666         if ($option & 4 or $option & 8) { 
667             global $xmlrpcerruser;
668             return new xmlrpcresp(0, $xmlrpcerruser + 1, "Invalid option");
669         }
670     }
671     include_once("lib/TextSearchQuery.php");
672     $query = new TextSearchQuery($searchstring, $case_exact, $regex ? 'auto' : 'none');
673     $dbh = $request->getDbh();
674     $iterator = $dbh->titleSearch($query);
675     $pages = array();
676     while ($page = $iterator->next()) {
677         $pages[] = short_string($page->getName());
678     } 
679     return new xmlrpcresp(new xmlrpcval($pages, "array"));
680 }
681
682 /** 
683  * array wiki.listPlugins()
684  *
685  * Returns an array of all available plugins. 
686  * For EditToolbar pluginPulldown via AJAX
687  *
688  * @author: Reini Urban
689  */
690 $wiki_dmap['listPlugins']
691 = array('signature'     => array(array($xmlrpcArray)),
692         'documentation' => "Return names of all plugins",
693         'function'      => 'listPlugins');
694
695 function listPlugins($params)
696 {
697     $plugin_dir = 'lib/plugin';
698     if (defined('PHPWIKI_DIR'))
699         $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
700     $pd = new fileSet($plugin_dir, '*.php');
701     $plugins = $pd->getFiles();
702     unset($pd);
703     sort($plugins);
704     $RetArray = array();
705     if (!empty($plugins)) {
706         require_once("lib/WikiPlugin.php");
707         $w = new WikiPluginLoader;
708         foreach ($plugins as $plugin) {
709             $pluginName = str_replace(".php", "", $plugin);
710             $p = $w->getPlugin($pluginName, false); // second arg?
711             // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
712             if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
713                 $RetArray[] = short_string($pluginName);
714             }
715         }
716     }
717   
718     return new xmlrpcresp(new xmlrpcval($RetArray, "array"));
719 }
720
721 /** 
722  * String wiki.getPluginSynopsis(String plugin)
723  *
724  * For EditToolbar pluginPulldown via AJAX
725  *
726  * @author: Reini Urban
727  */
728 $wiki_dmap['getPluginSynopsis']
729 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString)),
730         'documentation' => "Return plugin synopsis",
731         'function'      => 'getPluginSynopsis');
732
733 function getPluginSynopsis($params)
734 {
735     $ParamPlugin = $params->getParam(0);
736     $pluginName = short_string_decode($ParamPlugin->scalarval());
737
738     require_once("lib/WikiPlugin.php");
739     $w = new WikiPluginLoader;
740     $synopsis = '';
741     $p = $w->getPlugin($pluginName, false); // second arg?
742     // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
743     if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
744         $plugin_args = '';
745         $desc = $p->getArgumentsDescription();
746         $src = array("\n",'"',"'",'|','[',']','\\');
747         $replace = array('%0A','%22','%27','%7C','%5B','%5D','%5C');
748         $desc = str_replace("<br />",' ',$desc->asXML());
749         if ($desc)
750             $plugin_args = '\n'.str_replace($src, $replace, $desc);
751         $synopsis = "<?plugin ".$pluginName.$plugin_args."?>"; // args?
752     }
753    
754     return new xmlrpcresp(short_string($synopsis));
755 }
756
757 /** 
758  * array wiki.callPlugin(String name, String args)
759  *
760  * Returns an array of pages as returned by the plugins PageList call. 
761  * Only valid for plugins returning pagelists, e.g. BackLinks, AllPages, ...
762  * For various AJAX or WikiFormRich calls.
763  *
764  * @author: Reini Urban
765  */
766 $wiki_dmap['callPlugin']
767 = array('signature'     => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)),
768         'documentation' => "Returns an array of pages as returned by the plugins PageList call",
769         'function'      => 'callPlugin');
770
771 function callPlugin($params)
772 {
773     global $request;
774     $dbi = $request->getDbh();
775     $ParamPlugin = $params->getParam(0);
776     $pluginName = short_string_decode($ParamPlugin->scalarval());
777     $ParamArgs = $params->getParam(1);
778     $plugin_args = short_string_decode($ParamArgs->scalarval());
779
780     $basepage = ''; //$pluginName;
781     require_once("lib/WikiPlugin.php");
782     $w = new WikiPluginLoader;
783     $p = $w->getPlugin($pluginName, false); // second arg?
784     $pagelist = $p->run($dbi, $plugin_args, $request, $basepage);
785     $list = array();
786     if (is_object($pagelist) and isa($pagelist, 'PageList')) {
787         foreach ($pagelist->_pages as $page) {
788             $list[] = $page->getName();
789         }
790     }
791     return new xmlrpcresp(new xmlrpcval($list, "array"));
792 }
793
794 /** 
795  * array wiki.listRelations([ Integer option = 1 ])
796  *
797  * Returns an array of all available relation names.
798  *   option: 1 relations only ( with 0 also )
799  *   option: 2 attributes only
800  *   option: 3 both, all names of relations and attributes 
801  *   option: 4 unsorted, this might be added as bitvalue: 7 = 4+3. default: sorted
802  * For some semanticweb autofill methods.
803  *
804  * @author: Reini Urban
805  */
806 $wiki_dmap['listRelations']
807 = array('signature'     => array(array($xmlrpcArray, $xmlrpcInt)),
808         'documentation' => "Return names of all relations",
809         'function'      => 'listRelations');
810
811 function listRelations($params)
812 {
813     global $request;
814     $dbh = $request->getDbh();
815     if (count($params->params) > 0) {
816         $ParamOption = $params->getParam(0);
817         $option = (int) $ParamOption->scalarval();
818     } else 
819         $option = 1;
820     $also_attributes = $option & 2; 
821     $only_attributes = $option & 2 and !($option & 1); 
822     $sorted = !($option & 4);
823     return new xmlrpcresp(new xmlrpcval($dbh->listRelations($also_attributes,
824                                                             $only_attributes,
825                                                             $sorted), 
826                                         "array"));
827 }
828
829 /** 
830  * String pingback.ping(String sourceURI, String targetURI)
831
832 Spec: http://www.hixie.ch/specs/pingback/pingback
833
834 Parameters
835     sourceURI of type string
836         The absolute URI of the post on the source page containing the
837         link to the target site.
838     targetURI of type string
839         The absolute URI of the target of the link, as given on the source page.
840 Return Value
841     A string, as described below.
842 Faults
843     If an error condition occurs, then the appropriate fault code from
844     the following list should be used. Clients can quickly determine
845     the kind of error from bits 5-8. 0×001x fault codes are used for
846     problems with the source URI, 0×002x codes are for problems with
847     the target URI, and 0×003x codes are used when the URIs are fine
848     but the pingback cannot be acknowledged for some other reaon.
849
850     0 
851         A generic fault code. Servers MAY use this error code instead
852         of any of the others if they do not have a way of determining
853         the correct fault code.
854     0×0010 (16)
855         The source URI does not exist.
856     0×0011 (17)
857         The source URI does not contain a link to the target URI, and
858         so cannot be used as a source.
859     0×0020 (32)
860         The specified target URI does not exist. This MUST only be
861         used when the target definitely does not exist, rather than
862         when the target may exist but is not recognised. See the next
863         error.
864     0×0021 (33)
865         The specified target URI cannot be used as a target. It either
866         doesn't exist, or it is not a pingback-enabled resource. For
867         example, on a blog, typically only permalinks are
868         pingback-enabled, and trying to pingback the home page, or a
869         set of posts, will fail with this error.
870     0×0030 (48)
871         The pingback has already been registered.
872     0×0031 (49)
873         Access denied.
874     0×0032 (50)
875         The server could not communicate with an upstream server, or
876         received an error from an upstream server, and therefore could
877         not complete the request. This is similar to HTTP's 402 Bad
878         Gateway error. This error SHOULD be used by pingback proxies
879         when propagating errors.
880
881     In addition, [FaultCodes] defines some standard fault codes that
882     servers MAY use to report higher level errors.
883
884 Servers MUST respond to this function call either with a single string
885 or with a fault code.
886
887 If the pingback request is successful, then the return value MUST be a
888 single string, containing as much information as the server deems
889 useful. This string is only expected to be used for debugging
890 purposes.
891
892 If the result is unsuccessful, then the server MUST respond with an
893 RPC fault value. The fault code should be either one of the codes
894 listed above, or the generic fault code zero if the server cannot
895 determine the correct fault code.
896
897 Clients MAY ignore the return value, whether the request was
898 successful or not. It is RECOMMENDED that clients do not show the
899 result of successful requests to the user.
900
901 Upon receiving a request, servers MAY do what they like. However, the
902 following steps are RECOMMENDED:
903
904    1. The server MAY attempt to fetch the source URI to verify that
905    the source does indeed link to the target.
906    2. The server MAY check its own data to ensure that the target
907    exists and is a valid entry.
908    3. The server MAY check that the pingback has not already been registered.
909    4. The server MAY record the pingback.
910    5. The server MAY regenerate the site's pages (if the pages are static).
911
912  * @author: Reini Urban
913  */
914 $wiki_dmap['pingback.ping']
915 = array('signature'     => array(array($xmlrpcString, $xmlrpcString, $xmlrpcString)),
916         'documentation' => "",
917         'function'      => 'pingBack');
918 function pingBack($params)
919 {
920     global $request;
921     $Param0 = $params->getParam(0);
922     $sourceURI = short_string_decode($Param0->scalarval());
923     $Param1 = $params->getParam(1);
924     $targetURI = short_string_decode($Param1->scalarval());
925     // TODO...
926 }
927
928 /* End of private WikiXMLRpc API extensions */
929 /* ======================================================================== */
930  
931 /** 
932  * Construct the server instance, and set up the dispatch map, 
933  * which maps the XML-RPC methods on to the wiki functions.
934  * Provide the "wiki." prefix to each function. Besides 
935  * the blog - pingback, ... - functions with a seperate namespace.
936  */
937 class XmlRpcServer extends xmlrpc_server
938 {
939     function XmlRpcServer ($request = false) {
940         global $wiki_dmap;
941         foreach ($wiki_dmap as $name => $val) {
942             if ($name == 'pingback.ping') // non-wiki methods
943                 $dmap[$name] = $val;
944             else
945                 $dmap['wiki.' . $name] = $val;
946         }
947
948         $this->xmlrpc_server($dmap, 0 /* delay service*/);
949     }
950
951     function service () {
952         global $ErrorManager;
953
954         $ErrorManager->pushErrorHandler(new WikiMethodCb($this, '_errorHandler'));
955         xmlrpc_server::service();
956         $ErrorManager->popErrorHandler();
957     }
958     
959     function _errorHandler ($e) {
960         $msg = htmlspecialchars($e->asString());
961         // '--' not allowed within xml comment
962         $msg = str_replace('--', '&#45;&#45;', $msg);
963         if (function_exists('xmlrpc_debugmsg'))
964             xmlrpc_debugmsg($msg);
965         return true;
966     }
967 }
968
969 // (c-file-style: "gnu")
970 // Local Variables:
971 // mode: php
972 // tab-width: 8
973 // c-basic-offset: 4
974 // c-hanging-comment-ender-p: nil
975 // indent-tabs-mode: nil
976 // End:   
977 ?>