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