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