Debian Codegraph @

includes/api/ApiMain.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @defgroup API API
22 */
23
24 namespace MediaWiki\Api;
25
26 use ILocalizedException;
27 use LogicException;
28 use MediaWiki;
29 use MediaWiki\Api\Validator\ApiParamValidator;
30 use MediaWiki\Context\DerivativeContext;
31 use MediaWiki\Context\IContextSource;
32 use MediaWiki\Context\RequestContext;
33 use MediaWiki\Debug\MWDebug;
34 use MediaWiki\Html\Html;
35 use MediaWiki\Logger\LoggerFactory;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Message\Message;
39 use MediaWiki\ParamValidator\TypeDef\UserDef;
40 use MediaWiki\Profiler\ProfilingContext;
41 use MediaWiki\Request\FauxRequest;
42 use MediaWiki\Request\WebRequest;
43 use MediaWiki\Request\WebRequestUpload;
44 use MediaWiki\Rest\HeaderParser\Origin;
45 use MediaWiki\Session\SessionManager;
46 use MediaWiki\StubObject\StubGlobalUser;
47 use MediaWiki\User\UserRigorOptions;
48 use MediaWiki\Utils\MWTimestamp;
49 use MediaWiki\WikiMap\WikiMap;
50 use MWExceptionHandler;
51 use MWExceptionRenderer;
52 use Profiler;
53 use Throwable;
54 use UnexpectedValueException;
55 use Wikimedia\AtEase\AtEase;
56 use Wikimedia\Message\MessageSpecifier;
57 use Wikimedia\ParamValidator\ParamValidator;
58 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
59 use Wikimedia\Stats\StatsFactory;
60 use Wikimedia\Timestamp\TimestampException;
61
62 /**
63 * This is the main API class, used for both external and internal processing.
64 * When executed, it will create the requested formatter object,
65 * instantiate and execute an object associated with the needed action,
66 * and use formatter to print results.
67 * In case of an exception, an error message will be printed using the same formatter.
68 *
69 * To use API from another application, run it using MediaWiki\Request\FauxRequest object, in which
70 * case any internal exceptions will not be handled but passed up to the caller.
71 * After successful execution, use getResult() for the resulting data.
72 *
73 * @newable
74 * @note marked as newable in 1.35 for lack of a better alternative,
75 * but should use a factory in the future.
76 * @ingroup API
77 */
78 class ApiMain extends ApiBase {
79 /**
80 * When no format parameter is given, this format will be used
81 */
82 private const API_DEFAULT_FORMAT = 'jsonfm';
83
84 /**
85 * When no uselang parameter is given, this language will be used
86 */
87 private const API_DEFAULT_USELANG = 'user';
88
89 /**
90 * List of available modules: action name => module class
91 */
92 private const MODULES = [
93 'login' => [
94 'class' => ApiLogin::class,
95 'services' => [
96 'AuthManager',
97 ],
98 ],
99 'clientlogin' => [
100 'class' => ApiClientLogin::class,
101 'services' => [
102 'AuthManager',
103 'UrlUtils',
104 ],
105 ],
106 'logout' => [
107 'class' => ApiLogout::class,
108 ],
109 'createaccount' => [
110 'class' => ApiAMCreateAccount::class,
111 'services' => [
112 'AuthManager',
113 'UrlUtils',
114 ],
115 ],
116 'linkaccount' => [
117 'class' => ApiLinkAccount::class,
118 'services' => [
119 'AuthManager',
120 'UrlUtils',
121 ],
122 ],
123 'unlinkaccount' => [
124 'class' => ApiRemoveAuthenticationData::class,
125 'services' => [
126 'AuthManager',
127 ],
128 ],
129 'changeauthenticationdata' => [
130 'class' => ApiChangeAuthenticationData::class,
131 'services' => [
132 'AuthManager',
133 ],
134 ],
135 'removeauthenticationdata' => [
136 'class' => ApiRemoveAuthenticationData::class,
137 'services' => [
138 'AuthManager',
139 ],
140 ],
141 'resetpassword' => [
142 'class' => ApiResetPassword::class,
143 'services' => [
144 'PasswordReset',
145 ]
146 ],
147 'query' => [
148 'class' => ApiQuery::class,
149 'services' => [
150 'ObjectFactory',
151 'WikiExporterFactory',
152 'TitleFormatter',
153 'TitleFactory',
154 ]
155 ],
156 'expandtemplates' => [
157 'class' => ApiExpandTemplates::class,
158 'services' => [
159 'RevisionStore',
160 'ParserFactory',
161 ]
162 ],
163 'parse' => [
164 'class' => ApiParse::class,
165 'services' => [
166 'RevisionLookup',
167 'SkinFactory',
168 'LanguageNameUtils',
169 'LinkBatchFactory',
170 'LinkCache',
171 'ContentHandlerFactory',
172 'ParserFactory',
173 'WikiPageFactory',
174 'ContentRenderer',
175 'ContentTransformer',
176 'CommentFormatter',
177 'TempUserCreator',
178 'UserFactory',
179 'UrlUtils',
180 'TitleFormatter',
181 'JsonCodec',
182 ]
183 ],
184 'stashedit' => [
185 'class' => ApiStashEdit::class,
186 'services' => [
187 'ContentHandlerFactory',
188 'PageEditStash',
189 'RevisionLookup',
190 'StatsFactory',
191 'WikiPageFactory',
192 'TempUserCreator',
193 'UserFactory',
194 ]
195 ],
196 'opensearch' => [
197 'class' => ApiOpenSearch::class,
198 'services' => [
199 'LinkBatchFactory',
200 'SearchEngineConfig',
201 'SearchEngineFactory',
202 'UrlUtils',
203 ]
204 ],
205 'feedcontributions' => [
206 'class' => ApiFeedContributions::class,
207 'services' => [
208 'RevisionStore',
209 'LinkRenderer',
210 'LinkBatchFactory',
211 'HookContainer',
212 'DBLoadBalancerFactory',
213 'NamespaceInfo',
214 'UserFactory',
215 'CommentFormatter',
216 ]
217 ],
218 'feedrecentchanges' => [
219 'class' => ApiFeedRecentChanges::class,
220 'services' => [
221 'SpecialPageFactory',
222 'TempUserConfig',
223 ]
224 ],
225 'feedwatchlist' => [
226 'class' => ApiFeedWatchlist::class,
227 'services' => [
228 'ParserFactory',
229 ]
230 ],
231 'help' => [
232 'class' => ApiHelp::class,
233 'services' => [
234 'SkinFactory',
235 ]
236 ],
237 'paraminfo' => [
238 'class' => ApiParamInfo::class,
239 'services' => [
240 'UserFactory',
241 ],
242 ],
243 'rsd' => [
244 'class' => ApiRsd::class,
245 ],
246 'compare' => [
247 'class' => ApiComparePages::class,
248 'services' => [
249 'RevisionStore',
250 'ArchivedRevisionLookup',
251 'SlotRoleRegistry',
252 'ContentHandlerFactory',
253 'ContentTransformer',
254 'CommentFormatter',
255 'TempUserCreator',
256 'UserFactory',
257 ]
258 ],
259 'checktoken' => [
260 'class' => ApiCheckToken::class,
261 ],
262 'cspreport' => [
263 'class' => ApiCSPReport::class,
264 'services' => [
265 'UrlUtils',
266 ]
267 ],
268 'validatepassword' => [
269 'class' => ApiValidatePassword::class,
270 'services' => [
271 'AuthManager',
272 'UserFactory',
273 ]
274 ],
275
276 // Write modules
277 'purge' => [
278 'class' => ApiPurge::class,
279 'services' => [
280 'WikiPageFactory',
281 'TitleFormatter',
282 ],
283 ],
284 'setnotificationtimestamp' => [
285 'class' => ApiSetNotificationTimestamp::class,
286 'services' => [
287 'DBLoadBalancerFactory',
288 'RevisionStore',
289 'WatchedItemStore',
290 'TitleFormatter',
291 'TitleFactory',
292 ]
293 ],
294 'rollback' => [
295 'class' => ApiRollback::class,
296 'services' => [
297 'RollbackPageFactory',
298 'WatchlistManager',
299 'UserOptionsLookup',
300 ]
301 ],
302 'delete' => [
303 'class' => ApiDelete::class,
304 'services' => [
305 'RepoGroup',
306 'WatchlistManager',
307 'UserOptionsLookup',
308 'DeletePageFactory',
309 ]
310 ],
311 'undelete' => [
312 'class' => ApiUndelete::class,
313 'services' => [
314 'WatchlistManager',
315 'UserOptionsLookup',
316 'UndeletePageFactory',
317 'WikiPageFactory',
318 ]
319 ],
320 'protect' => [
321 'class' => ApiProtect::class,
322 'services' => [
323 'WatchlistManager',
324 'UserOptionsLookup',
325 'RestrictionStore',
326 ]
327 ],
328 'block' => [
329 'class' => ApiBlock::class,
330 'services' => [
331 'BlockPermissionCheckerFactory',
332 'BlockUserFactory',
333 'TitleFactory',
334 'UserIdentityLookup',
335 'WatchedItemStore',
336 'BlockUtils',
337 'BlockActionInfo',
338 'WatchlistManager',
339 'UserOptionsLookup',
340 ]
341 ],
342 'unblock' => [
343 'class' => ApiUnblock::class,
344 'services' => [
345 'BlockPermissionCheckerFactory',
346 'UnblockUserFactory',
347 'UserIdentityLookup',
348 'WatchedItemStore',
349 'WatchlistManager',
350 'UserOptionsLookup',
351 ]
352 ],
353 'move' => [
354 'class' => ApiMove::class,
355 'services' => [
356 'MovePageFactory',
357 'RepoGroup',
358 'WatchlistManager',
359 'UserOptionsLookup',
360 ]
361 ],
362 'edit' => [
363 'class' => ApiEditPage::class,
364 'services' => [
365 'ContentHandlerFactory',
366 'RevisionLookup',
367 'WatchedItemStore',
368 'WikiPageFactory',
369 'WatchlistManager',
370 'UserOptionsLookup',
371 'RedirectLookup',
372 'TempUserCreator',
373 'UserFactory',
374 ]
375 ],
376 'upload' => [
377 'class' => ApiUpload::class,
378 'services' => [
379 'JobQueueGroup',
380 'WatchlistManager',
381 'UserOptionsLookup',
382 ]
383 ],
384 'filerevert' => [
385 'class' => ApiFileRevert::class,
386 'services' => [
387 'RepoGroup',
388 ]
389 ],
390 'emailuser' => [
391 'class' => ApiEmailUser::class,
392 'services' => [
393 'EmailUserFactory',
394 'UserFactory',
395 ]
396 ],
397 'watch' => [
398 'class' => ApiWatch::class,
399 'services' => [
400 'WatchlistManager',
401 'TitleFormatter',
402 ]
403 ],
404 'patrol' => [
405 'class' => ApiPatrol::class,
406 'services' => [
407 'RevisionStore',
408 ]
409 ],
410 'import' => [
411 'class' => ApiImport::class,
412 'services' => [
413 'WikiImporterFactory',
414 ]
415 ],
416 'clearhasmsg' => [
417 'class' => ApiClearHasMsg::class,
418 'services' => [
419 'TalkPageNotificationManager',
420 ]
421 ],
422 'userrights' => [
423 'class' => ApiUserrights::class,
424 'services' => [
425 'UserGroupManager',
426 'WatchedItemStore',
427 'WatchlistManager',
428 'UserOptionsLookup',
429 ]
430 ],
431 'options' => [
432 'class' => ApiOptions::class,
433 'services' => [
434 'UserOptionsManager',
435 'PreferencesFactory',
436 ],
437 ],
438 'imagerotate' => [
439 'class' => ApiImageRotate::class,
440 'services' => [
441 'RepoGroup',
442 'TempFSFileFactory',
443 'TitleFactory',
444 ]
445 ],
446 'revisiondelete' => [
447 'class' => ApiRevisionDelete::class,
448 ],
449 'managetags' => [
450 'class' => ApiManageTags::class,
451 ],
452 'tag' => [
453 'class' => ApiTag::class,
454 'services' => [
455 'DBLoadBalancerFactory',
456 'RevisionStore',
457 'ChangeTagsStore',
458 ]
459 ],
460 'mergehistory' => [
461 'class' => ApiMergeHistory::class,
462 'services' => [
463 'MergeHistoryFactory',
464 ],
465 ],
466 'setpagelanguage' => [
467 'class' => ApiSetPageLanguage::class,
468 'services' => [
469 'DBLoadBalancerFactory',
470 'LanguageNameUtils',
471 ]
472 ],
473 'changecontentmodel' => [
474 'class' => ApiChangeContentModel::class,
475 'services' => [
476 'ContentHandlerFactory',
477 'ContentModelChangeFactory',
478 ]
479 ],
480 'acquiretempusername' => [
481 'class' => ApiAcquireTempUserName::class,
482 'services' => [
483 'TempUserCreator',
484 ]
485 ],
486 ];
487
488 /**
489 * List of available formats: format name => format class
490 */
491 private const FORMATS = [
492 'json' => [
493 'class' => ApiFormatJson::class,
494 ],
495 'jsonfm' => [
496 'class' => ApiFormatJson::class,
497 ],
498 'php' => [
499 'class' => ApiFormatPhp::class,
500 ],
501 'phpfm' => [
502 'class' => ApiFormatPhp::class,
503 ],
504 'xml' => [
505 'class' => ApiFormatXml::class,
506 ],
507 'xmlfm' => [
508 'class' => ApiFormatXml::class,
509 ],
510 'rawfm' => [
511 'class' => ApiFormatJson::class,
512 ],
513 'none' => [
514 'class' => ApiFormatNone::class,
515 ],
516 ];
517
518 /**
519 * List of user roles that are specifically relevant to the API.
520 * [ 'right' => [ 'msg' => 'Some message with a $1',
521 * 'params' => [ $someVarToSubst ] ],
522 * ];
523 */
524 private const RIGHTS_MAP = [
525 'apihighlimits' => [
526 'msg' => 'api-help-right-apihighlimits',
527 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]
528 ]
529 ];
530
531 /** @var ApiFormatBase|null */
532 private $mPrinter;
533
534 /** @var ApiModuleManager */
535 private $mModuleMgr;
536
537 /** @var ApiResult */
538 private $mResult;
539
540 /** @var ApiErrorFormatter */
541 private $mErrorFormatter;
542
543 /** @var ApiParamValidator */
544 private $mParamValidator;
545
546 /** @var ApiContinuationManager|null */
547 private $mContinuationManager;
548
549 /** @var string|null */
550 private $mAction;
551
552 /** @var bool */
553 private $mEnableWrite;
554
555 /** @var bool */
556 private $mInternalMode;
557
558 /** @var ApiBase */
559 private $mModule;
560
561 /** @var string */
562 private $mCacheMode = 'private';
563
564 /** @var array */
565 private $mCacheControl = [];
566
567 /** @var array */
568 private $mParamsUsed = [];
569
570 /** @var array */
571 private $mParamsSensitive = [];
572
573 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
574 private $lacksSameOriginSecurity = null;
575
576 /** @var StatsFactory */
577 private $statsFactory;
578
579 /**
580 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
581 *
582 * @stable to call
583 * @param IContextSource|WebRequest|null $context If this is an instance of
584 * MediaWiki\Request\FauxRequest, errors are thrown and no printing occurs
585 * @param bool $enableWrite Should be set to true if the api may modify data
586 * @param bool|null $internal Whether the API request is an internal faux
587 * request. If null or not given, the request is assumed to be internal
588 * if $context contains a FauxRequest.
589 */
590 public function __construct( $context = null, $enableWrite = false, $internal = null ) {
591 if ( $context === null ) {
592 $context = RequestContext::getMain();
593 } elseif ( $context instanceof WebRequest ) {
594 // BC for pre-1.19
595 $request = $context;
596 $context = RequestContext::getMain();
597 }
598 // We set a derivative context so we can change stuff later
599 $derivativeContext = new DerivativeContext( $context );
600 $this->setContext( $derivativeContext );
601
602 if ( isset( $request ) ) {
603 $derivativeContext->setRequest( $request );
604 } else {
605 $request = $this->getRequest();
606 }
607
608 $this->mInternalMode = $internal ?? ( $request instanceof FauxRequest );
609
610 // Special handling for the main module: $parent === $this
611 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
612
613 $config = $this->getConfig();
614 // TODO inject stuff, see T265644
615 $services = MediaWikiServices::getInstance();
616
617 if ( !$this->mInternalMode ) {
618 // If we're in a mode that breaks the same-origin policy, strip
619 // user credentials for security.
620 if ( $this->lacksSameOriginSecurity() ) {
621 wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
622 $user = $services->getUserFactory()->newAnonymous();
623 StubGlobalUser::setUser( $user );
624 $derivativeContext->setUser( $user );
625 $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
626 }
627 }
628
629 $this->mParamValidator = new ApiParamValidator(
630 $this,
631 $services->getObjectFactory()
632 );
633
634 $this->statsFactory = $services->getStatsFactory();
635
636 $this->mResult =
637 new ApiResult( $this->getConfig()->get( MainConfigNames::APIMaxResultSize ) );
638
639 // Setup uselang. This doesn't use $this->getParameter()
640 // because we're not ready to handle errors yet.
641 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
642 $uselang = $request->getRawVal( 'uselang' ) ?? self::API_DEFAULT_USELANG;
643 if ( $uselang === 'user' ) {
644 // Assume the parent context is going to return the user language
645 // for uselang=user (see T85635).
646 } else {
647 if ( $uselang === 'content' ) {
648 $uselang = $services->getContentLanguage()->getCode();
649 }
650 $code = RequestContext::sanitizeLangCode( $uselang );
651 $derivativeContext->setLanguage( $code );
652 if ( !$this->mInternalMode ) {
653 // phpcs:disable MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
654 global $wgLang;
655 $wgLang = $derivativeContext->getLanguage();
656 RequestContext::getMain()->setLanguage( $wgLang );
657 // phpcs:enable MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
658 }
659 }
660
661 // Set up the error formatter. This doesn't use $this->getParameter()
662 // because we're not ready to handle errors yet.
663 // Optimisation: Avoid slow getVal(), this isn't user-generated content.
664 $errorFormat = $request->getRawVal( 'errorformat' ) ?? 'bc';
665 $errorLangCode = $request->getRawVal( 'errorlang' ) ?? 'uselang';
666 $errorsUseDB = $request->getCheck( 'errorsuselocal' );
667 if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
668 if ( $errorLangCode === 'uselang' ) {
669 $errorLang = $this->getLanguage();
670 } elseif ( $errorLangCode === 'content' ) {
671 $errorLang = $services->getContentLanguage();
672 } else {
673 $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
674 $errorLang = $services->getLanguageFactory()->getLanguage( $errorLangCode );
675 }
676 $this->mErrorFormatter = new ApiErrorFormatter(
677 $this->mResult,
678 $errorLang,
679 $errorFormat,
680 $errorsUseDB
681 );
682 } else {
683 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
684 }
685 $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
686
687 $this->mModuleMgr = new ApiModuleManager(
688 $this,
689 $services->getObjectFactory()
690 );
691 $this->mModuleMgr->addModules( self::MODULES, 'action' );
692 $this->mModuleMgr->addModules( $config->get( MainConfigNames::APIModules ), 'action' );
693 $this->mModuleMgr->addModules( self::FORMATS, 'format' );
694 $this->mModuleMgr->addModules( $config->get( MainConfigNames::APIFormatModules ), 'format' );
695
696 $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
697
698 $this->mContinuationManager = null;
699 $this->mEnableWrite = $enableWrite;
700 }
701
702 /**
703 * Return true if the API was started by other PHP code using MediaWiki\Request\FauxRequest
704 * @return bool
705 */
706 public function isInternalMode() {
707 return $this->mInternalMode;
708 }
709
710 /**
711 * Get the ApiResult object associated with current request
712 *
713 * @return ApiResult
714 */
715 public function getResult() {
716 return $this->mResult;
717 }
718
719 /**
720 * Get the security flag for the current request
721 * @return bool
722 */
723 public function lacksSameOriginSecurity() {
724 if ( $this->lacksSameOriginSecurity !== null ) {
725 return $this->lacksSameOriginSecurity;
726 }
727
728 $request = $this->getRequest();
729
730 // JSONP mode
731 if ( $request->getCheck( 'callback' ) ||
732 // Anonymous CORS
733 $request->getVal( 'origin' ) === '*' ||
734 // Header to be used from XMLHTTPRequest when the request might
735 // otherwise be used for XSS.
736 $request->getHeader( 'Treat-as-Untrusted' ) !== false
737 ) {
738 $this->lacksSameOriginSecurity = true;
739 return true;
740 }
741
742 // Allow extensions to override.
743 $this->lacksSameOriginSecurity = !$this->getHookRunner()
744 ->onRequestHasSameOriginSecurity( $request );
745 return $this->lacksSameOriginSecurity;
746 }
747
748 /**
749 * Get the ApiErrorFormatter object associated with current request
750 * @return ApiErrorFormatter
751 */
752 public function getErrorFormatter() {
753 return $this->mErrorFormatter;
754 }
755
756 /**
757 * @return ApiContinuationManager|null
758 */
759 public function getContinuationManager() {
760 return $this->mContinuationManager;
761 }
762
763 /**
764 * @param ApiContinuationManager|null $manager
765 */
766 public function setContinuationManager( ?ApiContinuationManager $manager = null ) {
767 if ( $manager !== null && $this->mContinuationManager !== null ) {
768 throw new UnexpectedValueException(
769 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
770 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
771 );
772 }
773 $this->mContinuationManager = $manager;
774 }
775
776 /**
777 * Get the parameter validator
778 * @return ApiParamValidator
779 */
780 public function getParamValidator(): ApiParamValidator {
781 return $this->mParamValidator;
782 }
783
784 /**
785 * Get the API module object. Only works after executeAction()
786 *
787 * @return ApiBase
788 */
789 public function getModule() {
790 return $this->mModule;
791 }
792
793 /**
794 * Get the result formatter object. Only works after setupExecuteAction()
795 *
796 * @return ApiFormatBase
797 */
798 public function getPrinter() {
799 return $this->mPrinter;
800 }
801
802 /**
803 * Set how long the response should be cached.
804 *
805 * @param int $maxage
806 */
807 public function setCacheMaxAge( $maxage ) {
808 $this->setCacheControl( [
809 'max-age' => $maxage,
810 's-maxage' => $maxage
811 ] );
812 }
813
814 /**
815 * Set the type of caching headers which will be sent.
816 *
817 * @param string $mode One of:
818 * - 'public': Cache this object in public caches, if the maxage or smaxage
819 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
820 * not provided by any of these means, the object will be private.
821 * - 'private': Cache this object only in private client-side caches.
822 * - 'anon-public-user-private': Make this object cacheable for logged-out
823 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
824 * set consistently for a given URL, it cannot be set differently depending on
825 * things like the contents of the database, or whether the user is logged in.
826 *
827 * If the wiki does not allow anonymous users to read it, the mode set here
828 * will be ignored, and private caching headers will always be sent. In other words,
829 * the "public" mode is equivalent to saying that the data sent is as public as a page
830 * view.
831 *
832 * For user-dependent data, the private mode should generally be used. The
833 * anon-public-user-private mode should only be used where there is a particularly
834 * good performance reason for caching the anonymous response, but where the
835 * response to logged-in users may differ, or may contain private data.
836 *
837 * If this function is never called, then the default will be the private mode.
838 */
839 public function setCacheMode( $mode ) {
840 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
841 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
842
843 // Ignore for forwards-compatibility
844 return;
845 }
846
847 if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
848 // Private wiki, only private headers
849 if ( $mode !== 'private' ) {
850 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
851
852 return;
853 }
854 }
855
856 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
857 // User language is used for i18n, so we don't want to publicly
858 // cache. Anons are ok, because if they have non-default language
859 // then there's an appropriate Vary header set by whatever set
860 // their non-default language.
861 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
862 "'anon-public-user-private' due to uselang=user" );
863 $mode = 'anon-public-user-private';
864 }
865
866 wfDebug( __METHOD__ . ": setting cache mode $mode" );
867 $this->mCacheMode = $mode;
868 }
869
870 public function getCacheMode() {
871 return $this->mCacheMode;
872 }
873
874 /**
875 * Set directives (key/value pairs) for the Cache-Control header.
876 * Boolean values will be formatted as such, by including or omitting
877 * without an equals sign.
878 *
879 * Cache control values set here will only be used if the cache mode is not
880 * private, see setCacheMode().
881 *
882 * @param array $directives
883 */
884 public function setCacheControl( $directives ) {
885 $this->mCacheControl = $directives + $this->mCacheControl;
886 }
887
888 /**
889 * Create an instance of an output formatter by its name
890 *
891 * @param string $format
892 *
893 * @return ApiFormatBase
894 */
895 public function createPrinterByName( $format ) {
896 $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
897 if ( $printer === null ) {
898 $this->dieWithError(
899 [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
900 );
901 }
902
903 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
904 return $printer;
905 }
906
907 /**
908 * Execute api request. Any errors will be handled if the API was called by the remote client.
909 */
910 public function execute() {
911 if ( $this->mInternalMode ) {
912 $this->executeAction();
913 } else {
914 $this->executeActionWithErrorHandling();
915 }
916 }
917
918 /**
919 * Execute an action, and in case of an error, erase whatever partial results
920 * have been accumulated, and replace it with an error message and a help screen.
921 */
922 protected function executeActionWithErrorHandling() {
923 // Verify the CORS header before executing the action
924 if ( !$this->handleCORS() ) {
925 // handleCORS() has sent a 403, abort
926 return;
927 }
928
929 // Exit here if the request method was OPTIONS
930 // (assume there will be a followup GET or POST)
931 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
932 return;
933 }
934
935 // In case an error occurs during data output,
936 // clear the output buffer and print just the error information
937 $obLevel = ob_get_level();
938 ob_start();
939
940 $t = microtime( true );
941 $isError = false;
942 try {
943 $this->executeAction();
944 $runTime = microtime( true ) - $t;
945 $this->logRequest( $runTime );
946
947 $this->statsFactory->getTiming( 'api_executeTiming_seconds' )
948 ->setLabel( 'module', $this->mModule->getModuleName() )
949 ->copyToStatsdAt( 'api.' . $this->mModule->getModuleName() . '.executeTiming' )
950 ->observe( 1000 * $runTime );
951 } catch ( Throwable $e ) {
952 $this->handleException( $e );
953 $this->logRequest( microtime( true ) - $t, $e );
954 $isError = true;
955 }
956
957 // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
958 // as part of MediaWiki::preOutputCommit().
959 if (
960 $this->mCacheMode === 'private'
961 || (
962 $this->mCacheMode === 'anon-public-user-private'
963 && SessionManager::getGlobalSession()->isPersistent()
964 )
965 ) {
966 $this->getContext()->getOutput()->disableClientCache();
967 $this->getContext()->getOutput()->considerCacheSettingsFinal();
968 }
969
970 // Commit DBs and send any related cookies and headers
971 MediaWiki::preOutputCommit( $this->getContext() );
972
973 // Send cache headers after any code which might generate an error, to
974 // avoid sending public cache headers for errors.
975 $this->sendCacheHeaders( $isError );
976
977 // Executing the action might have already messed with the output
978 // buffers.
979 while ( ob_get_level() > $obLevel ) {
980 ob_end_flush();
981 }
982 }
983
984 /**
985 * Handle a throwable as an API response
986 *
987 * @since 1.23
988 * @param Throwable $e
989 */
990 protected function handleException( Throwable $e ) {
991 // T65145: Rollback any open database transactions
992 if ( !$e instanceof ApiUsageException ) {
993 // ApiUsageExceptions are intentional, so don't rollback if that's the case
994 MWExceptionHandler::rollbackPrimaryChangesAndLog(
995 $e,
996 MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
997 );
998 }
999
1000 // Allow extra cleanup and logging
1001 $this->getHookRunner()->onApiMain__onException( $this, $e );
1002
1003 // Handle any kind of exception by outputting properly formatted error message.
1004 // If this fails, an unhandled exception should be thrown so that global error
1005 // handler will process and log it.
1006
1007 $errCodes = $this->substituteResultWithError( $e );
1008
1009 // Error results should not be cached
1010 $this->setCacheMode( 'private' );
1011
1012 $response = $this->getRequest()->response();
1013 $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
1014 $response->header( $headerStr );
1015
1016 // Reset and print just the error message
1017 ob_clean();
1018
1019 // Printer may not be initialized if the extractRequestParams() fails for the main module
1020 $this->createErrorPrinter();
1021
1022 // Get desired HTTP code from an ApiUsageException. Don't use codes from other
1023 // exception types, as they are unlikely to be intended as an HTTP code.
1024 $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
1025
1026 $failed = false;
1027 try {
1028 $this->printResult( $httpCode );
1029 } catch ( ApiUsageException $ex ) {
1030 // The error printer itself is failing. Try suppressing its request
1031 // parameters and redo.
1032 $failed = true;
1033 $this->addWarning( 'apiwarn-errorprinterfailed' );
1034 foreach ( $ex->getStatusValue()->getMessages() as $error ) {
1035 try {
1036 $this->mPrinter->addWarning( $error );
1037 } catch ( Throwable $ex2 ) {
1038 // WTF?
1039 $this->addWarning( $error );
1040 }
1041 }
1042 }
1043 if ( $failed ) {
1044 $this->mPrinter = null;
1045 $this->createErrorPrinter();
1046 // @phan-suppress-next-line PhanNonClassMethodCall False positive
1047 $this->mPrinter->forceDefaultParams();
1048 if ( $httpCode ) {
1049 $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
1050 }
1051 $this->printResult( $httpCode );
1052 }
1053 }
1054
1055 /**
1056 * Handle a throwable from the ApiBeforeMain hook.
1057 *
1058 * This tries to print the throwable as an API response, to be more
1059 * friendly to clients. If it fails, it will rethrow the throwable.
1060 *
1061 * @since 1.23
1062 * @param Throwable $e
1063 * @throws Throwable
1064 */
1065 public static function handleApiBeforeMainException( Throwable $e ) {
1066 ob_start();
1067
1068 try {
1069 $main = new self( RequestContext::getMain(), false );
1070 $main->handleException( $e );
1071 $main->logRequest( 0, $e );
1072 } catch ( Throwable $e2 ) {
1073 // Nope, even that didn't work. Punt.
1074 throw $e;
1075 }
1076
1077 // Reset cache headers
1078 $main->sendCacheHeaders( true );
1079
1080 ob_end_flush();
1081 }
1082
1083 /**
1084 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
1085 *
1086 * If no origin parameter is present, nothing happens.
1087 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
1088 * is set and false is returned.
1089 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
1090 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
1091 * headers are set.
1092 * https://www.w3.org/TR/cors/#resource-requests
1093 * https://www.w3.org/TR/cors/#resource-preflight-requests
1094 *
1095 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
1096 */
1097 protected function handleCORS() {
1098 $originParam = $this->getParameter( 'origin' ); // defaults to null
1099 if ( $originParam === null ) {
1100 // No origin parameter, nothing to do
1101 return true;
1102 }
1103
1104 $request = $this->getRequest();
1105 $response = $request->response();
1106
1107 $allowTiming = false;
1108 $varyOrigin = true;
1109
1110 if ( $originParam === '*' ) {
1111 // Request for anonymous CORS
1112 // Technically we should check for the presence of an Origin header
1113 // and not process it as CORS if it's not set, but that would
1114 // require us to vary on Origin for all 'origin=*' requests which
1115 // we don't want to do.
1116 $matchedOrigin = true;
1117 $allowOrigin = '*';
1118 $allowCredentials = 'false';
1119 $varyOrigin = false; // No need to vary
1120 } else {
1121 // Non-anonymous CORS, check we allow the domain
1122
1123 // Origin: header is a space-separated list of origins, check all of them
1124 $originHeader = $request->getHeader( 'Origin' );
1125 if ( $originHeader === false ) {
1126 $origins = [];
1127 } else {
1128 $originHeader = trim( $originHeader );
1129 $origins = preg_split( '/\s+/', $originHeader );
1130 }
1131
1132 if ( !in_array( $originParam, $origins ) ) {
1133 // origin parameter set but incorrect
1134 // Send a 403 response
1135 $response->statusHeader( 403 );
1136 $response->header( 'Cache-Control: no-cache' );
1137 echo "'origin' parameter does not match Origin header\n";
1138
1139 return false;
1140 }
1141
1142 $config = $this->getConfig();
1143 $origin = Origin::parseHeaderList( $origins );
1144 $matchedOrigin = $origin->match(
1145 $config->get( MainConfigNames::CrossSiteAJAXdomains ),
1146 $config->get( MainConfigNames::CrossSiteAJAXdomainExceptions )
1147 );
1148
1149 $allowOrigin = $originHeader;
1150 $allowCredentials = 'true';
1151 $allowTiming = $originHeader;
1152 }
1153
1154 if ( $matchedOrigin ) {
1155 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
1156 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
1157 if ( $preflight ) {
1158 // We allow the actual request to send the following headers
1159 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
1160 $allowedHeaders = $this->getConfig()->get( MainConfigNames::AllowedCorsHeaders );
1161 if ( $requestedHeaders !== false ) {
1162 if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
1163 $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
1164 return true;
1165 }
1166 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
1167 }
1168
1169 // We only allow the actual request to be GET, POST, or HEAD
1170 $response->header( 'Access-Control-Allow-Methods: POST, GET, HEAD' );
1171 }
1172
1173 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
1174 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
1175 // https://www.w3.org/TR/resource-timing/#timing-allow-origin
1176 if ( $allowTiming !== false ) {
1177 $response->header( "Timing-Allow-Origin: $allowTiming" );
1178 }
1179
1180 if ( !$preflight ) {
1181 $response->header(
1182 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
1183 . 'MediaWiki-Login-Suppressed'
1184 );
1185 }
1186 } else {
1187 $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
1188 }
1189
1190 if ( $varyOrigin ) {
1191 $this->getOutput()->addVaryHeader( 'Origin' );
1192 }
1193
1194 return true;
1195 }
1196
1197 /**
1198 * Attempt to validate the value of Access-Control-Request-Headers against a list
1199 * of headers that we allow the follow up request to send.
1200 *
1201 * @param string $requestedHeaders Comma separated list of HTTP headers
1202 * @param string[] $allowedHeaders List of allowed HTTP headers
1203 * @return bool True if all requested headers are in the list of allowed headers
1204 */
1205 protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
1206 if ( trim( $requestedHeaders ) === '' ) {
1207 return true;
1208 }
1209 $requestedHeaders = explode( ',', $requestedHeaders );
1210 $allowedHeaders = array_change_key_case(
1211 array_fill_keys( $allowedHeaders, true ), CASE_LOWER );
1212 foreach ( $requestedHeaders as $rHeader ) {
1213 $rHeader = strtolower( trim( $rHeader ) );
1214 if ( !isset( $allowedHeaders[$rHeader] ) ) {
1215 LoggerFactory::getInstance( 'api-warning' )->warning(
1216 'CORS preflight failed on requested header: {header}', [
1217 'header' => $rHeader
1218 ]
1219 );
1220 return false;
1221 }
1222 }
1223 return true;
1224 }
1225
1226 /**
1227 * Send caching headers
1228 * @param bool $isError Whether an error response is being output
1229 * @since 1.26 added $isError parameter
1230 */
1231 protected function sendCacheHeaders( $isError ) {
1232 $response = $this->getRequest()->response();
1233 $out = $this->getOutput();
1234
1235 $out->addVaryHeader( 'Treat-as-Untrusted' );
1236
1237 $config = $this->getConfig();
1238
1239 if ( $config->get( MainConfigNames::VaryOnXFP ) ) {
1240 $out->addVaryHeader( 'X-Forwarded-Proto' );
1241 }
1242
1243 if ( !$isError && $this->mModule &&
1244 ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
1245 ) {
1246 $etag = $this->mModule->getConditionalRequestData( 'etag' );
1247 if ( $etag !== null ) {
1248 $response->header( "ETag: $etag" );
1249 }
1250 $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
1251 if ( $lastMod !== null ) {
1252 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
1253 }
1254 }
1255
1256 // The logic should be:
1257 // $this->mCacheControl['max-age'] is set?
1258 // Use it, the module knows better than our guess.
1259 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
1260 // Use 0 because we can guess caching is probably the wrong thing to do.
1261 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
1262 $maxage = 0;
1263 if ( isset( $this->mCacheControl['max-age'] ) ) {
1264 $maxage = $this->mCacheControl['max-age'];
1265 } elseif ( ( !$isError && $this->mModule && !$this->mModule->isWriteMode() ) ||
1266 $this->mCacheMode !== 'private'
1267 ) {
1268 $maxage = $this->getParameter( 'maxage' );
1269 }
1270 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
1271
1272 if ( $this->mCacheMode == 'private' ) {
1273 $response->header( "Cache-Control: $privateCache" );
1274 return;
1275 }
1276
1277 if ( $this->mCacheMode == 'anon-public-user-private' ) {
1278 $out->addVaryHeader( 'Cookie' );
1279 $response->header( $out->getVaryHeader() );
1280 if ( SessionManager::getGlobalSession()->isPersistent() ) {
1281 // Logged in or otherwise has session (e.g. anonymous users who have edited)
1282 // Mark request private
1283 $response->header( "Cache-Control: $privateCache" );
1284
1285 return;
1286 } // else anonymous, send public headers below
1287 }
1288
1289 // Send public headers
1290 $response->header( $out->getVaryHeader() );
1291
1292 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
1293 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
1294 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
1295 }
1296 if ( !isset( $this->mCacheControl['max-age'] ) ) {
1297 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
1298 }
1299
1300 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
1301 // Public cache not requested
1302 // Sending a Vary header in this case is harmless, and protects us
1303 // against conditional calls of setCacheMaxAge().
1304 $response->header( "Cache-Control: $privateCache" );
1305
1306 return;
1307 }
1308
1309 $this->mCacheControl['public'] = true;
1310
1311 // Send an Expires header
1312 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
1313 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
1314 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
1315
1316 // Construct the Cache-Control header
1317 $ccHeader = '';
1318 $separator = '';
1319 foreach ( $this->mCacheControl as $name => $value ) {
1320 if ( is_bool( $value ) ) {
1321 if ( $value ) {
1322 $ccHeader .= $separator . $name;
1323 $separator = ', ';
1324 }
1325 } else {
1326 $ccHeader .= $separator . "$name=$value";
1327 $separator = ', ';
1328 }
1329 }
1330
1331 $response->header( "Cache-Control: $ccHeader" );
1332 }
1333
1334 /**
1335 * Create the printer for error output
1336 */
1337 private function createErrorPrinter() {
1338 if ( !isset( $this->mPrinter ) ) {
1339 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
1340 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
1341 $value = self::API_DEFAULT_FORMAT;
1342 }
1343 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable getVal does not return null here
1344 $this->mPrinter = $this->createPrinterByName( $value );
1345 }
1346
1347 // Printer may not be able to handle errors. This is particularly
1348 // likely if the module returns something for getCustomPrinter().
1349 if ( !$this->mPrinter->canPrintErrors() ) {
1350 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1351 }
1352 }
1353
1354 /**
1355 * Create an error message for the given throwable.
1356 *
1357 * If an ApiUsageException, errors/warnings will be extracted from the
1358 * embedded StatusValue.
1359 *
1360 * Any other throwable will be returned with a generic code and wrapper
1361 * text around the throwable's (presumably English) message as a single
1362 * error (no warnings).
1363 *
1364 * @param Throwable $e
1365 * @param string $type 'error' or 'warning'
1366 * @return ApiMessage[]
1367 * @since 1.27
1368 */
1369 protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1370 $messages = [];
1371 if ( $e instanceof ApiUsageException ) {
1372 foreach ( $e->getStatusValue()->getMessages( $type ) as $msg ) {
1373 $messages[] = ApiMessage::create( $msg );
1374 }
1375 } elseif ( $type !== 'error' ) {
1376 // None of the rest have any messages for non-error types
1377 } else {
1378 // TODO: Avoid embedding arbitrary class names in the error code.
1379 $class = preg_replace( '#^Wikimedia\\\\Rdbms\\\\#', '', get_class( $e ) );
1380 $code = 'internal_api_error_' . $class;
1381 $data = [ 'errorclass' => get_class( $e ) ];
1382 if ( MWExceptionRenderer::shouldShowExceptionDetails() ) {
1383 if ( $e instanceof ILocalizedException ) {
1384 $msg = $e->getMessageObject();
1385 } elseif ( $e instanceof MessageSpecifier ) {
1386 $msg = Message::newFromSpecifier( $e );
1387 } else {
1388 $msg = wfEscapeWikiText( $e->getMessage() );
1389 }
1390 $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1391 } else {
1392 $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1393 }
1394
1395 $messages[] = ApiMessage::create( $params, $code, $data );
1396 }
1397 return $messages;
1398 }
1399
1400 /**
1401 * Replace the result data with the information about a throwable.
1402 * @param Throwable $e
1403 * @return string[] Error codes
1404 */
1405 protected function substituteResultWithError( Throwable $e ) {
1406 $result = $this->getResult();
1407 $formatter = $this->getErrorFormatter();
1408 $config = $this->getConfig();
1409 $errorCodes = [];
1410
1411 // Remember existing warnings and errors across the reset
1412 $errors = $result->getResultData( [ 'errors' ] );
1413 $warnings = $result->getResultData( [ 'warnings' ] );
1414 $result->reset();
1415 if ( $warnings !== null ) {
1416 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1417 }
1418 if ( $errors !== null ) {
1419 $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1420
1421 // Collect the copied error codes for the return value
1422 foreach ( $errors as $error ) {
1423 if ( isset( $error['code'] ) ) {
1424 $errorCodes[$error['code']] = true;
1425 }
1426 }
1427 }
1428
1429 // Add errors from the exception
1430 $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1431 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1432 if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1433 $errorCodes[$msg->getApiCode()] = true;
1434 } else {
1435 LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1436 'code' => $msg->getApiCode(),
1437 'exception' => $e,
1438 ] );
1439 $errorCodes['<invalid-code>'] = true;
1440 }
1441 $formatter->addError( $modulePath, $msg );
1442 }
1443 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1444 $formatter->addWarning( $modulePath, $msg );
1445 }
1446
1447 // Add additional data. Path depends on whether we're in BC mode or not.
1448 // Data depends on the type of exception.
1449 if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1450 $path = [ 'error' ];
1451 } else {
1452 $path = null;
1453 }
1454 if ( $e instanceof ApiUsageException ) {
1455 $link = (string)MediaWikiServices::getInstance()->getUrlUtils()->expand( wfScript( 'api' ) );
1456 $result->addContentValue(
1457 $path,
1458 'docref',
1459 trim(
1460 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1461 . ' '
1462 . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1463 )
1464 );
1465 } elseif ( $config->get( MainConfigNames::ShowExceptionDetails ) ) {
1466 $result->addContentValue(
1467 $path,
1468 'trace',
1469 $this->msg( 'api-exception-trace',
1470 get_class( $e ),
1471 $e->getFile(),
1472 $e->getLine(),
1473 MWExceptionHandler::getRedactedTraceAsString( $e )
1474 )->inLanguage( $formatter->getLanguage() )->text()
1475 );
1476 }
1477
1478 // Add the id and such
1479 $this->addRequestedFields( [ 'servedby' ] );
1480
1481 return array_keys( $errorCodes );
1482 }
1483
1484 /**
1485 * Add requested fields to the result
1486 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1487 * - servedby
1488 */
1489 protected function addRequestedFields( $force = [] ) {
1490 $result = $this->getResult();
1491
1492 $requestid = $this->getParameter( 'requestid' );
1493 if ( $requestid !== null ) {
1494 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1495 }
1496
1497 if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) && (
1498 in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1499 ) ) {
1500 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1501 }
1502
1503 if ( $this->getParameter( 'curtimestamp' ) ) {
1504 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1505 }
1506
1507 if ( $this->getParameter( 'responselanginfo' ) ) {
1508 $result->addValue(
1509 null,
1510 'uselang',
1511 $this->getLanguage()->getCode(),
1512 ApiResult::NO_SIZE_CHECK
1513 );
1514 $result->addValue(
1515 null,
1516 'errorlang',
1517 $this->getErrorFormatter()->getLanguage()->getCode(),
1518 ApiResult::NO_SIZE_CHECK
1519 );
1520 }
1521 }
1522
1523 /**
1524 * Set up for the execution.
1525 * @return array
1526 */
1527 protected function setupExecuteAction() {
1528 $this->addRequestedFields();
1529
1530 $params = $this->extractRequestParams();
1531 $this->mAction = $params['action'];
1532
1533 return $params;
1534 }
1535
1536 /**
1537 * Set up the module for response
1538 * @return ApiBase The module that will handle this action
1539 * @throws ApiUsageException
1540 */
1541 protected function setupModule() {
1542 // Instantiate the module requested by the user
1543 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1544 if ( $module === null ) {
1545 // Probably can't happen
1546 // @codeCoverageIgnoreStart
1547 $this->dieWithError(
1548 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ],
1549 'unknown_action'
1550 );
1551 // @codeCoverageIgnoreEnd
1552 }
1553 $moduleParams = $module->extractRequestParams();
1554
1555 // Check token, if necessary
1556 if ( $module->needsToken() === true ) {
1557 throw new LogicException(
1558 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1559 'See documentation for ApiBase::needsToken for details.'
1560 );
1561 }
1562 if ( $module->needsToken() ) {
1563 if ( !$module->mustBePosted() ) {
1564 throw new LogicException(
1565 "Module '{$module->getModuleName()}' must require POST to use tokens."
1566 );
1567 }
1568
1569 if ( !isset( $moduleParams['token'] ) ) {
1570 // Probably can't happen
1571 // @codeCoverageIgnoreStart
1572 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1573 // @codeCoverageIgnoreEnd
1574 }
1575
1576 $module->requirePostedParameters( [ 'token' ] );
1577
1578 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1579 $module->dieWithError( 'apierror-badtoken' );
1580 }
1581 }
1582
1583 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
1584 return $module;
1585 }
1586
1587 /**
1588 * @return array
1589 */
1590 private function getMaxLag() {
1591 $services = MediaWikiServices::getInstance();
1592 $dbLag = $services->getDBLoadBalancer()->getMaxLag();
1593 $lagInfo = [
1594 'host' => $dbLag[0],
1595 'lag' => $dbLag[1],
1596 'type' => 'db'
1597 ];
1598
1599 $jobQueueLagFactor =
1600 $this->getConfig()->get( MainConfigNames::JobQueueIncludeInMaxLagFactor );
1601 if ( $jobQueueLagFactor ) {
1602 // Turn total number of jobs into seconds by using the configured value
1603 $totalJobs = array_sum( $services->getJobQueueGroup()->getQueueSizes() );
1604 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1605 if ( $jobQueueLag > $lagInfo['lag'] ) {
1606 $lagInfo = [
1607 'host' => wfHostname(), // XXX: Is there a better value that could be used?
1608 'lag' => $jobQueueLag,
1609 'type' => 'jobqueue',
1610 'jobs' => $totalJobs,
1611 ];
1612 }
1613 }
1614
1615 $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1616
1617 return $lagInfo;
1618 }
1619
1620 /**
1621 * Check the max lag if necessary
1622 * @param ApiBase $module Api module being used
1623 * @param array $params Array an array containing the request parameters.
1624 * @return bool True on success, false should exit immediately
1625 */
1626 protected function checkMaxLag( $module, $params ) {
1627 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1628 $maxLag = $params['maxlag'];
1629 $lagInfo = $this->getMaxLag();
1630 if ( $lagInfo['lag'] > $maxLag ) {
1631 $response = $this->getRequest()->response();
1632
1633 $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1634 $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1635
1636 if ( $this->getConfig()->get( MainConfigNames::ShowHostnames ) ) {
1637 $this->dieWithError(
1638 [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1639 'maxlag',
1640 $lagInfo
1641 );
1642 }
1643
1644 $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1645 }
1646 }
1647
1648 return true;
1649 }
1650
1651 /**
1652 * Check selected RFC 7232 precondition headers
1653 *
1654 * RFC 7232 envisions a particular model where you send your request to "a
1655 * resource", and for write requests that you can read "the resource" by
1656 * changing the method to GET. When the API receives a GET request, it
1657 * works out even though "the resource" from RFC 7232's perspective might
1658 * be many resources from MediaWiki's perspective. But it totally fails for
1659 * a POST, since what HTTP sees as "the resource" is probably just
1660 * "/api.php" with all the interesting bits in the body.
1661 *
1662 * Therefore, we only support RFC 7232 precondition headers for GET (and
1663 * HEAD). That means we don't need to bother with If-Match and
1664 * If-Unmodified-Since since they only apply to modification requests.
1665 *
1666 * And since we don't support Range, If-Range is ignored too.
1667 *
1668 * @since 1.26
1669 * @param ApiBase $module Api module being used
1670 * @return bool True on success, false should exit immediately
1671 */
1672 protected function checkConditionalRequestHeaders( $module ) {
1673 if ( $this->mInternalMode ) {
1674 // No headers to check in internal mode
1675 return true;
1676 }
1677
1678 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1679 // Don't check POSTs
1680 return true;
1681 }
1682
1683 $return304 = false;
1684
1685 $ifNoneMatch = array_diff(
1686 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1687 [ '' ]
1688 );
1689 if ( $ifNoneMatch ) {
1690 // @phan-suppress-next-line PhanImpossibleTypeComparison
1691 if ( $ifNoneMatch === [ '*' ] ) {
1692 // API responses always "exist"
1693 $etag = '*';
1694 } else {
1695 $etag = $module->getConditionalRequestData( 'etag' );
1696 }
1697 }
1698 // @phan-suppress-next-line PhanPossiblyUndeclaredVariable $etag is declared when $ifNoneMatch is true
1699 if ( $ifNoneMatch && $etag !== null ) {
1700 $test = str_starts_with( $etag, 'W/' ) ? substr( $etag, 2 ) : $etag;
1701 $match = array_map( static function ( $s ) {
1702 return str_starts_with( $s, 'W/' ) ? substr( $s, 2 ) : $s;
1703 }, $ifNoneMatch );
1704 $return304 = in_array( $test, $match, true );
1705 } else {
1706 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1707
1708 // Some old browsers sends sizes after the date, like this:
1709 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1710 // Ignore that.
1711 $i = strpos( $value, ';' );
1712 if ( $i !== false ) {
1713 $value = trim( substr( $value, 0, $i ) );
1714 }
1715
1716 if ( $value !== '' ) {
1717 try {
1718 $ts = new MWTimestamp( $value );
1719 if (
1720 // RFC 7231 IMF-fixdate
1721 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1722 // RFC 850
1723 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1724 // asctime (with and without space-padded day)
1725 $ts->format( 'D M j H:i:s Y' ) === $value ||
1726 $ts->format( 'D M j H:i:s Y' ) === $value
1727 ) {
1728 $config = $this->getConfig();
1729 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1730 if ( $lastMod !== null ) {
1731 // Mix in some MediaWiki modification times
1732 $modifiedTimes = [
1733 'page' => $lastMod,
1734 'user' => $this->getUser()->getTouched(),
1735 'epoch' => $config->get( MainConfigNames::CacheEpoch ),
1736 ];
1737
1738 if ( $config->get( MainConfigNames::UseCdn ) ) {
1739 // T46570: the core page itself may not change, but resources might
1740 $modifiedTimes['sepoch'] = wfTimestamp(
1741 TS_MW, time() - $config->get( MainConfigNames::CdnMaxAge )
1742 );
1743 }
1744 $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1745 $lastMod = max( $modifiedTimes );
1746 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1747 }
1748 }
1749 } catch ( TimestampException $e ) {
1750 // Invalid timestamp, ignore it
1751 }
1752 }
1753 }
1754
1755 if ( $return304 ) {
1756 $this->getRequest()->response()->statusHeader( 304 );
1757
1758 // Avoid outputting the compressed representation of a zero-length body
1759 AtEase::suppressWarnings();
1760 ini_set( 'zlib.output_compression', 0 );
1761 AtEase::restoreWarnings();
1762 wfResetOutputBuffers( false );
1763
1764 return false;
1765 }
1766
1767 return true;
1768 }
1769
1770 /**
1771 * Check for sufficient permissions to execute
1772 * @param ApiBase $module An Api module
1773 */
1774 protected function checkExecutePermissions( $module ) {
1775 $user = $this->getUser();
1776 if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1777 !$this->getAuthority()->isAllowed( 'read' )
1778 ) {
1779 $this->dieWithError( 'apierror-readapidenied' );
1780 }
1781
1782 if ( $module->isWriteMode() ) {
1783 if ( !$this->mEnableWrite ) {
1784 $this->dieWithError( 'apierror-noapiwrite' );
1785 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1786 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1787 }
1788
1789 $this->checkReadOnly( $module );
1790 }
1791
1792 // Allow extensions to stop execution for arbitrary reasons.
1793 // TODO: change hook to accept Authority
1794 $message = 'hookaborted';
1795 if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1796 $this->dieWithError( $message );
1797 }
1798 }
1799
1800 /**
1801 * Check if the DB is read-only for this user
1802 * @param ApiBase $module An Api module
1803 */
1804 protected function checkReadOnly( $module ) {
1805 if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1806 $this->dieReadOnly();
1807 }
1808
1809 if ( $module->isWriteMode()
1810 && $this->getUser()->isBot()
1811 && MediaWikiServices::getInstance()->getDBLoadBalancer()->hasReplicaServers()
1812 ) {
1813 $this->checkBotReadOnly();
1814 }
1815 }
1816
1817 /**
1818 * Check whether we are readonly for bots
1819 */
1820 private function checkBotReadOnly() {
1821 // Figure out how many servers have passed the lag threshold
1822 $numLagged = 0;
1823 $lagLimit = $this->getConfig()->get( MainConfigNames::APIMaxLagThreshold );
1824 $laggedServers = [];
1825 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1826 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1827 if ( $lag > $lagLimit ) {
1828 ++$numLagged;
1829 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1830 }
1831 }
1832
1833 // If a majority of replica DBs are too lagged then disallow writes
1834 $replicaCount = $loadBalancer->getServerCount() - 1;
1835 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1836 $laggedServers = implode( ', ', $laggedServers );
1837 wfDebugLog(
1838 'api-readonly', // Deprecate this channel in favor of api-warning?
1839 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1840 );
1841 LoggerFactory::getInstance( 'api-warning' )->warning(
1842 "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1843 'laggeddbs' => $laggedServers,
1844 ]
1845 );
1846
1847 $this->dieWithError(
1848 'readonly_lag',
1849 'readonly',
1850 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1851 );
1852 }
1853 }
1854
1855 /**
1856 * Check asserts of the user's rights
1857 * @param array $params
1858 */
1859 protected function checkAsserts( $params ) {
1860 if ( isset( $params['assert'] ) ) {
1861 $user = $this->getUser();
1862 switch ( $params['assert'] ) {
1863 case 'anon':
1864 if ( $user->isRegistered() ) {
1865 $this->dieWithError( 'apierror-assertanonfailed' );
1866 }
1867 break;
1868 case 'user':
1869 if ( !$user->isRegistered() ) {
1870 $this->dieWithError( 'apierror-assertuserfailed' );
1871 }
1872 break;
1873 case 'bot':
1874 if ( !$this->getAuthority()->isAllowed( 'bot' ) ) {
1875 $this->dieWithError( 'apierror-assertbotfailed' );
1876 }
1877 break;
1878 }
1879 }
1880 if ( isset( $params['assertuser'] ) ) {
1881 // TODO inject stuff, see T265644
1882 $assertUser = MediaWikiServices::getInstance()->getUserFactory()
1883 ->newFromName( $params['assertuser'], UserRigorOptions::RIGOR_NONE );
1884 if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1885 $this->dieWithError(
1886 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1887 );
1888 }
1889 }
1890 }
1891
1892 /**
1893 * Check POST for external response and setup result printer
1894 * @param ApiBase $module An Api module
1895 * @param array $params An array with the request parameters
1896 */
1897 protected function setupExternalResponse( $module, $params ) {
1898 $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1899 $request = $this->getRequest();
1900
1901 if ( !in_array( $request->getMethod(), $validMethods ) ) {
1902 $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1903 }
1904
1905 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1906 // Module requires POST. GET request might still be allowed
1907 // if $wgDebugApi is true, otherwise fail.
1908 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1909 }
1910
1911 if ( $request->wasPosted() ) {
1912 if ( !$request->getHeader( 'Content-Type' ) ) {
1913 $this->addDeprecation(
1914 'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1915 );
1916 }
1917 $contentLength = $request->getHeader( 'Content-Length' );
1918 $maxPostSize = wfShorthandToInteger( ini_get( 'post_max_size' ), 0 );
1919 if ( $maxPostSize && $contentLength > $maxPostSize ) {
1920 $this->dieWithError(
1921 [ 'apierror-http-contenttoolarge', Message::sizeParam( $maxPostSize ) ],
1922 null, null, 413
1923 );
1924 }
1925 }
1926
1927 // See if custom printer is used
1928 $this->mPrinter = $module->getCustomPrinter() ??
1929 // Create an appropriate printer if not set
1930 $this->createPrinterByName( $params['format'] );
1931
1932 if ( $request->getProtocol() === 'http' &&
1933 (
1934 $this->getConfig()->get( MainConfigNames::ForceHTTPS ) ||
1935 $request->getSession()->shouldForceHTTPS() ||
1936 $this->getUser()->requiresHTTPS()
1937 )
1938 ) {
1939 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1940 }
1941 }
1942
1943 /**
1944 * Execute the actual module, without any error handling
1945 */
1946 protected function executeAction() {
1947 $params = $this->setupExecuteAction();
1948
1949 // Check asserts early so e.g. errors in parsing a module's parameters due to being
1950 // logged out don't override the client's intended "am I logged in?" check.
1951 $this->checkAsserts( $params );
1952
1953 $module = $this->setupModule();
1954 $this->mModule = $module;
1955
1956 if ( !$this->mInternalMode ) {
1957 ProfilingContext::singleton()->init( MW_ENTRY_POINT, $module->getModuleName() );
1958 $this->setRequestExpectations( $module );
1959 }
1960
1961 $this->checkExecutePermissions( $module );
1962
1963 if ( !$this->checkMaxLag( $module, $params ) ) {
1964 return;
1965 }
1966
1967 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1968 return;
1969 }
1970
1971 if ( !$this->mInternalMode ) {
1972 $this->setupExternalResponse( $module, $params );
1973 }
1974
1975 $module->execute();
1976 $this->getHookRunner()->onAPIAfterExecute( $module );
1977
1978 $this->reportUnusedParams();
1979
1980 if ( !$this->mInternalMode ) {
1981 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1982
1983 $this->printResult();
1984 }
1985 }
1986
1987 /**
1988 * Set database connection, query, and write expectations given this module request
1989 * @param ApiBase $module
1990 */
1991 protected function setRequestExpectations( ApiBase $module ) {
1992 $request = $this->getRequest();
1993
1994 $trxLimits = $this->getConfig()->get( MainConfigNames::TrxProfilerLimits );
1995 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1996 $trxProfiler->setLogger( LoggerFactory::getInstance( 'rdbms' ) );
1997 $trxProfiler->setStatsFactory( MediaWikiServices::getInstance()->getStatsFactory() );
1998 $trxProfiler->setRequestMethod( $request->getMethod() );
1999 if ( $request->hasSafeMethod() ) {
2000 $trxProfiler->setExpectations( $trxLimits['GET'], __METHOD__ );
2001 } elseif ( $request->wasPosted() && !$module->isWriteMode() ) {
2002 $trxProfiler->setExpectations( $trxLimits['POST-nonwrite'], __METHOD__ );
2003 } else {
2004 $trxProfiler->setExpectations( $trxLimits['POST'], __METHOD__ );
2005 }
2006 }
2007
2008 /**
2009 * Log the preceding request
2010 * @param float $time Time in seconds
2011 * @param Throwable|null $e Throwable caught while processing the request
2012 */
2013 protected function logRequest( $time, ?Throwable $e = null ) {
2014 $request = $this->getRequest();
2015
2016 $user = $this->getUser();
2017 $performer = [
2018 'user_text' => $user->getName(),
2019 ];
2020 if ( $user->isRegistered() ) {
2021 $performer['user_id'] = $user->getId();
2022 }
2023 $logCtx = [
2024 // https://gerrit.wikimedia.org/g/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
2025 '$schema' => '/mediawiki/api/request/1.0.0',
2026 'meta' => [
2027 'request_id' => WebRequest::getRequestId(),
2028 'id' => MediaWikiServices::getInstance()
2029 ->getGlobalIdGenerator()->newUUIDv4(),
2030 'dt' => wfTimestamp( TS_ISO_8601 ),
2031 'domain' => $this->getConfig()->get( MainConfigNames::ServerName ),
2032 // If using the EventBus extension (as intended) with this log channel,
2033 // this stream name will map to a Kafka topic.
2034 'stream' => 'mediawiki.api-request'
2035 ],
2036 'http' => [
2037 'method' => $request->getMethod(),
2038 'client_ip' => $request->getIP()
2039 ],
2040 'performer' => $performer,
2041 'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
2042 'backend_time_ms' => (int)round( $time * 1000 ),
2043 ];
2044
2045 // If set, these headers will be logged in http.request_headers.
2046 $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
2047 foreach ( $httpRequestHeadersToLog as $header ) {
2048 if ( $request->getHeader( $header ) ) {
2049 // Set the header in http.request_headers
2050 $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
2051 }
2052 }
2053
2054 if ( $e ) {
2055 $logCtx['api_error_codes'] = [];
2056 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
2057 $logCtx['api_error_codes'][] = $msg->getApiCode();
2058 }
2059 }
2060
2061 // Construct space separated message for 'api' log channel
2062 $msg = "API {$request->getMethod()} " .
2063 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
2064 " {$logCtx['http']['client_ip']} " .
2065 "T={$logCtx['backend_time_ms']}ms";
2066
2067 $sensitive = array_fill_keys( $this->getSensitiveParams(), true );
2068 foreach ( $this->getParamsUsed() as $name ) {
2069 $value = $request->getVal( $name );
2070 if ( $value === null ) {
2071 continue;
2072 }
2073
2074 if ( isset( $sensitive[$name] ) ) {
2075 $value = '[redacted]';
2076 $encValue = '[redacted]';
2077 } elseif ( strlen( $value ) > 256 ) {
2078 $value = substr( $value, 0, 256 );
2079 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
2080 } else {
2081 $encValue = $this->encodeRequestLogValue( $value );
2082 }
2083
2084 $logCtx['params'][$name] = $value;
2085 $msg .= " {$name}={$encValue}";
2086 }
2087
2088 // Log an unstructured message to the api channel.
2089 wfDebugLog( 'api', $msg, 'private' );
2090
2091 // The api-request channel a structured data log channel.
2092 wfDebugLog( 'api-request', '', 'private', $logCtx );
2093 }
2094
2095 /**
2096 * Encode a value in a format suitable for a space-separated log line.
2097 * @param string $s
2098 * @return string
2099 */
2100 protected function encodeRequestLogValue( $s ) {
2101 static $table = [];
2102 if ( !$table ) {
2103 $chars = ';@$!*(),/:';
2104 $numChars = strlen( $chars );
2105 for ( $i = 0; $i < $numChars; $i++ ) {
2106 $table[rawurlencode( $chars[$i] )] = $chars[$i];
2107 }
2108 }
2109
2110 return strtr( rawurlencode( $s ), $table );
2111 }
2112
2113 /**
2114 * Get the request parameters used in the course of the preceding execute() request
2115 * @return array
2116 */
2117 protected function getParamsUsed() {
2118 return array_keys( $this->mParamsUsed );
2119 }
2120
2121 /**
2122 * Mark parameters as used
2123 * @param string|string[] $params
2124 */
2125 public function markParamsUsed( $params ) {
2126 $this->mParamsUsed += array_fill_keys( (array)$params, true );
2127 }
2128
2129 /**
2130 * Get the request parameters that should be considered sensitive
2131 * @since 1.29
2132 * @return array
2133 */
2134 protected function getSensitiveParams() {
2135 return array_keys( $this->mParamsSensitive );
2136 }
2137
2138 /**
2139 * Mark parameters as sensitive
2140 *
2141 * This is called automatically for you when declaring a parameter
2142 * with ApiBase::PARAM_SENSITIVE.
2143 *
2144 * @since 1.29
2145 * @param string|string[] $params
2146 */
2147 public function markParamsSensitive( $params ) {
2148 $this->mParamsSensitive += array_fill_keys( (array)$params, true );
2149 }
2150
2151 /**
2152 * Get a request value, and register the fact that it was used, for logging.
2153 * @param string $name
2154 * @param string|null $default
2155 * @return string|null
2156 */
2157 public function getVal( $name, $default = null ) {
2158 $this->mParamsUsed[$name] = true;
2159
2160 $ret = $this->getRequest()->getVal( $name );
2161 if ( $ret === null ) {
2162 if ( $this->getRequest()->getArray( $name ) !== null ) {
2163 // See T12262 for why we don't just implode( '|', ... ) the
2164 // array.
2165 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
2166 }
2167 $ret = $default;
2168 }
2169 return $ret;
2170 }
2171
2172 /**
2173 * Get a boolean request value, and register the fact that the parameter
2174 * was used, for logging.
2175 * @param string $name
2176 * @return bool
2177 */
2178 public function getCheck( $name ) {
2179 $this->mParamsUsed[$name] = true;
2180 return $this->getRequest()->getCheck( $name );
2181 }
2182
2183 /**
2184 * Get a request upload, and register the fact that it was used, for logging.
2185 *
2186 * @since 1.21
2187 * @param string $name Parameter name
2188 * @return WebRequestUpload
2189 */
2190 public function getUpload( $name ) {
2191 $this->mParamsUsed[$name] = true;
2192
2193 return $this->getRequest()->getUpload( $name );
2194 }
2195
2196 /**
2197 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
2198 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
2199 */
2200 protected function reportUnusedParams() {
2201 $paramsUsed = $this->getParamsUsed();
2202 $allParams = $this->getRequest()->getValueNames();
2203
2204 if ( !$this->mInternalMode ) {
2205 // Printer has not yet executed; don't warn that its parameters are unused
2206 $printerParams = $this->mPrinter->encodeParamName(
2207 array_keys( $this->mPrinter->getFinalParams() ?: [] )
2208 );
2209 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
2210 } else {
2211 $unusedParams = array_diff( $allParams, $paramsUsed );
2212 }
2213
2214 if ( count( $unusedParams ) ) {
2215 $this->addWarning( [
2216 'apierror-unrecognizedparams',
2217 Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
2218 count( $unusedParams )
2219 ] );
2220 }
2221 }
2222
2223 /**
2224 * Print results using the current printer
2225 *
2226 * @param int $httpCode HTTP status code, or 0 to not change
2227 */
2228 protected function printResult( $httpCode = 0 ) {
2229 if ( $this->getConfig()->get( MainConfigNames::DebugAPI ) !== false ) {
2230 $this->addWarning( 'apiwarn-wgdebugapi' );
2231 }
2232
2233 $printer = $this->mPrinter;
2234 $printer->initPrinter( false );
2235 if ( $httpCode ) {
2236 $printer->setHttpStatus( $httpCode );
2237 }
2238 $printer->execute();
2239 $printer->closePrinter();
2240 }
2241
2242 /**
2243 * @return bool
2244 */
2245 public function isReadMode() {
2246 return false;
2247 }
2248
2249 /**
2250 * See ApiBase for description.
2251 *
2252 * @return array
2253 */
2254 public function getAllowedParams() {
2255 return [
2256 'action' => [
2257 ParamValidator::PARAM_DEFAULT => 'help',
2258 ParamValidator::PARAM_TYPE => 'submodule',
2259 ],
2260 'format' => [
2261 ParamValidator::PARAM_DEFAULT => self::API_DEFAULT_FORMAT,
2262 ParamValidator::PARAM_TYPE => 'submodule',
2263 ],
2264 'maxlag' => [
2265 ParamValidator::PARAM_TYPE => 'integer'
2266 ],
2267 'smaxage' => [
2268 ParamValidator::PARAM_TYPE => 'integer',
2269 ParamValidator::PARAM_DEFAULT => 0,
2270 IntegerDef::PARAM_MIN => 0,
2271 ],
2272 'maxage' => [
2273 ParamValidator::PARAM_TYPE => 'integer',
2274 ParamValidator::PARAM_DEFAULT => 0,
2275 IntegerDef::PARAM_MIN => 0,
2276 ],
2277 'assert' => [
2278 ParamValidator::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
2279 ],
2280 'assertuser' => [
2281 ParamValidator::PARAM_TYPE => 'user',
2282 UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name', 'temp' ],
2283 ],
2284 'requestid' => null,
2285 'servedby' => false,
2286 'curtimestamp' => false,
2287 'responselanginfo' => false,
2288 'origin' => null,
2289 'uselang' => [
2290 ParamValidator::PARAM_DEFAULT => self::API_DEFAULT_USELANG,
2291 ],
2292 'variant' => null,
2293 'errorformat' => [
2294 ParamValidator::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
2295 ParamValidator::PARAM_DEFAULT => 'bc',
2296 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
2297 ],
2298 'errorlang' => [
2299 ParamValidator::PARAM_DEFAULT => 'uselang',
2300 ],
2301 'errorsuselocal' => [
2302 ParamValidator::PARAM_DEFAULT => false,
2303 ],
2304 ];
2305 }
2306
2307 /** @inheritDoc */
2308 protected function getExamplesMessages() {
2309 return [
2310 'action=help'
2311 => 'apihelp-help-example-main',
2312 'action=help&recursivesubmodules=1'
2313 => 'apihelp-help-example-recursive',
2314 ];
2315 }
2316
2317 /**
2318 * @inheritDoc
2319 * @phan-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
2320 */
2321 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2322 // Wish PHP had an "array_insert_before". Instead, we have to manually
2323 // reindex the array to get 'permissions' in the right place.
2324 $oldHelp = $help;
2325 $help = [];
2326 foreach ( $oldHelp as $k => $v ) {
2327 if ( $k === 'submodules' ) {
2328 $help['permissions'] = '';
2329 }
2330 $help[$k] = $v;
2331 }
2332 $help['datatypes'] = '';
2333 $help['templatedparams'] = '';
2334 $help['credits'] = '';
2335
2336 // Fill 'permissions'
2337 $help['permissions'] .= Html::openElement( 'div',
2338 [ 'class' => [ 'apihelp-block', 'apihelp-permissions' ] ] );
2339 $m = $this->msg( 'api-help-permissions' );
2340 if ( !$m->isDisabled() ) {
2341 $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
2342 $m->numParams( count( self::RIGHTS_MAP ) )->parse()
2343 );
2344 }
2345 $help['permissions'] .= Html::openElement( 'dl' );
2346 // TODO inject stuff, see T265644
2347 $groupPermissionsLookup = MediaWikiServices::getInstance()->getGroupPermissionsLookup();
2348 foreach ( self::RIGHTS_MAP as $right => $rightMsg ) {
2349 $help['permissions'] .= Html::element( 'dt', [], $right );
2350
2351 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
2352 $help['permissions'] .= Html::rawElement( 'dd', [], $rightMsg );
2353
2354 $groups = array_map( static function ( $group ) {
2355 return $group == '*' ? 'all' : $group;
2356 }, $groupPermissionsLookup->getGroupsWithPermission( $right ) );
2357
2358 $help['permissions'] .= Html::rawElement( 'dd', [],
2359 $this->msg( 'api-help-permissions-granted-to' )
2360 ->numParams( count( $groups ) )
2361 ->params( Message::listParam( $groups ) )
2362 ->parse()
2363 );
2364 }
2365 $help['permissions'] .= Html::closeElement( 'dl' );
2366 $help['permissions'] .= Html::closeElement( 'div' );
2367
2368 // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
2369 if ( empty( $options['nolead'] ) ) {
2370 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Must set when nolead is not set
2371 $level = $options['headerlevel'];
2372 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Must set when nolead is not set
2373 $tocnumber = &$options['tocnumber'];
2374
2375 $header = $this->msg( 'api-help-datatypes-header' )->parse();
2376 $headline = Html::rawElement(
2377 'h' . min( 6, $level ),
2378 [ 'class' => 'apihelp-header', 'id' => 'main/datatypes' ],
2379 $header
2380 );
2381 $help['datatypes'] .= $headline;
2382 $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
2383 $help['datatypes'] .= '<dl>';
2384 foreach ( $this->getParamValidator()->knownTypes() as $type ) {
2385 $m = $this->msg( "api-help-datatype-$type" );
2386 if ( !$m->isDisabled() ) {
2387 $help['datatypes'] .= Html::element( 'dt', [ 'id' => "main/datatype/$type" ], $type );
2388 $help['datatypes'] .= Html::rawElement( 'dd', [], $m->parseAsBlock() );
2389 }
2390 }
2391 $help['datatypes'] .= '</dl>';
2392 if ( !isset( $tocData['main/datatypes'] ) ) {
2393 $tocnumber[$level]++;
2394 $tocData['main/datatypes'] = [
2395 'toclevel' => count( $tocnumber ),
2396 'level' => $level,
2397 'anchor' => 'main/datatypes',
2398 'line' => $header,
2399 'number' => implode( '.', $tocnumber ),
2400 'index' => '',
2401 ];
2402 }
2403
2404 $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2405 $headline = Html::rawElement(
2406 'h' . min( 6, $level ),
2407 [ 'class' => 'apihelp-header', 'id' => 'main/templatedparams' ],
2408 $header
2409 );
2410 $help['templatedparams'] .= $headline;
2411 $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2412 if ( !isset( $tocData['main/templatedparams'] ) ) {
2413 $tocnumber[$level]++;
2414 $tocData['main/templatedparams'] = [
2415 'toclevel' => count( $tocnumber ),
2416 'level' => $level,
2417 'anchor' => 'main/templatedparams',
2418 'line' => $header,
2419 'number' => implode( '.', $tocnumber ),
2420 'index' => '',
2421 ];
2422 }
2423
2424 $header = $this->msg( 'api-credits-header' )->parse();
2425 $headline = Html::rawElement(
2426 'h' . min( 6, $level ),
2427 [ 'class' => 'apihelp-header', 'id' => 'main/credits' ],
2428 $header
2429 );
2430 $help['credits'] .= $headline;
2431 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2432 if ( !isset( $tocData['main/credits'] ) ) {
2433 $tocnumber[$level]++;
2434 $tocData['main/credits'] = [
2435 'toclevel' => count( $tocnumber ),
2436 'level' => $level,
2437 'anchor' => 'main/credits',
2438 'line' => $header,
2439 'number' => implode( '.', $tocnumber ),
2440 'index' => '',
2441 ];
2442 }
2443 }
2444 }
2445
2446 /** @var bool|null */
2447 private $mCanApiHighLimits = null;
2448
2449 /**
2450 * Check whether the current user is allowed to use high limits
2451 * @return bool
2452 */
2453 public function canApiHighLimits() {
2454 if ( !isset( $this->mCanApiHighLimits ) ) {
2455 $this->mCanApiHighLimits = $this->getAuthority()->isAllowed( 'apihighlimits' );
2456 }
2457
2458 return $this->mCanApiHighLimits;
2459 }
2460
2461 /**
2462 * Overrides to return this instance's module manager.
2463 * @return ApiModuleManager
2464 */
2465 public function getModuleManager() {
2466 return $this->mModuleMgr;
2467 }
2468
2469 /**
2470 * Fetches the user agent used for this request
2471 *
2472 * This returns the value of the 'Api-User-Agent' header, if any,
2473 * or the standard User-Agent header, otherwise.
2474 *
2475 * @return string
2476 */
2477 public function getUserAgent() {
2478 $agent = (string)$this->getRequest()->getHeader( 'Api-user-agent' );
2479 if ( $agent == '' ) {
2480 $agent = $this->getRequest()->getHeader( 'User-agent' );
2481 }
2482
2483 return $agent;
2484 }
2485 }
2486
2487 /**
2488 * For really cool vim folding this needs to be at the end:
2489 * vim: foldmarker=@{,@} foldmethod=marker
2490 */
2491
2492 /** @deprecated class alias since 1.43 */
2493 class_alias( ApiMain::class, 'ApiMain' );