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