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