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