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