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