Merge "mediawiki.Title: Fix typo "add" in documentation"
[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 // Figure out how many servers have passed the lag threshold
1185 $numLagged = 0;
1186 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1187 foreach ( wfGetLB()->getLagTimes() as $lag ) {
1188 if ( $lag > $lagLimit ) {
1189 ++$numLagged;
1190 }
1191 }
1192 // If a majority of slaves are too lagged then disallow writes
1193 $slaveCount = wfGetLB()->getServerCount() - 1;
1194 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1195 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1196 $this->dieUsage(
1197 $parsed['info'],
1198 $parsed['code'],
1199 /* http error */
1200 0,
1201 array( 'readonlyreason' => "Waiting for $numLagged lagged database(s)" )
1202 );
1203 }
1204 }
1205 }
1206
1207 /**
1208 * Check asserts of the user's rights
1209 * @param array $params
1210 */
1211 protected function checkAsserts( $params ) {
1212 if ( isset( $params['assert'] ) ) {
1213 $user = $this->getUser();
1214 switch ( $params['assert'] ) {
1215 case 'user':
1216 if ( $user->isAnon() ) {
1217 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1218 }
1219 break;
1220 case 'bot':
1221 if ( !$user->isAllowed( 'bot' ) ) {
1222 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1223 }
1224 break;
1225 }
1226 }
1227 }
1228
1229 /**
1230 * Check POST for external response and setup result printer
1231 * @param ApiBase $module An Api module
1232 * @param array $params An array with the request parameters
1233 */
1234 protected function setupExternalResponse( $module, $params ) {
1235 $request = $this->getRequest();
1236 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1237 // Module requires POST. GET request might still be allowed
1238 // if $wgDebugApi is true, otherwise fail.
1239 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
1240 }
1241
1242 // See if custom printer is used
1243 $this->mPrinter = $module->getCustomPrinter();
1244 if ( is_null( $this->mPrinter ) ) {
1245 // Create an appropriate printer
1246 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1247 }
1248
1249 if ( $request->getProtocol() === 'http' && (
1250 $request->getSession()->shouldForceHTTPS() ||
1251 ( $this->getUser()->isLoggedIn() &&
1252 $this->getUser()->requiresHTTPS() )
1253 ) ) {
1254 $this->logFeatureUsage( 'https-expected' );
1255 $this->setWarning( 'HTTP used when HTTPS was expected' );
1256 }
1257 }
1258
1259 /**
1260 * Execute the actual module, without any error handling
1261 */
1262 protected function executeAction() {
1263 $params = $this->setupExecuteAction();
1264 $module = $this->setupModule();
1265 $this->mModule = $module;
1266
1267 $this->setRequestExpectations( $module );
1268
1269 $this->checkExecutePermissions( $module );
1270
1271 if ( !$this->checkMaxLag( $module, $params ) ) {
1272 return;
1273 }
1274
1275 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1276 return;
1277 }
1278
1279 if ( !$this->mInternalMode ) {
1280 $this->setupExternalResponse( $module, $params );
1281 }
1282
1283 $this->checkAsserts( $params );
1284
1285 // Execute
1286 $module->execute();
1287 Hooks::run( 'APIAfterExecute', array( &$module ) );
1288
1289 $this->reportUnusedParams();
1290
1291 if ( !$this->mInternalMode ) {
1292 // append Debug information
1293 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1294
1295 // Print result data
1296 $this->printResult( false );
1297 }
1298 }
1299
1300 /**
1301 * Set database connection, query, and write expectations given this module request
1302 * @param ApiBase $module
1303 */
1304 protected function setRequestExpectations( ApiBase $module ) {
1305 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1306 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1307 if ( $this->getRequest()->wasPosted() ) {
1308 if ( $module->isWriteMode() ) {
1309 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1310 } else {
1311 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1312 }
1313 } else {
1314 $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1315 }
1316 }
1317
1318 /**
1319 * Log the preceding request
1320 * @param float $time Time in seconds
1321 */
1322 protected function logRequest( $time ) {
1323 $request = $this->getRequest();
1324 $logCtx = array(
1325 'dt' => date( 'c' ),
1326 'client_ip' => $request->getIP(),
1327 'user_agent' => $this->getUserAgent(),
1328 'wiki' => wfWikiID(),
1329 'time_backend_ms' => round( $time * 1000 ),
1330 'params' => array(),
1331 );
1332
1333 // Construct space separated message for 'api' log channel
1334 $msg = "API {$request->getMethod()} " .
1335 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1336 " {$logCtx['client_ip']} " .
1337 "T={$logCtx['time_backend_ms']}ms";
1338
1339 foreach ( $this->getParamsUsed() as $name ) {
1340 $value = $request->getVal( $name );
1341 if ( $value === null ) {
1342 continue;
1343 }
1344
1345 if ( strlen( $value ) > 256 ) {
1346 $value = substr( $value, 0, 256 );
1347 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1348 } else {
1349 $encValue = $this->encodeRequestLogValue( $value );
1350 }
1351
1352 $logCtx['params'][$name] = $value;
1353 $msg .= " {$name}={$encValue}";
1354 }
1355
1356 wfDebugLog( 'api', $msg, 'private' );
1357 // ApiRequest channel is for structured data consumers
1358 wfDebugLog( 'ApiRequest', '', 'private', $logCtx );
1359 }
1360
1361 /**
1362 * Encode a value in a format suitable for a space-separated log line.
1363 * @param string $s
1364 * @return string
1365 */
1366 protected function encodeRequestLogValue( $s ) {
1367 static $table;
1368 if ( !$table ) {
1369 $chars = ';@$!*(),/:';
1370 $numChars = strlen( $chars );
1371 for ( $i = 0; $i < $numChars; $i++ ) {
1372 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1373 }
1374 }
1375
1376 return strtr( rawurlencode( $s ), $table );
1377 }
1378
1379 /**
1380 * Get the request parameters used in the course of the preceding execute() request
1381 * @return array
1382 */
1383 protected function getParamsUsed() {
1384 return array_keys( $this->mParamsUsed );
1385 }
1386
1387 /**
1388 * Get a request value, and register the fact that it was used, for logging.
1389 * @param string $name
1390 * @param mixed $default
1391 * @return mixed
1392 */
1393 public function getVal( $name, $default = null ) {
1394 $this->mParamsUsed[$name] = true;
1395
1396 $ret = $this->getRequest()->getVal( $name );
1397 if ( $ret === null ) {
1398 if ( $this->getRequest()->getArray( $name ) !== null ) {
1399 // See bug 10262 for why we don't just join( '|', ... ) the
1400 // array.
1401 $this->setWarning(
1402 "Parameter '$name' uses unsupported PHP array syntax"
1403 );
1404 }
1405 $ret = $default;
1406 }
1407 return $ret;
1408 }
1409
1410 /**
1411 * Get a boolean request value, and register the fact that the parameter
1412 * was used, for logging.
1413 * @param string $name
1414 * @return bool
1415 */
1416 public function getCheck( $name ) {
1417 return $this->getVal( $name, null ) !== null;
1418 }
1419
1420 /**
1421 * Get a request upload, and register the fact that it was used, for logging.
1422 *
1423 * @since 1.21
1424 * @param string $name Parameter name
1425 * @return WebRequestUpload
1426 */
1427 public function getUpload( $name ) {
1428 $this->mParamsUsed[$name] = true;
1429
1430 return $this->getRequest()->getUpload( $name );
1431 }
1432
1433 /**
1434 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1435 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1436 */
1437 protected function reportUnusedParams() {
1438 $paramsUsed = $this->getParamsUsed();
1439 $allParams = $this->getRequest()->getValueNames();
1440
1441 if ( !$this->mInternalMode ) {
1442 // Printer has not yet executed; don't warn that its parameters are unused
1443 $printerParams = array_map(
1444 array( $this->mPrinter, 'encodeParamName' ),
1445 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1446 );
1447 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1448 } else {
1449 $unusedParams = array_diff( $allParams, $paramsUsed );
1450 }
1451
1452 if ( count( $unusedParams ) ) {
1453 $s = count( $unusedParams ) > 1 ? 's' : '';
1454 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1455 }
1456 }
1457
1458 /**
1459 * Print results using the current printer
1460 *
1461 * @param bool $isError
1462 */
1463 protected function printResult( $isError ) {
1464 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1465 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1466 }
1467
1468 $printer = $this->mPrinter;
1469 $printer->initPrinter( false );
1470 $printer->execute();
1471 $printer->closePrinter();
1472 }
1473
1474 /**
1475 * @return bool
1476 */
1477 public function isReadMode() {
1478 return false;
1479 }
1480
1481 /**
1482 * See ApiBase for description.
1483 *
1484 * @return array
1485 */
1486 public function getAllowedParams() {
1487 return array(
1488 'action' => array(
1489 ApiBase::PARAM_DFLT => 'help',
1490 ApiBase::PARAM_TYPE => 'submodule',
1491 ),
1492 'format' => array(
1493 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1494 ApiBase::PARAM_TYPE => 'submodule',
1495 ),
1496 'maxlag' => array(
1497 ApiBase::PARAM_TYPE => 'integer'
1498 ),
1499 'smaxage' => array(
1500 ApiBase::PARAM_TYPE => 'integer',
1501 ApiBase::PARAM_DFLT => 0
1502 ),
1503 'maxage' => array(
1504 ApiBase::PARAM_TYPE => 'integer',
1505 ApiBase::PARAM_DFLT => 0
1506 ),
1507 'assert' => array(
1508 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1509 ),
1510 'requestid' => null,
1511 'servedby' => false,
1512 'curtimestamp' => false,
1513 'origin' => null,
1514 'uselang' => array(
1515 ApiBase::PARAM_DFLT => 'user',
1516 ),
1517 );
1518 }
1519
1520 /** @see ApiBase::getExamplesMessages() */
1521 protected function getExamplesMessages() {
1522 return array(
1523 'action=help'
1524 => 'apihelp-help-example-main',
1525 'action=help&recursivesubmodules=1'
1526 => 'apihelp-help-example-recursive',
1527 );
1528 }
1529
1530 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1531 // Wish PHP had an "array_insert_before". Instead, we have to manually
1532 // reindex the array to get 'permissions' in the right place.
1533 $oldHelp = $help;
1534 $help = array();
1535 foreach ( $oldHelp as $k => $v ) {
1536 if ( $k === 'submodules' ) {
1537 $help['permissions'] = '';
1538 }
1539 $help[$k] = $v;
1540 }
1541 $help['datatypes'] = '';
1542 $help['credits'] = '';
1543
1544 // Fill 'permissions'
1545 $help['permissions'] .= Html::openElement( 'div',
1546 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1547 $m = $this->msg( 'api-help-permissions' );
1548 if ( !$m->isDisabled() ) {
1549 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1550 $m->numParams( count( self::$mRights ) )->parse()
1551 );
1552 }
1553 $help['permissions'] .= Html::openElement( 'dl' );
1554 foreach ( self::$mRights as $right => $rightMsg ) {
1555 $help['permissions'] .= Html::element( 'dt', null, $right );
1556
1557 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1558 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1559
1560 $groups = array_map( function ( $group ) {
1561 return $group == '*' ? 'all' : $group;
1562 }, User::getGroupsWithPermission( $right ) );
1563
1564 $help['permissions'] .= Html::rawElement( 'dd', null,
1565 $this->msg( 'api-help-permissions-granted-to' )
1566 ->numParams( count( $groups ) )
1567 ->params( $this->getLanguage()->commaList( $groups ) )
1568 ->parse()
1569 );
1570 }
1571 $help['permissions'] .= Html::closeElement( 'dl' );
1572 $help['permissions'] .= Html::closeElement( 'div' );
1573
1574 // Fill 'datatypes' and 'credits', if applicable
1575 if ( empty( $options['nolead'] ) ) {
1576 $level = $options['headerlevel'];
1577 $tocnumber = &$options['tocnumber'];
1578
1579 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1580 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1581 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1582 Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/datatypes' ) ) ) .
1583 $header
1584 );
1585 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1586 if ( !isset( $tocData['main/datatypes'] ) ) {
1587 $tocnumber[$level]++;
1588 $tocData['main/datatypes'] = array(
1589 'toclevel' => count( $tocnumber ),
1590 'level' => $level,
1591 'anchor' => 'main/datatypes',
1592 'line' => $header,
1593 'number' => join( '.', $tocnumber ),
1594 'index' => false,
1595 );
1596 }
1597
1598 $header = $this->msg( 'api-credits-header' )->parse();
1599 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1600 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1601 Html::element( 'span', array( 'id' => Sanitizer::escapeId( 'main/credits' ) ) ) .
1602 $header
1603 );
1604 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1605 if ( !isset( $tocData['main/credits'] ) ) {
1606 $tocnumber[$level]++;
1607 $tocData['main/credits'] = array(
1608 'toclevel' => count( $tocnumber ),
1609 'level' => $level,
1610 'anchor' => 'main/credits',
1611 'line' => $header,
1612 'number' => join( '.', $tocnumber ),
1613 'index' => false,
1614 );
1615 }
1616 }
1617 }
1618
1619 private $mCanApiHighLimits = null;
1620
1621 /**
1622 * Check whether the current user is allowed to use high limits
1623 * @return bool
1624 */
1625 public function canApiHighLimits() {
1626 if ( !isset( $this->mCanApiHighLimits ) ) {
1627 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1628 }
1629
1630 return $this->mCanApiHighLimits;
1631 }
1632
1633 /**
1634 * Overrides to return this instance's module manager.
1635 * @return ApiModuleManager
1636 */
1637 public function getModuleManager() {
1638 return $this->mModuleMgr;
1639 }
1640
1641 /**
1642 * Fetches the user agent used for this request
1643 *
1644 * The value will be the combination of the 'Api-User-Agent' header (if
1645 * any) and the standard User-Agent header (if any).
1646 *
1647 * @return string
1648 */
1649 public function getUserAgent() {
1650 return trim(
1651 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1652 $this->getRequest()->getHeader( 'User-agent' )
1653 );
1654 }
1655
1656 /************************************************************************//**
1657 * @name Deprecated
1658 * @{
1659 */
1660
1661 /**
1662 * Sets whether the pretty-printer should format *bold* and $italics$
1663 *
1664 * @deprecated since 1.25
1665 * @param bool $help
1666 */
1667 public function setHelp( $help = true ) {
1668 wfDeprecated( __METHOD__, '1.25' );
1669 $this->mPrinter->setHelp( $help );
1670 }
1671
1672 /**
1673 * Override the parent to generate help messages for all available modules.
1674 *
1675 * @deprecated since 1.25
1676 * @return string
1677 */
1678 public function makeHelpMsg() {
1679 wfDeprecated( __METHOD__, '1.25' );
1680
1681 $this->setHelp();
1682 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1683
1684 return ObjectCache::getMainWANInstance()->getWithSetCallback(
1685 wfMemcKey(
1686 'apihelp',
1687 $this->getModuleName(),
1688 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1689 ),
1690 $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1691 array( $this, 'reallyMakeHelpMsg' )
1692 );
1693 }
1694
1695 /**
1696 * @deprecated since 1.25
1697 * @return mixed|string
1698 */
1699 public function reallyMakeHelpMsg() {
1700 wfDeprecated( __METHOD__, '1.25' );
1701 $this->setHelp();
1702
1703 // Use parent to make default message for the main module
1704 $msg = parent::makeHelpMsg();
1705
1706 $astriks = str_repeat( '*** ', 14 );
1707 $msg .= "\n\n$astriks Modules $astriks\n\n";
1708
1709 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1710 $module = $this->mModuleMgr->getModule( $name );
1711 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1712
1713 $msg2 = $module->makeHelpMsg();
1714 if ( $msg2 !== false ) {
1715 $msg .= $msg2;
1716 }
1717 $msg .= "\n";
1718 }
1719
1720 $msg .= "\n$astriks Permissions $astriks\n\n";
1721 foreach ( self::$mRights as $right => $rightMsg ) {
1722 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1723 ->useDatabase( false )
1724 ->inLanguage( 'en' )
1725 ->text();
1726 $groups = User::getGroupsWithPermission( $right );
1727 $msg .= "* " . $right . " *\n $rightsMsg" .
1728 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1729 }
1730
1731 $msg .= "\n$astriks Formats $astriks\n\n";
1732 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1733 $module = $this->mModuleMgr->getModule( $name );
1734 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1735 $msg2 = $module->makeHelpMsg();
1736 if ( $msg2 !== false ) {
1737 $msg .= $msg2;
1738 }
1739 $msg .= "\n";
1740 }
1741
1742 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1743 $credits = str_replace( "\n", "\n ", $credits );
1744 $msg .= "\n*** Credits: ***\n $credits\n";
1745
1746 return $msg;
1747 }
1748
1749 /**
1750 * @deprecated since 1.25
1751 * @param ApiBase $module
1752 * @param string $paramName What type of request is this? e.g. action,
1753 * query, list, prop, meta, format
1754 * @return string
1755 */
1756 public static function makeHelpMsgHeader( $module, $paramName ) {
1757 wfDeprecated( __METHOD__, '1.25' );
1758 $modulePrefix = $module->getModulePrefix();
1759 if ( strval( $modulePrefix ) !== '' ) {
1760 $modulePrefix = "($modulePrefix) ";
1761 }
1762
1763 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1764 }
1765
1766 /**
1767 * Check whether the user wants us to show version information in the API help
1768 * @return bool
1769 * @deprecated since 1.21, always returns false
1770 */
1771 public function getShowVersions() {
1772 wfDeprecated( __METHOD__, '1.21' );
1773
1774 return false;
1775 }
1776
1777 /**
1778 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1779 * classes who wish to add their own modules to their lexicon or override the
1780 * behavior of inherent ones.
1781 *
1782 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1783 * @param string $name The identifier for this module.
1784 * @param ApiBase $class The class where this module is implemented.
1785 */
1786 protected function addModule( $name, $class ) {
1787 $this->getModuleManager()->addModule( $name, 'action', $class );
1788 }
1789
1790 /**
1791 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1792 * classes who wish to add to or modify current formatters.
1793 *
1794 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1795 * @param string $name The identifier for this format.
1796 * @param ApiFormatBase $class The class implementing this format.
1797 */
1798 protected function addFormat( $name, $class ) {
1799 $this->getModuleManager()->addModule( $name, 'format', $class );
1800 }
1801
1802 /**
1803 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1804 *
1805 * @since 1.18
1806 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1807 * @return array
1808 */
1809 public function getFormats() {
1810 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1811 }
1812
1813 /**@}*/
1814
1815 }
1816
1817 /**
1818 * This exception will be thrown when dieUsage is called to stop module execution.
1819 *
1820 * @ingroup API
1821 */
1822 class UsageException extends MWException {
1823
1824 private $mCodestr;
1825
1826 /**
1827 * @var null|array
1828 */
1829 private $mExtraData;
1830
1831 /**
1832 * @param string $message
1833 * @param string $codestr
1834 * @param int $code
1835 * @param array|null $extradata
1836 */
1837 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1838 parent::__construct( $message, $code );
1839 $this->mCodestr = $codestr;
1840 $this->mExtraData = $extradata;
1841 }
1842
1843 /**
1844 * @return string
1845 */
1846 public function getCodeString() {
1847 return $this->mCodestr;
1848 }
1849
1850 /**
1851 * @return array
1852 */
1853 public function getMessageArray() {
1854 $result = array(
1855 'code' => $this->mCodestr,
1856 'info' => $this->getMessage()
1857 );
1858 if ( is_array( $this->mExtraData ) ) {
1859 $result = array_merge( $result, $this->mExtraData );
1860 }
1861
1862 return $result;
1863 }
1864
1865 /**
1866 * @return string
1867 */
1868 public function __toString() {
1869 return "{$this->getCodeString()}: {$this->getMessage()}";
1870 }
1871 }
1872
1873 /**
1874 * For really cool vim folding this needs to be at the end:
1875 * vim: foldmarker=@{,@} foldmethod=marker
1876 */