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