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