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