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