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