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