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