]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/XmlRpcServer.php
Remove ENABLE_USER_NEW (always true), remove lib/WikiUser.php
[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     die('This is the address of the XML-RPC interface.' .
76         '  You must use XML-RPC calls to access information here.');
77 }
78
79 require_once 'lib/XmlRpcClient.php';
80 if (loadPhpExtension('xmlrpc')) { // fast c lib
81     require_once 'lib/XMLRPC/xmlrpcs_emu.inc';
82 } else { // slow php lib
83     global $_xmlrpcs_dmap;
84     require_once 'lib/XMLRPC/xmlrpcs.inc';
85 }
86
87 /**
88  * Helper function:  Looks up a page revision (most recent by default) in the wiki database
89  *
90  * @param xmlrpcmsg $params :  string pagename [int version]
91  * @return WikiDB _PageRevision object, or false if no such page
92  */
93
94 function _getPageRevision($params)
95 {
96     global $request;
97     $ParamPageName = $params->getParam(0);
98     $ParamVersion = $params->getParam(1);
99     $pagename = short_string_decode($ParamPageName->scalarval());
100     $version = ($ParamVersion) ? ($ParamVersion->scalarval()) : (0);
101     // FIXME:  test for version <=0 ??
102     $dbh = $request->getDbh();
103     if ($dbh->isWikiPage($pagename)) {
104         $page = $dbh->getPage($pagename);
105         if (!$version) {
106             $revision = $page->getCurrentRevision();
107         } else {
108             $revision = $page->getRevision($version);
109         }
110         return $revision;
111     }
112     return false;
113 }
114
115 /**
116  * Get an xmlrpc "No such page" error message
117  */
118 function NoSuchPage($pagename = '')
119 {
120     global $xmlrpcerruser;
121     return new xmlrpcresp(0, $xmlrpcerruser + 1, "No such page " . $pagename);
122 }
123
124 // ****************************************************************************
125 // Main API functions follow
126 // ****************************************************************************
127 global $wiki_dmap;
128
129 /**
130  * int getRPCVersionSupported(): Returns 1 for this version of the API
131  */
132 $wiki_dmap['getRPCVersionSupported']
133     = array('signature' => array(array($xmlrpcInt)),
134     'documentation' => 'Get the version of the wiki API',
135     'function' => 'getRPCVersionSupported');
136
137 // The function must be a function in the global scope which services the XML-RPC
138 // method.
139 function getRPCVersionSupported($params)
140 {
141     return new xmlrpcresp(new xmlrpcval((integer)WIKI_XMLRPC_VERSION, "int"));
142 }
143
144 /**
145  * array getRecentChanges(Date timestamp) : Get list of changed pages since
146  * timestamp, which should be in UTC. The result is an array, where each element
147  * is a struct:
148  *     name (string)       : Name of the page. The name is UTF-8 with URL encoding to make it ASCII.
149  *     lastModified (date) : Date of last modification, in UTC.
150  *     author (string)     : Name of the author (if available). Again, name is UTF-8 with URL encoding.
151  *     version (int)       : Current version.
152  *     summary (string)    : UTF-8 with URL encoding.
153  * A page MAY be specified multiple times. A page MAY NOT be specified multiple
154  * times with the same modification date.
155  * Additionally to API version 1 and 2 we added the summary field.
156  */
157 $wiki_dmap['getRecentChanges']
158     = array('signature' => array(array($xmlrpcArray, $xmlrpcDateTime)),
159     'documentation' => 'Get a list of changed pages since [timestamp]',
160     'function' => 'getRecentChanges');
161
162 function getRecentChanges($params)
163 {
164     global $request;
165     // Get the first parameter as an ISO 8601 date. Assume UTC
166     $encoded_date = $params->getParam(0);
167     $datetime = iso8601_decode($encoded_date->scalarval(), 1);
168     $dbh = $request->getDbh();
169     $pages = array();
170     $iterator = $dbh->mostRecent(array('since' => $datetime));
171     while ($page = $iterator->next()) {
172         // $page contains a WikiDB_PageRevision object
173         // no need to url encode $name, because it is already stored in that format ???
174         $name = short_string($page->getPageName());
175         $lastmodified = new xmlrpcval(iso8601_encode($page->get('mtime')), "dateTime.iso8601");
176         $author = short_string($page->get('author'));
177         $version = new xmlrpcval($page->getVersion(), 'int');
178
179         // Build an array of xmlrpc structs
180         $pages[] = new xmlrpcval(array('name' => $name,
181                 'lastModified' => $lastmodified,
182                 'author' => $author,
183                 'summary' => short_string($page->get('summary')),
184                 'version' => $version),
185             'struct');
186     }
187     return new xmlrpcresp(new xmlrpcval($pages, "array"));
188 }
189
190 /**
191  * base64 getPage( String pagename ): Get the raw Wiki text of page, latest version.
192  * Page name must be UTF-8, with URL encoding. Returned value is a binary object,
193  * with UTF-8 encoded page data.
194  */
195 $wiki_dmap['getPage']
196     = array('signature' => array(array($xmlrpcBase64, $xmlrpcString)),
197     'documentation' => 'Get the raw Wiki text of the current version of a page',
198     'function' => 'getPage');
199
200 function getPage($params)
201 {
202     $revision = _getPageRevision($params);
203
204     if (!$revision) {
205         $ParamPageName = $params->getParam(0);
206         $pagename = short_string_decode($ParamPageName->scalarval());
207         return NoSuchPage($pagename);
208     }
209
210     return new xmlrpcresp(long_string($revision->getPackedContent()));
211 }
212
213 /**
214  * base64 getPageVersion( String pagename, int version ): Get the raw Wiki text of page.
215  * Returns UTF-8, expects UTF-8 with URL encoding.
216  */
217 $wiki_dmap['getPageVersion']
218     = array('signature' => array(array($xmlrpcBase64, $xmlrpcString, $xmlrpcInt)),
219     'documentation' => 'Get the raw Wiki text of a page version',
220     'function' => 'getPageVersion');
221
222 function getPageVersion($params)
223 {
224     // error checking is done in getPage
225     return getPage($params);
226 }
227
228 /**
229  * base64 getPageHTML( String pagename ): Return page in rendered HTML.
230  * Returns UTF-8, expects UTF-8 with URL encoding.
231  */
232
233 $wiki_dmap['getPageHTML']
234     = array('signature' => array(array($xmlrpcBase64, $xmlrpcString)),
235     'documentation' => 'Get the current version of a page rendered in HTML',
236     'function' => 'getPageHTML');
237
238 function getPageHTML($params)
239 {
240     $revision = _getPageRevision($params);
241     if (!$revision)
242         return NoSuchPage();
243
244     $content = $revision->getTransformedContent();
245     $html = $content->asXML();
246     // HACK: Get rid of outer <div class="wikitext">
247     if (preg_match('/^\s*<div class="wikitext">/', $html, $m1)
248         && preg_match('@</div>\s*$@', $html, $m2)
249     ) {
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 {
433     global $request;
434
435     if (!$userid) {
436         if (!isset($_SERVER))
437             $_SERVER =& $GLOBALS['HTTP_SERVER_VARS'];
438         if (!isset($_ENV))
439             $_ENV =& $GLOBALS['HTTP_ENV_VARS'];
440         if (isset($_SERVER['REMOTE_USER']))
441             $userid = $_SERVER['REMOTE_USER'];
442         elseif (isset($_ENV['REMOTE_USER']))
443             $userid = $_ENV['REMOTE_USER']; elseif (isset($_SERVER['REMOTE_ADDR']))
444             $userid = $_SERVER['REMOTE_ADDR']; elseif (isset($_ENV['REMOTE_ADDR']))
445             $userid = $_ENV['REMOTE_ADDR']; elseif (isset($GLOBALS['REMOTE_ADDR']))
446             $userid = $GLOBALS['REMOTE_ADDR'];
447     }
448     return WikiUser($userid);
449 }
450
451 function putPage($params)
452 {
453     global $request;
454
455     $ParamPageName = $params->getParam(0);
456     $ParamContent = $params->getParam(1);
457     $pagename = short_string_decode($ParamPageName->scalarval());
458     $content = short_string_decode($ParamContent->scalarval());
459     $passwd = '';
460     if (count($params->params) > 2) {
461         $ParamAuthor = $params->getParam(2);
462         $userid = short_string_decode($ParamAuthor->scalarval());
463         if (count($params->params) > 3) {
464             $ParamPassword = $params->getParam(3);
465             $passwd = short_string_decode($ParamPassword->scalarval());
466         }
467     } else {
468         $userid = $request->_user->_userid;
469     }
470     $request->_user = _getUser($userid);
471     $request->_user->_group = $request->getGroup();
472     $request->_user->AuthCheck($userid, $passwd);
473
474     if (!mayAccessPage('edit', $pagename)) {
475         return new xmlrpcresp(
476             new xmlrpcval(
477                 array('code' => new xmlrpcval(401, "int"),
478                     'version' => new xmlrpcval(0, "int"),
479                     'message' =>
480                     short_string("no permission for "
481                         . $request->_user->UserName())),
482                 "struct"));
483     }
484
485     $now = time();
486     $dbh = $request->getDbh();
487     $page = $dbh->getPage($pagename);
488     $current = $page->getCurrentRevision();
489     $content = trim($content);
490     $version = $current->getVersion();
491     // $version = -1 will force create a new version
492     if ($current->getPackedContent() != $content) {
493         $init_meta = array('ctime' => $now,
494             'creator' => $userid,
495             'creator_id' => $userid,
496         );
497         $version_meta = array('author' => $userid,
498             'author_id' => $userid,
499             'summary' => isset($summary) ? $summary : _("xml-rpc change"),
500             'mtime' => $now,
501             'pagetype' => 'wikitext',
502             'wikitext' => $init_meta,
503         );
504         $version++;
505         $res = $page->save($content, $version, $version_meta);
506         if ($res)
507             $message = "Page $pagename version $version created";
508         else
509             $message = "Problem creating version $version of page $pagename";
510     } else {
511         $res = 0;
512         $message = $message = "Page $pagename unchanged";
513     }
514     return new xmlrpcresp(new xmlrpcval(array('code' => new xmlrpcval($res ? 200 : 400, "int"),
515             'version' => new xmlrpcval($version, "int"),
516             'message' => short_string($message)),
517         "struct"));
518 }
519
520 /* End of WikiXMLRpc API v2 */
521 /* ======================================================================== */
522 /* Start of private extensions */
523
524 /**
525  * struct getUploadedFileInfo( string localpath ) : returns a struct with elements:
526  *   lastModified (date): Last modification date
527  *   size (int): current version
528  * This is to sync uploaded files up to a remote master wiki. (SyncWiki)
529  * Not existing files return both 0.
530  *
531  * API notes: API v2 specs have array listAttachments( utf8 page ),
532  * base64 getAttachment( utf8 attachmentName ), putAttachment( utf8 attachmentName, base64 content )
533  */
534 $wiki_dmap['getUploadedFileInfo']
535     = array('signature' => array(array($xmlrpcStruct, $xmlrpcString)),
536     'documentation' => 'Gets date and size about an uploaded local file',
537     'function' => 'getUploadedFileInfo');
538
539 function getUploadedFileInfo($params)
540 {
541     // localpath is the relative part after "Upload:"
542     $ParamPath = $params->getParam(0);
543     $localpath = short_string_decode($ParamPath->scalarval());
544     preg_replace("/^[\\ \/ \.]/", "", $localpath); // strip hacks
545     $file = getUploadFilePath() . $localpath;
546     if (file_exists($file)) {
547         $size = filesize($file);
548         $lastmodified = filemtime($file);
549     } else {
550         $size = 0;
551         $lastmodified = 0;
552     }
553     return new xmlrpcresp(new xmlrpcval
554     (array('lastModified' => new xmlrpcval(iso8601_encode($lastmodified, 1),
555             "dateTime.iso8601"),
556             'size' => new xmlrpcval($size, "int")),
557         "struct"));
558 }
559
560 /**
561  * Publish-Subscribe (not yet implemented)
562  * Client subscribes to a RecentChanges-like channel, getting a short
563  * callback notification on every change. Like PageChangeNotification, just shorter
564  * and more complicated
565  * RSS2 support (not yet), since radio userland's rss-0.92. now called RSS2.
566  * BTW: Radio Userland deprecated this interface.
567  *
568  * boolean wiki.rssPleaseNotify ( notifyProcedure, port, path, protocol, urlList )
569  *   returns: true or false
570  *
571  * Check of the channel behind the rssurl has a cloud element,
572  * if the client has a direct IP connection (no NAT),
573  * register the client on the WikiDB notification handler
574  *
575  * http://backend.userland.com/publishSubscribeWalkthrough
576  * http://www.soapware.org/xmlStorageSystem#rssPleaseNotify
577  * http://www.thetwowayweb.com/soapmeetsrss#rsscloudInterface
578  */
579 $wiki_dmap['rssPleaseNotify']
580     = array('signature' => array(array($xmlrpcBoolean, $xmlrpcStruct)),
581     'documentation' => 'RSS2 change notification subscriber channel',
582     'function' => 'rssPleaseNotify');
583
584 function rssPleaseNotify($params)
585 {
586     // register the clients IP
587     return new xmlrpcresp(new xmlrpcval (0, "boolean"));
588 }
589
590 /*
591  *  boolean wiki.mailPasswordToUser ( username )
592  *  returns: true or false
593
594  */
595 $wiki_dmap['mailPasswordToUser']
596     = array('signature' => array(array($xmlrpcBoolean, $xmlrpcString)),
597     'documentation' => 'RSS2 user management helper',
598     'function' => 'mailPasswordToUser');
599
600 function mailPasswordToUser($params)
601 {
602     global $request;
603     $ParamUserid = $params->getParam(0);
604     $userid = short_string_decode($ParamUserid->scalarval());
605     $request->_user = _getUser($userid);
606     //$request->_prefs =& $request->_user->_prefs;
607     $email = $request->getPref('email');
608     $success = 0;
609     if ($email) {
610         $body = WikiURL('') . "\nPassword: " . $request->getPref('passwd');
611         $success = mail($email, "[" . WIKI_NAME . "} Password Request",
612             $body);
613     }
614     return new xmlrpcresp(new xmlrpcval ($success, "boolean"));
615 }
616
617 /**
618  * array wiki.titleSearch(String substring [, String option = "0"])
619  * returns an array of matching pagenames.
620  * TODO: standardize options
621  *
622  * @author: Reini Urban
623  */
624 $wiki_dmap['titleSearch']
625     = array('signature' => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)),
626     'documentation' => "Return matching pagenames.
627 Option 1: caseexact, 2: regex, 4: starts_with, 8: exact, 16: fallback",
628     'function' => 'titleSearch');
629
630 function titleSearch($params)
631 {
632     global $request;
633     $ParamPageName = $params->getParam(0);
634     $searchstring = short_string_decode($ParamPageName->scalarval());
635     if (count($params->params) > 1) {
636         $ParamOption = $params->getParam(1);
637         $option = (int)$ParamOption->scalarval();
638     } else
639         $option = 0;
640     // default option: substring, case-inexact
641
642     $case_exact = $option & 1;
643     $regex = $option & 2;
644     $fallback = $option & 16;
645     if (!$regex) {
646         if ($option & 4) { // STARTS_WITH
647             $regex = true;
648             $searchstring = "^" . $searchstring;
649         }
650         if ($option & 8) { // EXACT
651             $regex = true;
652             $searchstring = "^" . $searchstring . "$";
653         }
654     } else {
655         if ($option & 4 or $option & 8) {
656             global $xmlrpcerruser;
657             return new xmlrpcresp(0, $xmlrpcerruser + 1, "Invalid option");
658         }
659     }
660     include_once 'lib/TextSearchQuery.php';
661     $query = new TextSearchQuery($searchstring, $case_exact, $regex ? 'auto' : 'none');
662     $dbh = $request->getDbh();
663     $iterator = $dbh->titleSearch($query);
664     $pages = array();
665     while ($page = $iterator->next()) {
666         $pages[] = short_string($page->getName());
667     }
668     // On failure try again broader (substring + case inexact)
669     if ($fallback and empty($pages)) {
670         $query = new TextSearchQuery(short_string_decode($ParamPageName->scalarval()), false,
671             $regex ? 'auto' : 'none');
672         $dbh = $request->getDbh();
673         $iterator = $dbh->titleSearch($query);
674         while ($page = $iterator->next()) {
675             $pages[] = short_string($page->getName());
676         }
677     }
678     return new xmlrpcresp(new xmlrpcval($pages, "array"));
679 }
680
681 /**
682  * array wiki.listPlugins()
683  *
684  * Returns an array of all available plugins.
685  * For EditToolbar pluginPulldown via AJAX
686  *
687  * @author: Reini Urban
688  */
689 $wiki_dmap['listPlugins']
690     = array('signature' => array(array($xmlrpcArray)),
691     'documentation' => "Return names of all plugins",
692     'function' => 'listPlugins');
693
694 function listPlugins($params)
695 {
696     $plugin_dir = 'lib/plugin';
697     if (defined('PHPWIKI_DIR'))
698         $plugin_dir = PHPWIKI_DIR . "/$plugin_dir";
699     $pd = new fileSet($plugin_dir, '*.php');
700     $plugins = $pd->getFiles();
701     unset($pd);
702     sort($plugins);
703     $RetArray = array();
704     if (!empty($plugins)) {
705         require_once 'lib/WikiPlugin.php';
706         $w = new WikiPluginLoader();
707         foreach ($plugins as $plugin) {
708             $pluginName = str_replace(".php", "", $plugin);
709             $p = $w->getPlugin($pluginName, false); // second arg?
710             // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
711             if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
712                 $RetArray[] = short_string($pluginName);
713             }
714         }
715     }
716
717     return new xmlrpcresp(new xmlrpcval($RetArray, "array"));
718 }
719
720 /**
721  * String wiki.getPluginSynopsis(String plugin)
722  *
723  * For EditToolbar pluginPulldown via AJAX
724  *
725  * @author: Reini Urban
726  */
727 $wiki_dmap['getPluginSynopsis']
728     = array('signature' => array(array($xmlrpcArray, $xmlrpcString)),
729     'documentation' => "Return plugin synopsis",
730     'function' => 'getPluginSynopsis');
731
732 function getPluginSynopsis($params)
733 {
734     $ParamPlugin = $params->getParam(0);
735     $pluginName = short_string_decode($ParamPlugin->scalarval());
736
737     require_once 'lib/WikiPlugin.php';
738     $w = new WikiPluginLoader();
739     $synopsis = '';
740     $p = $w->getPlugin($pluginName, false); // second arg?
741     // trap php files which aren't WikiPlugin~s: wikiplugin + wikiplugin_cached only
742     if (strtolower(substr(get_parent_class($p), 0, 10)) == 'wikiplugin') {
743         $plugin_args = '';
744         $desc = $p->getArgumentsDescription();
745         $src = array("\n", '"', "'", '|', '[', ']', '\\');
746         $replace = array('%0A', '%22', '%27', '%7C', '%5B', '%5D', '%5C');
747         $desc = str_replace("<br />", ' ', $desc->asXML());
748         if ($desc)
749             $plugin_args = '\n' . str_replace($src, $replace, $desc);
750         $synopsis = "<?plugin " . $pluginName . $plugin_args . "?>"; // args?
751     }
752
753     return new xmlrpcresp(short_string($synopsis));
754 }
755
756 /**
757  * array wiki.callPlugin(String name, String args)
758  *
759  * Returns an array of pages as returned by the plugins PageList call.
760  * Only valid for plugins returning pagelists, e.g. BackLinks, AllPages, ...
761  * For various AJAX or WikiFormRich calls.
762  *
763  * @author: Reini Urban
764  */
765 $wiki_dmap['callPlugin']
766     = array('signature' => array(array($xmlrpcArray, $xmlrpcString, $xmlrpcString)),
767     'documentation' => "Returns an array of pages as returned by the plugins PageList call",
768     'function' => 'callPlugin');
769
770 function callPlugin($params)
771 {
772     global $request;
773     $dbi = $request->getDbh();
774     $ParamPlugin = $params->getParam(0);
775     $pluginName = short_string_decode($ParamPlugin->scalarval());
776     $ParamArgs = $params->getParam(1);
777     $plugin_args = short_string_decode($ParamArgs->scalarval());
778
779     $basepage = ''; //$pluginName;
780     require_once 'lib/WikiPlugin.php';
781     $w = new WikiPluginLoader();
782     $p = $w->getPlugin($pluginName, false); // second arg?
783     $pagelist = $p->run($dbi, $plugin_args, $request, $basepage);
784     $list = array();
785     if (is_object($pagelist) and isa($pagelist, 'PageList')) {
786         foreach ($pagelist->_pages as $page) {
787             $list[] = $page->getName();
788         }
789     }
790     return new xmlrpcresp(new xmlrpcval($list, "array"));
791 }
792
793 /**
794  * array wiki.listRelations([ Integer option = 1 ])
795  *
796  * Returns an array of all available relation names.
797  *   option: 1 relations only ( with 0 also )
798  *   option: 2 attributes only
799  *   option: 3 both, all names of relations and attributes
800  *   option: 4 unsorted, this might be added as bitvalue: 7 = 4+3. default: sorted
801  * For some semanticweb autofill methods.
802  *
803  * @author: Reini Urban
804  */
805 $wiki_dmap['listRelations']
806     = array('signature' => array(array($xmlrpcArray, $xmlrpcInt)),
807     'documentation' => "Return names of all relations",
808     'function' => 'listRelations');
809
810 function listRelations($params)
811 {
812     global $request;
813     $dbh = $request->getDbh();
814     if (count($params->params) > 0) {
815         $ParamOption = $params->getParam(0);
816         $option = (int)$ParamOption->scalarval();
817     } else
818         $option = 1;
819     $also_attributes = $option & 2;
820     $only_attributes = $option & 2 and !($option & 1);
821     $sorted = !($option & 4);
822     return new xmlrpcresp(new xmlrpcval($dbh->listRelations($also_attributes,
823             $only_attributes,
824             $sorted),
825         "array"));
826 }
827
828 /**
829  * String pingback.ping(String sourceURI, String targetURI)
830
831 Spec: http://www.hixie.ch/specs/pingback/pingback
832
833 Parameters
834 sourceURI of type string
835 The absolute URI of the post on the source page containing the
836 link to the target site.
837 targetURI of type string
838 The absolute URI of the target of the link, as given on the source page.
839 Return Value
840 A string, as described below.
841 Faults
842 If an error condition occurs, then the appropriate fault code from
843 the following list should be used. Clients can quickly determine
844 the kind of error from bits 5-8. 0x001x fault codes are used for
845 problems with the source URI, 0x002x codes are for problems with
846 the target URI, and 0x003x codes are used when the URIs are fine
847 but the pingback cannot be acknowledged for some other reaon.
848
849 0
850 A generic fault code. Servers MAY use this error code instead
851 of any of the others if they do not have a way of determining
852 the correct fault code.
853 0x0010 (16)
854 The source URI does not exist.
855 0x0011 (17)
856 The source URI does not contain a link to the target URI, and
857 so cannot be used as a source.
858 0x0020 (32)
859 The specified target URI does not exist. This MUST only be
860 used when the target definitely does not exist, rather than
861 when the target may exist but is not recognised. See the next
862 error.
863 0x0021 (33)
864 The specified target URI cannot be used as a target. It either
865 doesn't exist, or it is not a pingback-enabled resource. For
866 example, on a blog, typically only permalinks are
867 pingback-enabled, and trying to pingback the home page, or a
868 set of posts, will fail with this error.
869 0x0030 (48)
870 The pingback has already been registered.
871 0x0031 (49)
872 Access denied.
873 0x0032 (50)
874 The server could not communicate with an upstream server, or
875 received an error from an upstream server, and therefore could
876 not complete the request. This is similar to HTTP's 402 Bad
877 Gateway error. This error SHOULD be used by pingback proxies
878 when propagating errors.
879
880 In addition, [FaultCodes] defines some standard fault codes that
881 servers MAY use to report higher level errors.
882
883 Servers MUST respond to this function call either with a single string
884 or with a fault code.
885
886 If the pingback request is successful, then the return value MUST be a
887 single string, containing as much information as the server deems
888 useful. This string is only expected to be used for debugging
889 purposes.
890
891 If the result is unsuccessful, then the server MUST respond with an
892 RPC fault value. The fault code should be either one of the codes
893 listed above, or the generic fault code zero if the server cannot
894 determine the correct fault code.
895
896 Clients MAY ignore the return value, whether the request was
897 successful or not. It is RECOMMENDED that clients do not show the
898 result of successful requests to the user.
899
900 Upon receiving a request, servers MAY do what they like. However, the
901 following steps are RECOMMENDED:
902
903 1. The server MAY attempt to fetch the source URI to verify that
904 the source does indeed link to the target.
905 2. The server MAY check its own data to ensure that the target
906 exists and is a valid entry.
907 3. The server MAY check that the pingback has not already been registered.
908 4. The server MAY record the pingback.
909 5. The server MAY regenerate the site's pages (if the pages are static).
910  * @author: Reini Urban
911  */
912 $wiki_dmap['pingback.ping']
913     = array('signature' => array(array($xmlrpcString, $xmlrpcString, $xmlrpcString)),
914     'documentation' => "",
915     'function' => 'pingBack');
916 function pingBack($params)
917 {
918     global $request;
919     $Param0 = $params->getParam(0);
920     $sourceURI = short_string_decode($Param0->scalarval());
921     $Param1 = $params->getParam(1);
922     $targetURI = short_string_decode($Param1->scalarval());
923     // TODO...
924 }
925
926 /* End of private WikiXMLRpc API extensions */
927 /* ======================================================================== */
928
929 /**
930  * Construct the server instance, and set up the dispatch map,
931  * which maps the XML-RPC methods on to the wiki functions.
932  * Provide the "wiki." prefix to each function. Besides
933  * the blog - pingback, ... - functions with a separate namespace.
934  */
935 class XmlRpcServer extends xmlrpc_server
936 {
937     function __construct($request = false)
938     {
939         global $wiki_dmap;
940         foreach ($wiki_dmap as $name => $val) {
941             if ($name == 'pingback.ping') // non-wiki methods
942                 $dmap[$name] = $val;
943             else
944                 $dmap['wiki.' . $name] = $val;
945         }
946
947         $this->xmlrpc_server($dmap, 0 /* delay service*/);
948     }
949
950     function service()
951     {
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     {
961         $msg = htmlspecialchars($e->asString());
962         // '--' not allowed within xml comment
963         $msg = str_replace('--', '&#45;&#45;', $msg);
964         if (function_exists('xmlrpc_debugmsg'))
965             xmlrpc_debugmsg($msg);
966         return true;
967     }
968 }
969
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: