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