465025c93e9c5cbf6d9a6bfe061037afcdeb9847
[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 * When no format parameter is given, this format will be used
44 */
45 const API_DEFAULT_FORMAT = 'jsonfm';
46
47 /**
48 * List of available modules: action name => module class
49 */
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
62 'help' => 'ApiHelp',
63 'paraminfo' => 'ApiParamInfo',
64 'rsd' => 'ApiRsd',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
67 'checktoken' => 'ApiCheckToken',
68
69 // Write modules
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
78 'move' => 'ApiMove',
79 'edit' => 'ApiEditPage',
80 'upload' => 'ApiUpload',
81 'filerevert' => 'ApiFileRevert',
82 'emailuser' => 'ApiEmailUser',
83 'watch' => 'ApiWatch',
84 'patrol' => 'ApiPatrol',
85 'import' => 'ApiImport',
86 'clearhasmsg' => 'ApiClearHasMsg',
87 'userrights' => 'ApiUserrights',
88 'options' => 'ApiOptions',
89 'imagerotate' => 'ApiImageRotate',
90 'revisiondelete' => 'ApiRevisionDelete',
91 'managetags' => 'ApiManageTags',
92 'tag' => 'ApiTag',
93 );
94
95 /**
96 * List of available formats: format name => format class
97 */
98 private static $Formats = array(
99 'json' => 'ApiFormatJson',
100 'jsonfm' => 'ApiFormatJson',
101 'php' => 'ApiFormatPhp',
102 'phpfm' => 'ApiFormatPhp',
103 'wddx' => 'ApiFormatWddx',
104 'wddxfm' => 'ApiFormatWddx',
105 'xml' => 'ApiFormatXml',
106 'xmlfm' => 'ApiFormatXml',
107 'yaml' => 'ApiFormatYaml',
108 'yamlfm' => 'ApiFormatYaml',
109 'rawfm' => 'ApiFormatJson',
110 'txt' => 'ApiFormatTxt',
111 'txtfm' => 'ApiFormatTxt',
112 'dbg' => 'ApiFormatDbg',
113 'dbgfm' => 'ApiFormatDbg',
114 'dump' => 'ApiFormatDump',
115 'dumpfm' => 'ApiFormatDump',
116 'none' => 'ApiFormatNone',
117 );
118
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
120 /**
121 * List of user roles that are specifically relevant to the API.
122 * array( 'right' => array ( 'msg' => 'Some message with a $1',
123 * 'params' => array ( $someVarToSubst ) ),
124 * );
125 */
126 private static $mRights = array(
127 'writeapi' => array(
128 'msg' => 'right-writeapi',
129 'params' => array()
130 ),
131 'apihighlimits' => array(
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
134 )
135 );
136 // @codingStandardsIgnoreEnd
137
138 /**
139 * @var ApiFormatBase
140 */
141 private $mPrinter;
142
143 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
144 private $mAction;
145 private $mEnableWrite;
146 private $mInternalMode, $mSquidMaxage, $mModule;
147
148 private $mCacheMode = 'private';
149 private $mCacheControl = array();
150 private $mParamsUsed = array();
151
152 /**
153 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
154 *
155 * @param IContextSource|WebRequest $context If this is an instance of
156 * FauxRequest, errors are thrown and no printing occurs
157 * @param bool $enableWrite Should be set to true if the api may modify data
158 */
159 public function __construct( $context = null, $enableWrite = false ) {
160 if ( $context === null ) {
161 $context = RequestContext::getMain();
162 } elseif ( $context instanceof WebRequest ) {
163 // BC for pre-1.19
164 $request = $context;
165 $context = RequestContext::getMain();
166 }
167 // We set a derivative context so we can change stuff later
168 $this->setContext( new DerivativeContext( $context ) );
169
170 if ( isset( $request ) ) {
171 $this->getContext()->setRequest( $request );
172 }
173
174 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
175
176 // Special handling for the main module: $parent === $this
177 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
178
179 if ( !$this->mInternalMode ) {
180 // Impose module restrictions.
181 // If the current user cannot read,
182 // Remove all modules other than login
183 global $wgUser;
184
185 if ( $this->lacksSameOriginSecurity() ) {
186 // If we're in a mode that breaks the same-origin policy, strip
187 // user credentials for security.
188 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
189 $wgUser = new User();
190 $this->getContext()->setUser( $wgUser );
191 }
192 }
193
194 $uselang = $this->getParameter( 'uselang' );
195 if ( $uselang === 'user' ) {
196 // Assume the parent context is going to return the user language
197 // for uselang=user (see T85635).
198 } else {
199 if ( $uselang === 'content' ) {
200 global $wgContLang;
201 $uselang = $wgContLang->getCode();
202 }
203 $code = RequestContext::sanitizeLangCode( $uselang );
204 $this->getContext()->setLanguage( $code );
205 if ( !$this->mInternalMode ) {
206 global $wgLang;
207 $wgLang = $this->getContext()->getLanguage();
208 RequestContext::getMain()->setLanguage( $wgLang );
209 }
210 }
211
212 $config = $this->getConfig();
213 $this->mModuleMgr = new ApiModuleManager( $this );
214 $this->mModuleMgr->addModules( self::$Modules, 'action' );
215 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
216 $this->mModuleMgr->addModules( self::$Formats, 'format' );
217 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
218
219 Hooks::run( 'ApiMain::moduleManager', array( $this->mModuleMgr ) );
220
221 $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
222 $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
223 $this->mResult->setErrorFormatter( $this->mErrorFormatter );
224 $this->mResult->setMainForContinuation( $this );
225 $this->mContinuationManager = null;
226 $this->mEnableWrite = $enableWrite;
227
228 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
229 $this->mCommit = false;
230 }
231
232 /**
233 * Return true if the API was started by other PHP code using FauxRequest
234 * @return bool
235 */
236 public function isInternalMode() {
237 return $this->mInternalMode;
238 }
239
240 /**
241 * Get the ApiResult object associated with current request
242 *
243 * @return ApiResult
244 */
245 public function getResult() {
246 return $this->mResult;
247 }
248
249 /**
250 * Get the ApiErrorFormatter object associated with current request
251 * @return ApiErrorFormatter
252 */
253 public function getErrorFormatter() {
254 return $this->mErrorFormatter;
255 }
256
257 /**
258 * Get the continuation manager
259 * @return ApiContinuationManager|null
260 */
261 public function getContinuationManager() {
262 return $this->mContinuationManager;
263 }
264
265 /**
266 * Set the continuation manager
267 * @param ApiContinuationManager|null
268 */
269 public function setContinuationManager( $manager ) {
270 if ( $manager !== null ) {
271 if ( !$manager instanceof ApiContinuationManager ) {
272 throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
273 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
274 );
275 }
276 if ( $this->mContinuationManager !== null ) {
277 throw new UnexpectedValueException(
278 __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
279 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
280 );
281 }
282 }
283 $this->mContinuationManager = $manager;
284 }
285
286 /**
287 * Get the API module object. Only works after executeAction()
288 *
289 * @return ApiBase
290 */
291 public function getModule() {
292 return $this->mModule;
293 }
294
295 /**
296 * Get the result formatter object. Only works after setupExecuteAction()
297 *
298 * @return ApiFormatBase
299 */
300 public function getPrinter() {
301 return $this->mPrinter;
302 }
303
304 /**
305 * Set how long the response should be cached.
306 *
307 * @param int $maxage
308 */
309 public function setCacheMaxAge( $maxage ) {
310 $this->setCacheControl( array(
311 'max-age' => $maxage,
312 's-maxage' => $maxage
313 ) );
314 }
315
316 /**
317 * Set the type of caching headers which will be sent.
318 *
319 * @param string $mode One of:
320 * - 'public': Cache this object in public caches, if the maxage or smaxage
321 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
322 * not provided by any of these means, the object will be private.
323 * - 'private': Cache this object only in private client-side caches.
324 * - 'anon-public-user-private': Make this object cacheable for logged-out
325 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
326 * set consistently for a given URL, it cannot be set differently depending on
327 * things like the contents of the database, or whether the user is logged in.
328 *
329 * If the wiki does not allow anonymous users to read it, the mode set here
330 * will be ignored, and private caching headers will always be sent. In other words,
331 * the "public" mode is equivalent to saying that the data sent is as public as a page
332 * view.
333 *
334 * For user-dependent data, the private mode should generally be used. The
335 * anon-public-user-private mode should only be used where there is a particularly
336 * good performance reason for caching the anonymous response, but where the
337 * response to logged-in users may differ, or may contain private data.
338 *
339 * If this function is never called, then the default will be the private mode.
340 */
341 public function setCacheMode( $mode ) {
342 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
343 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
344
345 // Ignore for forwards-compatibility
346 return;
347 }
348
349 if ( !User::isEveryoneAllowed( 'read' ) ) {
350 // Private wiki, only private headers
351 if ( $mode !== 'private' ) {
352 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
353
354 return;
355 }
356 }
357
358 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
359 // User language is used for i18n, so we don't want to publicly
360 // cache. Anons are ok, because if they have non-default language
361 // then there's an appropriate Vary header set by whatever set
362 // their non-default language.
363 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
364 "'anon-public-user-private' due to uselang=user\n" );
365 $mode = 'anon-public-user-private';
366 }
367
368 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
369 $this->mCacheMode = $mode;
370 }
371
372 /**
373 * Set directives (key/value pairs) for the Cache-Control header.
374 * Boolean values will be formatted as such, by including or omitting
375 * without an equals sign.
376 *
377 * Cache control values set here will only be used if the cache mode is not
378 * private, see setCacheMode().
379 *
380 * @param array $directives
381 */
382 public function setCacheControl( $directives ) {
383 $this->mCacheControl = $directives + $this->mCacheControl;
384 }
385
386 /**
387 * Create an instance of an output formatter by its name
388 *
389 * @param string $format
390 *
391 * @return ApiFormatBase
392 */
393 public function createPrinterByName( $format ) {
394 $printer = $this->mModuleMgr->getModule( $format, 'format' );
395 if ( $printer === null ) {
396 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
397 }
398
399 return $printer;
400 }
401
402 /**
403 * Execute api request. Any errors will be handled if the API was called by the remote client.
404 */
405 public function execute() {
406 if ( $this->mInternalMode ) {
407 $this->executeAction();
408 } else {
409 $this->executeActionWithErrorHandling();
410 }
411 }
412
413 /**
414 * Execute an action, and in case of an error, erase whatever partial results
415 * have been accumulated, and replace it with an error message and a help screen.
416 */
417 protected function executeActionWithErrorHandling() {
418 // Verify the CORS header before executing the action
419 if ( !$this->handleCORS() ) {
420 // handleCORS() has sent a 403, abort
421 return;
422 }
423
424 // Exit here if the request method was OPTIONS
425 // (assume there will be a followup GET or POST)
426 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
427 return;
428 }
429
430 // In case an error occurs during data output,
431 // clear the output buffer and print just the error information
432 ob_start();
433
434 $t = microtime( true );
435 try {
436 $this->executeAction();
437 } catch ( Exception $e ) {
438 $this->handleException( $e );
439 }
440
441 // Log the request whether or not there was an error
442 $this->logRequest( microtime( true ) - $t );
443
444 // Send cache headers after any code which might generate an error, to
445 // avoid sending public cache headers for errors.
446 $this->sendCacheHeaders();
447
448 ob_end_flush();
449 }
450
451 /**
452 * Handle an exception as an API response
453 *
454 * @since 1.23
455 * @param Exception $e
456 */
457 protected function handleException( Exception $e ) {
458 // Bug 63145: Rollback any open database transactions
459 if ( !( $e instanceof UsageException ) ) {
460 // UsageExceptions are intentional, so don't rollback if that's the case
461 try {
462 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
463 } catch ( DBError $e2 ) {
464 // Rollback threw an exception too. Log it, but don't interrupt
465 // our regularly scheduled exception handling.
466 MWExceptionHandler::logException( $e2 );
467 }
468 }
469
470 // Allow extra cleanup and logging
471 Hooks::run( 'ApiMain::onException', array( $this, $e ) );
472
473 // Log it
474 if ( !( $e instanceof UsageException ) ) {
475 MWExceptionHandler::logException( $e );
476 }
477
478 // Handle any kind of exception by outputting properly formatted error message.
479 // If this fails, an unhandled exception should be thrown so that global error
480 // handler will process and log it.
481
482 $errCode = $this->substituteResultWithError( $e );
483
484 // Error results should not be cached
485 $this->setCacheMode( 'private' );
486
487 $response = $this->getRequest()->response();
488 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
489 if ( $e->getCode() === 0 ) {
490 $response->header( $headerStr );
491 } else {
492 $response->header( $headerStr, true, $e->getCode() );
493 }
494
495 // Reset and print just the error message
496 ob_clean();
497
498 $this->printResult( true );
499 }
500
501 /**
502 * Handle an exception from the ApiBeforeMain hook.
503 *
504 * This tries to print the exception as an API response, to be more
505 * friendly to clients. If it fails, it will rethrow the exception.
506 *
507 * @since 1.23
508 * @param Exception $e
509 * @throws Exception
510 */
511 public static function handleApiBeforeMainException( Exception $e ) {
512 ob_start();
513
514 try {
515 $main = new self( RequestContext::getMain(), false );
516 $main->handleException( $e );
517 } catch ( Exception $e2 ) {
518 // Nope, even that didn't work. Punt.
519 throw $e;
520 }
521
522 // Log the request and reset cache headers
523 $main->logRequest( 0 );
524 $main->sendCacheHeaders();
525
526 ob_end_flush();
527 }
528
529 /**
530 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
531 *
532 * If no origin parameter is present, nothing happens.
533 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
534 * is set and false is returned.
535 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
536 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
537 * headers are set.
538 * http://www.w3.org/TR/cors/#resource-requests
539 * http://www.w3.org/TR/cors/#resource-preflight-requests
540 *
541 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
542 */
543 protected function handleCORS() {
544 $originParam = $this->getParameter( 'origin' ); // defaults to null
545 if ( $originParam === null ) {
546 // No origin parameter, nothing to do
547 return true;
548 }
549
550 $request = $this->getRequest();
551 $response = $request->response();
552
553 // Origin: header is a space-separated list of origins, check all of them
554 $originHeader = $request->getHeader( 'Origin' );
555 if ( $originHeader === false ) {
556 $origins = array();
557 } else {
558 $originHeader = trim( $originHeader );
559 $origins = preg_split( '/\s+/', $originHeader );
560 }
561
562 if ( !in_array( $originParam, $origins ) ) {
563 // origin parameter set but incorrect
564 // Send a 403 response
565 $message = HttpStatus::getMessage( 403 );
566 $response->header( "HTTP/1.1 403 $message", true, 403 );
567 $response->header( 'Cache-Control: no-cache' );
568 echo "'origin' parameter does not match Origin header\n";
569
570 return false;
571 }
572
573 $config = $this->getConfig();
574 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
575 $originParam,
576 $config->get( 'CrossSiteAJAXdomains' ),
577 $config->get( 'CrossSiteAJAXdomainExceptions' )
578 );
579
580 if ( $matchOrigin ) {
581 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
582 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
583 if ( $preflight ) {
584 // This is a CORS preflight request
585 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
586 // If method is not a case-sensitive match, do not set any additional headers and terminate.
587 return true;
588 }
589 // We allow the actual request to send the following headers
590 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
591 if ( $requestedHeaders !== false ) {
592 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
593 return true;
594 }
595 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
596 }
597
598 // We only allow the actual request to be GET or POST
599 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
600 }
601
602 $response->header( "Access-Control-Allow-Origin: $originHeader" );
603 $response->header( 'Access-Control-Allow-Credentials: true' );
604 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
605
606 if ( !$preflight ) {
607 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
608 }
609 }
610
611 $this->getOutput()->addVaryHeader( 'Origin' );
612 return true;
613 }
614
615 /**
616 * Attempt to match an Origin header against a set of rules and a set of exceptions
617 * @param string $value Origin header
618 * @param array $rules Set of wildcard rules
619 * @param array $exceptions Set of wildcard rules
620 * @return bool True if $value matches a rule in $rules and doesn't match
621 * any rules in $exceptions, false otherwise
622 */
623 protected static function matchOrigin( $value, $rules, $exceptions ) {
624 foreach ( $rules as $rule ) {
625 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
626 // Rule matches, check exceptions
627 foreach ( $exceptions as $exc ) {
628 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
629 return false;
630 }
631 }
632
633 return true;
634 }
635 }
636
637 return false;
638 }
639
640 /**
641 * Attempt to validate the value of Access-Control-Request-Headers against a list
642 * of headers that we allow the follow up request to send.
643 *
644 * @param string $requestedHeaders Comma seperated list of HTTP headers
645 * @return bool True if all requested headers are in the list of allowed headers
646 */
647 protected static function matchRequestedHeaders( $requestedHeaders ) {
648 if ( trim( $requestedHeaders ) === '' ) {
649 return true;
650 }
651 $requestedHeaders = explode( ',', $requestedHeaders );
652 $allowedAuthorHeaders = array_flip( array(
653 /* simple headers (see spec) */
654 'accept',
655 'accept-language',
656 'content-language',
657 'content-type',
658 /* non-authorable headers in XHR, which are however requested by some UAs */
659 'accept-encoding',
660 'dnt',
661 'origin',
662 /* MediaWiki whitelist */
663 'api-user-agent',
664 ) );
665 foreach ( $requestedHeaders as $rHeader ) {
666 $rHeader = strtolower( trim( $rHeader ) );
667 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
668 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
669 return false;
670 }
671 }
672 return true;
673 }
674
675 /**
676 * Helper function to convert wildcard string into a regex
677 * '*' => '.*?'
678 * '?' => '.'
679 *
680 * @param string $wildcard String with wildcards
681 * @return string Regular expression
682 */
683 protected static function wildcardToRegex( $wildcard ) {
684 $wildcard = preg_quote( $wildcard, '/' );
685 $wildcard = str_replace(
686 array( '\*', '\?' ),
687 array( '.*?', '.' ),
688 $wildcard
689 );
690
691 return "/^https?:\/\/$wildcard$/";
692 }
693
694 protected function sendCacheHeaders() {
695 $response = $this->getRequest()->response();
696 $out = $this->getOutput();
697
698 $config = $this->getConfig();
699
700 if ( $config->get( 'VaryOnXFP' ) ) {
701 $out->addVaryHeader( 'X-Forwarded-Proto' );
702 }
703
704 // The logic should be:
705 // $this->mCacheControl['max-age'] is set?
706 // Use it, the module knows better than our guess.
707 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
708 // Use 0 because we can guess caching is probably the wrong thing to do.
709 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
710 $maxage = 0;
711 if ( isset( $this->mCacheControl['max-age'] ) ) {
712 $maxage = $this->mCacheControl['max-age'];
713 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
714 $this->mCacheMode !== 'private'
715 ) {
716 $maxage = $this->getParameter( 'maxage' );
717 }
718 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
719
720 if ( $this->mCacheMode == 'private' ) {
721 $response->header( "Cache-Control: $privateCache" );
722 return;
723 }
724
725 $useXVO = $config->get( 'UseXVO' );
726 if ( $this->mCacheMode == 'anon-public-user-private' ) {
727 $out->addVaryHeader( 'Cookie' );
728 $response->header( $out->getVaryHeader() );
729 if ( $useXVO ) {
730 $response->header( $out->getXVO() );
731 if ( $out->haveCacheVaryCookies() ) {
732 // Logged in, mark this request private
733 $response->header( "Cache-Control: $privateCache" );
734 return;
735 }
736 // Logged out, send normal public headers below
737 } elseif ( session_id() != '' ) {
738 // Logged in or otherwise has session (e.g. anonymous users who have edited)
739 // Mark request private
740 $response->header( "Cache-Control: $privateCache" );
741
742 return;
743 } // else no XVO and anonymous, send public headers below
744 }
745
746 // Send public headers
747 $response->header( $out->getVaryHeader() );
748 if ( $useXVO ) {
749 $response->header( $out->getXVO() );
750 }
751
752 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
753 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
754 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
755 }
756 if ( !isset( $this->mCacheControl['max-age'] ) ) {
757 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
758 }
759
760 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
761 // Public cache not requested
762 // Sending a Vary header in this case is harmless, and protects us
763 // against conditional calls of setCacheMaxAge().
764 $response->header( "Cache-Control: $privateCache" );
765
766 return;
767 }
768
769 $this->mCacheControl['public'] = true;
770
771 // Send an Expires header
772 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
773 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
774 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
775
776 // Construct the Cache-Control header
777 $ccHeader = '';
778 $separator = '';
779 foreach ( $this->mCacheControl as $name => $value ) {
780 if ( is_bool( $value ) ) {
781 if ( $value ) {
782 $ccHeader .= $separator . $name;
783 $separator = ', ';
784 }
785 } else {
786 $ccHeader .= $separator . "$name=$value";
787 $separator = ', ';
788 }
789 }
790
791 $response->header( "Cache-Control: $ccHeader" );
792 }
793
794 /**
795 * Replace the result data with the information about an exception.
796 * Returns the error code
797 * @param Exception $e
798 * @return string
799 */
800 protected function substituteResultWithError( $e ) {
801 $result = $this->getResult();
802
803 // Printer may not be initialized if the extractRequestParams() fails for the main module
804 if ( !isset( $this->mPrinter ) ) {
805 // The printer has not been created yet. Try to manually get formatter value.
806 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
807 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
808 $value = self::API_DEFAULT_FORMAT;
809 }
810
811 $this->mPrinter = $this->createPrinterByName( $value );
812 }
813
814 // Printer may not be able to handle errors. This is particularly
815 // likely if the module returns something for getCustomPrinter().
816 if ( !$this->mPrinter->canPrintErrors() ) {
817 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
818 }
819
820 // Update raw mode flag for the selected printer.
821 $result->setRawMode( $this->mPrinter->getNeedsRawData() );
822
823 $config = $this->getConfig();
824
825 if ( $e instanceof UsageException ) {
826 // User entered incorrect parameters - generate error response
827 $errMessage = $e->getMessageArray();
828 $link = wfExpandUrl( wfScript( 'api' ) );
829 ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
830 } else {
831 // Something is seriously wrong
832 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
833 $info = 'Database query error';
834 } else {
835 $info = "Exception Caught: {$e->getMessage()}";
836 }
837
838 $errMessage = array(
839 'code' => 'internal_api_error_' . get_class( $e ),
840 'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info,
841 );
842 if ( $config->get( 'ShowExceptionDetails' ) ) {
843 ApiResult::setContentValue(
844 $errMessage,
845 'trace',
846 MWExceptionHandler::getRedactedTraceAsString( $e )
847 );
848 }
849 }
850
851 // Remember all the warnings to re-add them later
852 $warnings = $result->getResultData( array( 'warnings' ) );
853
854 $result->reset();
855 // Re-add the id
856 $requestid = $this->getParameter( 'requestid' );
857 if ( !is_null( $requestid ) ) {
858 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
859 }
860 if ( $config->get( 'ShowHostnames' ) ) {
861 // servedby is especially useful when debugging errors
862 $result->addValue( null, 'servedby', wfHostName(), ApiResult::NO_SIZE_CHECK );
863 }
864 if ( $warnings !== null ) {
865 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
866 }
867
868 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
869
870 return $errMessage['code'];
871 }
872
873 /**
874 * Set up for the execution.
875 * @return array
876 */
877 protected function setupExecuteAction() {
878 // First add the id to the top element
879 $result = $this->getResult();
880 $requestid = $this->getParameter( 'requestid' );
881 if ( !is_null( $requestid ) ) {
882 $result->addValue( null, 'requestid', $requestid );
883 }
884
885 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
886 $servedby = $this->getParameter( 'servedby' );
887 if ( $servedby ) {
888 $result->addValue( null, 'servedby', wfHostName() );
889 }
890 }
891
892 if ( $this->getParameter( 'curtimestamp' ) ) {
893 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
894 ApiResult::NO_SIZE_CHECK );
895 }
896
897 $params = $this->extractRequestParams();
898
899 $this->mAction = $params['action'];
900
901 if ( !is_string( $this->mAction ) ) {
902 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
903 }
904
905 return $params;
906 }
907
908 /**
909 * Set up the module for response
910 * @return ApiBase The module that will handle this action
911 * @throws MWException
912 * @throws UsageException
913 */
914 protected function setupModule() {
915 // Instantiate the module requested by the user
916 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
917 if ( $module === null ) {
918 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
919 }
920 $moduleParams = $module->extractRequestParams();
921
922 // Check token, if necessary
923 if ( $module->needsToken() === true ) {
924 throw new MWException(
925 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
926 "See documentation for ApiBase::needsToken for details."
927 );
928 }
929 if ( $module->needsToken() ) {
930 if ( !$module->mustBePosted() ) {
931 throw new MWException(
932 "Module '{$module->getModuleName()}' must require POST to use tokens."
933 );
934 }
935
936 if ( !isset( $moduleParams['token'] ) ) {
937 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
938 }
939
940 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
941 array_key_exists(
942 $module->encodeParamName( 'token' ),
943 $this->getRequest()->getQueryValues()
944 )
945 ) {
946 $this->dieUsage(
947 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
948 'mustposttoken'
949 );
950 }
951
952 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
953 $this->dieUsageMsg( 'sessionfailure' );
954 }
955 }
956
957 return $module;
958 }
959
960 /**
961 * Check the max lag if necessary
962 * @param ApiBase $module Api module being used
963 * @param array $params Array an array containing the request parameters.
964 * @return bool True on success, false should exit immediately
965 */
966 protected function checkMaxLag( $module, $params ) {
967 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
968 // Check for maxlag
969 $maxLag = $params['maxlag'];
970 list( $host, $lag ) = wfGetLB()->getMaxLag();
971 if ( $lag > $maxLag ) {
972 $response = $this->getRequest()->response();
973
974 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
975 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
976
977 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
978 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
979 }
980
981 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
982 }
983 }
984
985 return true;
986 }
987
988 /**
989 * Check for sufficient permissions to execute
990 * @param ApiBase $module An Api module
991 */
992 protected function checkExecutePermissions( $module ) {
993 $user = $this->getUser();
994 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
995 !$user->isAllowed( 'read' )
996 ) {
997 $this->dieUsageMsg( 'readrequired' );
998 }
999 if ( $module->isWriteMode() ) {
1000 if ( !$this->mEnableWrite ) {
1001 $this->dieUsageMsg( 'writedisabled' );
1002 }
1003 if ( !$user->isAllowed( 'writeapi' ) ) {
1004 $this->dieUsageMsg( 'writerequired' );
1005 }
1006 if ( wfReadOnly() ) {
1007 $this->dieReadOnly();
1008 }
1009 }
1010
1011 // Allow extensions to stop execution for arbitrary reasons.
1012 $message = false;
1013 if ( !Hooks::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1014 $this->dieUsageMsg( $message );
1015 }
1016 }
1017
1018 /**
1019 * Check asserts of the user's rights
1020 * @param array $params
1021 */
1022 protected function checkAsserts( $params ) {
1023 if ( isset( $params['assert'] ) ) {
1024 $user = $this->getUser();
1025 switch ( $params['assert'] ) {
1026 case 'user':
1027 if ( $user->isAnon() ) {
1028 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1029 }
1030 break;
1031 case 'bot':
1032 if ( !$user->isAllowed( 'bot' ) ) {
1033 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1034 }
1035 break;
1036 }
1037 }
1038 }
1039
1040 /**
1041 * Check POST for external response and setup result printer
1042 * @param ApiBase $module An Api module
1043 * @param array $params An array with the request parameters
1044 */
1045 protected function setupExternalResponse( $module, $params ) {
1046 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1047 // Module requires POST. GET request might still be allowed
1048 // if $wgDebugApi is true, otherwise fail.
1049 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
1050 }
1051
1052 // See if custom printer is used
1053 $this->mPrinter = $module->getCustomPrinter();
1054 if ( is_null( $this->mPrinter ) ) {
1055 // Create an appropriate printer
1056 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1057 }
1058
1059 if ( $this->mPrinter->getNeedsRawData() ) {
1060 $this->getResult()->setRawMode();
1061 }
1062 }
1063
1064 /**
1065 * Execute the actual module, without any error handling
1066 */
1067 protected function executeAction() {
1068 $params = $this->setupExecuteAction();
1069 $module = $this->setupModule();
1070 $this->mModule = $module;
1071
1072 $this->checkExecutePermissions( $module );
1073
1074 if ( !$this->checkMaxLag( $module, $params ) ) {
1075 return;
1076 }
1077
1078 if ( !$this->mInternalMode ) {
1079 $this->setupExternalResponse( $module, $params );
1080 }
1081
1082 $this->checkAsserts( $params );
1083
1084 // Execute
1085 $module->execute();
1086 Hooks::run( 'APIAfterExecute', array( &$module ) );
1087
1088 $this->reportUnusedParams();
1089
1090 if ( !$this->mInternalMode ) {
1091 //append Debug information
1092 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1093
1094 // Print result data
1095 $this->printResult( false );
1096 }
1097 }
1098
1099 /**
1100 * Log the preceding request
1101 * @param int $time Time in seconds
1102 */
1103 protected function logRequest( $time ) {
1104 $request = $this->getRequest();
1105 $milliseconds = $time === null ? '?' : round( $time * 1000 );
1106 $s = 'API' .
1107 ' ' . $request->getMethod() .
1108 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1109 ' ' . $request->getIP() .
1110 ' T=' . $milliseconds . 'ms';
1111 foreach ( $this->getParamsUsed() as $name ) {
1112 $value = $request->getVal( $name );
1113 if ( $value === null ) {
1114 continue;
1115 }
1116 $s .= ' ' . $name . '=';
1117 if ( strlen( $value ) > 256 ) {
1118 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1119 $s .= $encValue . '[...]';
1120 } else {
1121 $s .= $this->encodeRequestLogValue( $value );
1122 }
1123 }
1124 $s .= "\n";
1125 wfDebugLog( 'api', $s, 'private' );
1126 }
1127
1128 /**
1129 * Encode a value in a format suitable for a space-separated log line.
1130 * @param string $s
1131 * @return string
1132 */
1133 protected function encodeRequestLogValue( $s ) {
1134 static $table;
1135 if ( !$table ) {
1136 $chars = ';@$!*(),/:';
1137 $numChars = strlen( $chars );
1138 for ( $i = 0; $i < $numChars; $i++ ) {
1139 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1140 }
1141 }
1142
1143 return strtr( rawurlencode( $s ), $table );
1144 }
1145
1146 /**
1147 * Get the request parameters used in the course of the preceding execute() request
1148 * @return array
1149 */
1150 protected function getParamsUsed() {
1151 return array_keys( $this->mParamsUsed );
1152 }
1153
1154 /**
1155 * Get a request value, and register the fact that it was used, for logging.
1156 * @param string $name
1157 * @param mixed $default
1158 * @return mixed
1159 */
1160 public function getVal( $name, $default = null ) {
1161 $this->mParamsUsed[$name] = true;
1162
1163 $ret = $this->getRequest()->getVal( $name );
1164 if ( $ret === null ) {
1165 if ( $this->getRequest()->getArray( $name ) !== null ) {
1166 // See bug 10262 for why we don't just join( '|', ... ) the
1167 // array.
1168 $this->setWarning(
1169 "Parameter '$name' uses unsupported PHP array syntax"
1170 );
1171 }
1172 $ret = $default;
1173 }
1174 return $ret;
1175 }
1176
1177 /**
1178 * Get a boolean request value, and register the fact that the parameter
1179 * was used, for logging.
1180 * @param string $name
1181 * @return bool
1182 */
1183 public function getCheck( $name ) {
1184 return $this->getVal( $name, null ) !== null;
1185 }
1186
1187 /**
1188 * Get a request upload, and register the fact that it was used, for logging.
1189 *
1190 * @since 1.21
1191 * @param string $name Parameter name
1192 * @return WebRequestUpload
1193 */
1194 public function getUpload( $name ) {
1195 $this->mParamsUsed[$name] = true;
1196
1197 return $this->getRequest()->getUpload( $name );
1198 }
1199
1200 /**
1201 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1202 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1203 */
1204 protected function reportUnusedParams() {
1205 $paramsUsed = $this->getParamsUsed();
1206 $allParams = $this->getRequest()->getValueNames();
1207
1208 if ( !$this->mInternalMode ) {
1209 // Printer has not yet executed; don't warn that its parameters are unused
1210 $printerParams = array_map(
1211 array( $this->mPrinter, 'encodeParamName' ),
1212 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1213 );
1214 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1215 } else {
1216 $unusedParams = array_diff( $allParams, $paramsUsed );
1217 }
1218
1219 if ( count( $unusedParams ) ) {
1220 $s = count( $unusedParams ) > 1 ? 's' : '';
1221 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1222 }
1223 }
1224
1225 /**
1226 * Print results using the current printer
1227 *
1228 * @param bool $isError
1229 */
1230 protected function printResult( $isError ) {
1231 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1232 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1233 }
1234
1235 $printer = $this->mPrinter;
1236 $printer->initPrinter( false );
1237 $printer->execute();
1238 $printer->closePrinter();
1239 }
1240
1241 /**
1242 * @return bool
1243 */
1244 public function isReadMode() {
1245 return false;
1246 }
1247
1248 /**
1249 * See ApiBase for description.
1250 *
1251 * @return array
1252 */
1253 public function getAllowedParams() {
1254 return array(
1255 'action' => array(
1256 ApiBase::PARAM_DFLT => 'help',
1257 ApiBase::PARAM_TYPE => 'submodule',
1258 ),
1259 'format' => array(
1260 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1261 ApiBase::PARAM_TYPE => 'submodule',
1262 ),
1263 'maxlag' => array(
1264 ApiBase::PARAM_TYPE => 'integer'
1265 ),
1266 'smaxage' => array(
1267 ApiBase::PARAM_TYPE => 'integer',
1268 ApiBase::PARAM_DFLT => 0
1269 ),
1270 'maxage' => array(
1271 ApiBase::PARAM_TYPE => 'integer',
1272 ApiBase::PARAM_DFLT => 0
1273 ),
1274 'assert' => array(
1275 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1276 ),
1277 'requestid' => null,
1278 'servedby' => false,
1279 'curtimestamp' => false,
1280 'origin' => null,
1281 'uselang' => array(
1282 ApiBase::PARAM_DFLT => 'user',
1283 ),
1284 );
1285 }
1286
1287 /** @see ApiBase::getExamplesMessages() */
1288 protected function getExamplesMessages() {
1289 return array(
1290 'action=help'
1291 => 'apihelp-help-example-main',
1292 'action=help&recursivesubmodules=1'
1293 => 'apihelp-help-example-recursive',
1294 );
1295 }
1296
1297 public function modifyHelp( array &$help, array $options ) {
1298 // Wish PHP had an "array_insert_before". Instead, we have to manually
1299 // reindex the array to get 'permissions' in the right place.
1300 $oldHelp = $help;
1301 $help = array();
1302 foreach ( $oldHelp as $k => $v ) {
1303 if ( $k === 'submodules' ) {
1304 $help['permissions'] = '';
1305 }
1306 $help[$k] = $v;
1307 }
1308 $help['credits'] = '';
1309
1310 // Fill 'permissions'
1311 $help['permissions'] .= Html::openElement( 'div',
1312 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1313 $m = $this->msg( 'api-help-permissions' );
1314 if ( !$m->isDisabled() ) {
1315 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1316 $m->numParams( count( self::$mRights ) )->parse()
1317 );
1318 }
1319 $help['permissions'] .= Html::openElement( 'dl' );
1320 foreach ( self::$mRights as $right => $rightMsg ) {
1321 $help['permissions'] .= Html::element( 'dt', null, $right );
1322
1323 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1324 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1325
1326 $groups = array_map( function ( $group ) {
1327 return $group == '*' ? 'all' : $group;
1328 }, User::getGroupsWithPermission( $right ) );
1329
1330 $help['permissions'] .= Html::rawElement( 'dd', null,
1331 $this->msg( 'api-help-permissions-granted-to' )
1332 ->numParams( count( $groups ) )
1333 ->params( $this->getLanguage()->commaList( $groups ) )
1334 ->parse()
1335 );
1336 }
1337 $help['permissions'] .= Html::closeElement( 'dl' );
1338 $help['permissions'] .= Html::closeElement( 'div' );
1339
1340 // Fill 'credits', if applicable
1341 if ( empty( $options['nolead'] ) ) {
1342 $help['credits'] .= Html::element( 'h' . min( 6, $options['headerlevel'] + 1 ),
1343 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1344 $this->msg( 'api-credits-header' )->parse()
1345 );
1346 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1347 }
1348 }
1349
1350 private $mCanApiHighLimits = null;
1351
1352 /**
1353 * Check whether the current user is allowed to use high limits
1354 * @return bool
1355 */
1356 public function canApiHighLimits() {
1357 if ( !isset( $this->mCanApiHighLimits ) ) {
1358 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1359 }
1360
1361 return $this->mCanApiHighLimits;
1362 }
1363
1364 /**
1365 * Overrides to return this instance's module manager.
1366 * @return ApiModuleManager
1367 */
1368 public function getModuleManager() {
1369 return $this->mModuleMgr;
1370 }
1371
1372 /**
1373 * Fetches the user agent used for this request
1374 *
1375 * The value will be the combination of the 'Api-User-Agent' header (if
1376 * any) and the standard User-Agent header (if any).
1377 *
1378 * @return string
1379 */
1380 public function getUserAgent() {
1381 return trim(
1382 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1383 $this->getRequest()->getHeader( 'User-agent' )
1384 );
1385 }
1386
1387 /************************************************************************//**
1388 * @name Deprecated
1389 * @{
1390 */
1391
1392 /**
1393 * Sets whether the pretty-printer should format *bold* and $italics$
1394 *
1395 * @deprecated since 1.25
1396 * @param bool $help
1397 */
1398 public function setHelp( $help = true ) {
1399 wfDeprecated( __METHOD__, '1.25' );
1400 $this->mPrinter->setHelp( $help );
1401 }
1402
1403 /**
1404 * Override the parent to generate help messages for all available modules.
1405 *
1406 * @deprecated since 1.25
1407 * @return string
1408 */
1409 public function makeHelpMsg() {
1410 wfDeprecated( __METHOD__, '1.25' );
1411 global $wgMemc;
1412 $this->setHelp();
1413 // Get help text from cache if present
1414 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1415 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1416
1417 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1418 if ( $cacheHelpTimeout > 0 ) {
1419 $cached = $wgMemc->get( $key );
1420 if ( $cached ) {
1421 return $cached;
1422 }
1423 }
1424 $retval = $this->reallyMakeHelpMsg();
1425 if ( $cacheHelpTimeout > 0 ) {
1426 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1427 }
1428
1429 return $retval;
1430 }
1431
1432 /**
1433 * @deprecated since 1.25
1434 * @return mixed|string
1435 */
1436 public function reallyMakeHelpMsg() {
1437 wfDeprecated( __METHOD__, '1.25' );
1438 $this->setHelp();
1439
1440 // Use parent to make default message for the main module
1441 $msg = parent::makeHelpMsg();
1442
1443 $astriks = str_repeat( '*** ', 14 );
1444 $msg .= "\n\n$astriks Modules $astriks\n\n";
1445
1446 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1447 $module = $this->mModuleMgr->getModule( $name );
1448 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1449
1450 $msg2 = $module->makeHelpMsg();
1451 if ( $msg2 !== false ) {
1452 $msg .= $msg2;
1453 }
1454 $msg .= "\n";
1455 }
1456
1457 $msg .= "\n$astriks Permissions $astriks\n\n";
1458 foreach ( self::$mRights as $right => $rightMsg ) {
1459 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1460 ->useDatabase( false )
1461 ->inLanguage( 'en' )
1462 ->text();
1463 $groups = User::getGroupsWithPermission( $right );
1464 $msg .= "* " . $right . " *\n $rightsMsg" .
1465 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1466 }
1467
1468 $msg .= "\n$astriks Formats $astriks\n\n";
1469 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1470 $module = $this->mModuleMgr->getModule( $name );
1471 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1472 $msg2 = $module->makeHelpMsg();
1473 if ( $msg2 !== false ) {
1474 $msg .= $msg2;
1475 }
1476 $msg .= "\n";
1477 }
1478
1479 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1480 $credits = str_replace( "\n", "\n ", $credits );
1481 $msg .= "\n*** Credits: ***\n $credits\n";
1482
1483 return $msg;
1484 }
1485
1486 /**
1487 * @deprecated since 1.25
1488 * @param ApiBase $module
1489 * @param string $paramName What type of request is this? e.g. action,
1490 * query, list, prop, meta, format
1491 * @return string
1492 */
1493 public static function makeHelpMsgHeader( $module, $paramName ) {
1494 wfDeprecated( __METHOD__, '1.25' );
1495 $modulePrefix = $module->getModulePrefix();
1496 if ( strval( $modulePrefix ) !== '' ) {
1497 $modulePrefix = "($modulePrefix) ";
1498 }
1499
1500 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1501 }
1502
1503 /**
1504 * Check whether the user wants us to show version information in the API help
1505 * @return bool
1506 * @deprecated since 1.21, always returns false
1507 */
1508 public function getShowVersions() {
1509 wfDeprecated( __METHOD__, '1.21' );
1510
1511 return false;
1512 }
1513
1514 /**
1515 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1516 * classes who wish to add their own modules to their lexicon or override the
1517 * behavior of inherent ones.
1518 *
1519 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1520 * @param string $name The identifier for this module.
1521 * @param ApiBase $class The class where this module is implemented.
1522 */
1523 protected function addModule( $name, $class ) {
1524 $this->getModuleManager()->addModule( $name, 'action', $class );
1525 }
1526
1527 /**
1528 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1529 * classes who wish to add to or modify current formatters.
1530 *
1531 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1532 * @param string $name The identifier for this format.
1533 * @param ApiFormatBase $class The class implementing this format.
1534 */
1535 protected function addFormat( $name, $class ) {
1536 $this->getModuleManager()->addModule( $name, 'format', $class );
1537 }
1538
1539 /**
1540 * Get the array mapping module names to class names
1541 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1542 * @return array
1543 */
1544 function getModules() {
1545 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1546 }
1547
1548 /**
1549 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1550 *
1551 * @since 1.18
1552 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1553 * @return array
1554 */
1555 public function getFormats() {
1556 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1557 }
1558
1559 /**@}*/
1560
1561 }
1562
1563 /**
1564 * This exception will be thrown when dieUsage is called to stop module execution.
1565 *
1566 * @ingroup API
1567 */
1568 class UsageException extends MWException {
1569
1570 private $mCodestr;
1571
1572 /**
1573 * @var null|array
1574 */
1575 private $mExtraData;
1576
1577 /**
1578 * @param string $message
1579 * @param string $codestr
1580 * @param int $code
1581 * @param array|null $extradata
1582 */
1583 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1584 parent::__construct( $message, $code );
1585 $this->mCodestr = $codestr;
1586 $this->mExtraData = $extradata;
1587 }
1588
1589 /**
1590 * @return string
1591 */
1592 public function getCodeString() {
1593 return $this->mCodestr;
1594 }
1595
1596 /**
1597 * @return array
1598 */
1599 public function getMessageArray() {
1600 $result = array(
1601 'code' => $this->mCodestr,
1602 'info' => $this->getMessage()
1603 );
1604 if ( is_array( $this->mExtraData ) ) {
1605 $result = array_merge( $result, $this->mExtraData );
1606 }
1607
1608 return $result;
1609 }
1610
1611 /**
1612 * @return string
1613 */
1614 public function __toString() {
1615 return "{$this->getCodeString()}: {$this->getMessage()}";
1616 }
1617 }
1618
1619 /**
1620 * For really cool vim folding this needs to be at the end:
1621 * vim: foldmarker=@{,@} foldmethod=marker
1622 */