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