Merge "Fix list=logevents for new revision delete log entries"
[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 try {
420 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
421 } catch ( DBError $e2 ) {
422 // Rollback threw an exception too. Log it, but don't interrupt
423 // our regularly scheduled exception handling.
424 MWExceptionHandler::logException( $e2 );
425 }
426 }
427
428 // Allow extra cleanup and logging
429 Hooks::run( 'ApiMain::onException', array( $this, $e ) );
430
431 // Log it
432 if ( !( $e instanceof UsageException ) ) {
433 MWExceptionHandler::logException( $e );
434 }
435
436 // Handle any kind of exception by outputting properly formatted error message.
437 // If this fails, an unhandled exception should be thrown so that global error
438 // handler will process and log it.
439
440 $errCode = $this->substituteResultWithError( $e );
441
442 // Error results should not be cached
443 $this->setCacheMode( 'private' );
444
445 $response = $this->getRequest()->response();
446 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
447 if ( $e->getCode() === 0 ) {
448 $response->header( $headerStr );
449 } else {
450 $response->header( $headerStr, true, $e->getCode() );
451 }
452
453 // Reset and print just the error message
454 ob_clean();
455
456 $this->printResult( true );
457 }
458
459 /**
460 * Handle an exception from the ApiBeforeMain hook.
461 *
462 * This tries to print the exception as an API response, to be more
463 * friendly to clients. If it fails, it will rethrow the exception.
464 *
465 * @since 1.23
466 * @param Exception $e
467 * @throws Exception
468 */
469 public static function handleApiBeforeMainException( Exception $e ) {
470 ob_start();
471
472 try {
473 $main = new self( RequestContext::getMain(), false );
474 $main->handleException( $e );
475 } catch ( Exception $e2 ) {
476 // Nope, even that didn't work. Punt.
477 throw $e;
478 }
479
480 // Log the request and reset cache headers
481 $main->logRequest( 0 );
482 $main->sendCacheHeaders();
483
484 ob_end_flush();
485 }
486
487 /**
488 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
489 *
490 * If no origin parameter is present, nothing happens.
491 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
492 * is set and false is returned.
493 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
494 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
495 * headers are set.
496 * http://www.w3.org/TR/cors/#resource-requests
497 * http://www.w3.org/TR/cors/#resource-preflight-requests
498 *
499 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
500 */
501 protected function handleCORS() {
502 $originParam = $this->getParameter( 'origin' ); // defaults to null
503 if ( $originParam === null ) {
504 // No origin parameter, nothing to do
505 return true;
506 }
507
508 $request = $this->getRequest();
509 $response = $request->response();
510
511 // Origin: header is a space-separated list of origins, check all of them
512 $originHeader = $request->getHeader( 'Origin' );
513 if ( $originHeader === false ) {
514 $origins = array();
515 } else {
516 $originHeader = trim( $originHeader );
517 $origins = preg_split( '/\s+/', $originHeader );
518 }
519
520 if ( !in_array( $originParam, $origins ) ) {
521 // origin parameter set but incorrect
522 // Send a 403 response
523 $message = HttpStatus::getMessage( 403 );
524 $response->header( "HTTP/1.1 403 $message", true, 403 );
525 $response->header( 'Cache-Control: no-cache' );
526 echo "'origin' parameter does not match Origin header\n";
527
528 return false;
529 }
530
531 $config = $this->getConfig();
532 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
533 $originParam,
534 $config->get( 'CrossSiteAJAXdomains' ),
535 $config->get( 'CrossSiteAJAXdomainExceptions' )
536 );
537
538 if ( $matchOrigin ) {
539 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
540 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
541 if ( $preflight ) {
542 // This is a CORS preflight request
543 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
544 // If method is not a case-sensitive match, do not set any additional headers and terminate.
545 return true;
546 }
547 // We allow the actual request to send the following headers
548 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
549 if ( $requestedHeaders !== false ) {
550 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
551 return true;
552 }
553 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
554 }
555
556 // We only allow the actual request to be GET or POST
557 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
558 }
559
560 $response->header( "Access-Control-Allow-Origin: $originHeader" );
561 $response->header( 'Access-Control-Allow-Credentials: true' );
562 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
563
564 if ( !$preflight ) {
565 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
566 }
567 }
568
569 $this->getOutput()->addVaryHeader( 'Origin' );
570 return true;
571 }
572
573 /**
574 * Attempt to match an Origin header against a set of rules and a set of exceptions
575 * @param string $value Origin header
576 * @param array $rules Set of wildcard rules
577 * @param array $exceptions Set of wildcard rules
578 * @return bool True if $value matches a rule in $rules and doesn't match
579 * any rules in $exceptions, false otherwise
580 */
581 protected static function matchOrigin( $value, $rules, $exceptions ) {
582 foreach ( $rules as $rule ) {
583 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
584 // Rule matches, check exceptions
585 foreach ( $exceptions as $exc ) {
586 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
587 return false;
588 }
589 }
590
591 return true;
592 }
593 }
594
595 return false;
596 }
597
598 /**
599 * Attempt to validate the value of Access-Control-Request-Headers against a list
600 * of headers that we allow the follow up request to send.
601 *
602 * @param string $requestedHeaders Comma seperated list of HTTP headers
603 * @return bool True if all requested headers are in the list of allowed headers
604 */
605 protected static function matchRequestedHeaders( $requestedHeaders ) {
606 if ( trim( $requestedHeaders ) === '' ) {
607 return true;
608 }
609 $requestedHeaders = explode( ',', $requestedHeaders );
610 $allowedAuthorHeaders = array_flip( array(
611 /* simple headers (see spec) */
612 'accept',
613 'accept-language',
614 'content-language',
615 'content-type',
616 /* non-authorable headers in XHR, which are however requested by some UAs */
617 'accept-encoding',
618 'dnt',
619 'origin',
620 /* MediaWiki whitelist */
621 'api-user-agent',
622 ) );
623 foreach ( $requestedHeaders as $rHeader ) {
624 $rHeader = strtolower( trim( $rHeader ) );
625 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
626 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
627 return false;
628 }
629 }
630 return true;
631 }
632
633 /**
634 * Helper function to convert wildcard string into a regex
635 * '*' => '.*?'
636 * '?' => '.'
637 *
638 * @param string $wildcard String with wildcards
639 * @return string Regular expression
640 */
641 protected static function wildcardToRegex( $wildcard ) {
642 $wildcard = preg_quote( $wildcard, '/' );
643 $wildcard = str_replace(
644 array( '\*', '\?' ),
645 array( '.*?', '.' ),
646 $wildcard
647 );
648
649 return "/^https?:\/\/$wildcard$/";
650 }
651
652 protected function sendCacheHeaders() {
653 $response = $this->getRequest()->response();
654 $out = $this->getOutput();
655
656 $config = $this->getConfig();
657
658 if ( $config->get( 'VaryOnXFP' ) ) {
659 $out->addVaryHeader( 'X-Forwarded-Proto' );
660 }
661
662 // The logic should be:
663 // $this->mCacheControl['max-age'] is set?
664 // Use it, the module knows better than our guess.
665 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
666 // Use 0 because we can guess caching is probably the wrong thing to do.
667 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
668 $maxage = 0;
669 if ( isset( $this->mCacheControl['max-age'] ) ) {
670 $maxage = $this->mCacheControl['max-age'];
671 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
672 $this->mCacheMode !== 'private'
673 ) {
674 $maxage = $this->getParameter( 'maxage' );
675 }
676 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
677
678 if ( $this->mCacheMode == 'private' ) {
679 $response->header( "Cache-Control: $privateCache" );
680 return;
681 }
682
683 $useXVO = $config->get( 'UseXVO' );
684 if ( $this->mCacheMode == 'anon-public-user-private' ) {
685 $out->addVaryHeader( 'Cookie' );
686 $response->header( $out->getVaryHeader() );
687 if ( $useXVO ) {
688 $response->header( $out->getXVO() );
689 if ( $out->haveCacheVaryCookies() ) {
690 // Logged in, mark this request private
691 $response->header( "Cache-Control: $privateCache" );
692 return;
693 }
694 // Logged out, send normal public headers below
695 } elseif ( session_id() != '' ) {
696 // Logged in or otherwise has session (e.g. anonymous users who have edited)
697 // Mark request private
698 $response->header( "Cache-Control: $privateCache" );
699
700 return;
701 } // else no XVO and anonymous, send public headers below
702 }
703
704 // Send public headers
705 $response->header( $out->getVaryHeader() );
706 if ( $useXVO ) {
707 $response->header( $out->getXVO() );
708 }
709
710 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
711 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
712 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
713 }
714 if ( !isset( $this->mCacheControl['max-age'] ) ) {
715 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
716 }
717
718 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
719 // Public cache not requested
720 // Sending a Vary header in this case is harmless, and protects us
721 // against conditional calls of setCacheMaxAge().
722 $response->header( "Cache-Control: $privateCache" );
723
724 return;
725 }
726
727 $this->mCacheControl['public'] = true;
728
729 // Send an Expires header
730 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
731 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
732 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
733
734 // Construct the Cache-Control header
735 $ccHeader = '';
736 $separator = '';
737 foreach ( $this->mCacheControl as $name => $value ) {
738 if ( is_bool( $value ) ) {
739 if ( $value ) {
740 $ccHeader .= $separator . $name;
741 $separator = ', ';
742 }
743 } else {
744 $ccHeader .= $separator . "$name=$value";
745 $separator = ', ';
746 }
747 }
748
749 $response->header( "Cache-Control: $ccHeader" );
750 }
751
752 /**
753 * Replace the result data with the information about an exception.
754 * Returns the error code
755 * @param Exception $e
756 * @return string
757 */
758 protected function substituteResultWithError( $e ) {
759 $result = $this->getResult();
760
761 // Printer may not be initialized if the extractRequestParams() fails for the main module
762 if ( !isset( $this->mPrinter ) ) {
763 // The printer has not been created yet. Try to manually get formatter value.
764 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
765 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
766 $value = self::API_DEFAULT_FORMAT;
767 }
768
769 $this->mPrinter = $this->createPrinterByName( $value );
770 }
771
772 // Printer may not be able to handle errors. This is particularly
773 // likely if the module returns something for getCustomPrinter().
774 if ( !$this->mPrinter->canPrintErrors() ) {
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->execute();
1044 Hooks::run( 'APIAfterExecute', array( &$module ) );
1045
1046 $this->reportUnusedParams();
1047
1048 if ( !$this->mInternalMode ) {
1049 //append Debug information
1050 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1051
1052 // Print result data
1053 $this->printResult( false );
1054 }
1055 }
1056
1057 /**
1058 * Log the preceding request
1059 * @param int $time Time in seconds
1060 */
1061 protected function logRequest( $time ) {
1062 $request = $this->getRequest();
1063 $milliseconds = $time === null ? '?' : round( $time * 1000 );
1064 $s = 'API' .
1065 ' ' . $request->getMethod() .
1066 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1067 ' ' . $request->getIP() .
1068 ' T=' . $milliseconds . 'ms';
1069 foreach ( $this->getParamsUsed() as $name ) {
1070 $value = $request->getVal( $name );
1071 if ( $value === null ) {
1072 continue;
1073 }
1074 $s .= ' ' . $name . '=';
1075 if ( strlen( $value ) > 256 ) {
1076 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1077 $s .= $encValue . '[...]';
1078 } else {
1079 $s .= $this->encodeRequestLogValue( $value );
1080 }
1081 }
1082 $s .= "\n";
1083 wfDebugLog( 'api', $s, 'private' );
1084 }
1085
1086 /**
1087 * Encode a value in a format suitable for a space-separated log line.
1088 * @param string $s
1089 * @return string
1090 */
1091 protected function encodeRequestLogValue( $s ) {
1092 static $table;
1093 if ( !$table ) {
1094 $chars = ';@$!*(),/:';
1095 $numChars = strlen( $chars );
1096 for ( $i = 0; $i < $numChars; $i++ ) {
1097 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1098 }
1099 }
1100
1101 return strtr( rawurlencode( $s ), $table );
1102 }
1103
1104 /**
1105 * Get the request parameters used in the course of the preceding execute() request
1106 * @return array
1107 */
1108 protected function getParamsUsed() {
1109 return array_keys( $this->mParamsUsed );
1110 }
1111
1112 /**
1113 * Get a request value, and register the fact that it was used, for logging.
1114 * @param string $name
1115 * @param mixed $default
1116 * @return mixed
1117 */
1118 public function getVal( $name, $default = null ) {
1119 $this->mParamsUsed[$name] = true;
1120
1121 $ret = $this->getRequest()->getVal( $name );
1122 if ( $ret === null ) {
1123 if ( $this->getRequest()->getArray( $name ) !== null ) {
1124 // See bug 10262 for why we don't just join( '|', ... ) the
1125 // array.
1126 $this->setWarning(
1127 "Parameter '$name' uses unsupported PHP array syntax"
1128 );
1129 }
1130 $ret = $default;
1131 }
1132 return $ret;
1133 }
1134
1135 /**
1136 * Get a boolean request value, and register the fact that the parameter
1137 * was used, for logging.
1138 * @param string $name
1139 * @return bool
1140 */
1141 public function getCheck( $name ) {
1142 return $this->getVal( $name, null ) !== null;
1143 }
1144
1145 /**
1146 * Get a request upload, and register the fact that it was used, for logging.
1147 *
1148 * @since 1.21
1149 * @param string $name Parameter name
1150 * @return WebRequestUpload
1151 */
1152 public function getUpload( $name ) {
1153 $this->mParamsUsed[$name] = true;
1154
1155 return $this->getRequest()->getUpload( $name );
1156 }
1157
1158 /**
1159 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1160 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1161 */
1162 protected function reportUnusedParams() {
1163 $paramsUsed = $this->getParamsUsed();
1164 $allParams = $this->getRequest()->getValueNames();
1165
1166 if ( !$this->mInternalMode ) {
1167 // Printer has not yet executed; don't warn that its parameters are unused
1168 $printerParams = array_map(
1169 array( $this->mPrinter, 'encodeParamName' ),
1170 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1171 );
1172 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1173 } else {
1174 $unusedParams = array_diff( $allParams, $paramsUsed );
1175 }
1176
1177 if ( count( $unusedParams ) ) {
1178 $s = count( $unusedParams ) > 1 ? 's' : '';
1179 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1180 }
1181 }
1182
1183 /**
1184 * Print results using the current printer
1185 *
1186 * @param bool $isError
1187 */
1188 protected function printResult( $isError ) {
1189 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1190 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1191 }
1192
1193 $this->getResult()->cleanUpUTF8();
1194 $printer = $this->mPrinter;
1195
1196 $printer->initPrinter( false );
1197 $printer->execute();
1198 $printer->closePrinter();
1199 }
1200
1201 /**
1202 * @return bool
1203 */
1204 public function isReadMode() {
1205 return false;
1206 }
1207
1208 /**
1209 * See ApiBase for description.
1210 *
1211 * @return array
1212 */
1213 public function getAllowedParams() {
1214 return array(
1215 'action' => array(
1216 ApiBase::PARAM_DFLT => 'help',
1217 ApiBase::PARAM_TYPE => 'submodule',
1218 ),
1219 'format' => array(
1220 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1221 ApiBase::PARAM_TYPE => 'submodule',
1222 ),
1223 'maxlag' => array(
1224 ApiBase::PARAM_TYPE => 'integer'
1225 ),
1226 'smaxage' => array(
1227 ApiBase::PARAM_TYPE => 'integer',
1228 ApiBase::PARAM_DFLT => 0
1229 ),
1230 'maxage' => array(
1231 ApiBase::PARAM_TYPE => 'integer',
1232 ApiBase::PARAM_DFLT => 0
1233 ),
1234 'assert' => array(
1235 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1236 ),
1237 'requestid' => null,
1238 'servedby' => false,
1239 'curtimestamp' => false,
1240 'origin' => null,
1241 'uselang' => array(
1242 ApiBase::PARAM_DFLT => 'user',
1243 ),
1244 );
1245 }
1246
1247 /** @see ApiBase::getExamplesMessages() */
1248 protected function getExamplesMessages() {
1249 return array(
1250 'action=help'
1251 => 'apihelp-help-example-main',
1252 'action=help&recursivesubmodules=1'
1253 => 'apihelp-help-example-recursive',
1254 );
1255 }
1256
1257 public function modifyHelp( array &$help, array $options ) {
1258 // Wish PHP had an "array_insert_before". Instead, we have to manually
1259 // reindex the array to get 'permissions' in the right place.
1260 $oldHelp = $help;
1261 $help = array();
1262 foreach ( $oldHelp as $k => $v ) {
1263 if ( $k === 'submodules' ) {
1264 $help['permissions'] = '';
1265 }
1266 $help[$k] = $v;
1267 }
1268 $help['credits'] = '';
1269
1270 // Fill 'permissions'
1271 $help['permissions'] .= Html::openElement( 'div',
1272 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1273 $m = $this->msg( 'api-help-permissions' );
1274 if ( !$m->isDisabled() ) {
1275 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1276 $m->numParams( count( self::$mRights ) )->parse()
1277 );
1278 }
1279 $help['permissions'] .= Html::openElement( 'dl' );
1280 foreach ( self::$mRights as $right => $rightMsg ) {
1281 $help['permissions'] .= Html::element( 'dt', null, $right );
1282
1283 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1284 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1285
1286 $groups = array_map( function ( $group ) {
1287 return $group == '*' ? 'all' : $group;
1288 }, User::getGroupsWithPermission( $right ) );
1289
1290 $help['permissions'] .= Html::rawElement( 'dd', null,
1291 $this->msg( 'api-help-permissions-granted-to' )
1292 ->numParams( count( $groups ) )
1293 ->params( $this->getLanguage()->commaList( $groups ) )
1294 ->parse()
1295 );
1296 }
1297 $help['permissions'] .= Html::closeElement( 'dl' );
1298 $help['permissions'] .= Html::closeElement( 'div' );
1299
1300 // Fill 'credits', if applicable
1301 if ( empty( $options['nolead'] ) ) {
1302 $help['credits'] .= Html::element( 'h' . min( 6, $options['headerlevel'] + 1 ),
1303 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1304 $this->msg( 'api-credits-header' )->parse()
1305 );
1306 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1307 }
1308 }
1309
1310 private $mCanApiHighLimits = null;
1311
1312 /**
1313 * Check whether the current user is allowed to use high limits
1314 * @return bool
1315 */
1316 public function canApiHighLimits() {
1317 if ( !isset( $this->mCanApiHighLimits ) ) {
1318 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1319 }
1320
1321 return $this->mCanApiHighLimits;
1322 }
1323
1324 /**
1325 * Overrides to return this instance's module manager.
1326 * @return ApiModuleManager
1327 */
1328 public function getModuleManager() {
1329 return $this->mModuleMgr;
1330 }
1331
1332 /**
1333 * Fetches the user agent used for this request
1334 *
1335 * The value will be the combination of the 'Api-User-Agent' header (if
1336 * any) and the standard User-Agent header (if any).
1337 *
1338 * @return string
1339 */
1340 public function getUserAgent() {
1341 return trim(
1342 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1343 $this->getRequest()->getHeader( 'User-agent' )
1344 );
1345 }
1346
1347 /************************************************************************//**
1348 * @name Deprecated
1349 * @{
1350 */
1351
1352 /**
1353 * Sets whether the pretty-printer should format *bold* and $italics$
1354 *
1355 * @deprecated since 1.25
1356 * @param bool $help
1357 */
1358 public function setHelp( $help = true ) {
1359 wfDeprecated( __METHOD__, '1.25' );
1360 $this->mPrinter->setHelp( $help );
1361 }
1362
1363 /**
1364 * Override the parent to generate help messages for all available modules.
1365 *
1366 * @deprecated since 1.25
1367 * @return string
1368 */
1369 public function makeHelpMsg() {
1370 wfDeprecated( __METHOD__, '1.25' );
1371 global $wgMemc;
1372 $this->setHelp();
1373 // Get help text from cache if present
1374 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1375 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1376
1377 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1378 if ( $cacheHelpTimeout > 0 ) {
1379 $cached = $wgMemc->get( $key );
1380 if ( $cached ) {
1381 return $cached;
1382 }
1383 }
1384 $retval = $this->reallyMakeHelpMsg();
1385 if ( $cacheHelpTimeout > 0 ) {
1386 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1387 }
1388
1389 return $retval;
1390 }
1391
1392 /**
1393 * @deprecated since 1.25
1394 * @return mixed|string
1395 */
1396 public function reallyMakeHelpMsg() {
1397 wfDeprecated( __METHOD__, '1.25' );
1398 $this->setHelp();
1399
1400 // Use parent to make default message for the main module
1401 $msg = parent::makeHelpMsg();
1402
1403 $astriks = str_repeat( '*** ', 14 );
1404 $msg .= "\n\n$astriks Modules $astriks\n\n";
1405
1406 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1407 $module = $this->mModuleMgr->getModule( $name );
1408 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1409
1410 $msg2 = $module->makeHelpMsg();
1411 if ( $msg2 !== false ) {
1412 $msg .= $msg2;
1413 }
1414 $msg .= "\n";
1415 }
1416
1417 $msg .= "\n$astriks Permissions $astriks\n\n";
1418 foreach ( self::$mRights as $right => $rightMsg ) {
1419 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1420 ->useDatabase( false )
1421 ->inLanguage( 'en' )
1422 ->text();
1423 $groups = User::getGroupsWithPermission( $right );
1424 $msg .= "* " . $right . " *\n $rightsMsg" .
1425 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1426 }
1427
1428 $msg .= "\n$astriks Formats $astriks\n\n";
1429 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1430 $module = $this->mModuleMgr->getModule( $name );
1431 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1432 $msg2 = $module->makeHelpMsg();
1433 if ( $msg2 !== false ) {
1434 $msg .= $msg2;
1435 }
1436 $msg .= "\n";
1437 }
1438
1439 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1440 $credits = str_replace( "\n", "\n ", $credits );
1441 $msg .= "\n*** Credits: ***\n $credits\n";
1442
1443 return $msg;
1444 }
1445
1446 /**
1447 * @deprecated since 1.25
1448 * @param ApiBase $module
1449 * @param string $paramName What type of request is this? e.g. action,
1450 * query, list, prop, meta, format
1451 * @return string
1452 */
1453 public static function makeHelpMsgHeader( $module, $paramName ) {
1454 wfDeprecated( __METHOD__, '1.25' );
1455 $modulePrefix = $module->getModulePrefix();
1456 if ( strval( $modulePrefix ) !== '' ) {
1457 $modulePrefix = "($modulePrefix) ";
1458 }
1459
1460 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1461 }
1462
1463 /**
1464 * Check whether the user wants us to show version information in the API help
1465 * @return bool
1466 * @deprecated since 1.21, always returns false
1467 */
1468 public function getShowVersions() {
1469 wfDeprecated( __METHOD__, '1.21' );
1470
1471 return false;
1472 }
1473
1474 /**
1475 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1476 * classes who wish to add their own modules to their lexicon or override the
1477 * behavior of inherent ones.
1478 *
1479 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1480 * @param string $name The identifier for this module.
1481 * @param ApiBase $class The class where this module is implemented.
1482 */
1483 protected function addModule( $name, $class ) {
1484 $this->getModuleManager()->addModule( $name, 'action', $class );
1485 }
1486
1487 /**
1488 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1489 * classes who wish to add to or modify current formatters.
1490 *
1491 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1492 * @param string $name The identifier for this format.
1493 * @param ApiFormatBase $class The class implementing this format.
1494 */
1495 protected function addFormat( $name, $class ) {
1496 $this->getModuleManager()->addModule( $name, 'format', $class );
1497 }
1498
1499 /**
1500 * Get the array mapping module names to class names
1501 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1502 * @return array
1503 */
1504 function getModules() {
1505 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1506 }
1507
1508 /**
1509 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1510 *
1511 * @since 1.18
1512 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1513 * @return array
1514 */
1515 public function getFormats() {
1516 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1517 }
1518
1519 /**@}*/
1520
1521 }
1522
1523 /**
1524 * This exception will be thrown when dieUsage is called to stop module execution.
1525 *
1526 * @ingroup API
1527 */
1528 class UsageException extends MWException {
1529
1530 private $mCodestr;
1531
1532 /**
1533 * @var null|array
1534 */
1535 private $mExtraData;
1536
1537 /**
1538 * @param string $message
1539 * @param string $codestr
1540 * @param int $code
1541 * @param array|null $extradata
1542 */
1543 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1544 parent::__construct( $message, $code );
1545 $this->mCodestr = $codestr;
1546 $this->mExtraData = $extradata;
1547 }
1548
1549 /**
1550 * @return string
1551 */
1552 public function getCodeString() {
1553 return $this->mCodestr;
1554 }
1555
1556 /**
1557 * @return array
1558 */
1559 public function getMessageArray() {
1560 $result = array(
1561 'code' => $this->mCodestr,
1562 'info' => $this->getMessage()
1563 );
1564 if ( is_array( $this->mExtraData ) ) {
1565 $result = array_merge( $result, $this->mExtraData );
1566 }
1567
1568 return $result;
1569 }
1570
1571 /**
1572 * @return string
1573 */
1574 public function __toString() {
1575 return "{$this->getCodeString()}: {$this->getMessage()}";
1576 }
1577 }
1578
1579 /**
1580 * For really cool vim folding this needs to be at the end:
1581 * vim: foldmarker=@{,@} foldmethod=marker
1582 */