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