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