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