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