Revert to r34430 in order to revert r34431 which is breaking the site (unindexed...
[lhc/web/wiklou.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 'logout' => 'ApiLogout',
57 'query' => 'ApiQuery',
58 'expandtemplates' => 'ApiExpandTemplates',
59 'parse' => 'ApiParse',
60 'opensearch' => 'ApiOpenSearch',
61 'feedwatchlist' => 'ApiFeedWatchlist',
62 'help' => 'ApiHelp',
63 'paraminfo' => 'ApiParamInfo',
64 );
65
66 private static $WriteModules = array (
67 'rollback' => 'ApiRollback',
68 'delete' => 'ApiDelete',
69 'undelete' => 'ApiUndelete',
70 'protect' => 'ApiProtect',
71 'block' => 'ApiBlock',
72 'unblock' => 'ApiUnblock',
73 'move' => 'ApiMove',
74 'edit' => 'ApiEditPage',
75 );
76
77 /**
78 * List of available formats: format name => format class
79 */
80 private static $Formats = array (
81 'json' => 'ApiFormatJson',
82 'jsonfm' => 'ApiFormatJson',
83 'php' => 'ApiFormatPhp',
84 'phpfm' => 'ApiFormatPhp',
85 'wddx' => 'ApiFormatWddx',
86 'wddxfm' => 'ApiFormatWddx',
87 'xml' => 'ApiFormatXml',
88 'xmlfm' => 'ApiFormatXml',
89 'yaml' => 'ApiFormatYaml',
90 'yamlfm' => 'ApiFormatYaml',
91 'rawfm' => 'ApiFormatJson',
92 'txt' => 'ApiFormatTxt',
93 'txtfm' => 'ApiFormatTxt',
94 'dbg' => 'ApiFormatDbg',
95 'dbgfm' => 'ApiFormatDbg'
96 );
97
98 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames, $mCommit;
99 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
100
101 /**
102 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
103 *
104 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
105 * @param $enableWrite bool should be set to true if the api may modify data
106 */
107 public function __construct($request, $enableWrite = false) {
108
109 $this->mInternalMode = ($request instanceof FauxRequest);
110
111 // Special handling for the main module: $parent === $this
112 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
113
114 if (!$this->mInternalMode) {
115
116 // Impose module restrictions.
117 // If the current user cannot read,
118 // Remove all modules other than login
119 global $wgUser;
120
121 if( $request->getVal( 'callback' ) !== null ) {
122 // JSON callback allows cross-site reads.
123 // For safety, strip user credentials.
124 wfDebug( "API: stripping user credentials for JSON callback\n" );
125 $wgUser = new User();
126 }
127
128 if (!$wgUser->isAllowed('read')) {
129 self::$Modules = array(
130 'login' => self::$Modules['login'],
131 'logout' => self::$Modules['logout'],
132 'help' => self::$Modules['help'],
133 );
134 }
135 }
136
137 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
138 $this->mModules = $wgAPIModules + self :: $Modules;
139 if($wgEnableWriteAPI)
140 $this->mModules += self::$WriteModules;
141
142 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
143 $this->mFormats = self :: $Formats;
144 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
145
146 $this->mResult = new ApiResult($this);
147 $this->mShowVersions = false;
148 $this->mEnableWrite = $enableWrite;
149
150 $this->mRequest = & $request;
151
152 $this->mSquidMaxage = 0;
153 $this->mCommit = false;
154 }
155
156 /**
157 * Return true if the API was started by other PHP code using FauxRequest
158 */
159 public function isInternalMode() {
160 return $this->mInternalMode;
161 }
162
163 /**
164 * Return the request object that contains client's request
165 */
166 public function getRequest() {
167 return $this->mRequest;
168 }
169
170 /**
171 * Get the ApiResult object asscosiated with current request
172 */
173 public function getResult() {
174 return $this->mResult;
175 }
176
177 /**
178 * This method will simply cause an error if the write mode was disabled for this api.
179 */
180 public function requestWriteMode() {
181 if (!$this->mEnableWrite)
182 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
183 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
184 }
185
186 /**
187 * Set how long the response should be cached.
188 */
189 public function setCacheMaxAge($maxage) {
190 $this->mSquidMaxage = $maxage;
191 }
192
193 /**
194 * Create an instance of an output formatter by its name
195 */
196 public function createPrinterByName($format) {
197 return new $this->mFormats[$format] ($this, $format);
198 }
199
200 /**
201 * Schedule a database commit
202 */
203 public function scheduleCommit() {
204 $this->mCommit = true;
205 }
206
207 /**
208 * Execute api request. Any errors will be handled if the API was called by the remote client.
209 */
210 public function execute() {
211 $this->profileIn();
212 if ($this->mInternalMode)
213 $this->executeAction();
214 else
215 $this->executeActionWithErrorHandling();
216 if($this->mCommit)
217 {
218 $dbw = wfGetDb(DB_MASTER);
219 $dbw->immediateCommit();
220 }
221 $this->profileOut();
222 }
223
224 /**
225 * Execute an action, and in case of an error, erase whatever partial results
226 * have been accumulated, and replace it with an error message and a help screen.
227 */
228 protected function executeActionWithErrorHandling() {
229
230 // In case an error occurs during data output,
231 // clear the output buffer and print just the error information
232 ob_start();
233
234 try {
235 $this->executeAction();
236 } catch (Exception $e) {
237 //
238 // Handle any kind of exception by outputing properly formatted error message.
239 // If this fails, an unhandled exception should be thrown so that global error
240 // handler will process and log it.
241 //
242
243 $errCode = $this->substituteResultWithError($e);
244
245 // Error results should not be cached
246 $this->setCacheMaxAge(0);
247
248 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
249 if ($e->getCode() === 0)
250 header($headerStr, true);
251 else
252 header($headerStr, true, $e->getCode());
253
254 // Reset and print just the error message
255 ob_clean();
256
257 // If the error occured during printing, do a printer->profileOut()
258 $this->mPrinter->safeProfileOut();
259 $this->printResult(true);
260 }
261
262 // Set the cache expiration at the last moment, as any errors may change the expiration.
263 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
264 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
265 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
266 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
267
268 if($this->mPrinter->getIsHtml())
269 echo wfReportTime();
270
271 ob_end_flush();
272 }
273
274 /**
275 * Replace the result data with the information about an exception.
276 * Returns the error code
277 */
278 protected function substituteResultWithError($e) {
279
280 // Printer may not be initialized if the extractRequestParams() fails for the main module
281 if (!isset ($this->mPrinter)) {
282 // The printer has not been created yet. Try to manually get formatter value.
283 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
284 if (!in_array($value, $this->mFormatNames))
285 $value = self::API_DEFAULT_FORMAT;
286
287 $this->mPrinter = $this->createPrinterByName($value);
288 if ($this->mPrinter->getNeedsRawData())
289 $this->getResult()->setRawMode();
290 }
291
292 if ($e instanceof UsageException) {
293 //
294 // User entered incorrect parameters - print usage screen
295 //
296 $errMessage = array (
297 'code' => $e->getCodeString(),
298 'info' => $e->getMessage());
299
300 // Only print the help message when this is for the developer, not runtime
301 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
302 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
303
304 } else {
305 //
306 // Something is seriously wrong
307 //
308 $errMessage = array (
309 'code' => 'internal_api_error_'. get_class($e),
310 'info' => "Exception Caught: {$e->getMessage()}"
311 );
312 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
313 }
314
315 $this->getResult()->reset();
316 $this->getResult()->addValue(null, 'error', $errMessage);
317
318 return $errMessage['code'];
319 }
320
321 /**
322 * Execute the actual module, without any error handling
323 */
324 protected function executeAction() {
325
326 $params = $this->extractRequestParams();
327
328 $this->mShowVersions = $params['version'];
329 $this->mAction = $params['action'];
330
331 // Instantiate the module requested by the user
332 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
333
334 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
335 // Check for maxlag
336 global $wgShowHostnames;
337 $maxLag = $params['maxlag'];
338 list( $host, $lag ) = wfGetLB()->getMaxLag();
339 if ( $lag > $maxLag ) {
340 if( $wgShowHostnames ) {
341 ApiBase :: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
342 } else {
343 ApiBase :: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
344 }
345 return;
346 }
347 }
348
349 if (!$this->mInternalMode) {
350 // Ignore mustBePosted() for internal calls
351 if($module->mustBePosted() && !$this->mRequest->wasPosted())
352 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
353
354 // See if custom printer is used
355 $this->mPrinter = $module->getCustomPrinter();
356 if (is_null($this->mPrinter)) {
357 // Create an appropriate printer
358 $this->mPrinter = $this->createPrinterByName($params['format']);
359 }
360
361 if ($this->mPrinter->getNeedsRawData())
362 $this->getResult()->setRawMode();
363 }
364
365 // Execute
366 $module->profileIn();
367 $module->execute();
368 $module->profileOut();
369
370 if (!$this->mInternalMode) {
371 // Print result data
372 $this->printResult(false);
373 }
374 }
375
376 /**
377 * Print results using the current printer
378 */
379 protected function printResult($isError) {
380 $printer = $this->mPrinter;
381 $printer->profileIn();
382
383 /* If the help message is requested in the default (xmlfm) format,
384 * tell the printer not to escape ampersands so that our links do
385 * not break. */
386 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
387 && $this->getParameter('format') == ApiMain::API_DEFAULT_FORMAT );
388
389 $printer->initPrinter($isError);
390
391 $printer->execute();
392 $printer->closePrinter();
393 $printer->profileOut();
394 }
395
396 /**
397 * See ApiBase for description.
398 */
399 public function getAllowedParams() {
400 return array (
401 'format' => array (
402 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
403 ApiBase :: PARAM_TYPE => $this->mFormatNames
404 ),
405 'action' => array (
406 ApiBase :: PARAM_DFLT => 'help',
407 ApiBase :: PARAM_TYPE => $this->mModuleNames
408 ),
409 'version' => false,
410 'maxlag' => array (
411 ApiBase :: PARAM_TYPE => 'integer'
412 ),
413 );
414 }
415
416 /**
417 * See ApiBase for description.
418 */
419 public function getParamDescription() {
420 return array (
421 'format' => 'The format of the output',
422 'action' => 'What action you would like to perform',
423 'version' => 'When showing help, include version for each module',
424 'maxlag' => 'Maximum lag'
425 );
426 }
427
428 /**
429 * See ApiBase for description.
430 */
431 public function getDescription() {
432 return array (
433 '',
434 '',
435 '******************************************************************',
436 '** **',
437 '** This is an auto-generated MediaWiki API documentation page **',
438 '** **',
439 '** Documentation and Examples: **',
440 '** http://www.mediawiki.org/wiki/API **',
441 '** **',
442 '******************************************************************',
443 '',
444 'Status: All features shown on this page should be working, but the API',
445 ' is still in active development, and may change at any time.',
446 ' Make sure to monitor our mailing list for any updates.',
447 '',
448 'Documentation: http://www.mediawiki.org/wiki/API',
449 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
450 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
451 '',
452 '',
453 '',
454 '',
455 '',
456 );
457 }
458
459 /**
460 * Returns an array of strings with credits for the API
461 */
462 protected function getCredits() {
463 return array(
464 'API developers:',
465 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
466 ' Victor Vasiliev - vasilvv at gee mail dot com',
467 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
468 '',
469 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
470 'or file a bug report at http://bugzilla.wikimedia.org/'
471 );
472 }
473
474 /**
475 * Override the parent to generate help messages for all available modules.
476 */
477 public function makeHelpMsg() {
478
479 $this->mPrinter->setHelp();
480
481 // Use parent to make default message for the main module
482 $msg = parent :: makeHelpMsg();
483
484 $astriks = str_repeat('*** ', 10);
485 $msg .= "\n\n$astriks Modules $astriks\n\n";
486 foreach( $this->mModules as $moduleName => $unused ) {
487 $module = new $this->mModules[$moduleName] ($this, $moduleName);
488 $msg .= self::makeHelpMsgHeader($module, 'action');
489 $msg2 = $module->makeHelpMsg();
490 if ($msg2 !== false)
491 $msg .= $msg2;
492 $msg .= "\n";
493 }
494
495 $msg .= "\n$astriks Formats $astriks\n\n";
496 foreach( $this->mFormats as $formatName => $unused ) {
497 $module = $this->createPrinterByName($formatName);
498 $msg .= self::makeHelpMsgHeader($module, 'format');
499 $msg2 = $module->makeHelpMsg();
500 if ($msg2 !== false)
501 $msg .= $msg2;
502 $msg .= "\n";
503 }
504
505 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
506
507
508 return $msg;
509 }
510
511 public static function makeHelpMsgHeader($module, $paramName) {
512 $modulePrefix = $module->getModulePrefix();
513 if (!empty($modulePrefix))
514 $modulePrefix = "($modulePrefix) ";
515
516 return "* $paramName={$module->getModuleName()} $modulePrefix*";
517 }
518
519 private $mIsBot = null;
520 private $mIsSysop = null;
521 private $mCanApiHighLimits = null;
522
523 /**
524 * Returns true if the currently logged in user is a bot, false otherwise
525 * OBSOLETE, use canApiHighLimits() instead
526 */
527 public function isBot() {
528 if (!isset ($this->mIsBot)) {
529 global $wgUser;
530 $this->mIsBot = $wgUser->isAllowed('bot');
531 }
532 return $this->mIsBot;
533 }
534
535 /**
536 * Similar to isBot(), this method returns true if the logged in user is
537 * a sysop, and false if not.
538 * OBSOLETE, use canApiHighLimits() instead
539 */
540 public function isSysop() {
541 if (!isset ($this->mIsSysop)) {
542 global $wgUser;
543 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
544 }
545
546 return $this->mIsSysop;
547 }
548
549 public function canApiHighLimits() {
550 if (!isset($this->mCanApiHighLimits)) {
551 global $wgUser;
552 $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
553 }
554
555 return $this->mCanApiHighLimits;
556 }
557
558 public function getShowVersions() {
559 return $this->mShowVersions;
560 }
561
562 /**
563 * Returns the version information of this file, plus it includes
564 * the versions for all files that are not callable proper API modules
565 */
566 public function getVersion() {
567 $vers = array ();
568 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
569 $vers[] = __CLASS__ . ': $Id$';
570 $vers[] = ApiBase :: getBaseVersion();
571 $vers[] = ApiFormatBase :: getBaseVersion();
572 $vers[] = ApiQueryBase :: getBaseVersion();
573 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
574 return $vers;
575 }
576
577 /**
578 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
579 * classes who wish to add their own modules to their lexicon or override the
580 * behavior of inherent ones.
581 *
582 * @access protected
583 * @param $mdlName String The identifier for this module.
584 * @param $mdlClass String The class where this module is implemented.
585 */
586 protected function addModule( $mdlName, $mdlClass ) {
587 $this->mModules[$mdlName] = $mdlClass;
588 }
589
590 /**
591 * Add or overwrite an output format for this ApiMain. Intended for use by extending
592 * classes who wish to add to or modify current formatters.
593 *
594 * @access protected
595 * @param $fmtName The identifier for this format.
596 * @param $fmtClass The class implementing this format.
597 */
598 protected function addFormat( $fmtName, $fmtClass ) {
599 $this->mFormats[$fmtName] = $fmtClass;
600 }
601
602 /**
603 * Get the array mapping module names to class names
604 */
605 function getModules() {
606 return $this->mModules;
607 }
608 }
609
610 /**
611 * This exception will be thrown when dieUsage is called to stop module execution.
612 * The exception handling code will print a help screen explaining how this API may be used.
613 *
614 * @addtogroup API
615 */
616 class UsageException extends Exception {
617
618 private $mCodestr;
619
620 public function __construct($message, $codestr, $code = 0) {
621 parent :: __construct($message, $code);
622 $this->mCodestr = $codestr;
623 }
624 public function getCodeString() {
625 return $this->mCodestr;
626 }
627 public function __toString() {
628 return "{$this->getCodeString()}: {$this->getMessage()}";
629 }
630 }