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