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