Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like ApiMain often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ApiMain, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 41 | class ApiMain extends ApiBase { |
||
| 42 | /** |
||
| 43 | * When no format parameter is given, this format will be used |
||
| 44 | */ |
||
| 45 | const API_DEFAULT_FORMAT = 'jsonfm'; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * List of available modules: action name => module class |
||
| 49 | */ |
||
| 50 | private static $Modules = [ |
||
| 51 | 'login' => 'ApiLogin', |
||
| 52 | 'clientlogin' => 'ApiClientLogin', |
||
| 53 | 'logout' => 'ApiLogout', |
||
| 54 | 'createaccount' => 'ApiAMCreateAccount', |
||
| 55 | 'linkaccount' => 'ApiLinkAccount', |
||
| 56 | 'unlinkaccount' => 'ApiRemoveAuthenticationData', |
||
| 57 | 'changeauthenticationdata' => 'ApiChangeAuthenticationData', |
||
| 58 | 'removeauthenticationdata' => 'ApiRemoveAuthenticationData', |
||
| 59 | 'resetpassword' => 'ApiResetPassword', |
||
| 60 | 'query' => 'ApiQuery', |
||
| 61 | 'expandtemplates' => 'ApiExpandTemplates', |
||
| 62 | 'parse' => 'ApiParse', |
||
| 63 | 'stashedit' => 'ApiStashEdit', |
||
| 64 | 'opensearch' => 'ApiOpenSearch', |
||
| 65 | 'feedcontributions' => 'ApiFeedContributions', |
||
| 66 | 'feedrecentchanges' => 'ApiFeedRecentChanges', |
||
| 67 | 'feedwatchlist' => 'ApiFeedWatchlist', |
||
| 68 | 'help' => 'ApiHelp', |
||
| 69 | 'paraminfo' => 'ApiParamInfo', |
||
| 70 | 'rsd' => 'ApiRsd', |
||
| 71 | 'compare' => 'ApiComparePages', |
||
| 72 | 'tokens' => 'ApiTokens', |
||
| 73 | 'checktoken' => 'ApiCheckToken', |
||
| 74 | |||
| 75 | // Write modules |
||
| 76 | 'purge' => 'ApiPurge', |
||
| 77 | 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp', |
||
| 78 | 'rollback' => 'ApiRollback', |
||
| 79 | 'delete' => 'ApiDelete', |
||
| 80 | 'undelete' => 'ApiUndelete', |
||
| 81 | 'protect' => 'ApiProtect', |
||
| 82 | 'block' => 'ApiBlock', |
||
| 83 | 'unblock' => 'ApiUnblock', |
||
| 84 | 'move' => 'ApiMove', |
||
| 85 | 'edit' => 'ApiEditPage', |
||
| 86 | 'upload' => 'ApiUpload', |
||
| 87 | 'filerevert' => 'ApiFileRevert', |
||
| 88 | 'emailuser' => 'ApiEmailUser', |
||
| 89 | 'watch' => 'ApiWatch', |
||
| 90 | 'patrol' => 'ApiPatrol', |
||
| 91 | 'import' => 'ApiImport', |
||
| 92 | 'clearhasmsg' => 'ApiClearHasMsg', |
||
| 93 | 'userrights' => 'ApiUserrights', |
||
| 94 | 'options' => 'ApiOptions', |
||
| 95 | 'imagerotate' => 'ApiImageRotate', |
||
| 96 | 'revisiondelete' => 'ApiRevisionDelete', |
||
| 97 | 'managetags' => 'ApiManageTags', |
||
| 98 | 'tag' => 'ApiTag', |
||
| 99 | 'mergehistory' => 'ApiMergeHistory', |
||
| 100 | ]; |
||
| 101 | |||
| 102 | /** |
||
| 103 | * List of available formats: format name => format class |
||
| 104 | */ |
||
| 105 | private static $Formats = [ |
||
| 106 | 'json' => 'ApiFormatJson', |
||
| 107 | 'jsonfm' => 'ApiFormatJson', |
||
| 108 | 'php' => 'ApiFormatPhp', |
||
| 109 | 'phpfm' => 'ApiFormatPhp', |
||
| 110 | 'xml' => 'ApiFormatXml', |
||
| 111 | 'xmlfm' => 'ApiFormatXml', |
||
| 112 | 'rawfm' => 'ApiFormatJson', |
||
| 113 | 'none' => 'ApiFormatNone', |
||
| 114 | ]; |
||
| 115 | |||
| 116 | // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line |
||
| 117 | /** |
||
| 118 | * List of user roles that are specifically relevant to the API. |
||
| 119 | * array( 'right' => array ( 'msg' => 'Some message with a $1', |
||
| 120 | * 'params' => array ( $someVarToSubst ) ), |
||
| 121 | * ); |
||
| 122 | */ |
||
| 123 | private static $mRights = [ |
||
| 124 | 'writeapi' => [ |
||
| 125 | 'msg' => 'right-writeapi', |
||
| 126 | 'params' => [] |
||
| 127 | ], |
||
| 128 | 'apihighlimits' => [ |
||
| 129 | 'msg' => 'api-help-right-apihighlimits', |
||
| 130 | 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ] |
||
| 131 | ] |
||
| 132 | ]; |
||
| 133 | // @codingStandardsIgnoreEnd |
||
| 134 | |||
| 135 | /** |
||
| 136 | * @var ApiFormatBase |
||
| 137 | */ |
||
| 138 | private $mPrinter; |
||
| 139 | |||
| 140 | private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager; |
||
|
|
|||
| 141 | private $mAction; |
||
| 142 | private $mEnableWrite; |
||
| 143 | private $mInternalMode, $mSquidMaxage; |
||
| 144 | /** @var ApiBase */ |
||
| 145 | private $mModule; |
||
| 146 | |||
| 147 | private $mCacheMode = 'private'; |
||
| 148 | private $mCacheControl = []; |
||
| 149 | private $mParamsUsed = []; |
||
| 150 | |||
| 151 | /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */ |
||
| 152 | private $lacksSameOriginSecurity = null; |
||
| 153 | |||
| 154 | /** |
||
| 155 | * Constructs an instance of ApiMain that utilizes the module and format specified by $request. |
||
| 156 | * |
||
| 157 | * @param IContextSource|WebRequest $context If this is an instance of |
||
| 158 | * FauxRequest, errors are thrown and no printing occurs |
||
| 159 | * @param bool $enableWrite Should be set to true if the api may modify data |
||
| 160 | */ |
||
| 161 | public function __construct( $context = null, $enableWrite = false ) { |
||
| 162 | if ( $context === null ) { |
||
| 163 | $context = RequestContext::getMain(); |
||
| 164 | } elseif ( $context instanceof WebRequest ) { |
||
| 165 | // BC for pre-1.19 |
||
| 166 | $request = $context; |
||
| 167 | $context = RequestContext::getMain(); |
||
| 168 | } |
||
| 169 | // We set a derivative context so we can change stuff later |
||
| 170 | $this->setContext( new DerivativeContext( $context ) ); |
||
| 171 | |||
| 172 | if ( isset( $request ) ) { |
||
| 173 | $this->getContext()->setRequest( $request ); |
||
| 174 | } |
||
| 175 | |||
| 176 | $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest ); |
||
| 177 | |||
| 178 | // Special handling for the main module: $parent === $this |
||
| 179 | parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' ); |
||
| 180 | |||
| 181 | if ( !$this->mInternalMode ) { |
||
| 182 | // Impose module restrictions. |
||
| 183 | // If the current user cannot read, |
||
| 184 | // Remove all modules other than login |
||
| 185 | global $wgUser; |
||
| 186 | |||
| 187 | if ( $this->lacksSameOriginSecurity() ) { |
||
| 188 | // If we're in a mode that breaks the same-origin policy, strip |
||
| 189 | // user credentials for security. |
||
| 190 | wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" ); |
||
| 191 | $wgUser = new User(); |
||
| 192 | $this->getContext()->setUser( $wgUser ); |
||
| 193 | } |
||
| 194 | } |
||
| 195 | |||
| 196 | $uselang = $this->getParameter( 'uselang' ); |
||
| 197 | if ( $uselang === 'user' ) { |
||
| 198 | // Assume the parent context is going to return the user language |
||
| 199 | // for uselang=user (see T85635). |
||
| 200 | } else { |
||
| 201 | if ( $uselang === 'content' ) { |
||
| 202 | global $wgContLang; |
||
| 203 | $uselang = $wgContLang->getCode(); |
||
| 204 | } |
||
| 205 | $code = RequestContext::sanitizeLangCode( $uselang ); |
||
| 206 | $this->getContext()->setLanguage( $code ); |
||
| 207 | if ( !$this->mInternalMode ) { |
||
| 208 | global $wgLang; |
||
| 209 | $wgLang = $this->getContext()->getLanguage(); |
||
| 210 | RequestContext::getMain()->setLanguage( $wgLang ); |
||
| 211 | } |
||
| 212 | } |
||
| 213 | |||
| 214 | $config = $this->getConfig(); |
||
| 215 | $this->mModuleMgr = new ApiModuleManager( $this ); |
||
| 216 | $this->mModuleMgr->addModules( self::$Modules, 'action' ); |
||
| 217 | $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' ); |
||
| 218 | $this->mModuleMgr->addModules( self::$Formats, 'format' ); |
||
| 219 | $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' ); |
||
| 220 | |||
| 221 | Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] ); |
||
| 222 | |||
| 223 | $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) ); |
||
| 224 | $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult ); |
||
| 225 | $this->mResult->setErrorFormatter( $this->mErrorFormatter ); |
||
| 226 | $this->mResult->setMainForContinuation( $this ); |
||
| 227 | $this->mContinuationManager = null; |
||
| 228 | $this->mEnableWrite = $enableWrite; |
||
| 229 | |||
| 230 | $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling() |
||
| 231 | $this->mCommit = false; |
||
| 232 | } |
||
| 233 | |||
| 234 | /** |
||
| 235 | * Return true if the API was started by other PHP code using FauxRequest |
||
| 236 | * @return bool |
||
| 237 | */ |
||
| 238 | public function isInternalMode() { |
||
| 239 | return $this->mInternalMode; |
||
| 240 | } |
||
| 241 | |||
| 242 | /** |
||
| 243 | * Get the ApiResult object associated with current request |
||
| 244 | * |
||
| 245 | * @return ApiResult |
||
| 246 | */ |
||
| 247 | public function getResult() { |
||
| 248 | return $this->mResult; |
||
| 249 | } |
||
| 250 | |||
| 251 | /** |
||
| 252 | * Get the security flag for the current request |
||
| 253 | * @return bool |
||
| 254 | */ |
||
| 255 | public function lacksSameOriginSecurity() { |
||
| 279 | |||
| 280 | /** |
||
| 281 | * Get the ApiErrorFormatter object associated with current request |
||
| 282 | * @return ApiErrorFormatter |
||
| 283 | */ |
||
| 284 | public function getErrorFormatter() { |
||
| 285 | return $this->mErrorFormatter; |
||
| 286 | } |
||
| 287 | |||
| 288 | /** |
||
| 289 | * Get the continuation manager |
||
| 290 | * @return ApiContinuationManager|null |
||
| 291 | */ |
||
| 292 | public function getContinuationManager() { |
||
| 293 | return $this->mContinuationManager; |
||
| 294 | } |
||
| 295 | |||
| 296 | /** |
||
| 297 | * Set the continuation manager |
||
| 298 | * @param ApiContinuationManager|null |
||
| 299 | */ |
||
| 300 | public function setContinuationManager( $manager ) { |
||
| 301 | if ( $manager !== null ) { |
||
| 302 | if ( !$manager instanceof ApiContinuationManager ) { |
||
| 303 | throw new InvalidArgumentException( __METHOD__ . ': Was passed ' . |
||
| 304 | is_object( $manager ) ? get_class( $manager ) : gettype( $manager ) |
||
| 305 | ); |
||
| 306 | } |
||
| 307 | if ( $this->mContinuationManager !== null ) { |
||
| 308 | throw new UnexpectedValueException( |
||
| 309 | __METHOD__ . ': tried to set manager from ' . $manager->getSource() . |
||
| 310 | ' when a manager is already set from ' . $this->mContinuationManager->getSource() |
||
| 311 | ); |
||
| 312 | } |
||
| 313 | } |
||
| 314 | $this->mContinuationManager = $manager; |
||
| 315 | } |
||
| 316 | |||
| 317 | /** |
||
| 318 | * Get the API module object. Only works after executeAction() |
||
| 319 | * |
||
| 320 | * @return ApiBase |
||
| 321 | */ |
||
| 322 | public function getModule() { |
||
| 323 | return $this->mModule; |
||
| 324 | } |
||
| 325 | |||
| 326 | /** |
||
| 327 | * Get the result formatter object. Only works after setupExecuteAction() |
||
| 328 | * |
||
| 329 | * @return ApiFormatBase |
||
| 330 | */ |
||
| 331 | public function getPrinter() { |
||
| 332 | return $this->mPrinter; |
||
| 333 | } |
||
| 334 | |||
| 335 | /** |
||
| 336 | * Set how long the response should be cached. |
||
| 337 | * |
||
| 338 | * @param int $maxage |
||
| 339 | */ |
||
| 340 | public function setCacheMaxAge( $maxage ) { |
||
| 341 | $this->setCacheControl( [ |
||
| 342 | 'max-age' => $maxage, |
||
| 343 | 's-maxage' => $maxage |
||
| 344 | ] ); |
||
| 345 | } |
||
| 346 | |||
| 347 | /** |
||
| 348 | * Set the type of caching headers which will be sent. |
||
| 349 | * |
||
| 350 | * @param string $mode One of: |
||
| 351 | * - 'public': Cache this object in public caches, if the maxage or smaxage |
||
| 352 | * parameter is set, or if setCacheMaxAge() was called. If a maximum age is |
||
| 353 | * not provided by any of these means, the object will be private. |
||
| 354 | * - 'private': Cache this object only in private client-side caches. |
||
| 355 | * - 'anon-public-user-private': Make this object cacheable for logged-out |
||
| 356 | * users, but private for logged-in users. IMPORTANT: If this is set, it must be |
||
| 357 | * set consistently for a given URL, it cannot be set differently depending on |
||
| 358 | * things like the contents of the database, or whether the user is logged in. |
||
| 359 | * |
||
| 360 | * If the wiki does not allow anonymous users to read it, the mode set here |
||
| 361 | * will be ignored, and private caching headers will always be sent. In other words, |
||
| 362 | * the "public" mode is equivalent to saying that the data sent is as public as a page |
||
| 363 | * view. |
||
| 364 | * |
||
| 365 | * For user-dependent data, the private mode should generally be used. The |
||
| 366 | * anon-public-user-private mode should only be used where there is a particularly |
||
| 367 | * good performance reason for caching the anonymous response, but where the |
||
| 368 | * response to logged-in users may differ, or may contain private data. |
||
| 369 | * |
||
| 370 | * If this function is never called, then the default will be the private mode. |
||
| 371 | */ |
||
| 372 | public function setCacheMode( $mode ) { |
||
| 373 | if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) { |
||
| 374 | wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" ); |
||
| 375 | |||
| 376 | // Ignore for forwards-compatibility |
||
| 377 | return; |
||
| 378 | } |
||
| 379 | |||
| 380 | if ( !User::isEveryoneAllowed( 'read' ) ) { |
||
| 381 | // Private wiki, only private headers |
||
| 382 | if ( $mode !== 'private' ) { |
||
| 383 | wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" ); |
||
| 384 | |||
| 385 | return; |
||
| 386 | } |
||
| 387 | } |
||
| 388 | |||
| 389 | if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) { |
||
| 390 | // User language is used for i18n, so we don't want to publicly |
||
| 391 | // cache. Anons are ok, because if they have non-default language |
||
| 392 | // then there's an appropriate Vary header set by whatever set |
||
| 393 | // their non-default language. |
||
| 394 | wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " . |
||
| 395 | "'anon-public-user-private' due to uselang=user\n" ); |
||
| 396 | $mode = 'anon-public-user-private'; |
||
| 397 | } |
||
| 398 | |||
| 399 | wfDebug( __METHOD__ . ": setting cache mode $mode\n" ); |
||
| 400 | $this->mCacheMode = $mode; |
||
| 401 | } |
||
| 402 | |||
| 403 | /** |
||
| 404 | * Set directives (key/value pairs) for the Cache-Control header. |
||
| 405 | * Boolean values will be formatted as such, by including or omitting |
||
| 406 | * without an equals sign. |
||
| 407 | * |
||
| 408 | * Cache control values set here will only be used if the cache mode is not |
||
| 409 | * private, see setCacheMode(). |
||
| 410 | * |
||
| 411 | * @param array $directives |
||
| 412 | */ |
||
| 413 | public function setCacheControl( $directives ) { |
||
| 414 | $this->mCacheControl = $directives + $this->mCacheControl; |
||
| 415 | } |
||
| 416 | |||
| 417 | /** |
||
| 418 | * Create an instance of an output formatter by its name |
||
| 419 | * |
||
| 420 | * @param string $format |
||
| 421 | * |
||
| 422 | * @return ApiFormatBase |
||
| 423 | */ |
||
| 424 | public function createPrinterByName( $format ) { |
||
| 425 | $printer = $this->mModuleMgr->getModule( $format, 'format' ); |
||
| 426 | if ( $printer === null ) { |
||
| 427 | $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' ); |
||
| 428 | } |
||
| 429 | |||
| 430 | return $printer; |
||
| 431 | } |
||
| 432 | |||
| 433 | /** |
||
| 434 | * Execute api request. Any errors will be handled if the API was called by the remote client. |
||
| 435 | */ |
||
| 436 | public function execute() { |
||
| 437 | if ( $this->mInternalMode ) { |
||
| 438 | $this->executeAction(); |
||
| 439 | } else { |
||
| 440 | $this->executeActionWithErrorHandling(); |
||
| 441 | } |
||
| 442 | } |
||
| 443 | |||
| 444 | /** |
||
| 445 | * Execute an action, and in case of an error, erase whatever partial results |
||
| 446 | * have been accumulated, and replace it with an error message and a help screen. |
||
| 447 | */ |
||
| 448 | protected function executeActionWithErrorHandling() { |
||
| 449 | // Verify the CORS header before executing the action |
||
| 450 | if ( !$this->handleCORS() ) { |
||
| 451 | // handleCORS() has sent a 403, abort |
||
| 452 | return; |
||
| 453 | } |
||
| 454 | |||
| 455 | // Exit here if the request method was OPTIONS |
||
| 456 | // (assume there will be a followup GET or POST) |
||
| 457 | if ( $this->getRequest()->getMethod() === 'OPTIONS' ) { |
||
| 458 | return; |
||
| 459 | } |
||
| 460 | |||
| 461 | // In case an error occurs during data output, |
||
| 462 | // clear the output buffer and print just the error information |
||
| 463 | $obLevel = ob_get_level(); |
||
| 464 | ob_start(); |
||
| 465 | |||
| 466 | $t = microtime( true ); |
||
| 467 | $isError = false; |
||
| 468 | try { |
||
| 469 | $this->executeAction(); |
||
| 470 | $runTime = microtime( true ) - $t; |
||
| 471 | $this->logRequest( $runTime ); |
||
| 472 | if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) { |
||
| 473 | $this->getStats()->timing( |
||
| 474 | 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime |
||
| 475 | ); |
||
| 476 | } |
||
| 477 | } catch ( Exception $e ) { |
||
| 478 | $this->handleException( $e ); |
||
| 479 | $this->logRequest( microtime( true ) - $t, $e ); |
||
| 480 | $isError = true; |
||
| 481 | } |
||
| 482 | |||
| 483 | // Commit DBs and send any related cookies and headers |
||
| 484 | MediaWiki::preOutputCommit( $this->getContext() ); |
||
| 485 | |||
| 486 | // Send cache headers after any code which might generate an error, to |
||
| 487 | // avoid sending public cache headers for errors. |
||
| 488 | $this->sendCacheHeaders( $isError ); |
||
| 489 | |||
| 490 | // Executing the action might have already messed with the output |
||
| 491 | // buffers. |
||
| 492 | while ( ob_get_level() > $obLevel ) { |
||
| 493 | ob_end_flush(); |
||
| 494 | } |
||
| 495 | } |
||
| 496 | |||
| 497 | /** |
||
| 498 | * Handle an exception as an API response |
||
| 499 | * |
||
| 500 | * @since 1.23 |
||
| 501 | * @param Exception $e |
||
| 502 | */ |
||
| 503 | protected function handleException( Exception $e ) { |
||
| 504 | // Bug 63145: Rollback any open database transactions |
||
| 505 | if ( !( $e instanceof UsageException ) ) { |
||
| 506 | // UsageExceptions are intentional, so don't rollback if that's the case |
||
| 507 | try { |
||
| 508 | MWExceptionHandler::rollbackMasterChangesAndLog( $e ); |
||
| 509 | } catch ( DBError $e2 ) { |
||
| 510 | // Rollback threw an exception too. Log it, but don't interrupt |
||
| 511 | // our regularly scheduled exception handling. |
||
| 512 | MWExceptionHandler::logException( $e2 ); |
||
| 513 | } |
||
| 514 | } |
||
| 515 | |||
| 516 | // Allow extra cleanup and logging |
||
| 517 | Hooks::run( 'ApiMain::onException', [ $this, $e ] ); |
||
| 518 | |||
| 519 | // Log it |
||
| 520 | if ( !( $e instanceof UsageException ) ) { |
||
| 521 | MWExceptionHandler::logException( $e ); |
||
| 522 | } |
||
| 523 | |||
| 524 | // Handle any kind of exception by outputting properly formatted error message. |
||
| 525 | // If this fails, an unhandled exception should be thrown so that global error |
||
| 526 | // handler will process and log it. |
||
| 527 | |||
| 528 | $errCode = $this->substituteResultWithError( $e ); |
||
| 529 | |||
| 530 | // Error results should not be cached |
||
| 531 | $this->setCacheMode( 'private' ); |
||
| 532 | |||
| 533 | $response = $this->getRequest()->response(); |
||
| 534 | $headerStr = 'MediaWiki-API-Error: ' . $errCode; |
||
| 535 | if ( $e->getCode() === 0 ) { |
||
| 536 | $response->header( $headerStr ); |
||
| 537 | } else { |
||
| 538 | $response->header( $headerStr, true, $e->getCode() ); |
||
| 539 | } |
||
| 540 | |||
| 541 | // Reset and print just the error message |
||
| 542 | ob_clean(); |
||
| 543 | |||
| 544 | // Printer may not be initialized if the extractRequestParams() fails for the main module |
||
| 545 | $this->createErrorPrinter(); |
||
| 546 | |||
| 547 | try { |
||
| 548 | $this->printResult( true ); |
||
| 549 | } catch ( UsageException $ex ) { |
||
| 550 | // The error printer itself is failing. Try suppressing its request |
||
| 551 | // parameters and redo. |
||
| 552 | $this->setWarning( |
||
| 553 | 'Error printer failed (will retry without params): ' . $ex->getMessage() |
||
| 554 | ); |
||
| 555 | $this->mPrinter = null; |
||
| 556 | $this->createErrorPrinter(); |
||
| 557 | $this->mPrinter->forceDefaultParams(); |
||
| 558 | $this->printResult( true ); |
||
| 559 | } |
||
| 560 | } |
||
| 561 | |||
| 562 | /** |
||
| 563 | * Handle an exception from the ApiBeforeMain hook. |
||
| 564 | * |
||
| 565 | * This tries to print the exception as an API response, to be more |
||
| 566 | * friendly to clients. If it fails, it will rethrow the exception. |
||
| 567 | * |
||
| 568 | * @since 1.23 |
||
| 569 | * @param Exception $e |
||
| 570 | * @throws Exception |
||
| 571 | */ |
||
| 572 | public static function handleApiBeforeMainException( Exception $e ) { |
||
| 573 | ob_start(); |
||
| 574 | |||
| 575 | try { |
||
| 576 | $main = new self( RequestContext::getMain(), false ); |
||
| 577 | $main->handleException( $e ); |
||
| 578 | $main->logRequest( 0, $e ); |
||
| 579 | } catch ( Exception $e2 ) { |
||
| 580 | // Nope, even that didn't work. Punt. |
||
| 581 | throw $e; |
||
| 582 | } |
||
| 583 | |||
| 584 | // Reset cache headers |
||
| 585 | $main->sendCacheHeaders( true ); |
||
| 586 | |||
| 587 | ob_end_flush(); |
||
| 588 | } |
||
| 589 | |||
| 590 | /** |
||
| 591 | * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. |
||
| 592 | * |
||
| 593 | * If no origin parameter is present, nothing happens. |
||
| 594 | * If an origin parameter is present but doesn't match the Origin header, a 403 status code |
||
| 595 | * is set and false is returned. |
||
| 596 | * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains |
||
| 597 | * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS |
||
| 598 | * headers are set. |
||
| 599 | * http://www.w3.org/TR/cors/#resource-requests |
||
| 600 | * http://www.w3.org/TR/cors/#resource-preflight-requests |
||
| 601 | * |
||
| 602 | * @return bool False if the caller should abort (403 case), true otherwise (all other cases) |
||
| 603 | */ |
||
| 604 | protected function handleCORS() { |
||
| 605 | $originParam = $this->getParameter( 'origin' ); // defaults to null |
||
| 606 | if ( $originParam === null ) { |
||
| 607 | // No origin parameter, nothing to do |
||
| 608 | return true; |
||
| 609 | } |
||
| 610 | |||
| 611 | $request = $this->getRequest(); |
||
| 612 | $response = $request->response(); |
||
| 613 | |||
| 614 | // Origin: header is a space-separated list of origins, check all of them |
||
| 615 | $originHeader = $request->getHeader( 'Origin' ); |
||
| 616 | if ( $originHeader === false ) { |
||
| 617 | $origins = []; |
||
| 618 | } else { |
||
| 619 | $originHeader = trim( $originHeader ); |
||
| 620 | $origins = preg_split( '/\s+/', $originHeader ); |
||
| 621 | } |
||
| 622 | |||
| 623 | if ( !in_array( $originParam, $origins ) ) { |
||
| 624 | // origin parameter set but incorrect |
||
| 625 | // Send a 403 response |
||
| 626 | $response->statusHeader( 403 ); |
||
| 627 | $response->header( 'Cache-Control: no-cache' ); |
||
| 628 | echo "'origin' parameter does not match Origin header\n"; |
||
| 629 | |||
| 630 | return false; |
||
| 631 | } |
||
| 632 | |||
| 633 | $config = $this->getConfig(); |
||
| 634 | $matchOrigin = count( $origins ) === 1 && self::matchOrigin( |
||
| 635 | $originParam, |
||
| 636 | $config->get( 'CrossSiteAJAXdomains' ), |
||
| 637 | $config->get( 'CrossSiteAJAXdomainExceptions' ) |
||
| 638 | ); |
||
| 639 | |||
| 640 | if ( $matchOrigin ) { |
||
| 641 | $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' ); |
||
| 642 | $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false; |
||
| 643 | if ( $preflight ) { |
||
| 644 | // This is a CORS preflight request |
||
| 645 | if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) { |
||
| 646 | // If method is not a case-sensitive match, do not set any additional headers and terminate. |
||
| 647 | return true; |
||
| 648 | } |
||
| 649 | // We allow the actual request to send the following headers |
||
| 650 | $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' ); |
||
| 651 | if ( $requestedHeaders !== false ) { |
||
| 652 | if ( !self::matchRequestedHeaders( $requestedHeaders ) ) { |
||
| 653 | return true; |
||
| 654 | } |
||
| 655 | $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders ); |
||
| 656 | } |
||
| 657 | |||
| 658 | // We only allow the actual request to be GET or POST |
||
| 659 | $response->header( 'Access-Control-Allow-Methods: POST, GET' ); |
||
| 660 | } |
||
| 661 | |||
| 662 | $response->header( "Access-Control-Allow-Origin: $originHeader" ); |
||
| 663 | $response->header( 'Access-Control-Allow-Credentials: true' ); |
||
| 664 | // http://www.w3.org/TR/resource-timing/#timing-allow-origin |
||
| 665 | $response->header( "Timing-Allow-Origin: $originHeader" ); |
||
| 666 | |||
| 667 | if ( !$preflight ) { |
||
| 668 | $response->header( |
||
| 669 | 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' |
||
| 670 | ); |
||
| 671 | } |
||
| 672 | } |
||
| 673 | |||
| 674 | $this->getOutput()->addVaryHeader( 'Origin' ); |
||
| 675 | return true; |
||
| 676 | } |
||
| 677 | |||
| 678 | /** |
||
| 679 | * Attempt to match an Origin header against a set of rules and a set of exceptions |
||
| 680 | * @param string $value Origin header |
||
| 681 | * @param array $rules Set of wildcard rules |
||
| 682 | * @param array $exceptions Set of wildcard rules |
||
| 683 | * @return bool True if $value matches a rule in $rules and doesn't match |
||
| 684 | * any rules in $exceptions, false otherwise |
||
| 685 | */ |
||
| 686 | protected static function matchOrigin( $value, $rules, $exceptions ) { |
||
| 687 | foreach ( $rules as $rule ) { |
||
| 688 | if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) { |
||
| 689 | // Rule matches, check exceptions |
||
| 690 | foreach ( $exceptions as $exc ) { |
||
| 691 | if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) { |
||
| 692 | return false; |
||
| 693 | } |
||
| 694 | } |
||
| 695 | |||
| 696 | return true; |
||
| 697 | } |
||
| 698 | } |
||
| 699 | |||
| 700 | return false; |
||
| 701 | } |
||
| 702 | |||
| 703 | /** |
||
| 704 | * Attempt to validate the value of Access-Control-Request-Headers against a list |
||
| 705 | * of headers that we allow the follow up request to send. |
||
| 706 | * |
||
| 707 | * @param string $requestedHeaders Comma seperated list of HTTP headers |
||
| 708 | * @return bool True if all requested headers are in the list of allowed headers |
||
| 709 | */ |
||
| 710 | protected static function matchRequestedHeaders( $requestedHeaders ) { |
||
| 711 | if ( trim( $requestedHeaders ) === '' ) { |
||
| 712 | return true; |
||
| 713 | } |
||
| 714 | $requestedHeaders = explode( ',', $requestedHeaders ); |
||
| 715 | $allowedAuthorHeaders = array_flip( [ |
||
| 716 | /* simple headers (see spec) */ |
||
| 717 | 'accept', |
||
| 718 | 'accept-language', |
||
| 719 | 'content-language', |
||
| 720 | 'content-type', |
||
| 721 | /* non-authorable headers in XHR, which are however requested by some UAs */ |
||
| 722 | 'accept-encoding', |
||
| 723 | 'dnt', |
||
| 724 | 'origin', |
||
| 725 | /* MediaWiki whitelist */ |
||
| 726 | 'api-user-agent', |
||
| 727 | ] ); |
||
| 728 | foreach ( $requestedHeaders as $rHeader ) { |
||
| 729 | $rHeader = strtolower( trim( $rHeader ) ); |
||
| 730 | if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) { |
||
| 731 | wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader ); |
||
| 732 | return false; |
||
| 733 | } |
||
| 734 | } |
||
| 735 | return true; |
||
| 736 | } |
||
| 737 | |||
| 738 | /** |
||
| 739 | * Helper function to convert wildcard string into a regex |
||
| 740 | * '*' => '.*?' |
||
| 741 | * '?' => '.' |
||
| 742 | * |
||
| 743 | * @param string $wildcard String with wildcards |
||
| 744 | * @return string Regular expression |
||
| 745 | */ |
||
| 746 | protected static function wildcardToRegex( $wildcard ) { |
||
| 747 | $wildcard = preg_quote( $wildcard, '/' ); |
||
| 748 | $wildcard = str_replace( |
||
| 749 | [ '\*', '\?' ], |
||
| 750 | [ '.*?', '.' ], |
||
| 751 | $wildcard |
||
| 752 | ); |
||
| 753 | |||
| 754 | return "/^https?:\/\/$wildcard$/"; |
||
| 755 | } |
||
| 756 | |||
| 757 | /** |
||
| 758 | * Send caching headers |
||
| 759 | * @param bool $isError Whether an error response is being output |
||
| 760 | * @since 1.26 added $isError parameter |
||
| 761 | */ |
||
| 762 | protected function sendCacheHeaders( $isError ) { |
||
| 876 | |||
| 877 | /** |
||
| 878 | * Create the printer for error output |
||
| 879 | */ |
||
| 880 | private function createErrorPrinter() { |
||
| 881 | if ( !isset( $this->mPrinter ) ) { |
||
| 882 | $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT ); |
||
| 883 | if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) { |
||
| 884 | $value = self::API_DEFAULT_FORMAT; |
||
| 885 | } |
||
| 886 | $this->mPrinter = $this->createPrinterByName( $value ); |
||
| 887 | } |
||
| 888 | |||
| 889 | // Printer may not be able to handle errors. This is particularly |
||
| 890 | // likely if the module returns something for getCustomPrinter(). |
||
| 891 | if ( !$this->mPrinter->canPrintErrors() ) { |
||
| 892 | $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT ); |
||
| 893 | } |
||
| 894 | } |
||
| 895 | |||
| 896 | /** |
||
| 897 | * Create an error message for the given exception. |
||
| 898 | * |
||
| 899 | * If the exception is a UsageException then |
||
| 900 | * UsageException::getMessageArray() will be called to create the message. |
||
| 901 | * |
||
| 902 | * @param Exception $e |
||
| 903 | * @return array ['code' => 'some string', 'info' => 'some other string'] |
||
| 904 | * @since 1.27 |
||
| 905 | */ |
||
| 906 | protected function errorMessageFromException( $e ) { |
||
| 926 | |||
| 927 | /** |
||
| 928 | * Replace the result data with the information about an exception. |
||
| 929 | * Returns the error code |
||
| 930 | * @param Exception $e |
||
| 931 | * @return string |
||
| 932 | */ |
||
| 933 | protected function substituteResultWithError( $e ) { |
||
| 974 | |||
| 975 | /** |
||
| 976 | * Set up for the execution. |
||
| 977 | * @return array |
||
| 978 | */ |
||
| 979 | protected function setupExecuteAction() { |
||
| 1009 | |||
| 1010 | /** |
||
| 1011 | * Set up the module for response |
||
| 1012 | * @return ApiBase The module that will handle this action |
||
| 1013 | * @throws MWException |
||
| 1014 | * @throws UsageException |
||
| 1015 | */ |
||
| 1016 | protected function setupModule() { |
||
| 1062 | |||
| 1063 | /** |
||
| 1064 | * Check the max lag if necessary |
||
| 1065 | * @param ApiBase $module Api module being used |
||
| 1066 | * @param array $params Array an array containing the request parameters. |
||
| 1067 | * @return bool True on success, false should exit immediately |
||
| 1068 | */ |
||
| 1069 | protected function checkMaxLag( $module, $params ) { |
||
| 1089 | |||
| 1090 | /** |
||
| 1091 | * Check selected RFC 7232 precondition headers |
||
| 1092 | * |
||
| 1093 | * RFC 7232 envisions a particular model where you send your request to "a |
||
| 1094 | * resource", and for write requests that you can read "the resource" by |
||
| 1095 | * changing the method to GET. When the API receives a GET request, it |
||
| 1096 | * works out even though "the resource" from RFC 7232's perspective might |
||
| 1097 | * be many resources from MediaWiki's perspective. But it totally fails for |
||
| 1098 | * a POST, since what HTTP sees as "the resource" is probably just |
||
| 1099 | * "/api.php" with all the interesting bits in the body. |
||
| 1100 | * |
||
| 1101 | * Therefore, we only support RFC 7232 precondition headers for GET (and |
||
| 1102 | * HEAD). That means we don't need to bother with If-Match and |
||
| 1103 | * If-Unmodified-Since since they only apply to modification requests. |
||
| 1104 | * |
||
| 1105 | * And since we don't support Range, If-Range is ignored too. |
||
| 1106 | * |
||
| 1107 | * @since 1.26 |
||
| 1108 | * @param ApiBase $module Api module being used |
||
| 1109 | * @return bool True on success, false should exit immediately |
||
| 1110 | */ |
||
| 1111 | protected function checkConditionalRequestHeaders( $module ) { |
||
| 1204 | |||
| 1205 | /** |
||
| 1206 | * Check for sufficient permissions to execute |
||
| 1207 | * @param ApiBase $module An Api module |
||
| 1208 | */ |
||
| 1209 | protected function checkExecutePermissions( $module ) { |
||
| 1238 | |||
| 1239 | /** |
||
| 1240 | * Check if the DB is read-only for this user |
||
| 1241 | * @param ApiBase $module An Api module |
||
| 1242 | */ |
||
| 1243 | protected function checkReadOnly( $module ) { |
||
| 1255 | |||
| 1256 | /** |
||
| 1257 | * Check whether we are readonly for bots |
||
| 1258 | */ |
||
| 1259 | private function checkBotReadOnly() { |
||
| 1291 | |||
| 1292 | /** |
||
| 1293 | * Check asserts of the user's rights |
||
| 1294 | * @param array $params |
||
| 1295 | */ |
||
| 1296 | protected function checkAsserts( $params ) { |
||
| 1313 | |||
| 1314 | /** |
||
| 1315 | * Check POST for external response and setup result printer |
||
| 1316 | * @param ApiBase $module An Api module |
||
| 1317 | * @param array $params An array with the request parameters |
||
| 1318 | */ |
||
| 1319 | protected function setupExternalResponse( $module, $params ) { |
||
| 1343 | |||
| 1344 | /** |
||
| 1345 | * Execute the actual module, without any error handling |
||
| 1346 | */ |
||
| 1347 | protected function executeAction() { |
||
| 1386 | |||
| 1387 | /** |
||
| 1388 | * Set database connection, query, and write expectations given this module request |
||
| 1389 | * @param ApiBase $module |
||
| 1390 | */ |
||
| 1391 | protected function setRequestExpectations( ApiBase $module ) { |
||
| 1403 | |||
| 1404 | /** |
||
| 1405 | * Log the preceding request |
||
| 1406 | * @param float $time Time in seconds |
||
| 1407 | * @param Exception $e Exception caught while processing the request |
||
| 1408 | */ |
||
| 1409 | protected function logRequest( $time, $e = null ) { |
||
| 1453 | |||
| 1454 | /** |
||
| 1455 | * Encode a value in a format suitable for a space-separated log line. |
||
| 1456 | * @param string $s |
||
| 1457 | * @return string |
||
| 1458 | */ |
||
| 1459 | protected function encodeRequestLogValue( $s ) { |
||
| 1471 | |||
| 1472 | /** |
||
| 1473 | * Get the request parameters used in the course of the preceding execute() request |
||
| 1474 | * @return array |
||
| 1475 | */ |
||
| 1476 | protected function getParamsUsed() { |
||
| 1479 | |||
| 1480 | /** |
||
| 1481 | * Mark parameters as used |
||
| 1482 | * @param string|string[] $params |
||
| 1483 | */ |
||
| 1484 | public function markParamsUsed( $params ) { |
||
| 1487 | |||
| 1488 | /** |
||
| 1489 | * Get a request value, and register the fact that it was used, for logging. |
||
| 1490 | * @param string $name |
||
| 1491 | * @param mixed $default |
||
| 1492 | * @return mixed |
||
| 1493 | */ |
||
| 1494 | public function getVal( $name, $default = null ) { |
||
| 1510 | |||
| 1511 | /** |
||
| 1512 | * Get a boolean request value, and register the fact that the parameter |
||
| 1513 | * was used, for logging. |
||
| 1514 | * @param string $name |
||
| 1515 | * @return bool |
||
| 1516 | */ |
||
| 1517 | public function getCheck( $name ) { |
||
| 1520 | |||
| 1521 | /** |
||
| 1522 | * Get a request upload, and register the fact that it was used, for logging. |
||
| 1523 | * |
||
| 1524 | * @since 1.21 |
||
| 1525 | * @param string $name Parameter name |
||
| 1526 | * @return WebRequestUpload |
||
| 1527 | */ |
||
| 1528 | public function getUpload( $name ) { |
||
| 1533 | |||
| 1534 | /** |
||
| 1535 | * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know, |
||
| 1536 | * for example in case of spelling mistakes or a missing 'g' prefix for generators. |
||
| 1537 | */ |
||
| 1538 | protected function reportUnusedParams() { |
||
| 1558 | |||
| 1559 | /** |
||
| 1560 | * Print results using the current printer |
||
| 1561 | * |
||
| 1562 | * @param bool $isError |
||
| 1563 | */ |
||
| 1564 | protected function printResult( $isError ) { |
||
| 1574 | |||
| 1575 | /** |
||
| 1576 | * @return bool |
||
| 1577 | */ |
||
| 1578 | public function isReadMode() { |
||
| 1581 | |||
| 1582 | /** |
||
| 1583 | * See ApiBase for description. |
||
| 1584 | * |
||
| 1585 | * @return array |
||
| 1586 | */ |
||
| 1587 | public function getAllowedParams() { |
||
| 1620 | |||
| 1621 | /** @see ApiBase::getExamplesMessages() */ |
||
| 1622 | protected function getExamplesMessages() { |
||
| 1630 | |||
| 1631 | public function modifyHelp( array &$help, array $options, array &$tocData ) { |
||
| 1728 | |||
| 1729 | private $mCanApiHighLimits = null; |
||
| 1730 | |||
| 1731 | /** |
||
| 1732 | * Check whether the current user is allowed to use high limits |
||
| 1733 | * @return bool |
||
| 1734 | */ |
||
| 1735 | public function canApiHighLimits() { |
||
| 1742 | |||
| 1743 | /** |
||
| 1744 | * Overrides to return this instance's module manager. |
||
| 1745 | * @return ApiModuleManager |
||
| 1746 | */ |
||
| 1747 | public function getModuleManager() { |
||
| 1750 | |||
| 1751 | /** |
||
| 1752 | * Fetches the user agent used for this request |
||
| 1753 | * |
||
| 1754 | * The value will be the combination of the 'Api-User-Agent' header (if |
||
| 1755 | * any) and the standard User-Agent header (if any). |
||
| 1756 | * |
||
| 1757 | * @return string |
||
| 1758 | */ |
||
| 1759 | public function getUserAgent() { |
||
| 1765 | |||
| 1766 | /************************************************************************//** |
||
| 1767 | * @name Deprecated |
||
| 1768 | * @{ |
||
| 1769 | */ |
||
| 1770 | |||
| 1771 | /** |
||
| 1772 | * Sets whether the pretty-printer should format *bold* and $italics$ |
||
| 1773 | * |
||
| 1774 | * @deprecated since 1.25 |
||
| 1775 | * @param bool $help |
||
| 1776 | */ |
||
| 1777 | public function setHelp( $help = true ) { |
||
| 1781 | |||
| 1782 | /** |
||
| 1783 | * Override the parent to generate help messages for all available modules. |
||
| 1784 | * |
||
| 1785 | * @deprecated since 1.25 |
||
| 1786 | * @return string |
||
| 1787 | */ |
||
| 1788 | public function makeHelpMsg() { |
||
| 1804 | |||
| 1805 | /** |
||
| 1806 | * @deprecated since 1.25 |
||
| 1807 | * @return mixed|string |
||
| 1808 | */ |
||
| 1809 | public function reallyMakeHelpMsg() { |
||
| 1858 | |||
| 1859 | /** |
||
| 1860 | * @deprecated since 1.25 |
||
| 1861 | * @param ApiBase $module |
||
| 1862 | * @param string $paramName What type of request is this? e.g. action, |
||
| 1863 | * query, list, prop, meta, format |
||
| 1864 | * @return string |
||
| 1865 | */ |
||
| 1866 | public static function makeHelpMsgHeader( $module, $paramName ) { |
||
| 1875 | |||
| 1876 | /**@}*/ |
||
| 1877 | |||
| 1878 | } |
||
| 1879 | |||
| 1940 |
Only declaring a single property per statement allows you to later on add doc comments more easily.
It is also recommended by PSR2, so it is a common style that many people expect.