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