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 | 'logout' => 'ApiLogout',  | 
            ||
| 53 | 'createaccount' => 'ApiCreateAccount',  | 
            ||
| 54 | 'query' => 'ApiQuery',  | 
            ||
| 55 | 'expandtemplates' => 'ApiExpandTemplates',  | 
            ||
| 56 | 'parse' => 'ApiParse',  | 
            ||
| 57 | 'stashedit' => 'ApiStashEdit',  | 
            ||
| 58 | 'opensearch' => 'ApiOpenSearch',  | 
            ||
| 59 | 'feedcontributions' => 'ApiFeedContributions',  | 
            ||
| 60 | 'feedrecentchanges' => 'ApiFeedRecentChanges',  | 
            ||
| 61 | 'feedwatchlist' => 'ApiFeedWatchlist',  | 
            ||
| 62 | 'help' => 'ApiHelp',  | 
            ||
| 63 | 'paraminfo' => 'ApiParamInfo',  | 
            ||
| 64 | 'rsd' => 'ApiRsd',  | 
            ||
| 65 | 'compare' => 'ApiComparePages',  | 
            ||
| 66 | 'tokens' => 'ApiTokens',  | 
            ||
| 67 | 'checktoken' => 'ApiCheckToken',  | 
            ||
| 68 | |||
| 69 | // Write modules  | 
            ||
| 70 | 'purge' => 'ApiPurge',  | 
            ||
| 71 | 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',  | 
            ||
| 72 | 'rollback' => 'ApiRollback',  | 
            ||
| 73 | 'delete' => 'ApiDelete',  | 
            ||
| 74 | 'undelete' => 'ApiUndelete',  | 
            ||
| 75 | 'protect' => 'ApiProtect',  | 
            ||
| 76 | 'block' => 'ApiBlock',  | 
            ||
| 77 | 'unblock' => 'ApiUnblock',  | 
            ||
| 78 | 'move' => 'ApiMove',  | 
            ||
| 79 | 'edit' => 'ApiEditPage',  | 
            ||
| 80 | 'upload' => 'ApiUpload',  | 
            ||
| 81 | 'filerevert' => 'ApiFileRevert',  | 
            ||
| 82 | 'emailuser' => 'ApiEmailUser',  | 
            ||
| 83 | 'watch' => 'ApiWatch',  | 
            ||
| 84 | 'patrol' => 'ApiPatrol',  | 
            ||
| 85 | 'import' => 'ApiImport',  | 
            ||
| 86 | 'clearhasmsg' => 'ApiClearHasMsg',  | 
            ||
| 87 | 'userrights' => 'ApiUserrights',  | 
            ||
| 88 | 'options' => 'ApiOptions',  | 
            ||
| 89 | 'imagerotate' => 'ApiImageRotate',  | 
            ||
| 90 | 'revisiondelete' => 'ApiRevisionDelete',  | 
            ||
| 91 | 'managetags' => 'ApiManageTags',  | 
            ||
| 92 | 'tag' => 'ApiTag',  | 
            ||
| 93 | 'mergehistory' => 'ApiMergeHistory',  | 
            ||
| 94 | ];  | 
            ||
| 95 | |||
| 96 | /**  | 
            ||
| 97 | * List of available formats: format name => format class  | 
            ||
| 98 | */  | 
            ||
| 99 | private static $Formats = [  | 
            ||
| 100 | 'json' => 'ApiFormatJson',  | 
            ||
| 101 | 'jsonfm' => 'ApiFormatJson',  | 
            ||
| 102 | 'php' => 'ApiFormatPhp',  | 
            ||
| 103 | 'phpfm' => 'ApiFormatPhp',  | 
            ||
| 104 | 'xml' => 'ApiFormatXml',  | 
            ||
| 105 | 'xmlfm' => 'ApiFormatXml',  | 
            ||
| 106 | 'rawfm' => 'ApiFormatJson',  | 
            ||
| 107 | 'none' => 'ApiFormatNone',  | 
            ||
| 108 | ];  | 
            ||
| 109 | |||
| 110 | // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line  | 
            ||
| 111 | /**  | 
            ||
| 112 | * List of user roles that are specifically relevant to the API.  | 
            ||
| 113 | * array( 'right' => array ( 'msg' => 'Some message with a $1',  | 
            ||
| 114 | * 'params' => array ( $someVarToSubst ) ),  | 
            ||
| 115 | * );  | 
            ||
| 116 | */  | 
            ||
| 117 | private static $mRights = [  | 
            ||
| 118 | 'writeapi' => [  | 
            ||
| 119 | 'msg' => 'right-writeapi',  | 
            ||
| 120 | 'params' => []  | 
            ||
| 121 | ],  | 
            ||
| 122 | 'apihighlimits' => [  | 
            ||
| 123 | 'msg' => 'api-help-right-apihighlimits',  | 
            ||
| 124 | 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ]  | 
            ||
| 125 | ]  | 
            ||
| 126 | ];  | 
            ||
| 127 | // @codingStandardsIgnoreEnd  | 
            ||
| 128 | |||
| 129 | /**  | 
            ||
| 130 | * @var ApiFormatBase  | 
            ||
| 131 | */  | 
            ||
| 132 | private $mPrinter;  | 
            ||
| 133 | |||
| 134 | private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;  | 
            ||
| 
                                                                                                    
                        
                         | 
                |||
| 135 | private $mAction;  | 
            ||
| 136 | private $mEnableWrite;  | 
            ||
| 137 | private $mInternalMode, $mSquidMaxage;  | 
            ||
| 138 | /** @var ApiBase */  | 
            ||
| 139 | private $mModule;  | 
            ||
| 140 | |||
| 141 | private $mCacheMode = 'private';  | 
            ||
| 142 | private $mCacheControl = [];  | 
            ||
| 143 | private $mParamsUsed = [];  | 
            ||
| 144 | |||
| 145 | /**  | 
            ||
| 146 | * Constructs an instance of ApiMain that utilizes the module and format specified by $request.  | 
            ||
| 147 | *  | 
            ||
| 148 | * @param IContextSource|WebRequest $context If this is an instance of  | 
            ||
| 149 | * FauxRequest, errors are thrown and no printing occurs  | 
            ||
| 150 | * @param bool $enableWrite Should be set to true if the api may modify data  | 
            ||
| 151 | */  | 
            ||
| 152 | 	public function __construct( $context = null, $enableWrite = false ) { | 
            ||
| 153 | 		if ( $context === null ) { | 
            ||
| 154 | $context = RequestContext::getMain();  | 
            ||
| 155 | 		} elseif ( $context instanceof WebRequest ) { | 
            ||
| 156 | // BC for pre-1.19  | 
            ||
| 157 | $request = $context;  | 
            ||
| 158 | $context = RequestContext::getMain();  | 
            ||
| 159 | }  | 
            ||
| 160 | // We set a derivative context so we can change stuff later  | 
            ||
| 161 | $this->setContext( new DerivativeContext( $context ) );  | 
            ||
| 162 | |||
| 163 | 		if ( isset( $request ) ) { | 
            ||
| 164 | $this->getContext()->setRequest( $request );  | 
            ||
| 165 | }  | 
            ||
| 166 | |||
| 167 | $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );  | 
            ||
| 168 | |||
| 169 | // Special handling for the main module: $parent === $this  | 
            ||
| 170 | parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );  | 
            ||
| 171 | |||
| 172 | 		if ( !$this->mInternalMode ) { | 
            ||
| 173 | // Impose module restrictions.  | 
            ||
| 174 | // If the current user cannot read,  | 
            ||
| 175 | // Remove all modules other than login  | 
            ||
| 176 | global $wgUser;  | 
            ||
| 177 | |||
| 178 | 			if ( $this->lacksSameOriginSecurity() ) { | 
            ||
| 179 | // If we're in a mode that breaks the same-origin policy, strip  | 
            ||
| 180 | // user credentials for security.  | 
            ||
| 181 | wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );  | 
            ||
| 182 | $wgUser = new User();  | 
            ||
| 183 | $this->getContext()->setUser( $wgUser );  | 
            ||
| 184 | }  | 
            ||
| 185 | }  | 
            ||
| 186 | |||
| 187 | $uselang = $this->getParameter( 'uselang' );  | 
            ||
| 188 | 		if ( $uselang === 'user' ) { | 
            ||
| 189 | // Assume the parent context is going to return the user language  | 
            ||
| 190 | // for uselang=user (see T85635).  | 
            ||
| 191 | 		} else { | 
            ||
| 192 | 			if ( $uselang === 'content' ) { | 
            ||
| 193 | global $wgContLang;  | 
            ||
| 194 | $uselang = $wgContLang->getCode();  | 
            ||
| 195 | }  | 
            ||
| 196 | $code = RequestContext::sanitizeLangCode( $uselang );  | 
            ||
| 197 | $this->getContext()->setLanguage( $code );  | 
            ||
| 198 | 			if ( !$this->mInternalMode ) { | 
            ||
| 199 | global $wgLang;  | 
            ||
| 200 | $wgLang = $this->getContext()->getLanguage();  | 
            ||
| 201 | RequestContext::getMain()->setLanguage( $wgLang );  | 
            ||
| 202 | }  | 
            ||
| 203 | }  | 
            ||
| 204 | |||
| 205 | $config = $this->getConfig();  | 
            ||
| 206 | $this->mModuleMgr = new ApiModuleManager( $this );  | 
            ||
| 207 | $this->mModuleMgr->addModules( self::$Modules, 'action' );  | 
            ||
| 208 | $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );  | 
            ||
| 209 | $this->mModuleMgr->addModules( self::$Formats, 'format' );  | 
            ||
| 210 | $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );  | 
            ||
| 211 | |||
| 212 | Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );  | 
            ||
| 213 | |||
| 214 | $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );  | 
            ||
| 215 | $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );  | 
            ||
| 216 | $this->mResult->setErrorFormatter( $this->mErrorFormatter );  | 
            ||
| 217 | $this->mResult->setMainForContinuation( $this );  | 
            ||
| 218 | $this->mContinuationManager = null;  | 
            ||
| 219 | $this->mEnableWrite = $enableWrite;  | 
            ||
| 220 | |||
| 221 | $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()  | 
            ||
| 222 | $this->mCommit = false;  | 
            ||
| 223 | }  | 
            ||
| 224 | |||
| 225 | /**  | 
            ||
| 226 | * Return true if the API was started by other PHP code using FauxRequest  | 
            ||
| 227 | * @return bool  | 
            ||
| 228 | */  | 
            ||
| 229 | 	public function isInternalMode() { | 
            ||
| 230 | return $this->mInternalMode;  | 
            ||
| 231 | }  | 
            ||
| 232 | |||
| 233 | /**  | 
            ||
| 234 | * Get the ApiResult object associated with current request  | 
            ||
| 235 | *  | 
            ||
| 236 | * @return ApiResult  | 
            ||
| 237 | */  | 
            ||
| 238 | 	public function getResult() { | 
            ||
| 239 | return $this->mResult;  | 
            ||
| 240 | }  | 
            ||
| 241 | |||
| 242 | /**  | 
            ||
| 243 | * Get the ApiErrorFormatter object associated with current request  | 
            ||
| 244 | * @return ApiErrorFormatter  | 
            ||
| 245 | */  | 
            ||
| 246 | 	public function getErrorFormatter() { | 
            ||
| 247 | return $this->mErrorFormatter;  | 
            ||
| 248 | }  | 
            ||
| 249 | |||
| 250 | /**  | 
            ||
| 251 | * Get the continuation manager  | 
            ||
| 252 | * @return ApiContinuationManager|null  | 
            ||
| 253 | */  | 
            ||
| 254 | 	public function getContinuationManager() { | 
            ||
| 255 | return $this->mContinuationManager;  | 
            ||
| 256 | }  | 
            ||
| 257 | |||
| 258 | /**  | 
            ||
| 259 | * Set the continuation manager  | 
            ||
| 260 | * @param ApiContinuationManager|null  | 
            ||
| 261 | */  | 
            ||
| 262 | 	public function setContinuationManager( $manager ) { | 
            ||
| 263 | 		if ( $manager !== null ) { | 
            ||
| 264 | 			if ( !$manager instanceof ApiContinuationManager ) { | 
            ||
| 265 | throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .  | 
            ||
| 266 | is_object( $manager ) ? get_class( $manager ) : gettype( $manager )  | 
            ||
| 267 | );  | 
            ||
| 268 | }  | 
            ||
| 269 | 			if ( $this->mContinuationManager !== null ) { | 
            ||
| 270 | throw new UnexpectedValueException(  | 
            ||
| 271 | __METHOD__ . ': tried to set manager from ' . $manager->getSource() .  | 
            ||
| 272 | ' when a manager is already set from ' . $this->mContinuationManager->getSource()  | 
            ||
| 273 | );  | 
            ||
| 274 | }  | 
            ||
| 275 | }  | 
            ||
| 276 | $this->mContinuationManager = $manager;  | 
            ||
| 277 | }  | 
            ||
| 278 | |||
| 279 | /**  | 
            ||
| 280 | * Get the API module object. Only works after executeAction()  | 
            ||
| 281 | *  | 
            ||
| 282 | * @return ApiBase  | 
            ||
| 283 | */  | 
            ||
| 284 | 	public function getModule() { | 
            ||
| 285 | return $this->mModule;  | 
            ||
| 286 | }  | 
            ||
| 287 | |||
| 288 | /**  | 
            ||
| 289 | * Get the result formatter object. Only works after setupExecuteAction()  | 
            ||
| 290 | *  | 
            ||
| 291 | * @return ApiFormatBase  | 
            ||
| 292 | */  | 
            ||
| 293 | 	public function getPrinter() { | 
            ||
| 294 | return $this->mPrinter;  | 
            ||
| 295 | }  | 
            ||
| 296 | |||
| 297 | /**  | 
            ||
| 298 | * Set how long the response should be cached.  | 
            ||
| 299 | *  | 
            ||
| 300 | * @param int $maxage  | 
            ||
| 301 | */  | 
            ||
| 302 | 	public function setCacheMaxAge( $maxage ) { | 
            ||
| 303 | $this->setCacheControl( [  | 
            ||
| 304 | 'max-age' => $maxage,  | 
            ||
| 305 | 's-maxage' => $maxage  | 
            ||
| 306 | ] );  | 
            ||
| 307 | }  | 
            ||
| 308 | |||
| 309 | /**  | 
            ||
| 310 | * Set the type of caching headers which will be sent.  | 
            ||
| 311 | *  | 
            ||
| 312 | * @param string $mode One of:  | 
            ||
| 313 | * - 'public': Cache this object in public caches, if the maxage or smaxage  | 
            ||
| 314 | * parameter is set, or if setCacheMaxAge() was called. If a maximum age is  | 
            ||
| 315 | * not provided by any of these means, the object will be private.  | 
            ||
| 316 | * - 'private': Cache this object only in private client-side caches.  | 
            ||
| 317 | * - 'anon-public-user-private': Make this object cacheable for logged-out  | 
            ||
| 318 | * users, but private for logged-in users. IMPORTANT: If this is set, it must be  | 
            ||
| 319 | * set consistently for a given URL, it cannot be set differently depending on  | 
            ||
| 320 | * things like the contents of the database, or whether the user is logged in.  | 
            ||
| 321 | *  | 
            ||
| 322 | * If the wiki does not allow anonymous users to read it, the mode set here  | 
            ||
| 323 | * will be ignored, and private caching headers will always be sent. In other words,  | 
            ||
| 324 | * the "public" mode is equivalent to saying that the data sent is as public as a page  | 
            ||
| 325 | * view.  | 
            ||
| 326 | *  | 
            ||
| 327 | * For user-dependent data, the private mode should generally be used. The  | 
            ||
| 328 | * anon-public-user-private mode should only be used where there is a particularly  | 
            ||
| 329 | * good performance reason for caching the anonymous response, but where the  | 
            ||
| 330 | * response to logged-in users may differ, or may contain private data.  | 
            ||
| 331 | *  | 
            ||
| 332 | * If this function is never called, then the default will be the private mode.  | 
            ||
| 333 | */  | 
            ||
| 334 | 	public function setCacheMode( $mode ) { | 
            ||
| 335 | 		if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) { | 
            ||
| 336 | wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );  | 
            ||
| 337 | |||
| 338 | // Ignore for forwards-compatibility  | 
            ||
| 339 | return;  | 
            ||
| 340 | }  | 
            ||
| 341 | |||
| 342 | 		if ( !User::isEveryoneAllowed( 'read' ) ) { | 
            ||
| 343 | // Private wiki, only private headers  | 
            ||
| 344 | 			if ( $mode !== 'private' ) { | 
            ||
| 345 | wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );  | 
            ||
| 346 | |||
| 347 | return;  | 
            ||
| 348 | }  | 
            ||
| 349 | }  | 
            ||
| 350 | |||
| 351 | 		if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) { | 
            ||
| 352 | // User language is used for i18n, so we don't want to publicly  | 
            ||
| 353 | // cache. Anons are ok, because if they have non-default language  | 
            ||
| 354 | // then there's an appropriate Vary header set by whatever set  | 
            ||
| 355 | // their non-default language.  | 
            ||
| 356 | wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .  | 
            ||
| 357 | "'anon-public-user-private' due to uselang=user\n" );  | 
            ||
| 358 | $mode = 'anon-public-user-private';  | 
            ||
| 359 | }  | 
            ||
| 360 | |||
| 361 | wfDebug( __METHOD__ . ": setting cache mode $mode\n" );  | 
            ||
| 362 | $this->mCacheMode = $mode;  | 
            ||
| 363 | }  | 
            ||
| 364 | |||
| 365 | /**  | 
            ||
| 366 | * Set directives (key/value pairs) for the Cache-Control header.  | 
            ||
| 367 | * Boolean values will be formatted as such, by including or omitting  | 
            ||
| 368 | * without an equals sign.  | 
            ||
| 369 | *  | 
            ||
| 370 | * Cache control values set here will only be used if the cache mode is not  | 
            ||
| 371 | * private, see setCacheMode().  | 
            ||
| 372 | *  | 
            ||
| 373 | * @param array $directives  | 
            ||
| 374 | */  | 
            ||
| 375 | 	public function setCacheControl( $directives ) { | 
            ||
| 376 | $this->mCacheControl = $directives + $this->mCacheControl;  | 
            ||
| 377 | }  | 
            ||
| 378 | |||
| 379 | /**  | 
            ||
| 380 | * Create an instance of an output formatter by its name  | 
            ||
| 381 | *  | 
            ||
| 382 | * @param string $format  | 
            ||
| 383 | *  | 
            ||
| 384 | * @return ApiFormatBase  | 
            ||
| 385 | */  | 
            ||
| 386 | 	public function createPrinterByName( $format ) { | 
            ||
| 387 | $printer = $this->mModuleMgr->getModule( $format, 'format' );  | 
            ||
| 388 | 		if ( $printer === null ) { | 
            ||
| 389 | 			$this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' ); | 
            ||
| 390 | }  | 
            ||
| 391 | |||
| 392 | return $printer;  | 
            ||
| 393 | }  | 
            ||
| 394 | |||
| 395 | /**  | 
            ||
| 396 | * Execute api request. Any errors will be handled if the API was called by the remote client.  | 
            ||
| 397 | */  | 
            ||
| 398 | 	public function execute() { | 
            ||
| 399 | 		if ( $this->mInternalMode ) { | 
            ||
| 400 | $this->executeAction();  | 
            ||
| 401 | 		} else { | 
            ||
| 402 | $this->executeActionWithErrorHandling();  | 
            ||
| 403 | }  | 
            ||
| 404 | }  | 
            ||
| 405 | |||
| 406 | /**  | 
            ||
| 407 | * Execute an action, and in case of an error, erase whatever partial results  | 
            ||
| 408 | * have been accumulated, and replace it with an error message and a help screen.  | 
            ||
| 409 | */  | 
            ||
| 410 | 	protected function executeActionWithErrorHandling() { | 
            ||
| 411 | // Verify the CORS header before executing the action  | 
            ||
| 412 | 		if ( !$this->handleCORS() ) { | 
            ||
| 413 | // handleCORS() has sent a 403, abort  | 
            ||
| 414 | return;  | 
            ||
| 415 | }  | 
            ||
| 416 | |||
| 417 | // Exit here if the request method was OPTIONS  | 
            ||
| 418 | // (assume there will be a followup GET or POST)  | 
            ||
| 419 | 		if ( $this->getRequest()->getMethod() === 'OPTIONS' ) { | 
            ||
| 420 | return;  | 
            ||
| 421 | }  | 
            ||
| 422 | |||
| 423 | // In case an error occurs during data output,  | 
            ||
| 424 | // clear the output buffer and print just the error information  | 
            ||
| 425 | $obLevel = ob_get_level();  | 
            ||
| 426 | ob_start();  | 
            ||
| 427 | |||
| 428 | $t = microtime( true );  | 
            ||
| 429 | $isError = false;  | 
            ||
| 430 | 		try { | 
            ||
| 431 | $this->executeAction();  | 
            ||
| 432 | $runTime = microtime( true ) - $t;  | 
            ||
| 433 | $this->logRequest( $runTime );  | 
            ||
| 434 | 			if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) { | 
            ||
| 435 | $this->getStats()->timing(  | 
            ||
| 436 | 'api.' . $this->getModuleName() . '.executeTiming', 1000 * $runTime );  | 
            ||
| 437 | }  | 
            ||
| 438 | 		} catch ( Exception $e ) { | 
            ||
| 439 | $this->handleException( $e );  | 
            ||
| 440 | $this->logRequest( microtime( true ) - $t, $e );  | 
            ||
| 441 | $isError = true;  | 
            ||
| 442 | }  | 
            ||
| 443 | |||
| 444 | // Commit DBs and send any related cookies and headers  | 
            ||
| 445 | MediaWiki::preOutputCommit( $this->getContext() );  | 
            ||
| 446 | |||
| 447 | // Send cache headers after any code which might generate an error, to  | 
            ||
| 448 | // avoid sending public cache headers for errors.  | 
            ||
| 449 | $this->sendCacheHeaders( $isError );  | 
            ||
| 450 | |||
| 451 | // Executing the action might have already messed with the output  | 
            ||
| 452 | // buffers.  | 
            ||
| 453 | 		while ( ob_get_level() > $obLevel ) { | 
            ||
| 454 | ob_end_flush();  | 
            ||
| 455 | }  | 
            ||
| 456 | }  | 
            ||
| 457 | |||
| 458 | /**  | 
            ||
| 459 | * Handle an exception as an API response  | 
            ||
| 460 | *  | 
            ||
| 461 | * @since 1.23  | 
            ||
| 462 | * @param Exception $e  | 
            ||
| 463 | */  | 
            ||
| 464 | 	protected function handleException( Exception $e ) { | 
            ||
| 522 | |||
| 523 | /**  | 
            ||
| 524 | * Handle an exception from the ApiBeforeMain hook.  | 
            ||
| 525 | *  | 
            ||
| 526 | * This tries to print the exception as an API response, to be more  | 
            ||
| 527 | * friendly to clients. If it fails, it will rethrow the exception.  | 
            ||
| 528 | *  | 
            ||
| 529 | * @since 1.23  | 
            ||
| 530 | * @param Exception $e  | 
            ||
| 531 | * @throws Exception  | 
            ||
| 532 | */  | 
            ||
| 533 | 	public static function handleApiBeforeMainException( Exception $e ) { | 
            ||
| 550 | |||
| 551 | /**  | 
            ||
| 552 | * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.  | 
            ||
| 553 | *  | 
            ||
| 554 | * If no origin parameter is present, nothing happens.  | 
            ||
| 555 | * If an origin parameter is present but doesn't match the Origin header, a 403 status code  | 
            ||
| 556 | * is set and false is returned.  | 
            ||
| 557 | * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains  | 
            ||
| 558 | * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS  | 
            ||
| 559 | * headers are set.  | 
            ||
| 560 | * http://www.w3.org/TR/cors/#resource-requests  | 
            ||
| 561 | * http://www.w3.org/TR/cors/#resource-preflight-requests  | 
            ||
| 562 | *  | 
            ||
| 563 | * @return bool False if the caller should abort (403 case), true otherwise (all other cases)  | 
            ||
| 564 | */  | 
            ||
| 565 | 	protected function handleCORS() { | 
            ||
| 638 | |||
| 639 | /**  | 
            ||
| 640 | * Attempt to match an Origin header against a set of rules and a set of exceptions  | 
            ||
| 641 | * @param string $value Origin header  | 
            ||
| 642 | * @param array $rules Set of wildcard rules  | 
            ||
| 643 | * @param array $exceptions Set of wildcard rules  | 
            ||
| 644 | * @return bool True if $value matches a rule in $rules and doesn't match  | 
            ||
| 645 | * any rules in $exceptions, false otherwise  | 
            ||
| 646 | */  | 
            ||
| 647 | 	protected static function matchOrigin( $value, $rules, $exceptions ) { | 
            ||
| 663 | |||
| 664 | /**  | 
            ||
| 665 | * Attempt to validate the value of Access-Control-Request-Headers against a list  | 
            ||
| 666 | * of headers that we allow the follow up request to send.  | 
            ||
| 667 | *  | 
            ||
| 668 | * @param string $requestedHeaders Comma seperated list of HTTP headers  | 
            ||
| 669 | * @return bool True if all requested headers are in the list of allowed headers  | 
            ||
| 670 | */  | 
            ||
| 671 | 	protected static function matchRequestedHeaders( $requestedHeaders ) { | 
            ||
| 698 | |||
| 699 | /**  | 
            ||
| 700 | * Helper function to convert wildcard string into a regex  | 
            ||
| 701 | * '*' => '.*?'  | 
            ||
| 702 | * '?' => '.'  | 
            ||
| 703 | *  | 
            ||
| 704 | * @param string $wildcard String with wildcards  | 
            ||
| 705 | * @return string Regular expression  | 
            ||
| 706 | */  | 
            ||
| 707 | 	protected static function wildcardToRegex( $wildcard ) { | 
            ||
| 717 | |||
| 718 | /**  | 
            ||
| 719 | * Send caching headers  | 
            ||
| 720 | * @param bool $isError Whether an error response is being output  | 
            ||
| 721 | * @since 1.26 added $isError parameter  | 
            ||
| 722 | */  | 
            ||
| 723 | 	protected function sendCacheHeaders( $isError ) { | 
            ||
| 835 | |||
| 836 | /**  | 
            ||
| 837 | * Create the printer for error output  | 
            ||
| 838 | */  | 
            ||
| 839 | 	private function createErrorPrinter() { | 
            ||
| 854 | |||
| 855 | /**  | 
            ||
| 856 | * Create an error message for the given exception.  | 
            ||
| 857 | *  | 
            ||
| 858 | * If the exception is a UsageException then  | 
            ||
| 859 | * UsageException::getMessageArray() will be called to create the message.  | 
            ||
| 860 | *  | 
            ||
| 861 | * @param Exception $e  | 
            ||
| 862 | * @return array ['code' => 'some string', 'info' => 'some other string']  | 
            ||
| 863 | * @since 1.27  | 
            ||
| 864 | */  | 
            ||
| 865 | 	protected function errorMessageFromException( $e ) { | 
            ||
| 885 | |||
| 886 | /**  | 
            ||
| 887 | * Replace the result data with the information about an exception.  | 
            ||
| 888 | * Returns the error code  | 
            ||
| 889 | * @param Exception $e  | 
            ||
| 890 | * @return string  | 
            ||
| 891 | */  | 
            ||
| 892 | 	protected function substituteResultWithError( $e ) { | 
            ||
| 933 | |||
| 934 | /**  | 
            ||
| 935 | * Set up for the execution.  | 
            ||
| 936 | * @return array  | 
            ||
| 937 | */  | 
            ||
| 938 | 	protected function setupExecuteAction() { | 
            ||
| 968 | |||
| 969 | /**  | 
            ||
| 970 | * Set up the module for response  | 
            ||
| 971 | * @return ApiBase The module that will handle this action  | 
            ||
| 972 | * @throws MWException  | 
            ||
| 973 | * @throws UsageException  | 
            ||
| 974 | */  | 
            ||
| 975 | 	protected function setupModule() { | 
            ||
| 1021 | |||
| 1022 | /**  | 
            ||
| 1023 | * Check the max lag if necessary  | 
            ||
| 1024 | * @param ApiBase $module Api module being used  | 
            ||
| 1025 | * @param array $params Array an array containing the request parameters.  | 
            ||
| 1026 | * @return bool True on success, false should exit immediately  | 
            ||
| 1027 | */  | 
            ||
| 1028 | 	protected function checkMaxLag( $module, $params ) { | 
            ||
| 1048 | |||
| 1049 | /**  | 
            ||
| 1050 | * Check selected RFC 7232 precondition headers  | 
            ||
| 1051 | *  | 
            ||
| 1052 | * RFC 7232 envisions a particular model where you send your request to "a  | 
            ||
| 1053 | * resource", and for write requests that you can read "the resource" by  | 
            ||
| 1054 | * changing the method to GET. When the API receives a GET request, it  | 
            ||
| 1055 | * works out even though "the resource" from RFC 7232's perspective might  | 
            ||
| 1056 | * be many resources from MediaWiki's perspective. But it totally fails for  | 
            ||
| 1057 | * a POST, since what HTTP sees as "the resource" is probably just  | 
            ||
| 1058 | * "/api.php" with all the interesting bits in the body.  | 
            ||
| 1059 | *  | 
            ||
| 1060 | * Therefore, we only support RFC 7232 precondition headers for GET (and  | 
            ||
| 1061 | * HEAD). That means we don't need to bother with If-Match and  | 
            ||
| 1062 | * If-Unmodified-Since since they only apply to modification requests.  | 
            ||
| 1063 | *  | 
            ||
| 1064 | * And since we don't support Range, If-Range is ignored too.  | 
            ||
| 1065 | *  | 
            ||
| 1066 | * @since 1.26  | 
            ||
| 1067 | * @param ApiBase $module Api module being used  | 
            ||
| 1068 | * @return bool True on success, false should exit immediately  | 
            ||
| 1069 | */  | 
            ||
| 1070 | 	protected function checkConditionalRequestHeaders( $module ) { | 
            ||
| 1163 | |||
| 1164 | /**  | 
            ||
| 1165 | * Check for sufficient permissions to execute  | 
            ||
| 1166 | * @param ApiBase $module An Api module  | 
            ||
| 1167 | */  | 
            ||
| 1168 | 	protected function checkExecutePermissions( $module ) { | 
            ||
| 1197 | |||
| 1198 | /**  | 
            ||
| 1199 | * Check if the DB is read-only for this user  | 
            ||
| 1200 | * @param ApiBase $module An Api module  | 
            ||
| 1201 | */  | 
            ||
| 1202 | 	protected function checkReadOnly( $module ) { | 
            ||
| 1214 | |||
| 1215 | /**  | 
            ||
| 1216 | * Check whether we are readonly for bots  | 
            ||
| 1217 | */  | 
            ||
| 1218 | 	private function checkBotReadOnly() { | 
            ||
| 1250 | |||
| 1251 | /**  | 
            ||
| 1252 | * Check asserts of the user's rights  | 
            ||
| 1253 | * @param array $params  | 
            ||
| 1254 | */  | 
            ||
| 1255 | 	protected function checkAsserts( $params ) { | 
            ||
| 1272 | |||
| 1273 | /**  | 
            ||
| 1274 | * Check POST for external response and setup result printer  | 
            ||
| 1275 | * @param ApiBase $module An Api module  | 
            ||
| 1276 | * @param array $params An array with the request parameters  | 
            ||
| 1277 | */  | 
            ||
| 1278 | 	protected function setupExternalResponse( $module, $params ) { | 
            ||
| 1302 | |||
| 1303 | /**  | 
            ||
| 1304 | * Execute the actual module, without any error handling  | 
            ||
| 1305 | */  | 
            ||
| 1306 | 	protected function executeAction() { | 
            ||
| 1345 | |||
| 1346 | /**  | 
            ||
| 1347 | * Set database connection, query, and write expectations given this module request  | 
            ||
| 1348 | * @param ApiBase $module  | 
            ||
| 1349 | */  | 
            ||
| 1350 | 	protected function setRequestExpectations( ApiBase $module ) { | 
            ||
| 1351 | $limits = $this->getConfig()->get( 'TrxProfilerLimits' );  | 
            ||
| 1352 | $trxProfiler = Profiler::instance()->getTransactionProfiler();  | 
            ||
| 1353 | 		if ( $this->getRequest()->wasPosted() ) { | 
            ||
| 1354 | 			if ( $module->isWriteMode() ) { | 
            ||
| 1355 | $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );  | 
            ||
| 1356 | 			} else { | 
            ||
| 1357 | $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );  | 
            ||
| 1358 | $this->getRequest()->markAsSafeRequest();  | 
            ||
| 1359 | }  | 
            ||
| 1364 | |||
| 1365 | /**  | 
            ||
| 1366 | * Log the preceding request  | 
            ||
| 1367 | * @param float $time Time in seconds  | 
            ||
| 1368 | * @param Exception $e Exception caught while processing the request  | 
            ||
| 1369 | */  | 
            ||
| 1370 | 	protected function logRequest( $time, $e = null ) { | 
            ||
| 1414 | |||
| 1415 | /**  | 
            ||
| 1416 | * Encode a value in a format suitable for a space-separated log line.  | 
            ||
| 1417 | * @param string $s  | 
            ||
| 1418 | * @return string  | 
            ||
| 1419 | */  | 
            ||
| 1420 | 	protected function encodeRequestLogValue( $s ) { | 
            ||
| 1432 | |||
| 1433 | /**  | 
            ||
| 1434 | * Get the request parameters used in the course of the preceding execute() request  | 
            ||
| 1435 | * @return array  | 
            ||
| 1436 | */  | 
            ||
| 1437 | 	protected function getParamsUsed() { | 
            ||
| 1440 | |||
| 1441 | /**  | 
            ||
| 1442 | * Get a request value, and register the fact that it was used, for logging.  | 
            ||
| 1443 | * @param string $name  | 
            ||
| 1444 | * @param mixed $default  | 
            ||
| 1445 | * @return mixed  | 
            ||
| 1446 | */  | 
            ||
| 1447 | 	public function getVal( $name, $default = null ) { | 
            ||
| 1463 | |||
| 1464 | /**  | 
            ||
| 1465 | * Get a boolean request value, and register the fact that the parameter  | 
            ||
| 1466 | * was used, for logging.  | 
            ||
| 1467 | * @param string $name  | 
            ||
| 1468 | * @return bool  | 
            ||
| 1469 | */  | 
            ||
| 1470 | 	public function getCheck( $name ) { | 
            ||
| 1473 | |||
| 1474 | /**  | 
            ||
| 1475 | * Get a request upload, and register the fact that it was used, for logging.  | 
            ||
| 1476 | *  | 
            ||
| 1477 | * @since 1.21  | 
            ||
| 1478 | * @param string $name Parameter name  | 
            ||
| 1479 | * @return WebRequestUpload  | 
            ||
| 1480 | */  | 
            ||
| 1481 | 	public function getUpload( $name ) { | 
            ||
| 1486 | |||
| 1487 | /**  | 
            ||
| 1488 | * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,  | 
            ||
| 1489 | * for example in case of spelling mistakes or a missing 'g' prefix for generators.  | 
            ||
| 1490 | */  | 
            ||
| 1491 | 	protected function reportUnusedParams() { | 
            ||
| 1511 | |||
| 1512 | /**  | 
            ||
| 1513 | * Print results using the current printer  | 
            ||
| 1514 | *  | 
            ||
| 1515 | * @param bool $isError  | 
            ||
| 1516 | */  | 
            ||
| 1517 | 	protected function printResult( $isError ) { | 
            ||
| 1527 | |||
| 1528 | /**  | 
            ||
| 1529 | * @return bool  | 
            ||
| 1530 | */  | 
            ||
| 1531 | 	public function isReadMode() { | 
            ||
| 1534 | |||
| 1535 | /**  | 
            ||
| 1536 | * See ApiBase for description.  | 
            ||
| 1537 | *  | 
            ||
| 1538 | * @return array  | 
            ||
| 1539 | */  | 
            ||
| 1540 | 	public function getAllowedParams() { | 
            ||
| 1573 | |||
| 1574 | /** @see ApiBase::getExamplesMessages() */  | 
            ||
| 1575 | 	protected function getExamplesMessages() { | 
            ||
| 1583 | |||
| 1584 | 	public function modifyHelp( array &$help, array $options, array &$tocData ) { | 
            ||
| 1672 | |||
| 1673 | private $mCanApiHighLimits = null;  | 
            ||
| 1674 | |||
| 1675 | /**  | 
            ||
| 1676 | * Check whether the current user is allowed to use high limits  | 
            ||
| 1677 | * @return bool  | 
            ||
| 1678 | */  | 
            ||
| 1679 | 	public function canApiHighLimits() { | 
            ||
| 1686 | |||
| 1687 | /**  | 
            ||
| 1688 | * Overrides to return this instance's module manager.  | 
            ||
| 1689 | * @return ApiModuleManager  | 
            ||
| 1690 | */  | 
            ||
| 1691 | 	public function getModuleManager() { | 
            ||
| 1694 | |||
| 1695 | /**  | 
            ||
| 1696 | * Fetches the user agent used for this request  | 
            ||
| 1697 | *  | 
            ||
| 1698 | * The value will be the combination of the 'Api-User-Agent' header (if  | 
            ||
| 1699 | * any) and the standard User-Agent header (if any).  | 
            ||
| 1700 | *  | 
            ||
| 1701 | * @return string  | 
            ||
| 1702 | */  | 
            ||
| 1703 | 	public function getUserAgent() { | 
            ||
| 1709 | |||
| 1710 | /************************************************************************//**  | 
            ||
| 1711 | * @name Deprecated  | 
            ||
| 1712 | 	 * @{ | 
            ||
| 1713 | */  | 
            ||
| 1714 | |||
| 1715 | /**  | 
            ||
| 1716 | * Sets whether the pretty-printer should format *bold* and $italics$  | 
            ||
| 1717 | *  | 
            ||
| 1718 | * @deprecated since 1.25  | 
            ||
| 1719 | * @param bool $help  | 
            ||
| 1720 | */  | 
            ||
| 1721 | 	public function setHelp( $help = true ) { | 
            ||
| 1725 | |||
| 1726 | /**  | 
            ||
| 1727 | * Override the parent to generate help messages for all available modules.  | 
            ||
| 1728 | *  | 
            ||
| 1729 | * @deprecated since 1.25  | 
            ||
| 1730 | * @return string  | 
            ||
| 1731 | */  | 
            ||
| 1732 | 	public function makeHelpMsg() { | 
            ||
| 1748 | |||
| 1749 | /**  | 
            ||
| 1750 | * @deprecated since 1.25  | 
            ||
| 1751 | * @return mixed|string  | 
            ||
| 1752 | */  | 
            ||
| 1753 | 	public function reallyMakeHelpMsg() { | 
            ||
| 1802 | |||
| 1803 | /**  | 
            ||
| 1804 | * @deprecated since 1.25  | 
            ||
| 1805 | * @param ApiBase $module  | 
            ||
| 1806 | * @param string $paramName What type of request is this? e.g. action,  | 
            ||
| 1807 | * query, list, prop, meta, format  | 
            ||
| 1808 | * @return string  | 
            ||
| 1809 | */  | 
            ||
| 1810 | 	public static function makeHelpMsgHeader( $module, $paramName ) { | 
            ||
| 1819 | |||
| 1820 | /**@}*/  | 
            ||
| 1821 | |||
| 1822 | }  | 
            ||
| 1823 | |||
| 1884 | 
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.