Merge "Avoid doNotifyQueueEmpty() race conditions for Redis"
[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 * When no format parameter is given, this format will be used
44 */
45 const API_DEFAULT_FORMAT = 'jsonfm';
46
47 /**
48 * List of available modules: action name => module class
49 */
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
62 'help' => 'ApiHelp',
63 'paraminfo' => 'ApiParamInfo',
64 'rsd' => 'ApiRsd',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
67 'checktoken' => 'ApiCheckToken',
68
69 // Write modules
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
78 'move' => 'ApiMove',
79 'edit' => 'ApiEditPage',
80 'upload' => 'ApiUpload',
81 'filerevert' => 'ApiFileRevert',
82 'emailuser' => 'ApiEmailUser',
83 'watch' => 'ApiWatch',
84 'patrol' => 'ApiPatrol',
85 'import' => 'ApiImport',
86 'clearhasmsg' => 'ApiClearHasMsg',
87 'userrights' => 'ApiUserrights',
88 'options' => 'ApiOptions',
89 'imagerotate' => 'ApiImageRotate',
90 'revisiondelete' => 'ApiRevisionDelete',
91 'managetags' => 'ApiManageTags',
92 'tag' => 'ApiTag',
93 );
94
95 /**
96 * List of available formats: format name => format class
97 */
98 private static $Formats = array(
99 'json' => 'ApiFormatJson',
100 'jsonfm' => 'ApiFormatJson',
101 'php' => 'ApiFormatPhp',
102 'phpfm' => 'ApiFormatPhp',
103 'xml' => 'ApiFormatXml',
104 'xmlfm' => 'ApiFormatXml',
105 'yaml' => 'ApiFormatYaml',
106 'yamlfm' => 'ApiFormatYaml',
107 'rawfm' => 'ApiFormatJson',
108 'txt' => 'ApiFormatTxt',
109 'txtfm' => 'ApiFormatTxt',
110 'dbg' => 'ApiFormatDbg',
111 'dbgfm' => 'ApiFormatDbg',
112 'none' => 'ApiFormatNone',
113 );
114
115 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
116 /**
117 * List of user roles that are specifically relevant to the API.
118 * array( 'right' => array ( 'msg' => 'Some message with a $1',
119 * 'params' => array ( $someVarToSubst ) ),
120 * );
121 */
122 private static $mRights = array(
123 'writeapi' => array(
124 'msg' => 'right-writeapi',
125 'params' => array()
126 ),
127 'apihighlimits' => array(
128 'msg' => 'api-help-right-apihighlimits',
129 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
130 )
131 );
132 // @codingStandardsIgnoreEnd
133
134 /**
135 * @var ApiFormatBase
136 */
137 private $mPrinter;
138
139 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
140 private $mAction;
141 private $mEnableWrite;
142 private $mInternalMode, $mSquidMaxage, $mModule;
143
144 private $mCacheMode = 'private';
145 private $mCacheControl = array();
146 private $mParamsUsed = array();
147
148 /**
149 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
150 *
151 * @param IContextSource|WebRequest $context If this is an instance of
152 * FauxRequest, errors are thrown and no printing occurs
153 * @param bool $enableWrite Should be set to true if the api may modify data
154 */
155 public function __construct( $context = null, $enableWrite = false ) {
156 if ( $context === null ) {
157 $context = RequestContext::getMain();
158 } elseif ( $context instanceof WebRequest ) {
159 // BC for pre-1.19
160 $request = $context;
161 $context = RequestContext::getMain();
162 }
163 // We set a derivative context so we can change stuff later
164 $this->setContext( new DerivativeContext( $context ) );
165
166 if ( isset( $request ) ) {
167 $this->getContext()->setRequest( $request );
168 }
169
170 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
171
172 // Special handling for the main module: $parent === $this
173 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
174
175 if ( !$this->mInternalMode ) {
176 // Impose module restrictions.
177 // If the current user cannot read,
178 // Remove all modules other than login
179 global $wgUser;
180
181 if ( $this->lacksSameOriginSecurity() ) {
182 // If we're in a mode that breaks the same-origin policy, strip
183 // user credentials for security.
184 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
185 $wgUser = new User();
186 $this->getContext()->setUser( $wgUser );
187 }
188 }
189
190 $uselang = $this->getParameter( 'uselang' );
191 if ( $uselang === 'user' ) {
192 // Assume the parent context is going to return the user language
193 // for uselang=user (see T85635).
194 } else {
195 if ( $uselang === 'content' ) {
196 global $wgContLang;
197 $uselang = $wgContLang->getCode();
198 }
199 $code = RequestContext::sanitizeLangCode( $uselang );
200 $this->getContext()->setLanguage( $code );
201 if ( !$this->mInternalMode ) {
202 global $wgLang;
203 $wgLang = $this->getContext()->getLanguage();
204 RequestContext::getMain()->setLanguage( $wgLang );
205 }
206 }
207
208 $config = $this->getConfig();
209 $this->mModuleMgr = new ApiModuleManager( $this );
210 $this->mModuleMgr->addModules( self::$Modules, 'action' );
211 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
212 $this->mModuleMgr->addModules( self::$Formats, 'format' );
213 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
214
215 Hooks::run( 'ApiMain::moduleManager', array( $this->mModuleMgr ) );
216
217 $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
218 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
219 $this->mResult->setErrorFormatter( $this->mErrorFormatter );
220 $this->mResult->setMainForContinuation( $this );
221 $this->mContinuationManager = null;
222 $this->mEnableWrite = $enableWrite;
223
224 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
225 $this->mCommit = false;
226 }
227
228 /**
229 * Return true if the API was started by other PHP code using FauxRequest
230 * @return bool
231 */
232 public function isInternalMode() {
233 return $this->mInternalMode;
234 }
235
236 /**
237 * Get the ApiResult object associated with current request
238 *
239 * @return ApiResult
240 */
241 public function getResult() {
242 return $this->mResult;
243 }
244
245 /**
246 * Get the ApiErrorFormatter object associated with current request
247 * @return ApiErrorFormatter
248 */
249 public function getErrorFormatter() {
250 return $this->mErrorFormatter;
251 }
252
253 /**
254 * Get the continuation manager
255 * @return ApiContinuationManager|null
256 */
257 public function getContinuationManager() {
258 return $this->mContinuationManager;
259 }
260
261 /**
262 * Set the continuation manager
263 * @param ApiContinuationManager|null
264 */
265 public function setContinuationManager( $manager ) {
266 if ( $manager !== null ) {
267 if ( !$manager instanceof ApiContinuationManager ) {
268 throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
269 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
270 );
271 }
272 if ( $this->mContinuationManager !== null ) {
273 throw new UnexpectedValueException(
274 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
275 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
276 );
277 }
278 }
279 $this->mContinuationManager = $manager;
280 }
281
282 /**
283 * Get the API module object. Only works after executeAction()
284 *
285 * @return ApiBase
286 */
287 public function getModule() {
288 return $this->mModule;
289 }
290
291 /**
292 * Get the result formatter object. Only works after setupExecuteAction()
293 *
294 * @return ApiFormatBase
295 */
296 public function getPrinter() {
297 return $this->mPrinter;
298 }
299
300 /**
301 * Set how long the response should be cached.
302 *
303 * @param int $maxage
304 */
305 public function setCacheMaxAge( $maxage ) {
306 $this->setCacheControl( array(
307 'max-age' => $maxage,
308 's-maxage' => $maxage
309 ) );
310 }
311
312 /**
313 * Set the type of caching headers which will be sent.
314 *
315 * @param string $mode One of:
316 * - 'public': Cache this object in public caches, if the maxage or smaxage
317 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
318 * not provided by any of these means, the object will be private.
319 * - 'private': Cache this object only in private client-side caches.
320 * - 'anon-public-user-private': Make this object cacheable for logged-out
321 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
322 * set consistently for a given URL, it cannot be set differently depending on
323 * things like the contents of the database, or whether the user is logged in.
324 *
325 * If the wiki does not allow anonymous users to read it, the mode set here
326 * will be ignored, and private caching headers will always be sent. In other words,
327 * the "public" mode is equivalent to saying that the data sent is as public as a page
328 * view.
329 *
330 * For user-dependent data, the private mode should generally be used. The
331 * anon-public-user-private mode should only be used where there is a particularly
332 * good performance reason for caching the anonymous response, but where the
333 * response to logged-in users may differ, or may contain private data.
334 *
335 * If this function is never called, then the default will be the private mode.
336 */
337 public function setCacheMode( $mode ) {
338 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
339 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
340
341 // Ignore for forwards-compatibility
342 return;
343 }
344
345 if ( !User::isEveryoneAllowed( 'read' ) ) {
346 // Private wiki, only private headers
347 if ( $mode !== 'private' ) {
348 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
349
350 return;
351 }
352 }
353
354 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
355 // User language is used for i18n, so we don't want to publicly
356 // cache. Anons are ok, because if they have non-default language
357 // then there's an appropriate Vary header set by whatever set
358 // their non-default language.
359 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
360 "'anon-public-user-private' due to uselang=user\n" );
361 $mode = 'anon-public-user-private';
362 }
363
364 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
365 $this->mCacheMode = $mode;
366 }
367
368 /**
369 * Set directives (key/value pairs) for the Cache-Control header.
370 * Boolean values will be formatted as such, by including or omitting
371 * without an equals sign.
372 *
373 * Cache control values set here will only be used if the cache mode is not
374 * private, see setCacheMode().
375 *
376 * @param array $directives
377 */
378 public function setCacheControl( $directives ) {
379 $this->mCacheControl = $directives + $this->mCacheControl;
380 }
381
382 /**
383 * Create an instance of an output formatter by its name
384 *
385 * @param string $format
386 *
387 * @return ApiFormatBase
388 */
389 public function createPrinterByName( $format ) {
390 $printer = $this->mModuleMgr->getModule( $format, 'format' );
391 if ( $printer === null ) {
392 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
393 }
394
395 return $printer;
396 }
397
398 /**
399 * Execute api request. Any errors will be handled if the API was called by the remote client.
400 */
401 public function execute() {
402 if ( $this->mInternalMode ) {
403 $this->executeAction();
404 } else {
405 $this->executeActionWithErrorHandling();
406 }
407 }
408
409 /**
410 * Execute an action, and in case of an error, erase whatever partial results
411 * have been accumulated, and replace it with an error message and a help screen.
412 */
413 protected function executeActionWithErrorHandling() {
414 // Verify the CORS header before executing the action
415 if ( !$this->handleCORS() ) {
416 // handleCORS() has sent a 403, abort
417 return;
418 }
419
420 // Exit here if the request method was OPTIONS
421 // (assume there will be a followup GET or POST)
422 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
423 return;
424 }
425
426 // In case an error occurs during data output,
427 // clear the output buffer and print just the error information
428 $obLevel = ob_get_level();
429 ob_start();
430
431 $t = microtime( true );
432 try {
433 $this->executeAction();
434 $isError = false;
435 } catch ( Exception $e ) {
436 $this->handleException( $e );
437 $isError = true;
438 }
439
440 // Log the request whether or not there was an error
441 $this->logRequest( microtime( true ) - $t );
442
443 // Send cache headers after any code which might generate an error, to
444 // avoid sending public cache headers for errors.
445 $this->sendCacheHeaders( $isError );
446
447 // Executing the action might have already messed with the output
448 // buffers.
449 while ( ob_get_level() > $obLevel ) {
450 ob_end_flush();
451 }
452 }
453
454 /**
455 * Handle an exception as an API response
456 *
457 * @since 1.23
458 * @param Exception $e
459 */
460 protected function handleException( Exception $e ) {
461 // Bug 63145: Rollback any open database transactions
462 if ( !( $e instanceof UsageException ) ) {
463 // UsageExceptions are intentional, so don't rollback if that's the case
464 try {
465 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
466 } catch ( DBError $e2 ) {
467 // Rollback threw an exception too. Log it, but don't interrupt
468 // our regularly scheduled exception handling.
469 MWExceptionHandler::logException( $e2 );
470 }
471 }
472
473 // Allow extra cleanup and logging
474 Hooks::run( 'ApiMain::onException', array( $this, $e ) );
475
476 // Log it
477 if ( !( $e instanceof UsageException ) ) {
478 MWExceptionHandler::logException( $e );
479 }
480
481 // Handle any kind of exception by outputting properly formatted error message.
482 // If this fails, an unhandled exception should be thrown so that global error
483 // handler will process and log it.
484
485 $errCode = $this->substituteResultWithError( $e );
486
487 // Error results should not be cached
488 $this->setCacheMode( 'private' );
489
490 $response = $this->getRequest()->response();
491 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
492 if ( $e->getCode() === 0 ) {
493 $response->header( $headerStr );
494 } else {
495 $response->header( $headerStr, true, $e->getCode() );
496 }
497
498 // Reset and print just the error message
499 ob_clean();
500
501 // Printer may not be initialized if the extractRequestParams() fails for the main module
502 $this->createErrorPrinter();
503
504 try {
505 $this->printResult( true );
506 } catch ( UsageException $ex ) {
507 // The error printer itself is failing. Try suppressing its request
508 // parameters and redo.
509 $this->setWarning(
510 'Error printer failed (will retry without params): ' . $ex->getMessage()
511 );
512 $this->mPrinter = null;
513 $this->createErrorPrinter();
514 $this->mPrinter->forceDefaultParams();
515 $this->printResult( true );
516 }
517 }
518
519 /**
520 * Handle an exception from the ApiBeforeMain hook.
521 *
522 * This tries to print the exception as an API response, to be more
523 * friendly to clients. If it fails, it will rethrow the exception.
524 *
525 * @since 1.23
526 * @param Exception $e
527 * @throws Exception
528 */
529 public static function handleApiBeforeMainException( Exception $e ) {
530 ob_start();
531
532 try {
533 $main = new self( RequestContext::getMain(), false );
534 $main->handleException( $e );
535 } catch ( Exception $e2 ) {
536 // Nope, even that didn't work. Punt.
537 throw $e;
538 }
539
540 // Log the request and reset cache headers
541 $main->logRequest( 0 );
542 $main->sendCacheHeaders( true );
543
544 ob_end_flush();
545 }
546
547 /**
548 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
549 *
550 * If no origin parameter is present, nothing happens.
551 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
552 * is set and false is returned.
553 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
554 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
555 * headers are set.
556 * http://www.w3.org/TR/cors/#resource-requests
557 * http://www.w3.org/TR/cors/#resource-preflight-requests
558 *
559 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
560 */
561 protected function handleCORS() {
562 $originParam = $this->getParameter( 'origin' ); // defaults to null
563 if ( $originParam === null ) {
564 // No origin parameter, nothing to do
565 return true;
566 }
567
568 $request = $this->getRequest();
569 $response = $request->response();
570
571 // Origin: header is a space-separated list of origins, check all of them
572 $originHeader = $request->getHeader( 'Origin' );
573 if ( $originHeader === false ) {
574 $origins = array();
575 } else {
576 $originHeader = trim( $originHeader );
577 $origins = preg_split( '/\s+/', $originHeader );
578 }
579
580 if ( !in_array( $originParam, $origins ) ) {
581 // origin parameter set but incorrect
582 // Send a 403 response
583 $response->statusHeader( 403 );
584 $response->header( 'Cache-Control: no-cache' );
585 echo "'origin' parameter does not match Origin header\n";
586
587 return false;
588 }
589
590 $config = $this->getConfig();
591 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
592 $originParam,
593 $config->get( 'CrossSiteAJAXdomains' ),
594 $config->get( 'CrossSiteAJAXdomainExceptions' )
595 );
596
597 if ( $matchOrigin ) {
598 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
599 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
600 if ( $preflight ) {
601 // This is a CORS preflight request
602 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
603 // If method is not a case-sensitive match, do not set any additional headers and terminate.
604 return true;
605 }
606 // We allow the actual request to send the following headers
607 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
608 if ( $requestedHeaders !== false ) {
609 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
610 return true;
611 }
612 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
613 }
614
615 // We only allow the actual request to be GET or POST
616 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
617 }
618
619 $response->header( "Access-Control-Allow-Origin: $originHeader" );
620 $response->header( 'Access-Control-Allow-Credentials: true' );
621 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
622 $response->header( "Timing-Allow-Origin: $originHeader" );
623
624 if ( !$preflight ) {
625 $response->header(
626 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
627 );
628 }
629 }
630
631 $this->getOutput()->addVaryHeader( 'Origin' );
632 return true;
633 }
634
635 /**
636 * Attempt to match an Origin header against a set of rules and a set of exceptions
637 * @param string $value Origin header
638 * @param array $rules Set of wildcard rules
639 * @param array $exceptions Set of wildcard rules
640 * @return bool True if $value matches a rule in $rules and doesn't match
641 * any rules in $exceptions, false otherwise
642 */
643 protected static function matchOrigin( $value, $rules, $exceptions ) {
644 foreach ( $rules as $rule ) {
645 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
646 // Rule matches, check exceptions
647 foreach ( $exceptions as $exc ) {
648 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
649 return false;
650 }
651 }
652
653 return true;
654 }
655 }
656
657 return false;
658 }
659
660 /**
661 * Attempt to validate the value of Access-Control-Request-Headers against a list
662 * of headers that we allow the follow up request to send.
663 *
664 * @param string $requestedHeaders Comma seperated list of HTTP headers
665 * @return bool True if all requested headers are in the list of allowed headers
666 */
667 protected static function matchRequestedHeaders( $requestedHeaders ) {
668 if ( trim( $requestedHeaders ) === '' ) {
669 return true;
670 }
671 $requestedHeaders = explode( ',', $requestedHeaders );
672 $allowedAuthorHeaders = array_flip( array(
673 /* simple headers (see spec) */
674 'accept',
675 'accept-language',
676 'content-language',
677 'content-type',
678 /* non-authorable headers in XHR, which are however requested by some UAs */
679 'accept-encoding',
680 'dnt',
681 'origin',
682 /* MediaWiki whitelist */
683 'api-user-agent',
684 ) );
685 foreach ( $requestedHeaders as $rHeader ) {
686 $rHeader = strtolower( trim( $rHeader ) );
687 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
688 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
689 return false;
690 }
691 }
692 return true;
693 }
694
695 /**
696 * Helper function to convert wildcard string into a regex
697 * '*' => '.*?'
698 * '?' => '.'
699 *
700 * @param string $wildcard String with wildcards
701 * @return string Regular expression
702 */
703 protected static function wildcardToRegex( $wildcard ) {
704 $wildcard = preg_quote( $wildcard, '/' );
705 $wildcard = str_replace(
706 array( '\*', '\?' ),
707 array( '.*?', '.' ),
708 $wildcard
709 );
710
711 return "/^https?:\/\/$wildcard$/";
712 }
713
714 /**
715 * Send caching headers
716 * @param boolean $isError Whether an error response is being output
717 * @since 1.26 added $isError parameter
718 */
719 protected function sendCacheHeaders( $isError ) {
720 $response = $this->getRequest()->response();
721 $out = $this->getOutput();
722
723 $config = $this->getConfig();
724
725 if ( $config->get( 'VaryOnXFP' ) ) {
726 $out->addVaryHeader( 'X-Forwarded-Proto' );
727 }
728
729 if ( !$isError && $this->mModule &&
730 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
731 ) {
732 $etag = $this->mModule->getConditionalRequestData( 'etag' );
733 if ( $etag !== null ) {
734 $response->header( "ETag: $etag" );
735 }
736 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
737 if ( $lastMod !== null ) {
738 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
739 }
740 }
741
742 // The logic should be:
743 // $this->mCacheControl['max-age'] is set?
744 // Use it, the module knows better than our guess.
745 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
746 // Use 0 because we can guess caching is probably the wrong thing to do.
747 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
748 $maxage = 0;
749 if ( isset( $this->mCacheControl['max-age'] ) ) {
750 $maxage = $this->mCacheControl['max-age'];
751 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
752 $this->mCacheMode !== 'private'
753 ) {
754 $maxage = $this->getParameter( 'maxage' );
755 }
756 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
757
758 if ( $this->mCacheMode == 'private' ) {
759 $response->header( "Cache-Control: $privateCache" );
760 return;
761 }
762
763 $useKeyHeader = $config->get( 'UseKeyHeader' );
764 if ( $this->mCacheMode == 'anon-public-user-private' ) {
765 $out->addVaryHeader( 'Cookie' );
766 $response->header( $out->getVaryHeader() );
767 if ( $useKeyHeader ) {
768 $response->header( $out->getKeyHeader() );
769 if ( $out->haveCacheVaryCookies() ) {
770 // Logged in, mark this request private
771 $response->header( "Cache-Control: $privateCache" );
772 return;
773 }
774 // Logged out, send normal public headers below
775 } elseif ( session_id() != '' ) {
776 // Logged in or otherwise has session (e.g. anonymous users who have edited)
777 // Mark request private
778 $response->header( "Cache-Control: $privateCache" );
779
780 return;
781 } // else no Key and anonymous, send public headers below
782 }
783
784 // Send public headers
785 $response->header( $out->getVaryHeader() );
786 if ( $useKeyHeader ) {
787 $response->header( $out->getKeyHeader() );
788 }
789
790 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
791 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
792 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
793 }
794 if ( !isset( $this->mCacheControl['max-age'] ) ) {
795 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
796 }
797
798 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
799 // Public cache not requested
800 // Sending a Vary header in this case is harmless, and protects us
801 // against conditional calls of setCacheMaxAge().
802 $response->header( "Cache-Control: $privateCache" );
803
804 return;
805 }
806
807 $this->mCacheControl['public'] = true;
808
809 // Send an Expires header
810 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
811 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
812 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
813
814 // Construct the Cache-Control header
815 $ccHeader = '';
816 $separator = '';
817 foreach ( $this->mCacheControl as $name => $value ) {
818 if ( is_bool( $value ) ) {
819 if ( $value ) {
820 $ccHeader .= $separator . $name;
821 $separator = ', ';
822 }
823 } else {
824 $ccHeader .= $separator . "$name=$value";
825 $separator = ', ';
826 }
827 }
828
829 $response->header( "Cache-Control: $ccHeader" );
830 }
831
832 /**
833 * Create the printer for error output
834 */
835 private function createErrorPrinter() {
836 if ( !isset( $this->mPrinter ) ) {
837 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
838 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
839 $value = self::API_DEFAULT_FORMAT;
840 }
841 $this->mPrinter = $this->createPrinterByName( $value );
842 }
843
844 // Printer may not be able to handle errors. This is particularly
845 // likely if the module returns something for getCustomPrinter().
846 if ( !$this->mPrinter->canPrintErrors() ) {
847 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
848 }
849 }
850
851 /**
852 * Replace the result data with the information about an exception.
853 * Returns the error code
854 * @param Exception $e
855 * @return string
856 */
857 protected function substituteResultWithError( $e ) {
858 $result = $this->getResult();
859 $config = $this->getConfig();
860
861 if ( $e instanceof UsageException ) {
862 // User entered incorrect parameters - generate error response
863 $errMessage = $e->getMessageArray();
864 $link = wfExpandUrl( wfScript( 'api' ) );
865 ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
866 } else {
867 // Something is seriously wrong
868 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
869 $info = 'Database query error';
870 } else {
871 $info = "Exception Caught: {$e->getMessage()}";
872 }
873
874 $errMessage = array(
875 'code' => 'internal_api_error_' . get_class( $e ),
876 'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info,
877 );
878 if ( $config->get( 'ShowExceptionDetails' ) ) {
879 ApiResult::setContentValue(
880 $errMessage,
881 'trace',
882 MWExceptionHandler::getRedactedTraceAsString( $e )
883 );
884 }
885 }
886
887 // Remember all the warnings to re-add them later
888 $warnings = $result->getResultData( array( 'warnings' ) );
889
890 $result->reset();
891 // Re-add the id
892 $requestid = $this->getParameter( 'requestid' );
893 if ( !is_null( $requestid ) ) {
894 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
895 }
896 if ( $config->get( 'ShowHostnames' ) ) {
897 // servedby is especially useful when debugging errors
898 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
899 }
900 if ( $warnings !== null ) {
901 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
902 }
903
904 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
905
906 return $errMessage['code'];
907 }
908
909 /**
910 * Set up for the execution.
911 * @return array
912 */
913 protected function setupExecuteAction() {
914 // First add the id to the top element
915 $result = $this->getResult();
916 $requestid = $this->getParameter( 'requestid' );
917 if ( !is_null( $requestid ) ) {
918 $result->addValue( null, 'requestid', $requestid );
919 }
920
921 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
922 $servedby = $this->getParameter( 'servedby' );
923 if ( $servedby ) {
924 $result->addValue( null, 'servedby', wfHostName() );
925 }
926 }
927
928 if ( $this->getParameter( 'curtimestamp' ) ) {
929 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
930 ApiResult::NO_SIZE_CHECK );
931 }
932
933 $params = $this->extractRequestParams();
934
935 $this->mAction = $params['action'];
936
937 if ( !is_string( $this->mAction ) ) {
938 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
939 }
940
941 return $params;
942 }
943
944 /**
945 * Set up the module for response
946 * @return ApiBase The module that will handle this action
947 * @throws MWException
948 * @throws UsageException
949 */
950 protected function setupModule() {
951 // Instantiate the module requested by the user
952 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
953 if ( $module === null ) {
954 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
955 }
956 $moduleParams = $module->extractRequestParams();
957
958 // Check token, if necessary
959 if ( $module->needsToken() === true ) {
960 throw new MWException(
961 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
962 "See documentation for ApiBase::needsToken for details."
963 );
964 }
965 if ( $module->needsToken() ) {
966 if ( !$module->mustBePosted() ) {
967 throw new MWException(
968 "Module '{$module->getModuleName()}' must require POST to use tokens."
969 );
970 }
971
972 if ( !isset( $moduleParams['token'] ) ) {
973 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
974 }
975
976 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
977 array_key_exists(
978 $module->encodeParamName( 'token' ),
979 $this->getRequest()->getQueryValues()
980 )
981 ) {
982 $this->dieUsage(
983 "The '{$module->encodeParamName( 'token' )}' parameter was " .
984 'found in the query string, but must be in the POST body',
985 'mustposttoken'
986 );
987 }
988
989 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
990 $this->dieUsageMsg( 'sessionfailure' );
991 }
992 }
993
994 return $module;
995 }
996
997 /**
998 * Check the max lag if necessary
999 * @param ApiBase $module Api module being used
1000 * @param array $params Array an array containing the request parameters.
1001 * @return bool True on success, false should exit immediately
1002 */
1003 protected function checkMaxLag( $module, $params ) {
1004 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1005 $maxLag = $params['maxlag'];
1006 list( $host, $lag ) = wfGetLB()->getMaxLag();
1007 if ( $lag > $maxLag ) {
1008 $response = $this->getRequest()->response();
1009
1010 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1011 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1012
1013 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1014 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1015 }
1016
1017 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1018 }
1019 }
1020
1021 return true;
1022 }
1023
1024 /**
1025 * Check selected RFC 7232 precondition headers
1026 *
1027 * RFC 7232 envisions a particular model where you send your request to "a
1028 * resource", and for write requests that you can read "the resource" by
1029 * changing the method to GET. When the API receives a GET request, it
1030 * works out even though "the resource" from RFC 7232's perspective might
1031 * be many resources from MediaWiki's perspective. But it totally fails for
1032 * a POST, since what HTTP sees as "the resource" is probably just
1033 * "/api.php" with all the interesting bits in the body.
1034 *
1035 * Therefore, we only support RFC 7232 precondition headers for GET (and
1036 * HEAD). That means we don't need to bother with If-Match and
1037 * If-Unmodified-Since since they only apply to modification requests.
1038 *
1039 * And since we don't support Range, If-Range is ignored too.
1040 *
1041 * @since 1.26
1042 * @param ApiBase $module Api module being used
1043 * @return bool True on success, false should exit immediately
1044 */
1045 protected function checkConditionalRequestHeaders( $module ) {
1046 if ( $this->mInternalMode ) {
1047 // No headers to check in internal mode
1048 return true;
1049 }
1050
1051 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1052 // Don't check POSTs
1053 return true;
1054 }
1055
1056 $return304 = false;
1057
1058 $ifNoneMatch = array_diff(
1059 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: array(),
1060 array( '' )
1061 );
1062 if ( $ifNoneMatch ) {
1063 if ( $ifNoneMatch === array( '*' ) ) {
1064 // API responses always "exist"
1065 $etag = '*';
1066 } else {
1067 $etag = $module->getConditionalRequestData( 'etag' );
1068 }
1069 }
1070 if ( $ifNoneMatch && $etag !== null ) {
1071 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1072 $match = array_map( function ( $s ) {
1073 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1074 }, $ifNoneMatch );
1075 $return304 = in_array( $test, $match, true );
1076 } else {
1077 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1078
1079 // Some old browsers sends sizes after the date, like this:
1080 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1081 // Ignore that.
1082 $i = strpos( $value, ';' );
1083 if ( $i !== false ) {
1084 $value = trim( substr( $value, 0, $i ) );
1085 }
1086
1087 if ( $value !== '' ) {
1088 try {
1089 $ts = new MWTimestamp( $value );
1090 if (
1091 // RFC 7231 IMF-fixdate
1092 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1093 // RFC 850
1094 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1095 // asctime (with and without space-padded day)
1096 $ts->format( 'D M j H:i:s Y' ) === $value ||
1097 $ts->format( 'D M j H:i:s Y' ) === $value
1098 ) {
1099 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1100 if ( $lastMod !== null ) {
1101 // Mix in some MediaWiki modification times
1102 $modifiedTimes = array(
1103 'page' => $lastMod,
1104 'user' => $this->getUser()->getTouched(),
1105 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1106 );
1107 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1108 // T46570: the core page itself may not change, but resources might
1109 $modifiedTimes['sepoch'] = wfTimestamp(
1110 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1111 );
1112 }
1113 Hooks::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
1114 $lastMod = max( $modifiedTimes );
1115 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1116 }
1117 }
1118 } catch ( TimestampException $e ) {
1119 // Invalid timestamp, ignore it
1120 }
1121 }
1122 }
1123
1124 if ( $return304 ) {
1125 $this->getRequest()->response()->statusHeader( 304 );
1126
1127 // Avoid outputting the compressed representation of a zero-length body
1128 MediaWiki\suppressWarnings();
1129 ini_set( 'zlib.output_compression', 0 );
1130 MediaWiki\restoreWarnings();
1131 wfClearOutputBuffers();
1132
1133 return false;
1134 }
1135
1136 return true;
1137 }
1138
1139 /**
1140 * Check for sufficient permissions to execute
1141 * @param ApiBase $module An Api module
1142 */
1143 protected function checkExecutePermissions( $module ) {
1144 $user = $this->getUser();
1145 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1146 !$user->isAllowed( 'read' )
1147 ) {
1148 $this->dieUsageMsg( 'readrequired' );
1149 }
1150
1151 if ( $module->isWriteMode() ) {
1152 if ( !$this->mEnableWrite ) {
1153 $this->dieUsageMsg( 'writedisabled' );
1154 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1155 $this->dieUsageMsg( 'writerequired' );
1156 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1157 $this->dieUsage(
1158 "Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules",
1159 'promised-nonwrite-api'
1160 );
1161 }
1162
1163 $this->checkReadOnly( $module );
1164 }
1165
1166 // Allow extensions to stop execution for arbitrary reasons.
1167 $message = false;
1168 if ( !Hooks::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1169 $this->dieUsageMsg( $message );
1170 }
1171 }
1172
1173 /**
1174 * Check if the DB is read-only for this user
1175 * @param ApiBase $module An Api module
1176 */
1177 protected function checkReadOnly( $module ) {
1178 if ( wfReadOnly() ) {
1179 $this->dieReadOnly();
1180 }
1181
1182 if ( $module->isWriteMode()
1183 && in_array( 'bot', $this->getUser()->getGroups() )
1184 && wfGetLB()->getServerCount() > 1
1185 ) {
1186 // Figure out how many servers have passed the lag threshold
1187 $numLagged = 0;
1188 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1189 foreach ( wfGetLB()->getLagTimes() as $lag ) {
1190 if ( $lag > $lagLimit ) {
1191 ++$numLagged;
1192 }
1193 }
1194 // If a majority of slaves are too lagged then disallow writes
1195 $slaveCount = wfGetLB()->getServerCount() - 1;
1196 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1197 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1198 $this->dieUsage(
1199 $parsed['info'],
1200 $parsed['code'],
1201 /* http error */
1202 0,
1203 array( 'readonlyreason' => "Waiting for $numLagged lagged database(s)" )
1204 );
1205 }
1206 }
1207 }
1208
1209 /**
1210 * Check asserts of the user's rights
1211 * @param array $params
1212 */
1213 protected function checkAsserts( $params ) {
1214 if ( isset( $params['assert'] ) ) {
1215 $user = $this->getUser();
1216 switch ( $params['assert'] ) {
1217 case 'user':
1218 if ( $user->isAnon() ) {
1219 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1220 }
1221 break;
1222 case 'bot':
1223 if ( !$user->isAllowed( 'bot' ) ) {
1224 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1225 }
1226 break;
1227 }
1228 }
1229 }
1230
1231 /**
1232 * Check POST for external response and setup result printer
1233 * @param ApiBase $module An Api module
1234 * @param array $params An array with the request parameters
1235 */
1236 protected function setupExternalResponse( $module, $params ) {
1237 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1238 // Module requires POST. GET request might still be allowed
1239 // if $wgDebugApi is true, otherwise fail.
1240 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
1241 }
1242
1243 // See if custom printer is used
1244 $this->mPrinter = $module->getCustomPrinter();
1245 if ( is_null( $this->mPrinter ) ) {
1246 // Create an appropriate printer
1247 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1248 }
1249 }
1250
1251 /**
1252 * Execute the actual module, without any error handling
1253 */
1254 protected function executeAction() {
1255 $params = $this->setupExecuteAction();
1256 $module = $this->setupModule();
1257 $this->mModule = $module;
1258
1259 $this->checkExecutePermissions( $module );
1260
1261 if ( !$this->checkMaxLag( $module, $params ) ) {
1262 return;
1263 }
1264
1265 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1266 return;
1267 }
1268
1269 if ( !$this->mInternalMode ) {
1270 $this->setupExternalResponse( $module, $params );
1271 }
1272
1273 $this->checkAsserts( $params );
1274
1275 // Execute
1276 $module->execute();
1277 Hooks::run( 'APIAfterExecute', array( &$module ) );
1278
1279 $this->reportUnusedParams();
1280
1281 if ( !$this->mInternalMode ) {
1282 // append Debug information
1283 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1284
1285 // Print result data
1286 $this->printResult( false );
1287 }
1288 }
1289
1290 /**
1291 * Log the preceding request
1292 * @param int $time Time in seconds
1293 */
1294 protected function logRequest( $time ) {
1295 $request = $this->getRequest();
1296 $milliseconds = $time === null ? '?' : round( $time * 1000 );
1297 $s = 'API' .
1298 ' ' . $request->getMethod() .
1299 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1300 ' ' . $request->getIP() .
1301 ' T=' . $milliseconds . 'ms';
1302 foreach ( $this->getParamsUsed() as $name ) {
1303 $value = $request->getVal( $name );
1304 if ( $value === null ) {
1305 continue;
1306 }
1307 $s .= ' ' . $name . '=';
1308 if ( strlen( $value ) > 256 ) {
1309 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1310 $s .= $encValue . '[...]';
1311 } else {
1312 $s .= $this->encodeRequestLogValue( $value );
1313 }
1314 }
1315 $s .= "\n";
1316 wfDebugLog( 'api', $s, 'private' );
1317 }
1318
1319 /**
1320 * Encode a value in a format suitable for a space-separated log line.
1321 * @param string $s
1322 * @return string
1323 */
1324 protected function encodeRequestLogValue( $s ) {
1325 static $table;
1326 if ( !$table ) {
1327 $chars = ';@$!*(),/:';
1328 $numChars = strlen( $chars );
1329 for ( $i = 0; $i < $numChars; $i++ ) {
1330 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1331 }
1332 }
1333
1334 return strtr( rawurlencode( $s ), $table );
1335 }
1336
1337 /**
1338 * Get the request parameters used in the course of the preceding execute() request
1339 * @return array
1340 */
1341 protected function getParamsUsed() {
1342 return array_keys( $this->mParamsUsed );
1343 }
1344
1345 /**
1346 * Get a request value, and register the fact that it was used, for logging.
1347 * @param string $name
1348 * @param mixed $default
1349 * @return mixed
1350 */
1351 public function getVal( $name, $default = null ) {
1352 $this->mParamsUsed[$name] = true;
1353
1354 $ret = $this->getRequest()->getVal( $name );
1355 if ( $ret === null ) {
1356 if ( $this->getRequest()->getArray( $name ) !== null ) {
1357 // See bug 10262 for why we don't just join( '|', ... ) the
1358 // array.
1359 $this->setWarning(
1360 "Parameter '$name' uses unsupported PHP array syntax"
1361 );
1362 }
1363 $ret = $default;
1364 }
1365 return $ret;
1366 }
1367
1368 /**
1369 * Get a boolean request value, and register the fact that the parameter
1370 * was used, for logging.
1371 * @param string $name
1372 * @return bool
1373 */
1374 public function getCheck( $name ) {
1375 return $this->getVal( $name, null ) !== null;
1376 }
1377
1378 /**
1379 * Get a request upload, and register the fact that it was used, for logging.
1380 *
1381 * @since 1.21
1382 * @param string $name Parameter name
1383 * @return WebRequestUpload
1384 */
1385 public function getUpload( $name ) {
1386 $this->mParamsUsed[$name] = true;
1387
1388 return $this->getRequest()->getUpload( $name );
1389 }
1390
1391 /**
1392 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1393 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1394 */
1395 protected function reportUnusedParams() {
1396 $paramsUsed = $this->getParamsUsed();
1397 $allParams = $this->getRequest()->getValueNames();
1398
1399 if ( !$this->mInternalMode ) {
1400 // Printer has not yet executed; don't warn that its parameters are unused
1401 $printerParams = array_map(
1402 array( $this->mPrinter, 'encodeParamName' ),
1403 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1404 );
1405 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1406 } else {
1407 $unusedParams = array_diff( $allParams, $paramsUsed );
1408 }
1409
1410 if ( count( $unusedParams ) ) {
1411 $s = count( $unusedParams ) > 1 ? 's' : '';
1412 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1413 }
1414 }
1415
1416 /**
1417 * Print results using the current printer
1418 *
1419 * @param bool $isError
1420 */
1421 protected function printResult( $isError ) {
1422 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1423 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1424 }
1425
1426 $printer = $this->mPrinter;
1427 $printer->initPrinter( false );
1428 $printer->execute();
1429 $printer->closePrinter();
1430 }
1431
1432 /**
1433 * @return bool
1434 */
1435 public function isReadMode() {
1436 return false;
1437 }
1438
1439 /**
1440 * See ApiBase for description.
1441 *
1442 * @return array
1443 */
1444 public function getAllowedParams() {
1445 return array(
1446 'action' => array(
1447 ApiBase::PARAM_DFLT => 'help',
1448 ApiBase::PARAM_TYPE => 'submodule',
1449 ),
1450 'format' => array(
1451 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1452 ApiBase::PARAM_TYPE => 'submodule',
1453 ),
1454 'maxlag' => array(
1455 ApiBase::PARAM_TYPE => 'integer'
1456 ),
1457 'smaxage' => array(
1458 ApiBase::PARAM_TYPE => 'integer',
1459 ApiBase::PARAM_DFLT => 0
1460 ),
1461 'maxage' => array(
1462 ApiBase::PARAM_TYPE => 'integer',
1463 ApiBase::PARAM_DFLT => 0
1464 ),
1465 'assert' => array(
1466 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1467 ),
1468 'requestid' => null,
1469 'servedby' => false,
1470 'curtimestamp' => false,
1471 'origin' => null,
1472 'uselang' => array(
1473 ApiBase::PARAM_DFLT => 'user',
1474 ),
1475 );
1476 }
1477
1478 /** @see ApiBase::getExamplesMessages() */
1479 protected function getExamplesMessages() {
1480 return array(
1481 'action=help'
1482 => 'apihelp-help-example-main',
1483 'action=help&recursivesubmodules=1'
1484 => 'apihelp-help-example-recursive',
1485 );
1486 }
1487
1488 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1489 // Wish PHP had an "array_insert_before". Instead, we have to manually
1490 // reindex the array to get 'permissions' in the right place.
1491 $oldHelp = $help;
1492 $help = array();
1493 foreach ( $oldHelp as $k => $v ) {
1494 if ( $k === 'submodules' ) {
1495 $help['permissions'] = '';
1496 }
1497 $help[$k] = $v;
1498 }
1499 $help['datatypes'] = '';
1500 $help['credits'] = '';
1501
1502 // Fill 'permissions'
1503 $help['permissions'] .= Html::openElement( 'div',
1504 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1505 $m = $this->msg( 'api-help-permissions' );
1506 if ( !$m->isDisabled() ) {
1507 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1508 $m->numParams( count( self::$mRights ) )->parse()
1509 );
1510 }
1511 $help['permissions'] .= Html::openElement( 'dl' );
1512 foreach ( self::$mRights as $right => $rightMsg ) {
1513 $help['permissions'] .= Html::element( 'dt', null, $right );
1514
1515 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1516 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1517
1518 $groups = array_map( function ( $group ) {
1519 return $group == '*' ? 'all' : $group;
1520 }, User::getGroupsWithPermission( $right ) );
1521
1522 $help['permissions'] .= Html::rawElement( 'dd', null,
1523 $this->msg( 'api-help-permissions-granted-to' )
1524 ->numParams( count( $groups ) )
1525 ->params( $this->getLanguage()->commaList( $groups ) )
1526 ->parse()
1527 );
1528 }
1529 $help['permissions'] .= Html::closeElement( 'dl' );
1530 $help['permissions'] .= Html::closeElement( 'div' );
1531
1532 // Fill 'datatypes' and 'credits', if applicable
1533 if ( empty( $options['nolead'] ) ) {
1534 $level = $options['headerlevel'];
1535 $tocnumber = &$options['tocnumber'];
1536
1537 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1538 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1539 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1540 Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/datatypes' ) ) ) .
1541 $header
1542 );
1543 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1544 if ( !isset( $tocData['main/datatypes'] ) ) {
1545 $tocnumber[$level]++;
1546 $tocData['main/datatypes'] = array(
1547 'toclevel' => count( $tocnumber ),
1548 'level' => $level,
1549 'anchor' => 'main/datatypes',
1550 'line' => $header,
1551 'number' => join( '.', $tocnumber ),
1552 'index' => false,
1553 );
1554 }
1555
1556 $header = $this->msg( 'api-credits-header' )->parse();
1557 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1558 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1559 Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/credits' ) ) ) .
1560 $header
1561 );
1562 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1563 if ( !isset( $tocData['main/credits'] ) ) {
1564 $tocnumber[$level]++;
1565 $tocData['main/credits'] = array(
1566 'toclevel' => count( $tocnumber ),
1567 'level' => $level,
1568 'anchor' => 'main/credits',
1569 'line' => $header,
1570 'number' => join( '.', $tocnumber ),
1571 'index' => false,
1572 );
1573 }
1574 }
1575 }
1576
1577 private $mCanApiHighLimits = null;
1578
1579 /**
1580 * Check whether the current user is allowed to use high limits
1581 * @return bool
1582 */
1583 public function canApiHighLimits() {
1584 if ( !isset( $this->mCanApiHighLimits ) ) {
1585 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1586 }
1587
1588 return $this->mCanApiHighLimits;
1589 }
1590
1591 /**
1592 * Overrides to return this instance's module manager.
1593 * @return ApiModuleManager
1594 */
1595 public function getModuleManager() {
1596 return $this->mModuleMgr;
1597 }
1598
1599 /**
1600 * Fetches the user agent used for this request
1601 *
1602 * The value will be the combination of the 'Api-User-Agent' header (if
1603 * any) and the standard User-Agent header (if any).
1604 *
1605 * @return string
1606 */
1607 public function getUserAgent() {
1608 return trim(
1609 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1610 $this->getRequest()->getHeader( 'User-agent' )
1611 );
1612 }
1613
1614 /************************************************************************//**
1615 * @name Deprecated
1616 * @{
1617 */
1618
1619 /**
1620 * Sets whether the pretty-printer should format *bold* and $italics$
1621 *
1622 * @deprecated since 1.25
1623 * @param bool $help
1624 */
1625 public function setHelp( $help = true ) {
1626 wfDeprecated( __METHOD__, '1.25' );
1627 $this->mPrinter->setHelp( $help );
1628 }
1629
1630 /**
1631 * Override the parent to generate help messages for all available modules.
1632 *
1633 * @deprecated since 1.25
1634 * @return string
1635 */
1636 public function makeHelpMsg() {
1637 wfDeprecated( __METHOD__, '1.25' );
1638
1639 $this->setHelp();
1640 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1641
1642 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1643 wfMemcKey(
1644 'apihelp',
1645 $this->getModuleName(),
1646 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1647 ),
1648 $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1649 array( $this, 'reallyMakeHelpMsg' )
1650 );
1651 }
1652
1653 /**
1654 * @deprecated since 1.25
1655 * @return mixed|string
1656 */
1657 public function reallyMakeHelpMsg() {
1658 wfDeprecated( __METHOD__, '1.25' );
1659 $this->setHelp();
1660
1661 // Use parent to make default message for the main module
1662 $msg = parent::makeHelpMsg();
1663
1664 $astriks = str_repeat( '*** ', 14 );
1665 $msg .= "\n\n$astriks Modules $astriks\n\n";
1666
1667 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1668 $module = $this->mModuleMgr->getModule( $name );
1669 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1670
1671 $msg2 = $module->makeHelpMsg();
1672 if ( $msg2 !== false ) {
1673 $msg .= $msg2;
1674 }
1675 $msg .= "\n";
1676 }
1677
1678 $msg .= "\n$astriks Permissions $astriks\n\n";
1679 foreach ( self::$mRights as $right => $rightMsg ) {
1680 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1681 ->useDatabase( false )
1682 ->inLanguage( 'en' )
1683 ->text();
1684 $groups = User::getGroupsWithPermission( $right );
1685 $msg .= "* " . $right . " *\n $rightsMsg" .
1686 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1687 }
1688
1689 $msg .= "\n$astriks Formats $astriks\n\n";
1690 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1691 $module = $this->mModuleMgr->getModule( $name );
1692 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1693 $msg2 = $module->makeHelpMsg();
1694 if ( $msg2 !== false ) {
1695 $msg .= $msg2;
1696 }
1697 $msg .= "\n";
1698 }
1699
1700 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1701 $credits = str_replace( "\n", "\n ", $credits );
1702 $msg .= "\n*** Credits: ***\n $credits\n";
1703
1704 return $msg;
1705 }
1706
1707 /**
1708 * @deprecated since 1.25
1709 * @param ApiBase $module
1710 * @param string $paramName What type of request is this? e.g. action,
1711 * query, list, prop, meta, format
1712 * @return string
1713 */
1714 public static function makeHelpMsgHeader( $module, $paramName ) {
1715 wfDeprecated( __METHOD__, '1.25' );
1716 $modulePrefix = $module->getModulePrefix();
1717 if ( strval( $modulePrefix ) !== '' ) {
1718 $modulePrefix = "($modulePrefix) ";
1719 }
1720
1721 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1722 }
1723
1724 /**
1725 * Check whether the user wants us to show version information in the API help
1726 * @return bool
1727 * @deprecated since 1.21, always returns false
1728 */
1729 public function getShowVersions() {
1730 wfDeprecated( __METHOD__, '1.21' );
1731
1732 return false;
1733 }
1734
1735 /**
1736 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1737 * classes who wish to add their own modules to their lexicon or override the
1738 * behavior of inherent ones.
1739 *
1740 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1741 * @param string $name The identifier for this module.
1742 * @param ApiBase $class The class where this module is implemented.
1743 */
1744 protected function addModule( $name, $class ) {
1745 $this->getModuleManager()->addModule( $name, 'action', $class );
1746 }
1747
1748 /**
1749 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1750 * classes who wish to add to or modify current formatters.
1751 *
1752 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1753 * @param string $name The identifier for this format.
1754 * @param ApiFormatBase $class The class implementing this format.
1755 */
1756 protected function addFormat( $name, $class ) {
1757 $this->getModuleManager()->addModule( $name, 'format', $class );
1758 }
1759
1760 /**
1761 * Get the array mapping module names to class names
1762 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1763 * @return array
1764 */
1765 function getModules() {
1766 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1767 }
1768
1769 /**
1770 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1771 *
1772 * @since 1.18
1773 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1774 * @return array
1775 */
1776 public function getFormats() {
1777 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1778 }
1779
1780 /**@}*/
1781
1782 }
1783
1784 /**
1785 * This exception will be thrown when dieUsage is called to stop module execution.
1786 *
1787 * @ingroup API
1788 */
1789 class UsageException extends MWException {
1790
1791 private $mCodestr;
1792
1793 /**
1794 * @var null|array
1795 */
1796 private $mExtraData;
1797
1798 /**
1799 * @param string $message
1800 * @param string $codestr
1801 * @param int $code
1802 * @param array|null $extradata
1803 */
1804 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1805 parent::__construct( $message, $code );
1806 $this->mCodestr = $codestr;
1807 $this->mExtraData = $extradata;
1808 }
1809
1810 /**
1811 * @return string
1812 */
1813 public function getCodeString() {
1814 return $this->mCodestr;
1815 }
1816
1817 /**
1818 * @return array
1819 */
1820 public function getMessageArray() {
1821 $result = array(
1822 'code' => $this->mCodestr,
1823 'info' => $this->getMessage()
1824 );
1825 if ( is_array( $this->mExtraData ) ) {
1826 $result = array_merge( $result, $this->mExtraData );
1827 }
1828
1829 return $result;
1830 }
1831
1832 /**
1833 * @return string
1834 */
1835 public function __toString() {
1836 return "{$this->getCodeString()}: {$this->getMessage()}";
1837 }
1838 }
1839
1840 /**
1841 * For really cool vim folding this needs to be at the end:
1842 * vim: foldmarker=@{,@} foldmethod=marker
1843 */