Reimplement CORS properly, addressing Tim's concerns
[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 /**
44 * When no format parameter is given, this format will be used
45 */
46 const API_DEFAULT_FORMAT = 'xmlfm';
47
48 /**
49 * List of available modules: action name => module class
50 */
51 private static $Modules = array(
52 'login' => 'ApiLogin',
53 'logout' => 'ApiLogout',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'opensearch' => 'ApiOpenSearch',
58 'feedcontributions' => 'ApiFeedContributions',
59 'feedwatchlist' => 'ApiFeedWatchlist',
60 'help' => 'ApiHelp',
61 'paraminfo' => 'ApiParamInfo',
62 'rsd' => 'ApiRsd',
63 'compare' => 'ApiComparePages',
64 'tokens' => 'ApiTokens',
65
66 // Write modules
67 'purge' => 'ApiPurge',
68 'rollback' => 'ApiRollback',
69 'delete' => 'ApiDelete',
70 'undelete' => 'ApiUndelete',
71 'protect' => 'ApiProtect',
72 'block' => 'ApiBlock',
73 'unblock' => 'ApiUnblock',
74 'move' => 'ApiMove',
75 'edit' => 'ApiEditPage',
76 'upload' => 'ApiUpload',
77 'filerevert' => 'ApiFileRevert',
78 'emailuser' => 'ApiEmailUser',
79 'watch' => 'ApiWatch',
80 'patrol' => 'ApiPatrol',
81 'import' => 'ApiImport',
82 'userrights' => 'ApiUserrights',
83 'options' => 'ApiOptions',
84 );
85
86 /**
87 * List of available formats: format name => format class
88 */
89 private static $Formats = array(
90 'json' => 'ApiFormatJson',
91 'jsonfm' => 'ApiFormatJson',
92 'php' => 'ApiFormatPhp',
93 'phpfm' => 'ApiFormatPhp',
94 'wddx' => 'ApiFormatWddx',
95 'wddxfm' => 'ApiFormatWddx',
96 'xml' => 'ApiFormatXml',
97 'xmlfm' => 'ApiFormatXml',
98 'yaml' => 'ApiFormatYaml',
99 'yamlfm' => 'ApiFormatYaml',
100 'rawfm' => 'ApiFormatJson',
101 'txt' => 'ApiFormatTxt',
102 'txtfm' => 'ApiFormatTxt',
103 'dbg' => 'ApiFormatDbg',
104 'dbgfm' => 'ApiFormatDbg',
105 'dump' => 'ApiFormatDump',
106 'dumpfm' => 'ApiFormatDump',
107 );
108
109 /**
110 * List of user roles that are specifically relevant to the API.
111 * array( 'right' => array ( 'msg' => 'Some message with a $1',
112 * 'params' => array ( $someVarToSubst ) ),
113 * );
114 */
115 private static $mRights = array(
116 'writeapi' => array(
117 'msg' => 'Use of the write API',
118 'params' => array()
119 ),
120 'apihighlimits' => array(
121 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
122 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
123 )
124 );
125
126 /**
127 * @var ApiFormatBase
128 */
129 private $mPrinter;
130
131 private $mModules, $mModuleNames, $mFormats, $mFormatNames;
132 private $mResult, $mAction, $mShowVersions, $mEnableWrite;
133 private $mInternalMode, $mSquidMaxage, $mModule;
134
135 private $mCacheMode = 'private';
136 private $mCacheControl = array();
137
138 /**
139 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
140 *
141 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
142 * @param $enableWrite bool should be set to true if the api may modify data
143 */
144 public function __construct( $context = null, $enableWrite = false ) {
145 if ( $context === null ) {
146 $context = RequestContext::getMain();
147 } elseif ( $context instanceof WebRequest ) {
148 // BC for pre-1.19
149 $request = $context;
150 $context = RequestContext::getMain();
151 }
152 // We set a derivative context so we can change stuff later
153 $this->setContext( new DerivativeContext( $context ) );
154
155 if ( isset( $request ) ) {
156 $this->getContext()->setRequest( $request );
157 }
158
159 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
160
161 // Special handling for the main module: $parent === $this
162 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
163
164 if ( !$this->mInternalMode ) {
165 // Impose module restrictions.
166 // If the current user cannot read,
167 // Remove all modules other than login
168 global $wgUser;
169
170 if ( $this->getRequest()->getVal( 'callback' ) !== null ) {
171 // JSON callback allows cross-site reads.
172 // For safety, strip user credentials.
173 wfDebug( "API: stripping user credentials for JSON callback\n" );
174 $wgUser = new User();
175 $this->getContext()->setUser( $wgUser );
176 }
177 }
178
179 global $wgAPIModules; // extension modules
180 $this->mModules = $wgAPIModules + self::$Modules;
181
182 $this->mModuleNames = array_keys( $this->mModules );
183 $this->mFormats = self::$Formats;
184 $this->mFormatNames = array_keys( $this->mFormats );
185
186 $this->mResult = new ApiResult( $this );
187 $this->mShowVersions = false;
188 $this->mEnableWrite = $enableWrite;
189
190 $this->mSquidMaxage = - 1; // flag for executeActionWithErrorHandling()
191 $this->mCommit = false;
192 }
193
194 /**
195 * Return true if the API was started by other PHP code using FauxRequest
196 * @return bool
197 */
198 public function isInternalMode() {
199 return $this->mInternalMode;
200 }
201
202 /**
203 * Get the ApiResult object associated with current request
204 *
205 * @return ApiResult
206 */
207 public function getResult() {
208 return $this->mResult;
209 }
210
211 /**
212 * Get the API module object. Only works after executeAction()
213 *
214 * @return ApiBase
215 */
216 public function getModule() {
217 return $this->mModule;
218 }
219
220 /**
221 * Get the result formatter object. Only works after setupExecuteAction()
222 *
223 * @return ApiFormatBase
224 */
225 public function getPrinter() {
226 return $this->mPrinter;
227 }
228
229 /**
230 * Set how long the response should be cached.
231 *
232 * @param $maxage
233 */
234 public function setCacheMaxAge( $maxage ) {
235 $this->setCacheControl( array(
236 'max-age' => $maxage,
237 's-maxage' => $maxage
238 ) );
239 }
240
241 /**
242 * Set the type of caching headers which will be sent.
243 *
244 * @param $mode String One of:
245 * - 'public': Cache this object in public caches, if the maxage or smaxage
246 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
247 * not provided by any of these means, the object will be private.
248 * - 'private': Cache this object only in private client-side caches.
249 * - 'anon-public-user-private': Make this object cacheable for logged-out
250 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
251 * set consistently for a given URL, it cannot be set differently depending on
252 * things like the contents of the database, or whether the user is logged in.
253 *
254 * If the wiki does not allow anonymous users to read it, the mode set here
255 * will be ignored, and private caching headers will always be sent. In other words,
256 * the "public" mode is equivalent to saying that the data sent is as public as a page
257 * view.
258 *
259 * For user-dependent data, the private mode should generally be used. The
260 * anon-public-user-private mode should only be used where there is a particularly
261 * good performance reason for caching the anonymous response, but where the
262 * response to logged-in users may differ, or may contain private data.
263 *
264 * If this function is never called, then the default will be the private mode.
265 */
266 public function setCacheMode( $mode ) {
267 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
268 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
269 // Ignore for forwards-compatibility
270 return;
271 }
272
273 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
274 // Private wiki, only private headers
275 if ( $mode !== 'private' ) {
276 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
277 return;
278 }
279 }
280
281 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
282 $this->mCacheMode = $mode;
283 }
284
285 /**
286 * @deprecated since 1.17 Private caching is now the default, so there is usually no
287 * need to call this function. If there is a need, you can use
288 * $this->setCacheMode('private')
289 */
290 public function setCachePrivate() {
291 wfDeprecated( __METHOD__, '1.17' );
292 $this->setCacheMode( 'private' );
293 }
294
295 /**
296 * Set directives (key/value pairs) for the Cache-Control header.
297 * Boolean values will be formatted as such, by including or omitting
298 * without an equals sign.
299 *
300 * Cache control values set here will only be used if the cache mode is not
301 * private, see setCacheMode().
302 *
303 * @param $directives array
304 */
305 public function setCacheControl( $directives ) {
306 $this->mCacheControl = $directives + $this->mCacheControl;
307 }
308
309 /**
310 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
311 * may be cached for anons but may not be cached for logged-in users.
312 *
313 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
314 * given URL must either always or never call this function; if it sometimes does and
315 * sometimes doesn't, stuff will break.
316 *
317 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
318 */
319 public function setVaryCookie() {
320 wfDeprecated( __METHOD__, '1.17' );
321 $this->setCacheMode( 'anon-public-user-private' );
322 }
323
324 /**
325 * Create an instance of an output formatter by its name
326 *
327 * @param $format string
328 *
329 * @return ApiFormatBase
330 */
331 public function createPrinterByName( $format ) {
332 if ( !isset( $this->mFormats[$format] ) ) {
333 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
334 }
335 return new $this->mFormats[$format] ( $this, $format );
336 }
337
338 /**
339 * Execute api request. Any errors will be handled if the API was called by the remote client.
340 */
341 public function execute() {
342 $this->profileIn();
343 if ( $this->mInternalMode ) {
344 $this->executeAction();
345 } else {
346 $this->executeActionWithErrorHandling();
347 }
348
349 $this->profileOut();
350 }
351
352 /**
353 * Execute an action, and in case of an error, erase whatever partial results
354 * have been accumulated, and replace it with an error message and a help screen.
355 */
356 protected function executeActionWithErrorHandling() {
357 // Verify the CORS header before executing the action
358 if ( !$this->handleCORS() ) {
359 // handleCORS() has sent a 403, abort
360 return;
361 }
362
363 // In case an error occurs during data output,
364 // clear the output buffer and print just the error information
365 ob_start();
366
367 try {
368 $this->executeAction();
369 } catch ( Exception $e ) {
370 // Log it
371 if ( !( $e instanceof UsageException ) ) {
372 wfDebugLog( 'exception', $e->getLogMessage() );
373 }
374
375 // Handle any kind of exception by outputing properly formatted error message.
376 // If this fails, an unhandled exception should be thrown so that global error
377 // handler will process and log it.
378
379 $errCode = $this->substituteResultWithError( $e );
380
381 // Error results should not be cached
382 $this->setCacheMode( 'private' );
383
384 $response = $this->getRequest()->response();
385 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
386 if ( $e->getCode() === 0 ) {
387 $response->header( $headerStr );
388 } else {
389 $response->header( $headerStr, true, $e->getCode() );
390 }
391
392 // Reset and print just the error message
393 ob_clean();
394
395 // If the error occured during printing, do a printer->profileOut()
396 $this->mPrinter->safeProfileOut();
397 $this->printResult( true );
398 }
399
400 // Send cache headers after any code which might generate an error, to
401 // avoid sending public cache headers for errors.
402 $this->sendCacheHeaders();
403
404 if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
405 echo wfReportTime();
406 }
407
408 ob_end_flush();
409 }
410
411 /**
412 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
413 *
414 * If no origin parameter is present, nothing happens.
415 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
416 * is set and false is returned.
417 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
418 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
419 * headers are set.
420 *
421 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
422 */
423 protected function handleCORS() {
424 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
425 $response = $this->getRequest()->response();
426 $originParam = $this->getParameter( 'origin' ); // defaults to null
427 if ( $originParam === null ) {
428 // No origin parameter, nothing to do
429 return true;
430 }
431 // Origin: header is a space-separated list of origins, check all of them
432 $originHeader = isset( $_SERVER['HTTP_ORIGIN'] ) ? $_SERVER['HTTP_ORIGIN'] : '';
433 $origins = explode( ' ', $originHeader );
434 if ( !in_array( $originParam, $origins ) ) {
435 // origin parameter set but incorrect
436 // Send a 403 response
437 $message = HttpStatus::getMessage( 403 );
438 $response->header( "HTTP/1.1 403 $message", true, 403 );
439 $response->header( 'Cache-Control: no-cache' );
440 echo "'origin' parameter does not match Origin header\n";
441 return false;
442 }
443 if ( self::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
444 $response->header( "Access-Control-Allow-Origin: $originParam" );
445 $response->header( 'Access-Control-Allow-Credentials: true' );
446 $this->getOutput()->addVaryHeader( 'Origin' );
447 }
448 return true;
449 }
450
451 /**
452 * Attempt to match an Origin header against a set of rules and a set of exceptions
453 * @param $value string Origin header
454 * @param $rules array Set of wildcard rules
455 * @param $exceptions array Set of wildcard rules
456 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
457 */
458 protected static function matchOrigin( $value, $rules, $exceptions ) {
459 foreach ( $rules as $rule ) {
460 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
461 // Rule matches, check exceptions
462 foreach ( $exceptions as $exc ) {
463 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
464 return false;
465 }
466 }
467 return true;
468 }
469 }
470 return false;
471 }
472
473 /**
474 * Helper function to convert wildcard string into a regex
475 * '*' => '.*?'
476 * '?' => '.'
477 *
478 * @param $wildcard string String with wildcards
479 * @return string Regular expression
480 */
481 protected static function wildcardToRegex( $wildcard ) {
482 $wildcard = preg_quote( $wildcard, '/' );
483 $wildcard = str_replace(
484 array( '\*', '\?' ),
485 array( '.*?', '.' ),
486 $wildcard
487 );
488 return "/https?:\/\/$wildcard/";
489 }
490
491 protected function sendCacheHeaders() {
492 global $wgUseXVO, $wgVaryOnXFP;
493 $response = $this->getRequest()->response();
494
495 if ( $this->mCacheMode == 'private' ) {
496 $response->header( 'Cache-Control: private' );
497 return;
498 }
499
500 if ( $this->mCacheMode == 'anon-public-user-private' ) {
501 $xfp = $wgVaryOnXFP ? ', X-Forwarded-Proto' : '';
502 $response->header( 'Vary: Accept-Encoding, Cookie' . $xfp );
503 if ( $wgUseXVO ) {
504 $out = $this->getOutput();
505 if ( $wgVaryOnXFP ) {
506 $out->addVaryHeader( 'X-Forwarded-Proto' );
507 }
508 $response->header( $out->getXVO() );
509 if ( $out->haveCacheVaryCookies() ) {
510 // Logged in, mark this request private
511 $response->header( 'Cache-Control: private' );
512 return;
513 }
514 // Logged out, send normal public headers below
515 } elseif ( session_id() != '' ) {
516 // Logged in or otherwise has session (e.g. anonymous users who have edited)
517 // Mark request private
518 $response->header( 'Cache-Control: private' );
519 return;
520 } // else no XVO and anonymous, send public headers below
521 }
522
523 // Send public headers
524 if ( $wgVaryOnXFP ) {
525 $response->header( 'Vary: Accept-Encoding, X-Forwarded-Proto' );
526 if ( $wgUseXVO ) {
527 // Bleeeeegh. Our header setting system sucks
528 $response->header( 'X-Vary-Options: Accept-Encoding;list-contains=gzip, X-Forwarded-Proto' );
529 }
530 }
531
532 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
533 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
534 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
535 }
536 if ( !isset( $this->mCacheControl['max-age'] ) ) {
537 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
538 }
539
540 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
541 // Public cache not requested
542 // Sending a Vary header in this case is harmless, and protects us
543 // against conditional calls of setCacheMaxAge().
544 $response->header( 'Cache-Control: private' );
545 return;
546 }
547
548 $this->mCacheControl['public'] = true;
549
550 // Send an Expires header
551 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
552 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
553 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
554
555 // Construct the Cache-Control header
556 $ccHeader = '';
557 $separator = '';
558 foreach ( $this->mCacheControl as $name => $value ) {
559 if ( is_bool( $value ) ) {
560 if ( $value ) {
561 $ccHeader .= $separator . $name;
562 $separator = ', ';
563 }
564 } else {
565 $ccHeader .= $separator . "$name=$value";
566 $separator = ', ';
567 }
568 }
569
570 $response->header( "Cache-Control: $ccHeader" );
571 }
572
573 /**
574 * Replace the result data with the information about an exception.
575 * Returns the error code
576 * @param $e Exception
577 * @return string
578 */
579 protected function substituteResultWithError( $e ) {
580 global $wgShowHostnames;
581
582 $result = $this->getResult();
583 // Printer may not be initialized if the extractRequestParams() fails for the main module
584 if ( !isset ( $this->mPrinter ) ) {
585 // The printer has not been created yet. Try to manually get formatter value.
586 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
587 if ( !in_array( $value, $this->mFormatNames ) ) {
588 $value = self::API_DEFAULT_FORMAT;
589 }
590
591 $this->mPrinter = $this->createPrinterByName( $value );
592 if ( $this->mPrinter->getNeedsRawData() ) {
593 $result->setRawMode();
594 }
595 }
596
597 if ( $e instanceof UsageException ) {
598 // User entered incorrect parameters - print usage screen
599 $errMessage = $e->getMessageArray();
600
601 // Only print the help message when this is for the developer, not runtime
602 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
603 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
604 }
605
606 } else {
607 global $wgShowSQLErrors, $wgShowExceptionDetails;
608 // Something is seriously wrong
609 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
610 $info = 'Database query error';
611 } else {
612 $info = "Exception Caught: {$e->getMessage()}";
613 }
614
615 $errMessage = array(
616 'code' => 'internal_api_error_' . get_class( $e ),
617 'info' => $info,
618 );
619 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
620 }
621
622 $result->reset();
623 $result->disableSizeCheck();
624 // Re-add the id
625 $requestid = $this->getParameter( 'requestid' );
626 if ( !is_null( $requestid ) ) {
627 $result->addValue( null, 'requestid', $requestid );
628 }
629
630 if ( $wgShowHostnames ) {
631 // servedby is especially useful when debugging errors
632 $result->addValue( null, 'servedby', wfHostName() );
633 }
634
635 $result->addValue( null, 'error', $errMessage );
636
637 return $errMessage['code'];
638 }
639
640 /**
641 * Set up for the execution.
642 * @return array
643 */
644 protected function setupExecuteAction() {
645 global $wgShowHostnames;
646
647 // First add the id to the top element
648 $result = $this->getResult();
649 $requestid = $this->getParameter( 'requestid' );
650 if ( !is_null( $requestid ) ) {
651 $result->addValue( null, 'requestid', $requestid );
652 }
653
654 if ( $wgShowHostnames ) {
655 $servedby = $this->getParameter( 'servedby' );
656 if ( $servedby ) {
657 $result->addValue( null, 'servedby', wfHostName() );
658 }
659 }
660
661 $params = $this->extractRequestParams();
662
663 $this->mShowVersions = $params['version'];
664 $this->mAction = $params['action'];
665
666 if ( !is_string( $this->mAction ) ) {
667 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
668 }
669
670 return $params;
671 }
672
673 /**
674 * Set up the module for response
675 * @return ApiBase The module that will handle this action
676 */
677 protected function setupModule() {
678 // Instantiate the module requested by the user
679 $module = new $this->mModules[$this->mAction] ( $this, $this->mAction );
680 $this->mModule = $module;
681
682 $moduleParams = $module->extractRequestParams();
683
684 // Die if token required, but not provided (unless there is a gettoken parameter)
685 if ( isset( $moduleParams['gettoken'] ) ) {
686 $gettoken = $moduleParams['gettoken'];
687 } else {
688 $gettoken = false;
689 }
690
691 $salt = $module->getTokenSalt();
692 if ( $salt !== false && !$gettoken ) {
693 if ( !isset( $moduleParams['token'] ) ) {
694 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
695 } else {
696 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
697 $this->dieUsageMsg( 'sessionfailure' );
698 }
699 }
700 }
701 return $module;
702 }
703
704 /**
705 * Check the max lag if necessary
706 * @param $module ApiBase object: Api module being used
707 * @param $params Array an array containing the request parameters.
708 * @return boolean True on success, false should exit immediately
709 */
710 protected function checkMaxLag( $module, $params ) {
711 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
712 // Check for maxlag
713 global $wgShowHostnames;
714 $maxLag = $params['maxlag'];
715 list( $host, $lag ) = wfGetLB()->getMaxLag();
716 if ( $lag > $maxLag ) {
717 $response = $this->getRequest()->response();
718
719 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
720 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
721
722 if ( $wgShowHostnames ) {
723 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
724 } else {
725 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
726 }
727 return false;
728 }
729 }
730 return true;
731 }
732
733 /**
734 * Check for sufficient permissions to execute
735 * @param $module ApiBase An Api module
736 */
737 protected function checkExecutePermissions( $module ) {
738 $user = $this->getUser();
739 if ( $module->isReadMode() && !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) &&
740 !$user->isAllowed( 'read' ) )
741 {
742 $this->dieUsageMsg( 'readrequired' );
743 }
744 if ( $module->isWriteMode() ) {
745 if ( !$this->mEnableWrite ) {
746 $this->dieUsageMsg( 'writedisabled' );
747 }
748 if ( !$user->isAllowed( 'writeapi' ) ) {
749 $this->dieUsageMsg( 'writerequired' );
750 }
751 if ( wfReadOnly() ) {
752 $this->dieReadOnly();
753 }
754 }
755 }
756
757 /**
758 * Check POST for external response and setup result printer
759 * @param $module ApiBase An Api module
760 * @param $params Array an array with the request parameters
761 */
762 protected function setupExternalResponse( $module, $params ) {
763 // Ignore mustBePosted() for internal calls
764 if ( $module->mustBePosted() && !$this->getRequest()->wasPosted() ) {
765 $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
766 }
767
768 // See if custom printer is used
769 $this->mPrinter = $module->getCustomPrinter();
770 if ( is_null( $this->mPrinter ) ) {
771 // Create an appropriate printer
772 $this->mPrinter = $this->createPrinterByName( $params['format'] );
773 }
774
775 if ( $this->mPrinter->getNeedsRawData() ) {
776 $this->getResult()->setRawMode();
777 }
778 }
779
780 /**
781 * Execute the actual module, without any error handling
782 */
783 protected function executeAction() {
784 $params = $this->setupExecuteAction();
785 $module = $this->setupModule();
786
787 $this->checkExecutePermissions( $module );
788
789 if ( !$this->checkMaxLag( $module, $params ) ) {
790 return;
791 }
792
793 if ( !$this->mInternalMode ) {
794 $this->setupExternalResponse( $module, $params );
795 }
796
797 // Execute
798 $module->profileIn();
799 $module->execute();
800 wfRunHooks( 'APIAfterExecute', array( &$module ) );
801 $module->profileOut();
802
803 if ( !$this->mInternalMode ) {
804 //append Debug information
805 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
806
807 // Print result data
808 $this->printResult( false );
809 }
810 }
811
812 /**
813 * Print results using the current printer
814 *
815 * @param $isError bool
816 */
817 protected function printResult( $isError ) {
818 $this->getResult()->cleanUpUTF8();
819 $printer = $this->mPrinter;
820 $printer->profileIn();
821
822 /**
823 * If the help message is requested in the default (xmlfm) format,
824 * tell the printer not to escape ampersands so that our links do
825 * not break.
826 */
827 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
828 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
829
830 $printer->initPrinter( $isError );
831
832 $printer->execute();
833 $printer->closePrinter();
834 $printer->profileOut();
835 }
836
837 /**
838 * @return bool
839 */
840 public function isReadMode() {
841 return false;
842 }
843
844 /**
845 * See ApiBase for description.
846 *
847 * @return array
848 */
849 public function getAllowedParams() {
850 return array(
851 'format' => array(
852 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
853 ApiBase::PARAM_TYPE => $this->mFormatNames
854 ),
855 'action' => array(
856 ApiBase::PARAM_DFLT => 'help',
857 ApiBase::PARAM_TYPE => $this->mModuleNames
858 ),
859 'version' => false,
860 'maxlag' => array(
861 ApiBase::PARAM_TYPE => 'integer'
862 ),
863 'smaxage' => array(
864 ApiBase::PARAM_TYPE => 'integer',
865 ApiBase::PARAM_DFLT => 0
866 ),
867 'maxage' => array(
868 ApiBase::PARAM_TYPE => 'integer',
869 ApiBase::PARAM_DFLT => 0
870 ),
871 'requestid' => null,
872 'servedby' => false,
873 'origin' => null,
874 );
875 }
876
877 /**
878 * See ApiBase for description.
879 *
880 * @return array
881 */
882 public function getParamDescription() {
883 return array(
884 'format' => 'The format of the output',
885 'action' => 'What action you would like to perform. See below for module help',
886 'version' => 'When showing help, include version for each module',
887 'maxlag' => array(
888 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
889 'To save actions causing any more site replication lag, this parameter can make the client',
890 'wait until the replication lag is less than the specified value.',
891 'In case of a replag error, a HTTP 503 error is returned, with the message like',
892 '"Waiting for $host: $lag seconds lagged\n".',
893 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
894 ),
895 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
896 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
897 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
898 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
899 'origin' => array(
900 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
901 'This must match one of the origins in the Origin: header exactly, so it has to be set to something like http://en.wikipedia.org or https://meta.wikimedia.org .',
902 'If this parameter does not match the Origin: header, a 403 response will be returned.',
903 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
904 ),
905 );
906 }
907
908 /**
909 * See ApiBase for description.
910 *
911 * @return array
912 */
913 public function getDescription() {
914 return array(
915 '',
916 '',
917 '**********************************************************************************************************',
918 '** **',
919 '** This is an auto-generated MediaWiki API documentation page **',
920 '** **',
921 '** Documentation and Examples: **',
922 '** https://www.mediawiki.org/wiki/API **',
923 '** **',
924 '**********************************************************************************************************',
925 '',
926 'Status: All features shown on this page should be working, but the API',
927 ' is still in active development, and may change at any time.',
928 ' Make sure to monitor our mailing list for any updates',
929 '',
930 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
931 ' with the key "MediaWiki-API-Error" and then both the value of the',
932 ' header and the error code sent back will be set to the same value',
933 '',
934 ' In the case of an invalid action being passed, these will have a value',
935 ' of "unknown_action"',
936 '',
937 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
938 '',
939 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
940 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
941 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
942 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
943 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
944 '',
945 '',
946 '',
947 '',
948 '',
949 );
950 }
951
952 /**
953 * @return array
954 */
955 public function getPossibleErrors() {
956 return array_merge( parent::getPossibleErrors(), array(
957 array( 'readonlytext' ),
958 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
959 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
960 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
961 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
962 ) );
963 }
964
965 /**
966 * Returns an array of strings with credits for the API
967 * @return array
968 */
969 protected function getCredits() {
970 return array(
971 'API developers:',
972 ' Roan Kattouw <Firstname>.<Lastname>@gmail.com (lead developer Sep 2007-present)',
973 ' Victor Vasiliev - vasilvv at gee mail dot com',
974 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
975 ' Sam Reed - sam @ reedyboy . net',
976 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
977 '',
978 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
979 'or file a bug report at https://bugzilla.wikimedia.org/'
980 );
981 }
982
983 /**
984 * Sets whether the pretty-printer should format *bold* and $italics$
985 *
986 * @param $help bool
987 */
988 public function setHelp( $help = true ) {
989 $this->mPrinter->setHelp( $help );
990 }
991
992 /**
993 * Override the parent to generate help messages for all available modules.
994 *
995 * @return string
996 */
997 public function makeHelpMsg() {
998 global $wgMemc, $wgAPICacheHelpTimeout;
999 $this->setHelp();
1000 // Get help text from cache if present
1001 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1002 SpecialVersion::getVersion( 'nodb' ) .
1003 $this->getShowVersions() );
1004 if ( $wgAPICacheHelpTimeout > 0 ) {
1005 $cached = $wgMemc->get( $key );
1006 if ( $cached ) {
1007 return $cached;
1008 }
1009 }
1010 $retval = $this->reallyMakeHelpMsg();
1011 if ( $wgAPICacheHelpTimeout > 0 ) {
1012 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1013 }
1014 return $retval;
1015 }
1016
1017 /**
1018 * @return mixed|string
1019 */
1020 public function reallyMakeHelpMsg() {
1021 $this->setHelp();
1022
1023 // Use parent to make default message for the main module
1024 $msg = parent::makeHelpMsg();
1025
1026 $astriks = str_repeat( '*** ', 14 );
1027 $msg .= "\n\n$astriks Modules $astriks\n\n";
1028 foreach ( array_keys( $this->mModules ) as $moduleName ) {
1029 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
1030 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1031 $msg2 = $module->makeHelpMsg();
1032 if ( $msg2 !== false ) {
1033 $msg .= $msg2;
1034 }
1035 $msg .= "\n";
1036 }
1037
1038 $msg .= "\n$astriks Permissions $astriks\n\n";
1039 foreach ( self::$mRights as $right => $rightMsg ) {
1040 $groups = User::getGroupsWithPermission( $right );
1041 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
1042 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1043
1044 }
1045
1046 $msg .= "\n$astriks Formats $astriks\n\n";
1047 foreach ( array_keys( $this->mFormats ) as $formatName ) {
1048 $module = $this->createPrinterByName( $formatName );
1049 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1050 $msg2 = $module->makeHelpMsg();
1051 if ( $msg2 !== false ) {
1052 $msg .= $msg2;
1053 }
1054 $msg .= "\n";
1055 }
1056
1057 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1058
1059 return $msg;
1060 }
1061
1062 /**
1063 * @param $module ApiBase
1064 * @param $paramName String What type of request is this? e.g. action, query, list, prop, meta, format
1065 * @return string
1066 */
1067 public static function makeHelpMsgHeader( $module, $paramName ) {
1068 $modulePrefix = $module->getModulePrefix();
1069 if ( strval( $modulePrefix ) !== '' ) {
1070 $modulePrefix = "($modulePrefix) ";
1071 }
1072
1073 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1074 }
1075
1076 private $mCanApiHighLimits = null;
1077
1078 /**
1079 * Check whether the current user is allowed to use high limits
1080 * @return bool
1081 */
1082 public function canApiHighLimits() {
1083 if ( !isset( $this->mCanApiHighLimits ) ) {
1084 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1085 }
1086
1087 return $this->mCanApiHighLimits;
1088 }
1089
1090 /**
1091 * Check whether the user wants us to show version information in the API help
1092 * @return bool
1093 */
1094 public function getShowVersions() {
1095 return $this->mShowVersions;
1096 }
1097
1098 /**
1099 * Returns the version information of this file, plus it includes
1100 * the versions for all files that are not callable proper API modules
1101 *
1102 * @return array
1103 */
1104 public function getVersion() {
1105 $vers = array();
1106 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
1107 $vers[] = __CLASS__ . ': $Id$';
1108 $vers[] = ApiBase::getBaseVersion();
1109 $vers[] = ApiFormatBase::getBaseVersion();
1110 $vers[] = ApiQueryBase::getBaseVersion();
1111 return $vers;
1112 }
1113
1114 /**
1115 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1116 * classes who wish to add their own modules to their lexicon or override the
1117 * behavior of inherent ones.
1118 *
1119 * @param $mdlName String The identifier for this module.
1120 * @param $mdlClass String The class where this module is implemented.
1121 */
1122 protected function addModule( $mdlName, $mdlClass ) {
1123 $this->mModules[$mdlName] = $mdlClass;
1124 }
1125
1126 /**
1127 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1128 * classes who wish to add to or modify current formatters.
1129 *
1130 * @param $fmtName string The identifier for this format.
1131 * @param $fmtClass ApiFormatBase The class implementing this format.
1132 */
1133 protected function addFormat( $fmtName, $fmtClass ) {
1134 $this->mFormats[$fmtName] = $fmtClass;
1135 }
1136
1137 /**
1138 * Get the array mapping module names to class names
1139 * @return array
1140 */
1141 function getModules() {
1142 return $this->mModules;
1143 }
1144
1145 /**
1146 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1147 *
1148 * @since 1.18
1149 * @return array
1150 */
1151 public function getFormats() {
1152 return $this->mFormats;
1153 }
1154 }
1155
1156 /**
1157 * This exception will be thrown when dieUsage is called to stop module execution.
1158 * The exception handling code will print a help screen explaining how this API may be used.
1159 *
1160 * @ingroup API
1161 */
1162 class UsageException extends MWException {
1163
1164 private $mCodestr;
1165 private $mExtraData;
1166
1167 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1168 parent::__construct( $message, $code );
1169 $this->mCodestr = $codestr;
1170 $this->mExtraData = $extradata;
1171 }
1172
1173 /**
1174 * @return string
1175 */
1176 public function getCodeString() {
1177 return $this->mCodestr;
1178 }
1179
1180 /**
1181 * @return array
1182 */
1183 public function getMessageArray() {
1184 $result = array(
1185 'code' => $this->mCodestr,
1186 'info' => $this->getMessage()
1187 );
1188 if ( is_array( $this->mExtraData ) ) {
1189 $result = array_merge( $result, $this->mExtraData );
1190 }
1191 return $result;
1192 }
1193
1194 /**
1195 * @return string
1196 */
1197 public function __toString() {
1198 return "{$this->getCodeString()}: {$this->getMessage()}";
1199 }
1200 }