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