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