]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiMain.php
MediaWiki 1.11.0
[autoinstalls/mediawiki.git] / includes / api / ApiMain.php
1 <?php
2
3 /*
4  * Created on Sep 4, 2006
5  *
6  * API for MediaWiki 1.8+
7  *
8  * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9  *
10  * This program 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  * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
22  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23  * http://www.gnu.org/copyleft/gpl.html
24  */
25
26 if (!defined('MEDIAWIKI')) {
27         // Eclipse helper - will be ignored in production
28         require_once ('ApiBase.php');
29 }
30
31 /**
32  * This is the main API class, used for both external and internal processing.
33  * When executed, it will create the requested formatter object,
34  * instantiate and execute an object associated with the needed action,
35  * and use formatter to print results.
36  * In case of an exception, an error message will be printed using the same formatter.
37  *
38  * To use API from another application, run it using FauxRequest object, in which
39  * case any internal exceptions will not be handled but passed up to the caller.
40  * After successful execution, use getResult() for the resulting data.   
41  *  
42  * @addtogroup API
43  */
44 class ApiMain extends ApiBase {
45
46         /**
47          * When no format parameter is given, this format will be used
48          */
49         const API_DEFAULT_FORMAT = 'xmlfm';
50
51         /**
52          * List of available modules: action name => module class
53          */
54         private static $Modules = array (
55                 'login' => 'ApiLogin',
56                 'query' => 'ApiQuery',
57                 'opensearch' => 'ApiOpenSearch',
58                 'feedwatchlist' => 'ApiFeedWatchlist',
59                 'help' => 'ApiHelp',
60         );
61
62         /**
63          * List of available formats: format name => format class
64          */
65         private static $Formats = array (
66                 'json' => 'ApiFormatJson',
67                 'jsonfm' => 'ApiFormatJson',
68                 'php' => 'ApiFormatPhp',
69                 'phpfm' => 'ApiFormatPhp',
70                 'wddx' => 'ApiFormatWddx',
71                 'wddxfm' => 'ApiFormatWddx',
72                 'xml' => 'ApiFormatXml',
73                 'xmlfm' => 'ApiFormatXml',
74                 'yaml' => 'ApiFormatYaml',
75                 'yamlfm' => 'ApiFormatYaml',
76                 'rawfm' => 'ApiFormatJson'
77         );
78
79         private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
80         private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
81
82         /**
83         * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
84         *
85         * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
86         * @param $enableWrite bool should be set to true if the api may modify data
87         */
88         public function __construct($request, $enableWrite = false) {
89
90                 $this->mInternalMode = ($request instanceof FauxRequest);
91
92                 // Special handling for the main module: $parent === $this
93                 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
94
95                 if (!$this->mInternalMode) {
96                         
97                         // Impose module restrictions.
98                         // If the current user cannot read, 
99                         // Remove all modules other than login
100                         global $wgUser;
101                         if (!$wgUser->isAllowed('read')) {
102                                 self::$Modules = array(
103                                         'login' => self::$Modules['login'],
104                                         'help' => self::$Modules['help']
105                                         ); 
106                         }
107                 }
108
109                 global $wgAPIModules; // extension modules
110                 $this->mModules = $wgAPIModules + self :: $Modules;
111
112                 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
113                 $this->mFormats = self :: $Formats;
114                 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
115
116                 $this->mResult = new ApiResult($this);
117                 $this->mShowVersions = false;
118                 $this->mEnableWrite = $enableWrite;
119
120                 $this->mRequest = & $request;
121
122                 $this->mSquidMaxage = 0;
123         }
124
125         /**
126          * Return true if the API was started by other PHP code using FauxRequest
127          */
128         public function isInternalMode() {
129                 return $this->mInternalMode;
130         }
131
132         /**
133          * Return the request object that contains client's request
134          */
135         public function getRequest() {
136                 return $this->mRequest;
137         }
138
139         /**
140          * Get the ApiResult object asscosiated with current request
141          */
142         public function getResult() {
143                 return $this->mResult;
144         }
145
146         /**
147          * This method will simply cause an error if the write mode was disabled for this api.
148          */
149         public function requestWriteMode() {
150                 if (!$this->mEnableWrite)
151                         $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
152                         'statement is included in the site\'s LocalSettings.php file', 'readonly');
153         }
154
155         /**
156          * Set how long the response should be cached.
157          */
158         public function setCacheMaxAge($maxage) {
159                 $this->mSquidMaxage = $maxage;
160         }
161
162         /**
163          * Create an instance of an output formatter by its name
164          */
165         public function createPrinterByName($format) {
166                 return new $this->mFormats[$format] ($this, $format);
167         }
168
169         /**
170          * Execute api request. Any errors will be handled if the API was called by the remote client. 
171          */
172         public function execute() {
173                 $this->profileIn();
174                 if ($this->mInternalMode)
175                         $this->executeAction();
176                 else
177                         $this->executeActionWithErrorHandling();
178                 $this->profileOut();
179         }
180
181         /**
182          * Execute an action, and in case of an error, erase whatever partial results
183          * have been accumulated, and replace it with an error message and a help screen.
184          */
185         protected function executeActionWithErrorHandling() {
186
187                 // In case an error occurs during data output,
188                 // clear the output buffer and print just the error information
189                 ob_start();
190
191                 try {
192                         $this->executeAction();
193                 } catch (Exception $e) {
194                         //
195                         // Handle any kind of exception by outputing properly formatted error message.
196                         // If this fails, an unhandled exception should be thrown so that global error
197                         // handler will process and log it.
198                         //
199
200                         $errCode = $this->substituteResultWithError($e);
201
202                         // Error results should not be cached
203                         $this->setCacheMaxAge(0);
204
205                         $headerStr = 'MediaWiki-API-Error: ' . $errCode;
206                         if ($e->getCode() === 0)
207                                 header($headerStr, true);
208                         else
209                                 header($headerStr, true, $e->getCode());
210
211                         // Reset and print just the error message
212                         ob_clean();
213
214                         // If the error occured during printing, do a printer->profileOut()
215                         $this->mPrinter->safeProfileOut();
216                         $this->printResult(true);
217                 }
218
219                 // Set the cache expiration at the last moment, as any errors may change the expiration.
220                 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
221                 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
222                 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
223                 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
224
225                 if($this->mPrinter->getIsHtml())
226                         echo wfReportTime();
227
228                 ob_end_flush();
229         }
230
231         /**
232          * Replace the result data with the information about an exception.
233          * Returns the error code 
234          */
235         protected function substituteResultWithError($e) {
236         
237                         // Printer may not be initialized if the extractRequestParams() fails for the main module
238                         if (!isset ($this->mPrinter)) {
239                                 // The printer has not been created yet. Try to manually get formatter value.
240                                 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
241                                 if (!in_array($value, $this->mFormatNames))
242                                         $value = self::API_DEFAULT_FORMAT;
243
244                                 $this->mPrinter = $this->createPrinterByName($value);
245                                 if ($this->mPrinter->getNeedsRawData())
246                                         $this->getResult()->setRawMode();
247                         }
248
249                         if ($e instanceof UsageException) {
250                                 //
251                                 // User entered incorrect parameters - print usage screen
252                                 //
253                                 $errMessage = array (
254                                 'code' => $e->getCodeString(),
255                                 'info' => $e->getMessage());
256                                 
257                                 // Only print the help message when this is for the developer, not runtime
258                                 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
259                                         ApiResult :: setContent($errMessage, $this->makeHelpMsg());
260
261                         } else {
262                                 //
263                                 // Something is seriously wrong
264                                 //
265                                 $errMessage = array (
266                                         'code' => 'internal_api_error',
267                                         'info' => "Exception Caught: {$e->getMessage()}"
268                                 );
269                                 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
270                         }
271
272                         $this->getResult()->reset();
273                         $this->getResult()->addValue(null, 'error', $errMessage);
274
275                 return $errMessage['code'];
276         }
277
278         /**
279          * Execute the actual module, without any error handling
280          */
281         protected function executeAction() {
282                 
283                 $params = $this->extractRequestParams();
284                 
285                 $this->mShowVersions = $params['version'];
286                 $this->mAction = $params['action'];
287
288                 // Instantiate the module requested by the user
289                 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
290
291                 if (!$this->mInternalMode) {
292
293                         // See if custom printer is used
294                         $this->mPrinter = $module->getCustomPrinter();
295                         if (is_null($this->mPrinter)) {
296                                 // Create an appropriate printer
297                                 $this->mPrinter = $this->createPrinterByName($params['format']);
298                         }
299
300                         if ($this->mPrinter->getNeedsRawData())
301                                 $this->getResult()->setRawMode();
302                 }
303
304                 // Execute
305                 $module->profileIn();
306                 $module->execute();
307                 $module->profileOut();
308
309                 if (!$this->mInternalMode) {
310                         // Print result data
311                         $this->printResult(false);
312                 }
313         }
314
315         /**
316          * Print results using the current printer
317          */
318         protected function printResult($isError) {
319                 $printer = $this->mPrinter;
320                 $printer->profileIn();
321                 $printer->initPrinter($isError);
322                 $printer->execute();
323                 $printer->closePrinter();
324                 $printer->profileOut();
325         }
326
327         /**
328          * See ApiBase for description.
329          */
330         protected function getAllowedParams() {
331                 return array (
332                         'format' => array (
333                                 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
334                                 ApiBase :: PARAM_TYPE => $this->mFormatNames
335                         ),
336                         'action' => array (
337                                 ApiBase :: PARAM_DFLT => 'help',
338                                 ApiBase :: PARAM_TYPE => $this->mModuleNames
339                         ),
340                         'version' => false
341                 );
342         }
343
344         /**
345          * See ApiBase for description.
346          */
347         protected function getParamDescription() {
348                 return array (
349                         'format' => 'The format of the output',
350                         'action' => 'What action you would like to perform',
351                         'version' => 'When showing help, include version for each module'
352                 );
353         }
354
355         /**
356          * See ApiBase for description.
357          */
358         protected function getDescription() {
359                 return array (
360                         '',
361                         '',
362                         '******************************************************************',
363                         '**                                                              **',
364                         '**  This is an auto-generated MediaWiki API documentation page  **',
365                         '**                                                              **',
366                         '**                  Documentation and Examples:                 **',
367                         '**               http://www.mediawiki.org/wiki/API              **',
368                         '**                                                              **',
369                         '******************************************************************',
370                         '',
371                         'Status:          All features shown on this page should be working, but the API',
372                         '                 is still in active development, and  may change at any time.',
373                         '                 Make sure to monitor our mailing list for any updates.',
374                         '',
375                         'Documentation:   http://www.mediawiki.org/wiki/API',
376                         'Mailing list:    http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
377                         'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
378                         '',
379                         '',
380                         '',
381                         '',
382                         '',
383                 );
384         }
385         
386         /**
387          * Returns an array of strings with credits for the API
388          */
389         protected function getCredits() {
390                 return array(
391                         'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
392                         'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
393                 );
394         }
395
396         /**
397          * Override the parent to generate help messages for all available modules.
398          */
399         public function makeHelpMsg() {
400
401                 // Use parent to make default message for the main module
402                 $msg = parent :: makeHelpMsg();
403
404                 $astriks = str_repeat('*** ', 10);
405                 $msg .= "\n\n$astriks Modules  $astriks\n\n";
406                 foreach( $this->mModules as $moduleName => $unused ) {
407                         $module = new $this->mModules[$moduleName] ($this, $moduleName);
408                         $msg .= self::makeHelpMsgHeader($module, 'action');
409                         $msg2 = $module->makeHelpMsg();
410                         if ($msg2 !== false)
411                                 $msg .= $msg2;
412                         $msg .= "\n";
413                 }
414
415                 $msg .= "\n$astriks Formats  $astriks\n\n";
416                 foreach( $this->mFormats as $formatName => $unused ) {
417                         $module = $this->createPrinterByName($formatName);
418                         $msg .= self::makeHelpMsgHeader($module, 'format');
419                         $msg2 = $module->makeHelpMsg();
420                         if ($msg2 !== false)
421                                 $msg .= $msg2;
422                         $msg .= "\n";
423                 }
424                 
425                 $msg .= "\n*** Credits: ***\n   " . implode("\n   ", $this->getCredits()) . "\n";
426                 
427
428                 return $msg;
429         }
430
431         public static function makeHelpMsgHeader($module, $paramName) {
432                 $modulePrefix = $module->getModulePrefix();
433                 if (!empty($modulePrefix))
434                         $modulePrefix = "($modulePrefix) "; 
435                 
436                 return "* $paramName={$module->getModuleName()} $modulePrefix*";
437         } 
438
439         private $mIsBot = null;
440         
441         private $mIsSysop = null;
442         
443         /**
444          * Returns true if the currently logged in user is a bot, false otherwise
445          */
446         public function isBot() {
447                 if (!isset ($this->mIsBot)) {
448                         global $wgUser;
449                         $this->mIsBot = $wgUser->isAllowed('bot');
450                 }
451                 return $this->mIsBot;
452         }
453         
454         /**
455          * Similar to isBot(), this method returns true if the logged in user is
456          * a sysop, and false if not.
457          */
458         public function isSysop() {
459                 if (!isset ($this->mIsSysop)) {
460                         global $wgUser;
461                         $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
462                 }
463
464                 return $this->mIsSysop;
465         }
466
467         public function getShowVersions() {
468                 return $this->mShowVersions;
469         }
470
471         /**
472          * Returns the version information of this file, plus it includes
473          * the versions for all files that are not callable proper API modules
474          */
475         public function getVersion() {
476                 $vers = array ();
477                 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
478                 $vers[] = __CLASS__ . ': $Id: ApiMain.php 25364 2007-08-31 15:23:48Z tstarling $';
479                 $vers[] = ApiBase :: getBaseVersion();
480                 $vers[] = ApiFormatBase :: getBaseVersion();
481                 $vers[] = ApiQueryBase :: getBaseVersion();
482                 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
483                 return $vers;
484         }
485
486         /**
487          * Add or overwrite a module in this ApiMain instance. Intended for use by extending
488          * classes who wish to add their own modules to their lexicon or override the 
489          * behavior of inherent ones.
490          *
491          * @access protected
492          * @param $mdlName String The identifier for this module.
493          * @param $mdlClass String The class where this module is implemented.
494          */
495         protected function addModule( $mdlName, $mdlClass ) {
496                 $this->mModules[$mdlName] = $mdlClass;
497         }
498
499         /**
500          * Add or overwrite an output format for this ApiMain. Intended for use by extending
501          * classes who wish to add to or modify current formatters.
502          *
503          * @access protected
504          * @param $fmtName The identifier for this format.
505          * @param $fmtClass The class implementing this format.
506          */
507         protected function addFormat( $fmtName, $fmtClass ) {
508                 $this->mFormats[$fmtName] = $fmtClass;
509         }
510 }
511
512 /**
513  * This exception will be thrown when dieUsage is called to stop module execution.
514  * The exception handling code will print a help screen explaining how this API may be used.
515  * 
516  * @addtogroup API
517  */
518 class UsageException extends Exception {
519
520         private $mCodestr;
521
522         public function __construct($message, $codestr, $code = 0) {
523                 parent :: __construct($message, $code);
524                 $this->mCodestr = $codestr;
525         }
526         public function getCodeString() {
527                 return $this->mCodestr;
528         }
529         public function __toString() {
530                 return "{$this->getCodeString()}: {$this->getMessage()}";
531         }
532 }
533