Merge "Exclude override to make method public from checks"
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 4, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @defgroup API API
26 */
27
28 /**
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
34 *
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
38 *
39 * @ingroup API
40 */
41 class ApiMain extends ApiBase {
42
43 /**
44 * When no format parameter is given, this format will be used
45 */
46 const API_DEFAULT_FORMAT = 'xmlfm';
47
48 /**
49 * List of available modules: action name => module class
50 */
51 private static $Modules = array(
52 'login' => 'ApiLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiCreateAccount',
55 'query' => 'ApiQuery',
56 'expandtemplates' => 'ApiExpandTemplates',
57 'parse' => 'ApiParse',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedwatchlist' => 'ApiFeedWatchlist',
61 'help' => 'ApiHelp',
62 'paraminfo' => 'ApiParamInfo',
63 'rsd' => 'ApiRsd',
64 'compare' => 'ApiComparePages',
65 'tokens' => 'ApiTokens',
66
67 // Write modules
68 'purge' => 'ApiPurge',
69 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
70 'rollback' => 'ApiRollback',
71 'delete' => 'ApiDelete',
72 'undelete' => 'ApiUndelete',
73 'protect' => 'ApiProtect',
74 'block' => 'ApiBlock',
75 'unblock' => 'ApiUnblock',
76 'move' => 'ApiMove',
77 'edit' => 'ApiEditPage',
78 'upload' => 'ApiUpload',
79 'filerevert' => 'ApiFileRevert',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
85 'options' => 'ApiOptions',
86 'imagerotate' => 'ApiImageRotate',
87 );
88
89 /**
90 * List of available formats: format name => format class
91 */
92 private static $Formats = array(
93 'json' => 'ApiFormatJson',
94 'jsonfm' => 'ApiFormatJson',
95 'php' => 'ApiFormatPhp',
96 'phpfm' => 'ApiFormatPhp',
97 'wddx' => 'ApiFormatWddx',
98 'wddxfm' => 'ApiFormatWddx',
99 'xml' => 'ApiFormatXml',
100 'xmlfm' => 'ApiFormatXml',
101 'yaml' => 'ApiFormatYaml',
102 'yamlfm' => 'ApiFormatYaml',
103 'rawfm' => 'ApiFormatJson',
104 'txt' => 'ApiFormatTxt',
105 'txtfm' => 'ApiFormatTxt',
106 'dbg' => 'ApiFormatDbg',
107 'dbgfm' => 'ApiFormatDbg',
108 'dump' => 'ApiFormatDump',
109 'dumpfm' => 'ApiFormatDump',
110 'none' => 'ApiFormatNone',
111 );
112
113 /**
114 * List of user roles that are specifically relevant to the API.
115 * array( 'right' => array ( 'msg' => 'Some message with a $1',
116 * 'params' => array ( $someVarToSubst ) ),
117 * );
118 */
119 private static $mRights = array(
120 'writeapi' => array(
121 'msg' => 'Use of the write API',
122 'params' => array()
123 ),
124 'apihighlimits' => array(
125 '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.',
126 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
127 )
128 );
129
130 /**
131 * @var ApiFormatBase
132 */
133 private $mPrinter;
134
135 private $mModuleMgr, $mResult;
136 private $mAction;
137 private $mEnableWrite;
138 private $mInternalMode, $mSquidMaxage, $mModule;
139
140 private $mCacheMode = 'private';
141 private $mCacheControl = array();
142 private $mParamsUsed = array();
143
144 /**
145 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
146 *
147 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
148 * @param bool $enableWrite should be set to true if the api may modify data
149 */
150 public function __construct( $context = null, $enableWrite = false ) {
151 if ( $context === null ) {
152 $context = RequestContext::getMain();
153 } elseif ( $context instanceof WebRequest ) {
154 // BC for pre-1.19
155 $request = $context;
156 $context = RequestContext::getMain();
157 }
158 // We set a derivative context so we can change stuff later
159 $this->setContext( new DerivativeContext( $context ) );
160
161 if ( isset( $request ) ) {
162 $this->getContext()->setRequest( $request );
163 }
164
165 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
166
167 // Special handling for the main module: $parent === $this
168 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
169
170 if ( !$this->mInternalMode ) {
171 // Impose module restrictions.
172 // If the current user cannot read,
173 // Remove all modules other than login
174 global $wgUser;
175
176 if ( $this->getVal( 'callback' ) !== null ) {
177 // JSON callback allows cross-site reads.
178 // For safety, strip user credentials.
179 wfDebug( "API: stripping user credentials for JSON callback\n" );
180 $wgUser = new User();
181 $this->getContext()->setUser( $wgUser );
182 }
183 }
184
185 global $wgAPIModules;
186 $this->mModuleMgr = new ApiModuleManager( $this );
187 $this->mModuleMgr->addModules( self::$Modules, 'action' );
188 $this->mModuleMgr->addModules( $wgAPIModules, 'action' );
189 $this->mModuleMgr->addModules( self::$Formats, 'format' );
190
191 $this->mResult = new ApiResult( $this );
192 $this->mEnableWrite = $enableWrite;
193
194 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
195 $this->mCommit = false;
196 }
197
198 /**
199 * Return true if the API was started by other PHP code using FauxRequest
200 * @return bool
201 */
202 public function isInternalMode() {
203 return $this->mInternalMode;
204 }
205
206 /**
207 * Get the ApiResult object associated with current request
208 *
209 * @return ApiResult
210 */
211 public function getResult() {
212 return $this->mResult;
213 }
214
215 /**
216 * Get the API module object. Only works after executeAction()
217 *
218 * @return ApiBase
219 */
220 public function getModule() {
221 return $this->mModule;
222 }
223
224 /**
225 * Get the result formatter object. Only works after setupExecuteAction()
226 *
227 * @return ApiFormatBase
228 */
229 public function getPrinter() {
230 return $this->mPrinter;
231 }
232
233 /**
234 * Set how long the response should be cached.
235 *
236 * @param $maxage
237 */
238 public function setCacheMaxAge( $maxage ) {
239 $this->setCacheControl( array(
240 'max-age' => $maxage,
241 's-maxage' => $maxage
242 ) );
243 }
244
245 /**
246 * Set the type of caching headers which will be sent.
247 *
248 * @param string $mode One of:
249 * - 'public': Cache this object in public caches, if the maxage or smaxage
250 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
251 * not provided by any of these means, the object will be private.
252 * - 'private': Cache this object only in private client-side caches.
253 * - 'anon-public-user-private': Make this object cacheable for logged-out
254 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
255 * set consistently for a given URL, it cannot be set differently depending on
256 * things like the contents of the database, or whether the user is logged in.
257 *
258 * If the wiki does not allow anonymous users to read it, the mode set here
259 * will be ignored, and private caching headers will always be sent. In other words,
260 * the "public" mode is equivalent to saying that the data sent is as public as a page
261 * view.
262 *
263 * For user-dependent data, the private mode should generally be used. The
264 * anon-public-user-private mode should only be used where there is a particularly
265 * good performance reason for caching the anonymous response, but where the
266 * response to logged-in users may differ, or may contain private data.
267 *
268 * If this function is never called, then the default will be the private mode.
269 */
270 public function setCacheMode( $mode ) {
271 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
272 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
273
274 // Ignore for forwards-compatibility
275 return;
276 }
277
278 if ( !User::isEveryoneAllowed( 'read' ) ) {
279 // Private wiki, only private headers
280 if ( $mode !== 'private' ) {
281 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
282
283 return;
284 }
285 }
286
287 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
288 $this->mCacheMode = $mode;
289 }
290
291 /**
292 * @deprecated since 1.17 Private caching is now the default, so there is usually no
293 * need to call this function. If there is a need, you can use
294 * $this->setCacheMode('private')
295 */
296 public function setCachePrivate() {
297 wfDeprecated( __METHOD__, '1.17' );
298 $this->setCacheMode( 'private' );
299 }
300
301 /**
302 * Set directives (key/value pairs) for the Cache-Control header.
303 * Boolean values will be formatted as such, by including or omitting
304 * without an equals sign.
305 *
306 * Cache control values set here will only be used if the cache mode is not
307 * private, see setCacheMode().
308 *
309 * @param $directives array
310 */
311 public function setCacheControl( $directives ) {
312 $this->mCacheControl = $directives + $this->mCacheControl;
313 }
314
315 /**
316 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
317 * may be cached for anons but may not be cached for logged-in users.
318 *
319 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
320 * given URL must either always or never call this function; if it sometimes does and
321 * sometimes doesn't, stuff will break.
322 *
323 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
324 */
325 public function setVaryCookie() {
326 wfDeprecated( __METHOD__, '1.17' );
327 $this->setCacheMode( 'anon-public-user-private' );
328 }
329
330 /**
331 * Create an instance of an output formatter by its name
332 *
333 * @param $format string
334 *
335 * @return ApiFormatBase
336 */
337 public function createPrinterByName( $format ) {
338 $printer = $this->mModuleMgr->getModule( $format, 'format' );
339 if ( $printer === null ) {
340 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
341 }
342
343 return $printer;
344 }
345
346 /**
347 * Execute api request. Any errors will be handled if the API was called by the remote client.
348 */
349 public function execute() {
350 $this->profileIn();
351 if ( $this->mInternalMode ) {
352 $this->executeAction();
353 } else {
354 $this->executeActionWithErrorHandling();
355 }
356
357 $this->profileOut();
358 }
359
360 /**
361 * Execute an action, and in case of an error, erase whatever partial results
362 * have been accumulated, and replace it with an error message and a help screen.
363 */
364 protected function executeActionWithErrorHandling() {
365 // Verify the CORS header before executing the action
366 if ( !$this->handleCORS() ) {
367 // handleCORS() has sent a 403, abort
368 return;
369 }
370
371 // Exit here if the request method was OPTIONS
372 // (assume there will be a followup GET or POST)
373 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
374 return;
375 }
376
377 // In case an error occurs during data output,
378 // clear the output buffer and print just the error information
379 ob_start();
380
381 $t = microtime( true );
382 try {
383 $this->executeAction();
384 } catch ( Exception $e ) {
385 // Allow extra cleanup and logging
386 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
387
388 // Log it
389 if ( !( $e instanceof UsageException ) ) {
390 MWExceptionHandler::logException( $e );
391 }
392
393 // Handle any kind of exception by outputting properly formatted error message.
394 // If this fails, an unhandled exception should be thrown so that global error
395 // handler will process and log it.
396
397 $errCode = $this->substituteResultWithError( $e );
398
399 // Error results should not be cached
400 $this->setCacheMode( 'private' );
401
402 $response = $this->getRequest()->response();
403 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
404 if ( $e->getCode() === 0 ) {
405 $response->header( $headerStr );
406 } else {
407 $response->header( $headerStr, true, $e->getCode() );
408 }
409
410 // Reset and print just the error message
411 ob_clean();
412
413 // If the error occurred during printing, do a printer->profileOut()
414 $this->mPrinter->safeProfileOut();
415 $this->printResult( true );
416 }
417
418 // Log the request whether or not there was an error
419 $this->logRequest( microtime( true ) - $t );
420
421 // Send cache headers after any code which might generate an error, to
422 // avoid sending public cache headers for errors.
423 $this->sendCacheHeaders();
424
425 if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
426 echo wfReportTime();
427 }
428
429 ob_end_flush();
430 }
431
432 /**
433 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
434 *
435 * If no origin parameter is present, nothing happens.
436 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
437 * is set and false is returned.
438 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
439 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
440 * headers are set.
441 *
442 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
443 */
444 protected function handleCORS() {
445 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
446
447 $originParam = $this->getParameter( 'origin' ); // defaults to null
448 if ( $originParam === null ) {
449 // No origin parameter, nothing to do
450 return true;
451 }
452
453 $request = $this->getRequest();
454 $response = $request->response();
455 // Origin: header is a space-separated list of origins, check all of them
456 $originHeader = $request->getHeader( 'Origin' );
457 if ( $originHeader === false ) {
458 $origins = array();
459 } else {
460 $origins = explode( ' ', $originHeader );
461 }
462 if ( !in_array( $originParam, $origins ) ) {
463 // origin parameter set but incorrect
464 // Send a 403 response
465 $message = HttpStatus::getMessage( 403 );
466 $response->header( "HTTP/1.1 403 $message", true, 403 );
467 $response->header( 'Cache-Control: no-cache' );
468 echo "'origin' parameter does not match Origin header\n";
469
470 return false;
471 }
472 if ( self::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
473 $response->header( "Access-Control-Allow-Origin: $originParam" );
474 $response->header( 'Access-Control-Allow-Credentials: true' );
475 $this->getOutput()->addVaryHeader( 'Origin' );
476 }
477
478 return true;
479 }
480
481 /**
482 * Attempt to match an Origin header against a set of rules and a set of exceptions
483 * @param string $value Origin header
484 * @param array $rules Set of wildcard rules
485 * @param array $exceptions Set of wildcard rules
486 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
487 */
488 protected static function matchOrigin( $value, $rules, $exceptions ) {
489 foreach ( $rules as $rule ) {
490 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
491 // Rule matches, check exceptions
492 foreach ( $exceptions as $exc ) {
493 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
494 return false;
495 }
496 }
497
498 return true;
499 }
500 }
501
502 return false;
503 }
504
505 /**
506 * Helper function to convert wildcard string into a regex
507 * '*' => '.*?'
508 * '?' => '.'
509 *
510 * @param string $wildcard String with wildcards
511 * @return string Regular expression
512 */
513 protected static function wildcardToRegex( $wildcard ) {
514 $wildcard = preg_quote( $wildcard, '/' );
515 $wildcard = str_replace(
516 array( '\*', '\?' ),
517 array( '.*?', '.' ),
518 $wildcard
519 );
520
521 return "/https?:\/\/$wildcard/";
522 }
523
524 protected function sendCacheHeaders() {
525 global $wgUseXVO, $wgVaryOnXFP;
526 $response = $this->getRequest()->response();
527 $out = $this->getOutput();
528
529 if ( $wgVaryOnXFP ) {
530 $out->addVaryHeader( 'X-Forwarded-Proto' );
531 }
532
533 if ( $this->mCacheMode == 'private' ) {
534 $response->header( 'Cache-Control: private' );
535
536 return;
537 }
538
539 if ( $this->mCacheMode == 'anon-public-user-private' ) {
540 $out->addVaryHeader( 'Cookie' );
541 $response->header( $out->getVaryHeader() );
542 if ( $wgUseXVO ) {
543 $response->header( $out->getXVO() );
544 if ( $out->haveCacheVaryCookies() ) {
545 // Logged in, mark this request private
546 $response->header( 'Cache-Control: private' );
547
548 return;
549 }
550 // Logged out, send normal public headers below
551 } elseif ( session_id() != '' ) {
552 // Logged in or otherwise has session (e.g. anonymous users who have edited)
553 // Mark request private
554 $response->header( 'Cache-Control: private' );
555
556 return;
557 } // else no XVO and anonymous, send public headers below
558 }
559
560 // Send public headers
561 $response->header( $out->getVaryHeader() );
562 if ( $wgUseXVO ) {
563 $response->header( $out->getXVO() );
564 }
565
566 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
567 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
568 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
569 }
570 if ( !isset( $this->mCacheControl['max-age'] ) ) {
571 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
572 }
573
574 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
575 // Public cache not requested
576 // Sending a Vary header in this case is harmless, and protects us
577 // against conditional calls of setCacheMaxAge().
578 $response->header( 'Cache-Control: private' );
579
580 return;
581 }
582
583 $this->mCacheControl['public'] = true;
584
585 // Send an Expires header
586 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
587 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
588 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
589
590 // Construct the Cache-Control header
591 $ccHeader = '';
592 $separator = '';
593 foreach ( $this->mCacheControl as $name => $value ) {
594 if ( is_bool( $value ) ) {
595 if ( $value ) {
596 $ccHeader .= $separator . $name;
597 $separator = ', ';
598 }
599 } else {
600 $ccHeader .= $separator . "$name=$value";
601 $separator = ', ';
602 }
603 }
604
605 $response->header( "Cache-Control: $ccHeader" );
606 }
607
608 /**
609 * Replace the result data with the information about an exception.
610 * Returns the error code
611 * @param $e Exception
612 * @return string
613 */
614 protected function substituteResultWithError( $e ) {
615 global $wgShowHostnames;
616
617 $result = $this->getResult();
618 // Printer may not be initialized if the extractRequestParams() fails for the main module
619 if ( !isset( $this->mPrinter ) ) {
620 // The printer has not been created yet. Try to manually get formatter value.
621 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
622 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
623 $value = self::API_DEFAULT_FORMAT;
624 }
625
626 $this->mPrinter = $this->createPrinterByName( $value );
627 if ( $this->mPrinter->getNeedsRawData() ) {
628 $result->setRawMode();
629 }
630 }
631
632 if ( $e instanceof UsageException ) {
633 // User entered incorrect parameters - print usage screen
634 $errMessage = $e->getMessageArray();
635
636 // Only print the help message when this is for the developer, not runtime
637 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
638 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
639 }
640 } else {
641 global $wgShowSQLErrors, $wgShowExceptionDetails;
642 // Something is seriously wrong
643 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
644 $info = 'Database query error';
645 } else {
646 $info = "Exception Caught: {$e->getMessage()}";
647 }
648
649 $errMessage = array(
650 'code' => 'internal_api_error_' . get_class( $e ),
651 'info' => $info,
652 );
653 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
654 }
655
656 // Remember all the warnings to re-add them later
657 $oldResult = $result->getData();
658 $warnings = isset( $oldResult['warnings'] ) ? $oldResult['warnings'] : null;
659
660 $result->reset();
661 $result->disableSizeCheck();
662 // Re-add the id
663 $requestid = $this->getParameter( 'requestid' );
664 if ( !is_null( $requestid ) ) {
665 $result->addValue( null, 'requestid', $requestid );
666 }
667 if ( $wgShowHostnames ) {
668 // servedby is especially useful when debugging errors
669 $result->addValue( null, 'servedby', wfHostName() );
670 }
671 if ( $warnings !== null ) {
672 $result->addValue( null, 'warnings', $warnings );
673 }
674
675 $result->addValue( null, 'error', $errMessage );
676
677 return $errMessage['code'];
678 }
679
680 /**
681 * Set up for the execution.
682 * @return array
683 */
684 protected function setupExecuteAction() {
685 global $wgShowHostnames;
686
687 // First add the id to the top element
688 $result = $this->getResult();
689 $requestid = $this->getParameter( 'requestid' );
690 if ( !is_null( $requestid ) ) {
691 $result->addValue( null, 'requestid', $requestid );
692 }
693
694 if ( $wgShowHostnames ) {
695 $servedby = $this->getParameter( 'servedby' );
696 if ( $servedby ) {
697 $result->addValue( null, 'servedby', wfHostName() );
698 }
699 }
700
701 $params = $this->extractRequestParams();
702
703 $this->mAction = $params['action'];
704
705 if ( !is_string( $this->mAction ) ) {
706 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
707 }
708
709 return $params;
710 }
711
712 /**
713 * Set up the module for response
714 * @return ApiBase The module that will handle this action
715 */
716 protected function setupModule() {
717 // Instantiate the module requested by the user
718 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
719 if ( $module === null ) {
720 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
721 }
722 $moduleParams = $module->extractRequestParams();
723
724 // Die if token required, but not provided
725 $salt = $module->getTokenSalt();
726 if ( $salt !== false ) {
727 if ( !isset( $moduleParams['token'] ) ) {
728 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
729 } else {
730 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
731 $this->dieUsageMsg( 'sessionfailure' );
732 }
733 }
734 }
735
736 return $module;
737 }
738
739 /**
740 * Check the max lag if necessary
741 * @param $module ApiBase object: Api module being used
742 * @param array $params an array containing the request parameters.
743 * @return boolean True on success, false should exit immediately
744 */
745 protected function checkMaxLag( $module, $params ) {
746 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
747 // Check for maxlag
748 global $wgShowHostnames;
749 $maxLag = $params['maxlag'];
750 list( $host, $lag ) = wfGetLB()->getMaxLag();
751 if ( $lag > $maxLag ) {
752 $response = $this->getRequest()->response();
753
754 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
755 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
756
757 if ( $wgShowHostnames ) {
758 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
759 } else {
760 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
761 }
762
763 return false;
764 }
765 }
766
767 return true;
768 }
769
770 /**
771 * Check for sufficient permissions to execute
772 * @param $module ApiBase An Api module
773 */
774 protected function checkExecutePermissions( $module ) {
775 $user = $this->getUser();
776 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
777 !$user->isAllowed( 'read' )
778 ) {
779 $this->dieUsageMsg( 'readrequired' );
780 }
781 if ( $module->isWriteMode() ) {
782 if ( !$this->mEnableWrite ) {
783 $this->dieUsageMsg( 'writedisabled' );
784 }
785 if ( !$user->isAllowed( 'writeapi' ) ) {
786 $this->dieUsageMsg( 'writerequired' );
787 }
788 if ( wfReadOnly() ) {
789 $this->dieReadOnly();
790 }
791 }
792
793 // Allow extensions to stop execution for arbitrary reasons.
794 $message = false;
795 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
796 $this->dieUsageMsg( $message );
797 }
798 }
799
800 /**
801 * Check POST for external response and setup result printer
802 * @param $module ApiBase An Api module
803 * @param array $params an array with the request parameters
804 */
805 protected function setupExternalResponse( $module, $params ) {
806 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
807 // Module requires POST. GET request might still be allowed
808 // if $wgDebugApi is true, otherwise fail.
809 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
810 }
811
812 // See if custom printer is used
813 $this->mPrinter = $module->getCustomPrinter();
814 if ( is_null( $this->mPrinter ) ) {
815 // Create an appropriate printer
816 $this->mPrinter = $this->createPrinterByName( $params['format'] );
817 }
818
819 if ( $this->mPrinter->getNeedsRawData() ) {
820 $this->getResult()->setRawMode();
821 }
822 }
823
824 /**
825 * Execute the actual module, without any error handling
826 */
827 protected function executeAction() {
828 $params = $this->setupExecuteAction();
829 $module = $this->setupModule();
830 $this->mModule = $module;
831
832 $this->checkExecutePermissions( $module );
833
834 if ( !$this->checkMaxLag( $module, $params ) ) {
835 return;
836 }
837
838 if ( !$this->mInternalMode ) {
839 $this->setupExternalResponse( $module, $params );
840 }
841
842 // Execute
843 $module->profileIn();
844 $module->execute();
845 wfRunHooks( 'APIAfterExecute', array( &$module ) );
846 $module->profileOut();
847
848 $this->reportUnusedParams();
849
850 if ( !$this->mInternalMode ) {
851 //append Debug information
852 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
853
854 // Print result data
855 $this->printResult( false );
856 }
857 }
858
859 /**
860 * Log the preceding request
861 * @param $time Time in seconds
862 */
863 protected function logRequest( $time ) {
864 $request = $this->getRequest();
865 $milliseconds = $time === null ? '?' : round( $time * 1000 );
866 $s = 'API' .
867 ' ' . $request->getMethod() .
868 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
869 ' ' . $request->getIP() .
870 ' T=' . $milliseconds . 'ms';
871 foreach ( $this->getParamsUsed() as $name ) {
872 $value = $request->getVal( $name );
873 if ( $value === null ) {
874 continue;
875 }
876 $s .= ' ' . $name . '=';
877 if ( strlen( $value ) > 256 ) {
878 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
879 $s .= $encValue . '[...]';
880 } else {
881 $s .= $this->encodeRequestLogValue( $value );
882 }
883 }
884 $s .= "\n";
885 wfDebugLog( 'api', $s, false );
886 }
887
888 /**
889 * Encode a value in a format suitable for a space-separated log line.
890 */
891 protected function encodeRequestLogValue( $s ) {
892 static $table;
893 if ( !$table ) {
894 $chars = ';@$!*(),/:';
895 for ( $i = 0; $i < strlen( $chars ); $i++ ) {
896 $table[rawurlencode( $chars[$i] )] = $chars[$i];
897 }
898 }
899
900 return strtr( rawurlencode( $s ), $table );
901 }
902
903 /**
904 * Get the request parameters used in the course of the preceding execute() request
905 */
906 protected function getParamsUsed() {
907 return array_keys( $this->mParamsUsed );
908 }
909
910 /**
911 * Get a request value, and register the fact that it was used, for logging.
912 */
913 public function getVal( $name, $default = null ) {
914 $this->mParamsUsed[$name] = true;
915
916 return $this->getRequest()->getVal( $name, $default );
917 }
918
919 /**
920 * Get a boolean request value, and register the fact that the parameter
921 * was used, for logging.
922 */
923 public function getCheck( $name ) {
924 $this->mParamsUsed[$name] = true;
925
926 return $this->getRequest()->getCheck( $name );
927 }
928
929 /**
930 * Get a request upload, and register the fact that it was used, for logging.
931 *
932 * @since 1.21
933 * @param string $name Parameter name
934 * @return WebRequestUpload
935 */
936 public function getUpload( $name ) {
937 $this->mParamsUsed[$name] = true;
938
939 return $this->getRequest()->getUpload( $name );
940 }
941
942 /**
943 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
944 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
945 */
946 protected function reportUnusedParams() {
947 $paramsUsed = $this->getParamsUsed();
948 $allParams = $this->getRequest()->getValueNames();
949
950 if ( !$this->mInternalMode ) {
951 // Printer has not yet executed; don't warn that its parameters are unused
952 $printerParams = array_map(
953 array( $this->mPrinter, 'encodeParamName' ),
954 array_keys( $this->mPrinter->getFinalParams() ?: array() )
955 );
956 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
957 } else {
958 $unusedParams = array_diff( $allParams, $paramsUsed );
959 }
960
961 if ( count( $unusedParams ) ) {
962 $s = count( $unusedParams ) > 1 ? 's' : '';
963 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
964 }
965 }
966
967 /**
968 * Print results using the current printer
969 *
970 * @param $isError bool
971 */
972 protected function printResult( $isError ) {
973 global $wgDebugAPI;
974 if ( $wgDebugAPI !== false ) {
975 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
976 }
977
978 $this->getResult()->cleanUpUTF8();
979 $printer = $this->mPrinter;
980 $printer->profileIn();
981
982 /**
983 * If the help message is requested in the default (xmlfm) format,
984 * tell the printer not to escape ampersands so that our links do
985 * not break.
986 */
987 $isHelp = $isError || $this->mAction == 'help';
988 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
989
990 $printer->initPrinter( $isHelp );
991
992 $printer->execute();
993 $printer->closePrinter();
994 $printer->profileOut();
995 }
996
997 /**
998 * @return bool
999 */
1000 public function isReadMode() {
1001 return false;
1002 }
1003
1004 /**
1005 * See ApiBase for description.
1006 *
1007 * @return array
1008 */
1009 public function getAllowedParams() {
1010 return array(
1011 'format' => array(
1012 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1013 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'format' )
1014 ),
1015 'action' => array(
1016 ApiBase::PARAM_DFLT => 'help',
1017 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'action' )
1018 ),
1019 'maxlag' => array(
1020 ApiBase::PARAM_TYPE => 'integer'
1021 ),
1022 'smaxage' => array(
1023 ApiBase::PARAM_TYPE => 'integer',
1024 ApiBase::PARAM_DFLT => 0
1025 ),
1026 'maxage' => array(
1027 ApiBase::PARAM_TYPE => 'integer',
1028 ApiBase::PARAM_DFLT => 0
1029 ),
1030 'requestid' => null,
1031 'servedby' => false,
1032 'origin' => null,
1033 );
1034 }
1035
1036 /**
1037 * See ApiBase for description.
1038 *
1039 * @return array
1040 */
1041 public function getParamDescription() {
1042 return array(
1043 'format' => 'The format of the output',
1044 'action' => 'What action you would like to perform. See below for module help',
1045 'maxlag' => array(
1046 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1047 'To save actions causing any more site replication lag, this parameter can make the client',
1048 'wait until the replication lag is less than the specified value.',
1049 'In case of a replag error, error code "maxlag" is returned, with the message like',
1050 '"Waiting for $host: $lag seconds lagged\n".',
1051 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1052 ),
1053 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1054 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1055 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1056 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1057 'origin' => array(
1058 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1059 'This must be included in any pre-flight request, and therefore must be part of the request URI (not the POST body).',
1060 'This must match one of the origins in the Origin: header exactly, so it has to be set to something like http://en.wikipedia.org or https://meta.wikimedia.org .',
1061 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1062 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1063 ),
1064 );
1065 }
1066
1067 /**
1068 * See ApiBase for description.
1069 *
1070 * @return array
1071 */
1072 public function getDescription() {
1073 return array(
1074 '',
1075 '',
1076 '**********************************************************************************************************',
1077 '** **',
1078 '** This is an auto-generated MediaWiki API documentation page **',
1079 '** **',
1080 '** Documentation and Examples: **',
1081 '** https://www.mediawiki.org/wiki/API **',
1082 '** **',
1083 '**********************************************************************************************************',
1084 '',
1085 'Status: All features shown on this page should be working, but the API',
1086 ' is still in active development, and may change at any time.',
1087 ' Make sure to monitor our mailing list for any updates',
1088 '',
1089 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1090 ' with the key "MediaWiki-API-Error" and then both the value of the',
1091 ' header and the error code sent back will be set to the same value',
1092 '',
1093 ' In the case of an invalid action being passed, these will have a value',
1094 ' of "unknown_action"',
1095 '',
1096 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1097 '',
1098 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1099 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1100 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1101 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1102 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1103 '',
1104 '',
1105 '',
1106 '',
1107 '',
1108 );
1109 }
1110
1111 /**
1112 * @return array
1113 */
1114 public function getPossibleErrors() {
1115 return array_merge( parent::getPossibleErrors(), array(
1116 array( 'readonlytext' ),
1117 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1118 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1119 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1120 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1121 ) );
1122 }
1123
1124 /**
1125 * Returns an array of strings with credits for the API
1126 * @return array
1127 */
1128 protected function getCredits() {
1129 return array(
1130 'API developers:',
1131 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-2009)',
1132 ' Victor Vasiliev - vasilvv @ gmail . com',
1133 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1134 ' Sam Reed - sam @ reedyboy . net',
1135 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1136 '',
1137 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1138 'or file a bug report at https://bugzilla.wikimedia.org/'
1139 );
1140 }
1141
1142 /**
1143 * Sets whether the pretty-printer should format *bold* and $italics$
1144 *
1145 * @param $help bool
1146 */
1147 public function setHelp( $help = true ) {
1148 $this->mPrinter->setHelp( $help );
1149 }
1150
1151 /**
1152 * Override the parent to generate help messages for all available modules.
1153 *
1154 * @return string
1155 */
1156 public function makeHelpMsg() {
1157 global $wgMemc, $wgAPICacheHelpTimeout;
1158 $this->setHelp();
1159 // Get help text from cache if present
1160 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1161 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1162 if ( $wgAPICacheHelpTimeout > 0 ) {
1163 $cached = $wgMemc->get( $key );
1164 if ( $cached ) {
1165 return $cached;
1166 }
1167 }
1168 $retval = $this->reallyMakeHelpMsg();
1169 if ( $wgAPICacheHelpTimeout > 0 ) {
1170 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1171 }
1172
1173 return $retval;
1174 }
1175
1176 /**
1177 * @return mixed|string
1178 */
1179 public function reallyMakeHelpMsg() {
1180 $this->setHelp();
1181
1182 // Use parent to make default message for the main module
1183 $msg = parent::makeHelpMsg();
1184
1185 $astriks = str_repeat( '*** ', 14 );
1186 $msg .= "\n\n$astriks Modules $astriks\n\n";
1187
1188 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1189 $module = $this->mModuleMgr->getModule( $name );
1190 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1191
1192 $msg2 = $module->makeHelpMsg();
1193 if ( $msg2 !== false ) {
1194 $msg .= $msg2;
1195 }
1196 $msg .= "\n";
1197 }
1198
1199 $msg .= "\n$astriks Permissions $astriks\n\n";
1200 foreach ( self::$mRights as $right => $rightMsg ) {
1201 $groups = User::getGroupsWithPermission( $right );
1202 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1203 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1204 }
1205
1206 $msg .= "\n$astriks Formats $astriks\n\n";
1207 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1208 $module = $this->mModuleMgr->getModule( $name );
1209 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1210 $msg2 = $module->makeHelpMsg();
1211 if ( $msg2 !== false ) {
1212 $msg .= $msg2;
1213 }
1214 $msg .= "\n";
1215 }
1216
1217 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1218
1219 return $msg;
1220 }
1221
1222 /**
1223 * @param $module ApiBase
1224 * @param string $paramName What type of request is this? e.g. action, query, list, prop, meta, format
1225 * @return string
1226 */
1227 public static function makeHelpMsgHeader( $module, $paramName ) {
1228 $modulePrefix = $module->getModulePrefix();
1229 if ( strval( $modulePrefix ) !== '' ) {
1230 $modulePrefix = "($modulePrefix) ";
1231 }
1232
1233 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1234 }
1235
1236 private $mCanApiHighLimits = null;
1237
1238 /**
1239 * Check whether the current user is allowed to use high limits
1240 * @return bool
1241 */
1242 public function canApiHighLimits() {
1243 if ( !isset( $this->mCanApiHighLimits ) ) {
1244 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1245 }
1246
1247 return $this->mCanApiHighLimits;
1248 }
1249
1250 /**
1251 * Check whether the user wants us to show version information in the API help
1252 * @return bool
1253 * @deprecated since 1.21, always returns false
1254 */
1255 public function getShowVersions() {
1256 wfDeprecated( __METHOD__, '1.21' );
1257
1258 return false;
1259 }
1260
1261 /**
1262 * Overrides to return this instance's module manager.
1263 * @return ApiModuleManager
1264 */
1265 public function getModuleManager() {
1266 return $this->mModuleMgr;
1267 }
1268
1269 /**
1270 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1271 * classes who wish to add their own modules to their lexicon or override the
1272 * behavior of inherent ones.
1273 *
1274 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1275 * @param string $name The identifier for this module.
1276 * @param $class ApiBase The class where this module is implemented.
1277 */
1278 protected function addModule( $name, $class ) {
1279 $this->getModuleManager()->addModule( $name, 'action', $class );
1280 }
1281
1282 /**
1283 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1284 * classes who wish to add to or modify current formatters.
1285 *
1286 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1287 * @param string $name The identifier for this format.
1288 * @param $class ApiFormatBase The class implementing this format.
1289 */
1290 protected function addFormat( $name, $class ) {
1291 $this->getModuleManager()->addModule( $name, 'format', $class );
1292 }
1293
1294 /**
1295 * Get the array mapping module names to class names
1296 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1297 * @return array
1298 */
1299 function getModules() {
1300 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1301 }
1302
1303 /**
1304 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1305 *
1306 * @since 1.18
1307 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1308 * @return array
1309 */
1310 public function getFormats() {
1311 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1312 }
1313 }
1314
1315 /**
1316 * This exception will be thrown when dieUsage is called to stop module execution.
1317 * The exception handling code will print a help screen explaining how this API may be used.
1318 *
1319 * @ingroup API
1320 */
1321 class UsageException extends MWException {
1322
1323 private $mCodestr;
1324
1325 /**
1326 * @var null|array
1327 */
1328 private $mExtraData;
1329
1330 /**
1331 * @param $message string
1332 * @param $codestr string
1333 * @param $code int
1334 * @param $extradata array|null
1335 */
1336 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1337 parent::__construct( $message, $code );
1338 $this->mCodestr = $codestr;
1339 $this->mExtraData = $extradata;
1340 }
1341
1342 /**
1343 * @return string
1344 */
1345 public function getCodeString() {
1346 return $this->mCodestr;
1347 }
1348
1349 /**
1350 * @return array
1351 */
1352 public function getMessageArray() {
1353 $result = array(
1354 'code' => $this->mCodestr,
1355 'info' => $this->getMessage()
1356 );
1357 if ( is_array( $this->mExtraData ) ) {
1358 $result = array_merge( $result, $this->mExtraData );
1359 }
1360
1361 return $result;
1362 }
1363
1364 /**
1365 * @return string
1366 */
1367 public function __toString() {
1368 return "{$this->getCodeString()}: {$this->getMessage()}";
1369 }
1370 }