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