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