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 |
||
43 | class ApiMain extends ApiBase { |
||
44 | /** |
||
45 | * When no format parameter is given, this format will be used |
||
46 | */ |
||
47 | const API_DEFAULT_FORMAT = 'jsonfm'; |
||
48 | |||
49 | /** |
||
50 | * List of available modules: action name => module class |
||
51 | */ |
||
52 | private static $Modules = [ |
||
53 | 'login' => 'ApiLogin', |
||
54 | 'clientlogin' => 'ApiClientLogin', |
||
55 | 'logout' => 'ApiLogout', |
||
56 | 'createaccount' => 'ApiAMCreateAccount', |
||
57 | 'linkaccount' => 'ApiLinkAccount', |
||
58 | 'unlinkaccount' => 'ApiRemoveAuthenticationData', |
||
59 | 'changeauthenticationdata' => 'ApiChangeAuthenticationData', |
||
60 | 'removeauthenticationdata' => 'ApiRemoveAuthenticationData', |
||
61 | 'resetpassword' => 'ApiResetPassword', |
||
62 | 'query' => 'ApiQuery', |
||
63 | 'expandtemplates' => 'ApiExpandTemplates', |
||
64 | 'parse' => 'ApiParse', |
||
65 | 'stashedit' => 'ApiStashEdit', |
||
66 | 'opensearch' => 'ApiOpenSearch', |
||
67 | 'feedcontributions' => 'ApiFeedContributions', |
||
68 | 'feedrecentchanges' => 'ApiFeedRecentChanges', |
||
69 | 'feedwatchlist' => 'ApiFeedWatchlist', |
||
70 | 'help' => 'ApiHelp', |
||
71 | 'paraminfo' => 'ApiParamInfo', |
||
72 | 'rsd' => 'ApiRsd', |
||
73 | 'compare' => 'ApiComparePages', |
||
74 | 'tokens' => 'ApiTokens', |
||
75 | 'checktoken' => 'ApiCheckToken', |
||
76 | 'cspreport' => 'ApiCSPReport', |
||
77 | |||
78 | // Write modules |
||
79 | 'purge' => 'ApiPurge', |
||
80 | 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp', |
||
81 | 'rollback' => 'ApiRollback', |
||
82 | 'delete' => 'ApiDelete', |
||
83 | 'undelete' => 'ApiUndelete', |
||
84 | 'protect' => 'ApiProtect', |
||
85 | 'block' => 'ApiBlock', |
||
86 | 'unblock' => 'ApiUnblock', |
||
87 | 'move' => 'ApiMove', |
||
88 | 'edit' => 'ApiEditPage', |
||
89 | 'upload' => 'ApiUpload', |
||
90 | 'filerevert' => 'ApiFileRevert', |
||
91 | 'emailuser' => 'ApiEmailUser', |
||
92 | 'watch' => 'ApiWatch', |
||
93 | 'patrol' => 'ApiPatrol', |
||
94 | 'import' => 'ApiImport', |
||
95 | 'clearhasmsg' => 'ApiClearHasMsg', |
||
96 | 'userrights' => 'ApiUserrights', |
||
97 | 'options' => 'ApiOptions', |
||
98 | 'imagerotate' => 'ApiImageRotate', |
||
99 | 'revisiondelete' => 'ApiRevisionDelete', |
||
100 | 'managetags' => 'ApiManageTags', |
||
101 | 'tag' => 'ApiTag', |
||
102 | 'mergehistory' => 'ApiMergeHistory', |
||
103 | ]; |
||
104 | |||
105 | /** |
||
106 | * List of available formats: format name => format class |
||
107 | */ |
||
108 | private static $Formats = [ |
||
109 | 'json' => 'ApiFormatJson', |
||
110 | 'jsonfm' => 'ApiFormatJson', |
||
111 | 'php' => 'ApiFormatPhp', |
||
112 | 'phpfm' => 'ApiFormatPhp', |
||
113 | 'xml' => 'ApiFormatXml', |
||
114 | 'xmlfm' => 'ApiFormatXml', |
||
115 | 'rawfm' => 'ApiFormatJson', |
||
116 | 'none' => 'ApiFormatNone', |
||
117 | ]; |
||
118 | |||
119 | // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line |
||
120 | /** |
||
121 | * List of user roles that are specifically relevant to the API. |
||
122 | * [ 'right' => [ 'msg' => 'Some message with a $1', |
||
123 | * 'params' => [ $someVarToSubst ] ], |
||
124 | * ]; |
||
125 | */ |
||
126 | private static $mRights = [ |
||
127 | 'writeapi' => [ |
||
128 | 'msg' => 'right-writeapi', |
||
129 | 'params' => [] |
||
130 | ], |
||
131 | 'apihighlimits' => [ |
||
132 | 'msg' => 'api-help-right-apihighlimits', |
||
133 | 'params' => [ ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ] |
||
134 | ] |
||
135 | ]; |
||
136 | // @codingStandardsIgnoreEnd |
||
137 | |||
138 | /** |
||
139 | * @var ApiFormatBase |
||
140 | */ |
||
141 | private $mPrinter; |
||
142 | |||
143 | private $mModuleMgr, $mResult, $mErrorFormatter; |
||
|
|||
144 | /** @var ApiContinuationManager|null */ |
||
145 | private $mContinuationManager; |
||
146 | private $mAction; |
||
147 | private $mEnableWrite; |
||
148 | private $mInternalMode, $mSquidMaxage; |
||
149 | /** @var ApiBase */ |
||
150 | private $mModule; |
||
151 | |||
152 | private $mCacheMode = 'private'; |
||
153 | private $mCacheControl = []; |
||
154 | private $mParamsUsed = []; |
||
155 | |||
156 | /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */ |
||
157 | private $lacksSameOriginSecurity = null; |
||
158 | |||
159 | /** |
||
160 | * Constructs an instance of ApiMain that utilizes the module and format specified by $request. |
||
161 | * |
||
162 | * @param IContextSource|WebRequest $context If this is an instance of |
||
163 | * FauxRequest, errors are thrown and no printing occurs |
||
164 | * @param bool $enableWrite Should be set to true if the api may modify data |
||
165 | */ |
||
166 | public function __construct( $context = null, $enableWrite = false ) { |
||
167 | if ( $context === null ) { |
||
168 | $context = RequestContext::getMain(); |
||
169 | } elseif ( $context instanceof WebRequest ) { |
||
170 | // BC for pre-1.19 |
||
171 | $request = $context; |
||
172 | $context = RequestContext::getMain(); |
||
173 | } |
||
174 | // We set a derivative context so we can change stuff later |
||
175 | $this->setContext( new DerivativeContext( $context ) ); |
||
176 | |||
177 | if ( isset( $request ) ) { |
||
178 | $this->getContext()->setRequest( $request ); |
||
179 | } else { |
||
180 | $request = $this->getRequest(); |
||
181 | } |
||
182 | |||
183 | $this->mInternalMode = ( $request instanceof FauxRequest ); |
||
184 | |||
185 | // Special handling for the main module: $parent === $this |
||
186 | parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' ); |
||
187 | |||
188 | $config = $this->getConfig(); |
||
189 | |||
190 | if ( !$this->mInternalMode ) { |
||
191 | // Log if a request with a non-whitelisted Origin header is seen |
||
192 | // with session cookies. |
||
193 | $originHeader = $request->getHeader( 'Origin' ); |
||
194 | View Code Duplication | if ( $originHeader === false ) { |
|
195 | $origins = []; |
||
196 | } else { |
||
197 | $originHeader = trim( $originHeader ); |
||
198 | $origins = preg_split( '/\s+/', $originHeader ); |
||
199 | } |
||
200 | $sessionCookies = array_intersect( |
||
201 | array_keys( $_COOKIE ), |
||
202 | MediaWiki\Session\SessionManager::singleton()->getVaryCookies() |
||
203 | ); |
||
204 | if ( $origins && $sessionCookies && ( |
||
205 | count( $origins ) !== 1 || !self::matchOrigin( |
||
206 | $origins[0], |
||
207 | $config->get( 'CrossSiteAJAXdomains' ), |
||
208 | $config->get( 'CrossSiteAJAXdomainExceptions' ) |
||
209 | ) |
||
210 | ) ) { |
||
211 | LoggerFactory::getInstance( 'cors' )->warning( |
||
212 | 'Non-whitelisted CORS request with session cookies', [ |
||
213 | 'origin' => $originHeader, |
||
214 | 'cookies' => $sessionCookies, |
||
215 | 'ip' => $request->getIP(), |
||
216 | 'userAgent' => $this->getUserAgent(), |
||
217 | 'wiki' => wfWikiID(), |
||
218 | ] |
||
219 | ); |
||
220 | } |
||
221 | |||
222 | // If we're in a mode that breaks the same-origin policy, strip |
||
223 | // user credentials for security. |
||
224 | if ( $this->lacksSameOriginSecurity() ) { |
||
225 | global $wgUser; |
||
226 | wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" ); |
||
227 | $wgUser = new User(); |
||
228 | $this->getContext()->setUser( $wgUser ); |
||
229 | } |
||
230 | } |
||
231 | |||
232 | $uselang = $this->getParameter( 'uselang' ); |
||
233 | if ( $uselang === 'user' ) { |
||
234 | // Assume the parent context is going to return the user language |
||
235 | // for uselang=user (see T85635). |
||
236 | } else { |
||
237 | if ( $uselang === 'content' ) { |
||
238 | global $wgContLang; |
||
239 | $uselang = $wgContLang->getCode(); |
||
240 | } |
||
241 | $code = RequestContext::sanitizeLangCode( $uselang ); |
||
242 | $this->getContext()->setLanguage( $code ); |
||
243 | if ( !$this->mInternalMode ) { |
||
244 | global $wgLang; |
||
245 | $wgLang = $this->getContext()->getLanguage(); |
||
246 | RequestContext::getMain()->setLanguage( $wgLang ); |
||
247 | } |
||
248 | } |
||
249 | |||
250 | $this->mModuleMgr = new ApiModuleManager( $this ); |
||
251 | $this->mModuleMgr->addModules( self::$Modules, 'action' ); |
||
252 | $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' ); |
||
253 | $this->mModuleMgr->addModules( self::$Formats, 'format' ); |
||
254 | $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' ); |
||
255 | |||
256 | Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] ); |
||
257 | |||
258 | $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) ); |
||
259 | $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult ); |
||
260 | $this->mResult->setErrorFormatter( $this->mErrorFormatter ); |
||
261 | $this->mContinuationManager = null; |
||
262 | $this->mEnableWrite = $enableWrite; |
||
263 | |||
264 | $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling() |
||
265 | $this->mCommit = false; |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * Return true if the API was started by other PHP code using FauxRequest |
||
270 | * @return bool |
||
271 | */ |
||
272 | public function isInternalMode() { |
||
273 | return $this->mInternalMode; |
||
274 | } |
||
275 | |||
276 | /** |
||
277 | * Get the ApiResult object associated with current request |
||
278 | * |
||
279 | * @return ApiResult |
||
280 | */ |
||
281 | public function getResult() { |
||
282 | return $this->mResult; |
||
283 | } |
||
284 | |||
285 | /** |
||
286 | * Get the security flag for the current request |
||
287 | * @return bool |
||
288 | */ |
||
289 | public function lacksSameOriginSecurity() { |
||
290 | if ( $this->lacksSameOriginSecurity !== null ) { |
||
291 | return $this->lacksSameOriginSecurity; |
||
292 | } |
||
293 | |||
294 | $request = $this->getRequest(); |
||
295 | |||
296 | // JSONP mode |
||
297 | if ( $request->getVal( 'callback' ) !== null ) { |
||
298 | $this->lacksSameOriginSecurity = true; |
||
299 | return true; |
||
300 | } |
||
301 | |||
302 | // Anonymous CORS |
||
303 | if ( $request->getVal( 'origin' ) === '*' ) { |
||
304 | $this->lacksSameOriginSecurity = true; |
||
305 | return true; |
||
306 | } |
||
307 | |||
308 | // Header to be used from XMLHTTPRequest when the request might |
||
309 | // otherwise be used for XSS. |
||
310 | if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) { |
||
311 | $this->lacksSameOriginSecurity = true; |
||
312 | return true; |
||
313 | } |
||
314 | |||
315 | // Allow extensions to override. |
||
316 | $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] ); |
||
317 | return $this->lacksSameOriginSecurity; |
||
318 | } |
||
319 | |||
320 | /** |
||
321 | * Get the ApiErrorFormatter object associated with current request |
||
322 | * @return ApiErrorFormatter |
||
323 | */ |
||
324 | public function getErrorFormatter() { |
||
325 | return $this->mErrorFormatter; |
||
326 | } |
||
327 | |||
328 | /** |
||
329 | * Get the continuation manager |
||
330 | * @return ApiContinuationManager|null |
||
331 | */ |
||
332 | public function getContinuationManager() { |
||
333 | return $this->mContinuationManager; |
||
334 | } |
||
335 | |||
336 | /** |
||
337 | * Set the continuation manager |
||
338 | * @param ApiContinuationManager|null |
||
339 | */ |
||
340 | public function setContinuationManager( $manager ) { |
||
341 | if ( $manager !== null ) { |
||
342 | if ( !$manager instanceof ApiContinuationManager ) { |
||
343 | throw new InvalidArgumentException( __METHOD__ . ': Was passed ' . |
||
344 | is_object( $manager ) ? get_class( $manager ) : gettype( $manager ) |
||
345 | ); |
||
346 | } |
||
347 | if ( $this->mContinuationManager !== null ) { |
||
348 | throw new UnexpectedValueException( |
||
349 | __METHOD__ . ': tried to set manager from ' . $manager->getSource() . |
||
350 | ' when a manager is already set from ' . $this->mContinuationManager->getSource() |
||
351 | ); |
||
352 | } |
||
353 | } |
||
354 | $this->mContinuationManager = $manager; |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * Get the API module object. Only works after executeAction() |
||
359 | * |
||
360 | * @return ApiBase |
||
361 | */ |
||
362 | public function getModule() { |
||
363 | return $this->mModule; |
||
364 | } |
||
365 | |||
366 | /** |
||
367 | * Get the result formatter object. Only works after setupExecuteAction() |
||
368 | * |
||
369 | * @return ApiFormatBase |
||
370 | */ |
||
371 | public function getPrinter() { |
||
372 | return $this->mPrinter; |
||
373 | } |
||
374 | |||
375 | /** |
||
376 | * Set how long the response should be cached. |
||
377 | * |
||
378 | * @param int $maxage |
||
379 | */ |
||
380 | public function setCacheMaxAge( $maxage ) { |
||
381 | $this->setCacheControl( [ |
||
382 | 'max-age' => $maxage, |
||
383 | 's-maxage' => $maxage |
||
384 | ] ); |
||
385 | } |
||
386 | |||
387 | /** |
||
388 | * Set the type of caching headers which will be sent. |
||
389 | * |
||
390 | * @param string $mode One of: |
||
391 | * - 'public': Cache this object in public caches, if the maxage or smaxage |
||
392 | * parameter is set, or if setCacheMaxAge() was called. If a maximum age is |
||
393 | * not provided by any of these means, the object will be private. |
||
394 | * - 'private': Cache this object only in private client-side caches. |
||
395 | * - 'anon-public-user-private': Make this object cacheable for logged-out |
||
396 | * users, but private for logged-in users. IMPORTANT: If this is set, it must be |
||
397 | * set consistently for a given URL, it cannot be set differently depending on |
||
398 | * things like the contents of the database, or whether the user is logged in. |
||
399 | * |
||
400 | * If the wiki does not allow anonymous users to read it, the mode set here |
||
401 | * will be ignored, and private caching headers will always be sent. In other words, |
||
402 | * the "public" mode is equivalent to saying that the data sent is as public as a page |
||
403 | * view. |
||
404 | * |
||
405 | * For user-dependent data, the private mode should generally be used. The |
||
406 | * anon-public-user-private mode should only be used where there is a particularly |
||
407 | * good performance reason for caching the anonymous response, but where the |
||
408 | * response to logged-in users may differ, or may contain private data. |
||
409 | * |
||
410 | * If this function is never called, then the default will be the private mode. |
||
411 | */ |
||
412 | public function setCacheMode( $mode ) { |
||
413 | if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) { |
||
414 | wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" ); |
||
415 | |||
416 | // Ignore for forwards-compatibility |
||
417 | return; |
||
418 | } |
||
419 | |||
420 | if ( !User::isEveryoneAllowed( 'read' ) ) { |
||
421 | // Private wiki, only private headers |
||
422 | if ( $mode !== 'private' ) { |
||
423 | wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" ); |
||
424 | |||
425 | return; |
||
426 | } |
||
427 | } |
||
428 | |||
429 | if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) { |
||
430 | // User language is used for i18n, so we don't want to publicly |
||
431 | // cache. Anons are ok, because if they have non-default language |
||
432 | // then there's an appropriate Vary header set by whatever set |
||
433 | // their non-default language. |
||
434 | wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " . |
||
435 | "'anon-public-user-private' due to uselang=user\n" ); |
||
436 | $mode = 'anon-public-user-private'; |
||
437 | } |
||
438 | |||
439 | wfDebug( __METHOD__ . ": setting cache mode $mode\n" ); |
||
440 | $this->mCacheMode = $mode; |
||
441 | } |
||
442 | |||
443 | /** |
||
444 | * Set directives (key/value pairs) for the Cache-Control header. |
||
445 | * Boolean values will be formatted as such, by including or omitting |
||
446 | * without an equals sign. |
||
447 | * |
||
448 | * Cache control values set here will only be used if the cache mode is not |
||
449 | * private, see setCacheMode(). |
||
450 | * |
||
451 | * @param array $directives |
||
452 | */ |
||
453 | public function setCacheControl( $directives ) { |
||
454 | $this->mCacheControl = $directives + $this->mCacheControl; |
||
455 | } |
||
456 | |||
457 | /** |
||
458 | * Create an instance of an output formatter by its name |
||
459 | * |
||
460 | * @param string $format |
||
461 | * |
||
462 | * @return ApiFormatBase |
||
463 | */ |
||
464 | public function createPrinterByName( $format ) { |
||
465 | $printer = $this->mModuleMgr->getModule( $format, 'format' ); |
||
466 | if ( $printer === null ) { |
||
467 | $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' ); |
||
468 | } |
||
469 | |||
470 | return $printer; |
||
471 | } |
||
472 | |||
473 | /** |
||
474 | * Execute api request. Any errors will be handled if the API was called by the remote client. |
||
475 | */ |
||
476 | public function execute() { |
||
477 | if ( $this->mInternalMode ) { |
||
478 | $this->executeAction(); |
||
479 | } else { |
||
480 | $this->executeActionWithErrorHandling(); |
||
481 | } |
||
482 | } |
||
483 | |||
484 | /** |
||
485 | * Execute an action, and in case of an error, erase whatever partial results |
||
486 | * have been accumulated, and replace it with an error message and a help screen. |
||
487 | */ |
||
488 | protected function executeActionWithErrorHandling() { |
||
489 | // Verify the CORS header before executing the action |
||
490 | if ( !$this->handleCORS() ) { |
||
491 | // handleCORS() has sent a 403, abort |
||
492 | return; |
||
493 | } |
||
494 | |||
495 | // Exit here if the request method was OPTIONS |
||
496 | // (assume there will be a followup GET or POST) |
||
497 | if ( $this->getRequest()->getMethod() === 'OPTIONS' ) { |
||
498 | return; |
||
499 | } |
||
500 | |||
501 | // In case an error occurs during data output, |
||
502 | // clear the output buffer and print just the error information |
||
503 | $obLevel = ob_get_level(); |
||
504 | ob_start(); |
||
505 | |||
506 | $t = microtime( true ); |
||
507 | $isError = false; |
||
508 | try { |
||
509 | $this->executeAction(); |
||
510 | $runTime = microtime( true ) - $t; |
||
511 | $this->logRequest( $runTime ); |
||
512 | if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) { |
||
513 | $this->getStats()->timing( |
||
514 | 'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime |
||
515 | ); |
||
516 | } |
||
517 | } catch ( Exception $e ) { |
||
518 | $this->handleException( $e ); |
||
519 | $this->logRequest( microtime( true ) - $t, $e ); |
||
520 | $isError = true; |
||
521 | } |
||
522 | |||
523 | // Commit DBs and send any related cookies and headers |
||
524 | MediaWiki::preOutputCommit( $this->getContext() ); |
||
525 | |||
526 | // Send cache headers after any code which might generate an error, to |
||
527 | // avoid sending public cache headers for errors. |
||
528 | $this->sendCacheHeaders( $isError ); |
||
529 | |||
530 | // Executing the action might have already messed with the output |
||
531 | // buffers. |
||
532 | while ( ob_get_level() > $obLevel ) { |
||
533 | ob_end_flush(); |
||
534 | } |
||
535 | } |
||
536 | |||
537 | /** |
||
538 | * Handle an exception as an API response |
||
539 | * |
||
540 | * @since 1.23 |
||
541 | * @param Exception $e |
||
542 | */ |
||
543 | protected function handleException( Exception $e ) { |
||
544 | // Bug 63145: Rollback any open database transactions |
||
545 | if ( !( $e instanceof UsageException ) ) { |
||
546 | // UsageExceptions are intentional, so don't rollback if that's the case |
||
547 | try { |
||
548 | MWExceptionHandler::rollbackMasterChangesAndLog( $e ); |
||
549 | } catch ( DBError $e2 ) { |
||
550 | // Rollback threw an exception too. Log it, but don't interrupt |
||
551 | // our regularly scheduled exception handling. |
||
552 | MWExceptionHandler::logException( $e2 ); |
||
553 | } |
||
554 | } |
||
555 | |||
556 | // Allow extra cleanup and logging |
||
557 | Hooks::run( 'ApiMain::onException', [ $this, $e ] ); |
||
558 | |||
559 | // Log it |
||
560 | if ( !( $e instanceof UsageException ) ) { |
||
561 | MWExceptionHandler::logException( $e ); |
||
562 | } |
||
563 | |||
564 | // Handle any kind of exception by outputting properly formatted error message. |
||
565 | // If this fails, an unhandled exception should be thrown so that global error |
||
566 | // handler will process and log it. |
||
567 | |||
568 | $errCode = $this->substituteResultWithError( $e ); |
||
569 | |||
570 | // Error results should not be cached |
||
571 | $this->setCacheMode( 'private' ); |
||
572 | |||
573 | $response = $this->getRequest()->response(); |
||
574 | $headerStr = 'MediaWiki-API-Error: ' . $errCode; |
||
575 | $response->header( $headerStr ); |
||
576 | |||
577 | // Reset and print just the error message |
||
578 | ob_clean(); |
||
579 | |||
580 | // Printer may not be initialized if the extractRequestParams() fails for the main module |
||
581 | $this->createErrorPrinter(); |
||
582 | |||
583 | try { |
||
584 | $this->printResult( $e->getCode() ); |
||
585 | } catch ( UsageException $ex ) { |
||
586 | // The error printer itself is failing. Try suppressing its request |
||
587 | // parameters and redo. |
||
588 | $this->setWarning( |
||
589 | 'Error printer failed (will retry without params): ' . $ex->getMessage() |
||
590 | ); |
||
591 | $this->mPrinter = null; |
||
592 | $this->createErrorPrinter(); |
||
593 | $this->mPrinter->forceDefaultParams(); |
||
594 | if ( $e->getCode() ) { |
||
595 | $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200 |
||
596 | } |
||
597 | $this->printResult( $e->getCode() ); |
||
598 | } |
||
599 | } |
||
600 | |||
601 | /** |
||
602 | * Handle an exception from the ApiBeforeMain hook. |
||
603 | * |
||
604 | * This tries to print the exception as an API response, to be more |
||
605 | * friendly to clients. If it fails, it will rethrow the exception. |
||
606 | * |
||
607 | * @since 1.23 |
||
608 | * @param Exception $e |
||
609 | * @throws Exception |
||
610 | */ |
||
611 | public static function handleApiBeforeMainException( Exception $e ) { |
||
628 | |||
629 | /** |
||
630 | * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. |
||
631 | * |
||
632 | * If no origin parameter is present, nothing happens. |
||
633 | * If an origin parameter is present but doesn't match the Origin header, a 403 status code |
||
634 | * is set and false is returned. |
||
635 | * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains |
||
636 | * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS |
||
637 | * headers are set. |
||
638 | * https://www.w3.org/TR/cors/#resource-requests |
||
639 | * https://www.w3.org/TR/cors/#resource-preflight-requests |
||
640 | * |
||
641 | * @return bool False if the caller should abort (403 case), true otherwise (all other cases) |
||
642 | */ |
||
643 | protected function handleCORS() { |
||
739 | |||
740 | /** |
||
741 | * Attempt to match an Origin header against a set of rules and a set of exceptions |
||
742 | * @param string $value Origin header |
||
743 | * @param array $rules Set of wildcard rules |
||
744 | * @param array $exceptions Set of wildcard rules |
||
745 | * @return bool True if $value matches a rule in $rules and doesn't match |
||
746 | * any rules in $exceptions, false otherwise |
||
747 | */ |
||
748 | protected static function matchOrigin( $value, $rules, $exceptions ) { |
||
764 | |||
765 | /** |
||
766 | * Attempt to validate the value of Access-Control-Request-Headers against a list |
||
767 | * of headers that we allow the follow up request to send. |
||
768 | * |
||
769 | * @param string $requestedHeaders Comma seperated list of HTTP headers |
||
770 | * @return bool True if all requested headers are in the list of allowed headers |
||
771 | */ |
||
772 | protected static function matchRequestedHeaders( $requestedHeaders ) { |
||
799 | |||
800 | /** |
||
801 | * Helper function to convert wildcard string into a regex |
||
802 | * '*' => '.*?' |
||
803 | * '?' => '.' |
||
804 | * |
||
805 | * @param string $wildcard String with wildcards |
||
806 | * @return string Regular expression |
||
807 | */ |
||
808 | protected static function wildcardToRegex( $wildcard ) { |
||
818 | |||
819 | /** |
||
820 | * Send caching headers |
||
821 | * @param bool $isError Whether an error response is being output |
||
822 | * @since 1.26 added $isError parameter |
||
823 | */ |
||
824 | protected function sendCacheHeaders( $isError ) { |
||
938 | |||
939 | /** |
||
940 | * Create the printer for error output |
||
941 | */ |
||
942 | private function createErrorPrinter() { |
||
957 | |||
958 | /** |
||
959 | * Create an error message for the given exception. |
||
960 | * |
||
961 | * If the exception is a UsageException then |
||
962 | * UsageException::getMessageArray() will be called to create the message. |
||
963 | * |
||
964 | * @param Exception $e |
||
965 | * @return array ['code' => 'some string', 'info' => 'some other string'] |
||
966 | * @since 1.27 |
||
967 | */ |
||
968 | protected function errorMessageFromException( $e ) { |
||
988 | |||
989 | /** |
||
990 | * Replace the result data with the information about an exception. |
||
991 | * Returns the error code |
||
992 | * @param Exception $e |
||
993 | * @return string |
||
994 | */ |
||
995 | protected function substituteResultWithError( $e ) { |
||
1036 | |||
1037 | /** |
||
1038 | * Set up for the execution. |
||
1039 | * @return array |
||
1040 | */ |
||
1041 | protected function setupExecuteAction() { |
||
1071 | |||
1072 | /** |
||
1073 | * Set up the module for response |
||
1074 | * @return ApiBase The module that will handle this action |
||
1075 | * @throws MWException |
||
1076 | * @throws UsageException |
||
1077 | */ |
||
1078 | protected function setupModule() { |
||
1079 | // Instantiate the module requested by the user |
||
1080 | $module = $this->mModuleMgr->getModule( $this->mAction, 'action' ); |
||
1081 | if ( $module === null ) { |
||
1082 | $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' ); |
||
1083 | } |
||
1084 | $moduleParams = $module->extractRequestParams(); |
||
1085 | |||
1086 | // Check token, if necessary |
||
1087 | if ( $module->needsToken() === true ) { |
||
1113 | |||
1114 | /** |
||
1115 | * Check the max lag if necessary |
||
1116 | * @param ApiBase $module Api module being used |
||
1117 | * @param array $params Array an array containing the request parameters. |
||
1118 | * @return bool True on success, false should exit immediately |
||
1119 | */ |
||
1120 | protected function checkMaxLag( $module, $params ) { |
||
1140 | |||
1141 | /** |
||
1142 | * Check selected RFC 7232 precondition headers |
||
1143 | * |
||
1144 | * RFC 7232 envisions a particular model where you send your request to "a |
||
1145 | * resource", and for write requests that you can read "the resource" by |
||
1146 | * changing the method to GET. When the API receives a GET request, it |
||
1147 | * works out even though "the resource" from RFC 7232's perspective might |
||
1148 | * be many resources from MediaWiki's perspective. But it totally fails for |
||
1149 | * a POST, since what HTTP sees as "the resource" is probably just |
||
1150 | * "/api.php" with all the interesting bits in the body. |
||
1151 | * |
||
1152 | * Therefore, we only support RFC 7232 precondition headers for GET (and |
||
1153 | * HEAD). That means we don't need to bother with If-Match and |
||
1154 | * If-Unmodified-Since since they only apply to modification requests. |
||
1155 | * |
||
1156 | * And since we don't support Range, If-Range is ignored too. |
||
1157 | * |
||
1158 | * @since 1.26 |
||
1159 | * @param ApiBase $module Api module being used |
||
1160 | * @return bool True on success, false should exit immediately |
||
1161 | */ |
||
1162 | protected function checkConditionalRequestHeaders( $module ) { |
||
1255 | |||
1256 | /** |
||
1257 | * Check for sufficient permissions to execute |
||
1258 | * @param ApiBase $module An Api module |
||
1259 | */ |
||
1260 | protected function checkExecutePermissions( $module ) { |
||
1289 | |||
1290 | /** |
||
1291 | * Check if the DB is read-only for this user |
||
1292 | * @param ApiBase $module An Api module |
||
1293 | */ |
||
1294 | protected function checkReadOnly( $module ) { |
||
1306 | |||
1307 | /** |
||
1308 | * Check whether we are readonly for bots |
||
1309 | */ |
||
1310 | private function checkBotReadOnly() { |
||
1342 | |||
1343 | /** |
||
1344 | * Check asserts of the user's rights |
||
1345 | * @param array $params |
||
1346 | */ |
||
1347 | protected function checkAsserts( $params ) { |
||
1373 | |||
1374 | /** |
||
1375 | * Check POST for external response and setup result printer |
||
1376 | * @param ApiBase $module An Api module |
||
1377 | * @param array $params An array with the request parameters |
||
1378 | */ |
||
1379 | protected function setupExternalResponse( $module, $params ) { |
||
1403 | |||
1404 | /** |
||
1405 | * Execute the actual module, without any error handling |
||
1406 | */ |
||
1407 | protected function executeAction() { |
||
1446 | |||
1447 | /** |
||
1448 | * Set database connection, query, and write expectations given this module request |
||
1449 | * @param ApiBase $module |
||
1450 | */ |
||
1451 | protected function setRequestExpectations( ApiBase $module ) { |
||
1464 | |||
1465 | /** |
||
1466 | * Log the preceding request |
||
1467 | * @param float $time Time in seconds |
||
1468 | * @param Exception $e Exception caught while processing the request |
||
1469 | */ |
||
1470 | protected function logRequest( $time, $e = null ) { |
||
1514 | |||
1515 | /** |
||
1516 | * Encode a value in a format suitable for a space-separated log line. |
||
1517 | * @param string $s |
||
1518 | * @return string |
||
1519 | */ |
||
1520 | protected function encodeRequestLogValue( $s ) { |
||
1532 | |||
1533 | /** |
||
1534 | * Get the request parameters used in the course of the preceding execute() request |
||
1535 | * @return array |
||
1536 | */ |
||
1537 | protected function getParamsUsed() { |
||
1540 | |||
1541 | /** |
||
1542 | * Mark parameters as used |
||
1543 | * @param string|string[] $params |
||
1544 | */ |
||
1545 | public function markParamsUsed( $params ) { |
||
1548 | |||
1549 | /** |
||
1550 | * Get a request value, and register the fact that it was used, for logging. |
||
1551 | * @param string $name |
||
1552 | * @param mixed $default |
||
1553 | * @return mixed |
||
1554 | */ |
||
1555 | public function getVal( $name, $default = null ) { |
||
1571 | |||
1572 | /** |
||
1573 | * Get a boolean request value, and register the fact that the parameter |
||
1574 | * was used, for logging. |
||
1575 | * @param string $name |
||
1576 | * @return bool |
||
1577 | */ |
||
1578 | public function getCheck( $name ) { |
||
1581 | |||
1582 | /** |
||
1583 | * Get a request upload, and register the fact that it was used, for logging. |
||
1584 | * |
||
1585 | * @since 1.21 |
||
1586 | * @param string $name Parameter name |
||
1587 | * @return WebRequestUpload |
||
1588 | */ |
||
1589 | public function getUpload( $name ) { |
||
1594 | |||
1595 | /** |
||
1596 | * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know, |
||
1597 | * for example in case of spelling mistakes or a missing 'g' prefix for generators. |
||
1598 | */ |
||
1599 | protected function reportUnusedParams() { |
||
1619 | |||
1620 | /** |
||
1621 | * Print results using the current printer |
||
1622 | * |
||
1623 | * @param int $httpCode HTTP status code, or 0 to not change |
||
1624 | */ |
||
1625 | protected function printResult( $httpCode = 0 ) { |
||
1638 | |||
1639 | /** |
||
1640 | * @return bool |
||
1641 | */ |
||
1642 | public function isReadMode() { |
||
1645 | |||
1646 | /** |
||
1647 | * See ApiBase for description. |
||
1648 | * |
||
1649 | * @return array |
||
1650 | */ |
||
1651 | public function getAllowedParams() { |
||
1687 | |||
1688 | /** @see ApiBase::getExamplesMessages() */ |
||
1689 | protected function getExamplesMessages() { |
||
1697 | |||
1698 | public function modifyHelp( array &$help, array $options, array &$tocData ) { |
||
1795 | |||
1796 | private $mCanApiHighLimits = null; |
||
1797 | |||
1798 | /** |
||
1799 | * Check whether the current user is allowed to use high limits |
||
1800 | * @return bool |
||
1801 | */ |
||
1802 | public function canApiHighLimits() { |
||
1809 | |||
1810 | /** |
||
1811 | * Overrides to return this instance's module manager. |
||
1812 | * @return ApiModuleManager |
||
1813 | */ |
||
1814 | public function getModuleManager() { |
||
1817 | |||
1818 | /** |
||
1819 | * Fetches the user agent used for this request |
||
1820 | * |
||
1821 | * The value will be the combination of the 'Api-User-Agent' header (if |
||
1822 | * any) and the standard User-Agent header (if any). |
||
1823 | * |
||
1824 | * @return string |
||
1825 | */ |
||
1826 | public function getUserAgent() { |
||
1832 | } |
||
1833 | |||
1902 |
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.