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