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