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