Add DROP INDEX support to DatabaseSqlite::replaceVars method
[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 MWException && !( $e instanceof UsageException ) ) {
387 global $wgLogExceptionBacktrace;
388 if ( $wgLogExceptionBacktrace ) {
389 wfDebugLog( 'exception', $e->getLogMessage() . "\n" . $e->getTraceAsString() . "\n" );
390 } else {
391 wfDebugLog( 'exception', $e->getLogMessage() );
392 }
393 }
394
395 // Handle any kind of exception by outputting properly formatted error message.
396 // If this fails, an unhandled exception should be thrown so that global error
397 // handler will process and log it.
398
399 $errCode = $this->substituteResultWithError( $e );
400
401 // Error results should not be cached
402 $this->setCacheMode( 'private' );
403
404 $response = $this->getRequest()->response();
405 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
406 if ( $e->getCode() === 0 ) {
407 $response->header( $headerStr );
408 } else {
409 $response->header( $headerStr, true, $e->getCode() );
410 }
411
412 // Reset and print just the error message
413 ob_clean();
414
415 // If the error occurred during printing, do a printer->profileOut()
416 $this->mPrinter->safeProfileOut();
417 $this->printResult( true );
418 }
419
420 // Log the request whether or not there was an error
421 $this->logRequest( microtime( true ) - $t );
422
423 // Send cache headers after any code which might generate an error, to
424 // avoid sending public cache headers for errors.
425 $this->sendCacheHeaders();
426
427 if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
428 echo wfReportTime();
429 }
430
431 ob_end_flush();
432 }
433
434 /**
435 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
436 *
437 * If no origin parameter is present, nothing happens.
438 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
439 * is set and false is returned.
440 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
441 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
442 * headers are set.
443 *
444 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
445 */
446 protected function handleCORS() {
447 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
448
449 $originParam = $this->getParameter( 'origin' ); // defaults to null
450 if ( $originParam === null ) {
451 // No origin parameter, nothing to do
452 return true;
453 }
454
455 $request = $this->getRequest();
456 $response = $request->response();
457 // Origin: header is a space-separated list of origins, check all of them
458 $originHeader = $request->getHeader( 'Origin' );
459 if ( $originHeader === false ) {
460 $origins = array();
461 } else {
462 $origins = explode( ' ', $originHeader );
463 }
464 if ( !in_array( $originParam, $origins ) ) {
465 // origin parameter set but incorrect
466 // Send a 403 response
467 $message = HttpStatus::getMessage( 403 );
468 $response->header( "HTTP/1.1 403 $message", true, 403 );
469 $response->header( 'Cache-Control: no-cache' );
470 echo "'origin' parameter does not match Origin header\n";
471 return false;
472 }
473 if ( self::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
474 $response->header( "Access-Control-Allow-Origin: $originParam" );
475 $response->header( 'Access-Control-Allow-Credentials: true' );
476 $this->getOutput()->addVaryHeader( 'Origin' );
477 }
478 return true;
479 }
480
481 /**
482 * Attempt to match an Origin header against a set of rules and a set of exceptions
483 * @param string $value Origin header
484 * @param array $rules Set of wildcard rules
485 * @param array $exceptions Set of wildcard rules
486 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
487 */
488 protected static function matchOrigin( $value, $rules, $exceptions ) {
489 foreach ( $rules as $rule ) {
490 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
491 // Rule matches, check exceptions
492 foreach ( $exceptions as $exc ) {
493 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
494 return false;
495 }
496 }
497 return true;
498 }
499 }
500 return false;
501 }
502
503 /**
504 * Helper function to convert wildcard string into a regex
505 * '*' => '.*?'
506 * '?' => '.'
507 *
508 * @param string $wildcard String with wildcards
509 * @return string Regular expression
510 */
511 protected static function wildcardToRegex( $wildcard ) {
512 $wildcard = preg_quote( $wildcard, '/' );
513 $wildcard = str_replace(
514 array( '\*', '\?' ),
515 array( '.*?', '.' ),
516 $wildcard
517 );
518 return "/https?:\/\/$wildcard/";
519 }
520
521 protected function sendCacheHeaders() {
522 global $wgUseXVO, $wgVaryOnXFP;
523 $response = $this->getRequest()->response();
524 $out = $this->getOutput();
525
526 if ( $wgVaryOnXFP ) {
527 $out->addVaryHeader( 'X-Forwarded-Proto' );
528 }
529
530 if ( $this->mCacheMode == 'private' ) {
531 $response->header( 'Cache-Control: private' );
532 return;
533 }
534
535 if ( $this->mCacheMode == 'anon-public-user-private' ) {
536 $out->addVaryHeader( 'Cookie' );
537 $response->header( $out->getVaryHeader() );
538 if ( $wgUseXVO ) {
539 $response->header( $out->getXVO() );
540 if ( $out->haveCacheVaryCookies() ) {
541 // Logged in, mark this request private
542 $response->header( 'Cache-Control: private' );
543 return;
544 }
545 // Logged out, send normal public headers below
546 } elseif ( session_id() != '' ) {
547 // Logged in or otherwise has session (e.g. anonymous users who have edited)
548 // Mark request private
549 $response->header( 'Cache-Control: private' );
550 return;
551 } // else no XVO and anonymous, send public headers below
552 }
553
554 // Send public headers
555 $response->header( $out->getVaryHeader() );
556 if ( $wgUseXVO ) {
557 $response->header( $out->getXVO() );
558 }
559
560 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
561 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
562 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
563 }
564 if ( !isset( $this->mCacheControl['max-age'] ) ) {
565 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
566 }
567
568 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
569 // Public cache not requested
570 // Sending a Vary header in this case is harmless, and protects us
571 // against conditional calls of setCacheMaxAge().
572 $response->header( 'Cache-Control: private' );
573 return;
574 }
575
576 $this->mCacheControl['public'] = true;
577
578 // Send an Expires header
579 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
580 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
581 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
582
583 // Construct the Cache-Control header
584 $ccHeader = '';
585 $separator = '';
586 foreach ( $this->mCacheControl as $name => $value ) {
587 if ( is_bool( $value ) ) {
588 if ( $value ) {
589 $ccHeader .= $separator . $name;
590 $separator = ', ';
591 }
592 } else {
593 $ccHeader .= $separator . "$name=$value";
594 $separator = ', ';
595 }
596 }
597
598 $response->header( "Cache-Control: $ccHeader" );
599 }
600
601 /**
602 * Replace the result data with the information about an exception.
603 * Returns the error code
604 * @param $e Exception
605 * @return string
606 */
607 protected function substituteResultWithError( $e ) {
608 global $wgShowHostnames;
609
610 $result = $this->getResult();
611 // Printer may not be initialized if the extractRequestParams() fails for the main module
612 if ( !isset( $this->mPrinter ) ) {
613 // The printer has not been created yet. Try to manually get formatter value.
614 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
615 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
616 $value = self::API_DEFAULT_FORMAT;
617 }
618
619 $this->mPrinter = $this->createPrinterByName( $value );
620 if ( $this->mPrinter->getNeedsRawData() ) {
621 $result->setRawMode();
622 }
623 }
624
625 if ( $e instanceof UsageException ) {
626 // User entered incorrect parameters - print usage screen
627 $errMessage = $e->getMessageArray();
628
629 // Only print the help message when this is for the developer, not runtime
630 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
631 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
632 }
633 } else {
634 global $wgShowSQLErrors, $wgShowExceptionDetails;
635 // Something is seriously wrong
636 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
637 $info = 'Database query error';
638 } else {
639 $info = "Exception Caught: {$e->getMessage()}";
640 }
641
642 $errMessage = array(
643 'code' => 'internal_api_error_' . get_class( $e ),
644 'info' => $info,
645 );
646 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
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 } else {
723 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
724 $this->dieUsageMsg( 'sessionfailure' );
725 }
726 }
727 }
728 return $module;
729 }
730
731 /**
732 * Check the max lag if necessary
733 * @param $module ApiBase object: Api module being used
734 * @param array $params an array containing the request parameters.
735 * @return boolean True on success, false should exit immediately
736 */
737 protected function checkMaxLag( $module, $params ) {
738 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
739 // Check for maxlag
740 global $wgShowHostnames;
741 $maxLag = $params['maxlag'];
742 list( $host, $lag ) = wfGetLB()->getMaxLag();
743 if ( $lag > $maxLag ) {
744 $response = $this->getRequest()->response();
745
746 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
747 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
748
749 if ( $wgShowHostnames ) {
750 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
751 } else {
752 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
753 }
754 return false;
755 }
756 }
757 return true;
758 }
759
760 /**
761 * Check for sufficient permissions to execute
762 * @param $module ApiBase An Api module
763 */
764 protected function checkExecutePermissions( $module ) {
765 $user = $this->getUser();
766 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
767 !$user->isAllowed( 'read' ) )
768 {
769 $this->dieUsageMsg( 'readrequired' );
770 }
771 if ( $module->isWriteMode() ) {
772 if ( !$this->mEnableWrite ) {
773 $this->dieUsageMsg( 'writedisabled' );
774 }
775 if ( !$user->isAllowed( 'writeapi' ) ) {
776 $this->dieUsageMsg( 'writerequired' );
777 }
778 if ( wfReadOnly() ) {
779 $this->dieReadOnly();
780 }
781 }
782
783 // Allow extensions to stop execution for arbitrary reasons.
784 $message = false;
785 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
786 $this->dieUsageMsg( $message );
787 }
788 }
789
790 /**
791 * Check POST for external response and setup result printer
792 * @param $module ApiBase An Api module
793 * @param array $params an array with the request parameters
794 */
795 protected function setupExternalResponse( $module, $params ) {
796 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
797 // Module requires POST. GET request might still be allowed
798 // if $wgDebugApi is true, otherwise fail.
799 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
800 }
801
802 // See if custom printer is used
803 $this->mPrinter = $module->getCustomPrinter();
804 if ( is_null( $this->mPrinter ) ) {
805 // Create an appropriate printer
806 $this->mPrinter = $this->createPrinterByName( $params['format'] );
807 }
808
809 if ( $this->mPrinter->getNeedsRawData() ) {
810 $this->getResult()->setRawMode();
811 }
812 }
813
814 /**
815 * Execute the actual module, without any error handling
816 */
817 protected function executeAction() {
818 $params = $this->setupExecuteAction();
819 $module = $this->setupModule();
820 $this->mModule = $module;
821
822 $this->checkExecutePermissions( $module );
823
824 if ( !$this->checkMaxLag( $module, $params ) ) {
825 return;
826 }
827
828 if ( !$this->mInternalMode ) {
829 $this->setupExternalResponse( $module, $params );
830 }
831
832 // Execute
833 $module->profileIn();
834 $module->execute();
835 wfRunHooks( 'APIAfterExecute', array( &$module ) );
836 $module->profileOut();
837
838 $this->reportUnusedParams();
839
840 if ( !$this->mInternalMode ) {
841 //append Debug information
842 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
843
844 // Print result data
845 $this->printResult( false );
846 }
847 }
848
849 /**
850 * Log the preceding request
851 * @param $time Time in seconds
852 */
853 protected function logRequest( $time ) {
854 $request = $this->getRequest();
855 $milliseconds = $time === null ? '?' : round( $time * 1000 );
856 $s = 'API' .
857 ' ' . $request->getMethod() .
858 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
859 ' ' . $request->getIP() .
860 ' T=' . $milliseconds . 'ms';
861 foreach ( $this->getParamsUsed() as $name ) {
862 $value = $request->getVal( $name );
863 if ( $value === null ) {
864 continue;
865 }
866 $s .= ' ' . $name . '=';
867 if ( strlen( $value ) > 256 ) {
868 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
869 $s .= $encValue . '[...]';
870 } else {
871 $s .= $this->encodeRequestLogValue( $value );
872 }
873 }
874 $s .= "\n";
875 wfDebugLog( 'api', $s, false );
876 }
877
878 /**
879 * Encode a value in a format suitable for a space-separated log line.
880 */
881 protected function encodeRequestLogValue( $s ) {
882 static $table;
883 if ( !$table ) {
884 $chars = ';@$!*(),/:';
885 for ( $i = 0; $i < strlen( $chars ); $i++ ) {
886 $table[rawurlencode( $chars[$i] )] = $chars[$i];
887 }
888 }
889 return strtr( rawurlencode( $s ), $table );
890 }
891
892 /**
893 * Get the request parameters used in the course of the preceding execute() request
894 */
895 protected function getParamsUsed() {
896 return array_keys( $this->mParamsUsed );
897 }
898
899 /**
900 * Get a request value, and register the fact that it was used, for logging.
901 */
902 public function getVal( $name, $default = null ) {
903 $this->mParamsUsed[$name] = true;
904 return $this->getRequest()->getVal( $name, $default );
905 }
906
907 /**
908 * Get a boolean request value, and register the fact that the parameter
909 * was used, for logging.
910 */
911 public function getCheck( $name ) {
912 $this->mParamsUsed[$name] = true;
913 return $this->getRequest()->getCheck( $name );
914 }
915
916 /**
917 * Get a request upload, and register the fact that it was used, for logging.
918 *
919 * @since 1.21
920 * @param string $name Parameter name
921 * @return WebRequestUpload
922 */
923 public function getUpload( $name ) {
924 $this->mParamsUsed[$name] = true;
925 return $this->getRequest()->getUpload( $name );
926 }
927
928 /**
929 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
930 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
931 */
932 protected function reportUnusedParams() {
933 $paramsUsed = $this->getParamsUsed();
934 $allParams = $this->getRequest()->getValueNames();
935
936 if ( !$this->mInternalMode ) {
937 // Printer has not yet executed; don't warn that its parameters are unused
938 $printerParams = array_map(
939 array( $this->mPrinter, 'encodeParamName' ),
940 array_keys( $this->mPrinter->getFinalParams() ?: array() )
941 );
942 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
943 } else {
944 $unusedParams = array_diff( $allParams, $paramsUsed );
945 }
946
947 if ( count( $unusedParams ) ) {
948 $s = count( $unusedParams ) > 1 ? 's' : '';
949 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
950 }
951 }
952
953 /**
954 * Print results using the current printer
955 *
956 * @param $isError bool
957 */
958 protected function printResult( $isError ) {
959 global $wgDebugAPI;
960 if ( $wgDebugAPI !== false ) {
961 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
962 }
963
964 $this->getResult()->cleanUpUTF8();
965 $printer = $this->mPrinter;
966 $printer->profileIn();
967
968 /**
969 * If the help message is requested in the default (xmlfm) format,
970 * tell the printer not to escape ampersands so that our links do
971 * not break.
972 */
973 $isHelp = $isError || $this->mAction == 'help';
974 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
975
976 $printer->initPrinter( $isHelp );
977
978 $printer->execute();
979 $printer->closePrinter();
980 $printer->profileOut();
981 }
982
983 /**
984 * @return bool
985 */
986 public function isReadMode() {
987 return false;
988 }
989
990 /**
991 * See ApiBase for description.
992 *
993 * @return array
994 */
995 public function getAllowedParams() {
996 return array(
997 'format' => array(
998 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
999 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'format' )
1000 ),
1001 'action' => array(
1002 ApiBase::PARAM_DFLT => 'help',
1003 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'action' )
1004 ),
1005 'maxlag' => array(
1006 ApiBase::PARAM_TYPE => 'integer'
1007 ),
1008 'smaxage' => array(
1009 ApiBase::PARAM_TYPE => 'integer',
1010 ApiBase::PARAM_DFLT => 0
1011 ),
1012 'maxage' => array(
1013 ApiBase::PARAM_TYPE => 'integer',
1014 ApiBase::PARAM_DFLT => 0
1015 ),
1016 'requestid' => null,
1017 'servedby' => false,
1018 'origin' => null,
1019 );
1020 }
1021
1022 /**
1023 * See ApiBase for description.
1024 *
1025 * @return array
1026 */
1027 public function getParamDescription() {
1028 return array(
1029 'format' => 'The format of the output',
1030 'action' => 'What action you would like to perform. See below for module help',
1031 'maxlag' => array(
1032 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1033 'To save actions causing any more site replication lag, this parameter can make the client',
1034 'wait until the replication lag is less than the specified value.',
1035 'In case of a replag error, error code "maxlag" is returned, with the message like',
1036 '"Waiting for $host: $lag seconds lagged\n".',
1037 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1038 ),
1039 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1040 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1041 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1042 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1043 'origin' => array(
1044 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1045 'This must be included in any pre-flight request, and therefore must be part of the request URI (not the POST body).',
1046 '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 .',
1047 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1048 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1049 ),
1050 );
1051 }
1052
1053 /**
1054 * See ApiBase for description.
1055 *
1056 * @return array
1057 */
1058 public function getDescription() {
1059 return array(
1060 '',
1061 '',
1062 '**********************************************************************************************************',
1063 '** **',
1064 '** This is an auto-generated MediaWiki API documentation page **',
1065 '** **',
1066 '** Documentation and Examples: **',
1067 '** https://www.mediawiki.org/wiki/API **',
1068 '** **',
1069 '**********************************************************************************************************',
1070 '',
1071 'Status: All features shown on this page should be working, but the API',
1072 ' is still in active development, and may change at any time.',
1073 ' Make sure to monitor our mailing list for any updates',
1074 '',
1075 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1076 ' with the key "MediaWiki-API-Error" and then both the value of the',
1077 ' header and the error code sent back will be set to the same value',
1078 '',
1079 ' In the case of an invalid action being passed, these will have a value',
1080 ' of "unknown_action"',
1081 '',
1082 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1083 '',
1084 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1085 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1086 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1087 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1088 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1089 '',
1090 '',
1091 '',
1092 '',
1093 '',
1094 );
1095 }
1096
1097 /**
1098 * @return array
1099 */
1100 public function getPossibleErrors() {
1101 return array_merge( parent::getPossibleErrors(), array(
1102 array( 'readonlytext' ),
1103 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1104 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1105 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1106 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1107 ) );
1108 }
1109
1110 /**
1111 * Returns an array of strings with credits for the API
1112 * @return array
1113 */
1114 protected function getCredits() {
1115 return array(
1116 'API developers:',
1117 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-2009)',
1118 ' Victor Vasiliev - vasilvv @ gmail . com',
1119 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1120 ' Sam Reed - sam @ reedyboy . net',
1121 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1122 '',
1123 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1124 'or file a bug report at https://bugzilla.wikimedia.org/'
1125 );
1126 }
1127
1128 /**
1129 * Sets whether the pretty-printer should format *bold* and $italics$
1130 *
1131 * @param $help bool
1132 */
1133 public function setHelp( $help = true ) {
1134 $this->mPrinter->setHelp( $help );
1135 }
1136
1137 /**
1138 * Override the parent to generate help messages for all available modules.
1139 *
1140 * @return string
1141 */
1142 public function makeHelpMsg() {
1143 global $wgMemc, $wgAPICacheHelpTimeout;
1144 $this->setHelp();
1145 // Get help text from cache if present
1146 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1147 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1148 if ( $wgAPICacheHelpTimeout > 0 ) {
1149 $cached = $wgMemc->get( $key );
1150 if ( $cached ) {
1151 return $cached;
1152 }
1153 }
1154 $retval = $this->reallyMakeHelpMsg();
1155 if ( $wgAPICacheHelpTimeout > 0 ) {
1156 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1157 }
1158 return $retval;
1159 }
1160
1161 /**
1162 * @return mixed|string
1163 */
1164 public function reallyMakeHelpMsg() {
1165 $this->setHelp();
1166
1167 // Use parent to make default message for the main module
1168 $msg = parent::makeHelpMsg();
1169
1170 $astriks = str_repeat( '*** ', 14 );
1171 $msg .= "\n\n$astriks Modules $astriks\n\n";
1172
1173 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1174 $module = $this->mModuleMgr->getModule( $name );
1175 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1176
1177 $msg2 = $module->makeHelpMsg();
1178 if ( $msg2 !== false ) {
1179 $msg .= $msg2;
1180 }
1181 $msg .= "\n";
1182 }
1183
1184 $msg .= "\n$astriks Permissions $astriks\n\n";
1185 foreach ( self::$mRights as $right => $rightMsg ) {
1186 $groups = User::getGroupsWithPermission( $right );
1187 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1188 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1189 }
1190
1191 $msg .= "\n$astriks Formats $astriks\n\n";
1192 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1193 $module = $this->mModuleMgr->getModule( $name );
1194 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1195 $msg2 = $module->makeHelpMsg();
1196 if ( $msg2 !== false ) {
1197 $msg .= $msg2;
1198 }
1199 $msg .= "\n";
1200 }
1201
1202 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1203
1204 return $msg;
1205 }
1206
1207 /**
1208 * @param $module ApiBase
1209 * @param string $paramName What type of request is this? e.g. action, query, list, prop, meta, format
1210 * @return string
1211 */
1212 public static function makeHelpMsgHeader( $module, $paramName ) {
1213 $modulePrefix = $module->getModulePrefix();
1214 if ( strval( $modulePrefix ) !== '' ) {
1215 $modulePrefix = "($modulePrefix) ";
1216 }
1217
1218 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1219 }
1220
1221 private $mCanApiHighLimits = null;
1222
1223 /**
1224 * Check whether the current user is allowed to use high limits
1225 * @return bool
1226 */
1227 public function canApiHighLimits() {
1228 if ( !isset( $this->mCanApiHighLimits ) ) {
1229 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1230 }
1231
1232 return $this->mCanApiHighLimits;
1233 }
1234
1235 /**
1236 * Check whether the user wants us to show version information in the API help
1237 * @return bool
1238 * @deprecated since 1.21, always returns false
1239 */
1240 public function getShowVersions() {
1241 wfDeprecated( __METHOD__, '1.21' );
1242 return false;
1243 }
1244
1245 /**
1246 * Overrides to return this instance's module manager.
1247 * @return ApiModuleManager
1248 */
1249 public function getModuleManager() {
1250 return $this->mModuleMgr;
1251 }
1252
1253 /**
1254 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1255 * classes who wish to add their own modules to their lexicon or override the
1256 * behavior of inherent ones.
1257 *
1258 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1259 * @param string $name The identifier for this module.
1260 * @param $class ApiBase The class where this module is implemented.
1261 */
1262 protected function addModule( $name, $class ) {
1263 $this->getModuleManager()->addModule( $name, 'action', $class );
1264 }
1265
1266 /**
1267 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1268 * classes who wish to add to or modify current formatters.
1269 *
1270 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1271 * @param string $name The identifier for this format.
1272 * @param $class ApiFormatBase The class implementing this format.
1273 */
1274 protected function addFormat( $name, $class ) {
1275 $this->getModuleManager()->addModule( $name, 'format', $class );
1276 }
1277
1278 /**
1279 * Get the array mapping module names to class names
1280 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1281 * @return array
1282 */
1283 function getModules() {
1284 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1285 }
1286
1287 /**
1288 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1289 *
1290 * @since 1.18
1291 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1292 * @return array
1293 */
1294 public function getFormats() {
1295 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1296 }
1297 }
1298
1299 /**
1300 * This exception will be thrown when dieUsage is called to stop module execution.
1301 * The exception handling code will print a help screen explaining how this API may be used.
1302 *
1303 * @ingroup API
1304 */
1305 class UsageException extends MWException {
1306
1307 private $mCodestr;
1308
1309 /**
1310 * @var null|array
1311 */
1312 private $mExtraData;
1313
1314 /**
1315 * @param $message string
1316 * @param $codestr string
1317 * @param $code int
1318 * @param $extradata array|null
1319 */
1320 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1321 parent::__construct( $message, $code );
1322 $this->mCodestr = $codestr;
1323 $this->mExtraData = $extradata;
1324 }
1325
1326 /**
1327 * @return string
1328 */
1329 public function getCodeString() {
1330 return $this->mCodestr;
1331 }
1332
1333 /**
1334 * @return array
1335 */
1336 public function getMessageArray() {
1337 $result = array(
1338 'code' => $this->mCodestr,
1339 'info' => $this->getMessage()
1340 );
1341 if ( is_array( $this->mExtraData ) ) {
1342 $result = array_merge( $result, $this->mExtraData );
1343 }
1344 return $result;
1345 }
1346
1347 /**
1348 * @return string
1349 */
1350 public function __toString() {
1351 return "{$this->getCodeString()}: {$this->getMessage()}";
1352 }
1353 }