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