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