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