Rewrote r69339 etc. to clean up API cache header handling.
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2
3 /**
4 * Created on Sep 4, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
31 /**
32 * @defgroup API API
33 */
34
35 /**
36 * This is the main API class, used for both external and internal processing.
37 * When executed, it will create the requested formatter object,
38 * instantiate and execute an object associated with the needed action,
39 * and use formatter to print results.
40 * In case of an exception, an error message will be printed using the same formatter.
41 *
42 * To use API from another application, run it using FauxRequest object, in which
43 * case any internal exceptions will not be handled but passed up to the caller.
44 * After successful execution, use getResult() for the resulting data.
45 *
46 * @ingroup API
47 */
48 class ApiMain extends ApiBase {
49
50 /**
51 * When no format parameter is given, this format will be used
52 */
53 const API_DEFAULT_FORMAT = 'xmlfm';
54
55 /**
56 * List of available modules: action name => module class
57 */
58 private static $Modules = array(
59 'login' => 'ApiLogin',
60 'logout' => 'ApiLogout',
61 'query' => 'ApiQuery',
62 'expandtemplates' => 'ApiExpandTemplates',
63 'parse' => 'ApiParse',
64 'opensearch' => 'ApiOpenSearch',
65 'feedwatchlist' => 'ApiFeedWatchlist',
66 'help' => 'ApiHelp',
67 'paraminfo' => 'ApiParamInfo',
68
69 // Write modules
70 'purge' => 'ApiPurge',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
77 'move' => 'ApiMove',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
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 );
107
108 /**
109 * List of user roles that are specifically relevant to the API.
110 * array( 'right' => array ( 'msg' => 'Some message with a $1',
111 * 'params' => array ( $someVarToSubst ) ),
112 * );
113 */
114 private static $mRights = array(
115 'writeapi' => array(
116 'msg' => 'Use of the write API',
117 'params' => array()
118 ),
119 'apihighlimits' => array(
120 '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.',
121 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
122 )
123 );
124
125 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
126 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest;
127 private $mInternalMode, $mSquidMaxage, $mModule, $mVaryCookie;
128
129 private $mCacheMode = 'private';
130 private $mCacheControl = array();
131
132 /**
133 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
134 *
135 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
136 * @param $enableWrite bool should be set to true if the api may modify data
137 */
138 public function __construct( $request, $enableWrite = false ) {
139 $this->mInternalMode = ( $request instanceof FauxRequest );
140
141 // Special handling for the main module: $parent === $this
142 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
143
144 if ( !$this->mInternalMode ) {
145 // Impose module restrictions.
146 // If the current user cannot read,
147 // Remove all modules other than login
148 global $wgUser;
149
150 if ( $request->getVal( 'callback' ) !== null ) {
151 // JSON callback allows cross-site reads.
152 // For safety, strip user credentials.
153 wfDebug( "API: stripping user credentials for JSON callback\n" );
154 $wgUser = new User();
155 }
156 }
157
158 global $wgAPIModules; // extension modules
159 $this->mModules = $wgAPIModules + self::$Modules;
160
161 $this->mModuleNames = array_keys( $this->mModules );
162 $this->mFormats = self::$Formats;
163 $this->mFormatNames = array_keys( $this->mFormats );
164
165 $this->mResult = new ApiResult( $this );
166 $this->mShowVersions = false;
167 $this->mEnableWrite = $enableWrite;
168
169 $this->mRequest = &$request;
170
171 $this->mSquidMaxage = - 1; // flag for executeActionWithErrorHandling()
172 $this->mCommit = false;
173 $this->mVaryCookie = false;
174 }
175
176 /**
177 * Return true if the API was started by other PHP code using FauxRequest
178 */
179 public function isInternalMode() {
180 return $this->mInternalMode;
181 }
182
183 /**
184 * Return the request object that contains client's request
185 */
186 public function getRequest() {
187 return $this->mRequest;
188 }
189
190 /**
191 * Get the ApiResult object associated with current request
192 */
193 public function getResult() {
194 return $this->mResult;
195 }
196
197 /**
198 * Get the API module object. Only works after executeAction()
199 */
200 public function getModule() {
201 return $this->mModule;
202 }
203
204 /**
205 * Get the result formatter object. Only works after setupExecuteAction()
206 */
207 public function getPrinter() {
208 return $this->mPrinter;
209 }
210
211 /**
212 * Set how long the response should be cached.
213 */
214 public function setCacheMaxAge( $maxage ) {
215 $this->setCacheControl( array(
216 'max-age' => $maxage,
217 's-maxage' => $maxage
218 ) );
219 }
220
221 /**
222 * Set the type of caching headers which will be sent.
223 *
224 * @param $mode One of:
225 * - 'public': Cache this object in public caches, if the maxage or smaxage
226 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
227 * not provided by any of these means, the object will be private.
228 * - 'private': Cache this object only in private client-side caches.
229 * - 'anon-public-user-private': Make this object cacheable for logged-out
230 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
231 * set consistently for a given URL, it cannot be set differently depending on
232 * things like the contents of the database, or whether the user is logged in.
233 *
234 * If the wiki does not allow anonymous users to read it, the mode set here
235 * will be ignored, and private caching headers will always be sent. In other words,
236 * the "public" mode is equivalent to saying that the data sent is as public as a page
237 * view.
238 *
239 * For user-dependent data, the private mode should generally be used. The
240 * anon-public-user-private mode should only be used where there is a particularly
241 * good performance reason for caching the anonymous response, but where the
242 * response to logged-in users may differ, or may contain private data.
243 *
244 * If this function is never called, then the default will be the private mode.
245 */
246 public function setCacheMode( $mode ) {
247 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
248 wfDebug( __METHOD__.": unrecognised cache mode \"$mode\"\n" );
249 // Ignore for forwards-compatibility
250 return;
251 }
252
253 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
254 // Private wiki, only private headers
255 if ( $mode !== 'private' ) {
256 wfDebug( __METHOD__.": ignoring request for $mode cache mode, private wiki\n" );
257 return;
258 }
259 }
260
261 wfDebug( __METHOD__.": setting cache mode $mode\n" );
262 $this->mCacheMode = $mode;
263 }
264
265 /**
266 * @deprecated Private caching is now the default, so there is usually no
267 * need to call this function. If there is a need, you can use
268 * $this->setCacheMode('private')
269 */
270 public function setCachePrivate() {
271 $this->setCacheMode( 'private' );
272 }
273
274 /**
275 * Set directives (key/value pairs) for the Cache-Control header.
276 * Boolean values will be formatted as such, by including or omitting
277 * without an equals sign.
278 *
279 * Cache control values set here will only be used if the cache mode is not
280 * private, see setCacheMode().
281 */
282 public function setCacheControl( $directives ) {
283 $this->mCacheControl = $directives + $this->mCacheControl;
284 }
285
286 /**
287 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
288 * may be cached for anons but may not be cached for logged-in users.
289 *
290 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
291 * given URL must either always or never call this function; if it sometimes does and
292 * sometimes doesn't, stuff will break.
293 *
294 * @deprecated Use setCacheMode( 'anon-public-user-private' )
295 */
296 public function setVaryCookie() {
297 $this->setCacheMode( 'anon-public-user-private' );
298 }
299
300 /**
301 * Create an instance of an output formatter by its name
302 */
303 public function createPrinterByName( $format ) {
304 if ( !isset( $this->mFormats[$format] ) ) {
305 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
306 }
307 return new $this->mFormats[$format] ( $this, $format );
308 }
309
310 /**
311 * Execute api request. Any errors will be handled if the API was called by the remote client.
312 */
313 public function execute() {
314 $this->profileIn();
315 if ( $this->mInternalMode ) {
316 $this->executeAction();
317 } else {
318 $this->executeActionWithErrorHandling();
319 }
320
321 $this->profileOut();
322 }
323
324 /**
325 * Execute an action, and in case of an error, erase whatever partial results
326 * have been accumulated, and replace it with an error message and a help screen.
327 */
328 protected function executeActionWithErrorHandling() {
329 // In case an error occurs during data output,
330 // clear the output buffer and print just the error information
331 ob_start();
332
333 try {
334 $this->executeAction();
335 } catch ( Exception $e ) {
336 // Log it
337 if ( $e instanceof MWException ) {
338 wfDebugLog( 'exception', $e->getLogMessage() );
339 }
340
341 //
342 // Handle any kind of exception by outputing properly formatted error message.
343 // If this fails, an unhandled exception should be thrown so that global error
344 // handler will process and log it.
345 //
346
347 $errCode = $this->substituteResultWithError( $e );
348
349 // Error results should not be cached
350 $this->setCacheMode( 'private' );
351
352 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
353 if ( $e->getCode() === 0 ) {
354 header( $headerStr );
355 } else {
356 header( $headerStr, true, $e->getCode() );
357 }
358
359 // Reset and print just the error message
360 ob_clean();
361
362 // If the error occured during printing, do a printer->profileOut()
363 $this->mPrinter->safeProfileOut();
364 $this->printResult( true );
365 }
366
367 // Send cache headers after any code which might generate an error, to
368 // avoid sending public cache headers for errors.
369 $this->sendCacheHeaders();
370
371 if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
372 echo wfReportTime();
373 }
374
375 ob_end_flush();
376 }
377
378 protected function sendCacheHeaders() {
379 if ( $this->mCacheMode == 'private' ) {
380 header( 'Cache-Control: private' );
381 return;
382 }
383
384 if ( $this->mCacheMode == 'anon-public-user-private' ) {
385 global $wgUseXVO, $wgOut;
386 header( 'Vary: Accept-Encoding, Cookie' );
387 if ( $wgUseXVO ) {
388 header( $wgOut->getXVO() );
389 if ( $wgOut->haveCacheVaryCookies() ) {
390 // Logged in, mark this request private
391 header( 'Cache-Control: private' );
392 return;
393 }
394 // Logged out, send normal public headers below
395 } elseif ( session_id() != '' ) {
396 // Logged in or otherwise has session (e.g. anonymous users who have edited)
397 // Mark request private
398 header( 'Cache-Control: private' );
399 return;
400 } // else no XVO and anonymous, send public headers below
401 } else /* if public */ {
402 // Give a debugging message if the user object is unstubbed on a public request
403 global $wgUser;
404 if ( !( $wgUser instanceof StubUser ) ) {
405 wfDebug( __METHOD__." \$wgUser is unstubbed on a public request!\n" );
406 }
407 }
408
409 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
410 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
411 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
412 }
413 if ( !isset( $this->mCacheControl['max-age'] ) ) {
414 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
415 }
416
417 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
418 // Public cache not requested
419 // Sending a Vary header in this case is harmless, and protects us
420 // against conditional calls of setCacheMaxAge().
421 header( 'Cache-Control: private' );
422 return;
423 }
424
425 $this->mCacheControl['public'] = true;
426
427 // Send an Expires header
428 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
429 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
430 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
431
432 // Construct the Cache-Control header
433 $ccHeader = '';
434 $separator = '';
435 foreach ( $this->mCacheControl as $name => $value ) {
436 if ( is_bool( $value ) ) {
437 if ( $value ) {
438 $ccHeader .= $separator . $name;
439 $separator = ', ';
440 }
441 } else {
442 $ccHeader .= $separator . "$name=$value";
443 $separator = ', ';
444 }
445 }
446
447 header( "Cache-Control: $ccHeader" );
448 }
449
450 /**
451 * Replace the result data with the information about an exception.
452 * Returns the error code
453 */
454 protected function substituteResultWithError( $e ) {
455 // Printer may not be initialized if the extractRequestParams() fails for the main module
456 if ( !isset ( $this->mPrinter ) ) {
457 // The printer has not been created yet. Try to manually get formatter value.
458 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
459 if ( !in_array( $value, $this->mFormatNames ) ) {
460 $value = self::API_DEFAULT_FORMAT;
461 }
462
463 $this->mPrinter = $this->createPrinterByName( $value );
464 if ( $this->mPrinter->getNeedsRawData() ) {
465 $this->getResult()->setRawMode();
466 }
467 }
468
469 if ( $e instanceof UsageException ) {
470 //
471 // User entered incorrect parameters - print usage screen
472 //
473 $errMessage = $e->getMessageArray();
474
475 // Only print the help message when this is for the developer, not runtime
476 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
477 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
478 }
479
480 } else {
481 global $wgShowSQLErrors, $wgShowExceptionDetails;
482 //
483 // Something is seriously wrong
484 //
485 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
486 $info = 'Database query error';
487 } else {
488 $info = "Exception Caught: {$e->getMessage()}";
489 }
490
491 $errMessage = array(
492 'code' => 'internal_api_error_' . get_class( $e ),
493 'info' => $info,
494 );
495 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
496 }
497
498 $this->getResult()->reset();
499 $this->getResult()->disableSizeCheck();
500 // Re-add the id
501 $requestid = $this->getParameter( 'requestid' );
502 if ( !is_null( $requestid ) ) {
503 $this->getResult()->addValue( null, 'requestid', $requestid );
504 }
505 // servedby is especially useful when debugging errors
506 $this->getResult()->addValue( null, 'servedby', wfHostName() );
507 $this->getResult()->addValue( null, 'error', $errMessage );
508
509 return $errMessage['code'];
510 }
511
512 /**
513 * Set up for the execution.
514 */
515 protected function setupExecuteAction() {
516 // First add the id to the top element
517 $requestid = $this->getParameter( 'requestid' );
518 if ( !is_null( $requestid ) ) {
519 $this->getResult()->addValue( null, 'requestid', $requestid );
520 }
521 $servedby = $this->getParameter( 'servedby' );
522 if( $servedby ) {
523 $this->getResult()->addValue( null, 'servedby', wfHostName() );
524 }
525
526 $params = $this->extractRequestParams();
527
528 $this->mShowVersions = $params['version'];
529 $this->mAction = $params['action'];
530
531 if ( !is_string( $this->mAction ) ) {
532 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
533 }
534
535 return $params;
536 }
537
538 /**
539 * Set up the module for response
540 * @return Object the module that will handle this action
541 */
542 protected function setupModule() {
543 // Instantiate the module requested by the user
544 $module = new $this->mModules[$this->mAction] ( $this, $this->mAction );
545 $this->mModule = $module;
546
547 $moduleParams = $module->extractRequestParams();
548
549 // Die if token required, but not provided (unless there is a gettoken parameter)
550 $salt = $module->getTokenSalt();
551 if ( $salt !== false && !isset( $moduleParams['gettoken'] ) ) {
552 if ( !isset( $moduleParams['token'] ) ) {
553 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
554 } else {
555 global $wgUser;
556 if ( !$wgUser->matchEditToken( $moduleParams['token'], $salt ) ) {
557 $this->dieUsageMsg( array( 'sessionfailure' ) );
558 }
559 }
560 }
561 return $module;
562 }
563
564 /**
565 * Check the max lag if necessary
566 * @param $module ApiBase object: Api module being used
567 * @param $params Array an array containing the request parameters.
568 * @return boolean True on success, false should exit immediately
569 */
570 protected function checkMaxLag( $module, $params ) {
571 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
572 // Check for maxlag
573 global $wgShowHostnames;
574 $maxLag = $params['maxlag'];
575 list( $host, $lag ) = wfGetLB()->getMaxLag();
576 if ( $lag > $maxLag ) {
577 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
578 header( 'X-Database-Lag: ' . intval( $lag ) );
579 if ( $wgShowHostnames ) {
580 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
581 } else {
582 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
583 }
584 return false;
585 }
586 }
587 return true;
588 }
589
590
591 /**
592 * Check for sufficient permissions to execute
593 * @param $module object An Api module
594 */
595 protected function checkExecutePermissions( $module ) {
596 global $wgUser;
597 if ( $module->isReadMode() && !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) &&
598 !$wgUser->isAllowed( 'read' ) )
599 {
600 $this->dieUsageMsg( array( 'readrequired' ) );
601 }
602 if ( $module->isWriteMode() ) {
603 if ( !$this->mEnableWrite ) {
604 $this->dieUsageMsg( array( 'writedisabled' ) );
605 }
606 if ( !$wgUser->isAllowed( 'writeapi' ) ) {
607 $this->dieUsageMsg( array( 'writerequired' ) );
608 }
609 if ( wfReadOnly() ) {
610 $this->dieReadOnly();
611 }
612 }
613 }
614
615 /**
616 * Check POST for external response and setup result printer
617 * @param $module object An Api module
618 * @param $params Array an array with the request parameters
619 */
620 protected function setupExternalResponse( $module, $params ) {
621 // Ignore mustBePosted() for internal calls
622 if ( $module->mustBePosted() && !$this->mRequest->wasPosted() ) {
623 $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
624 }
625
626 // See if custom printer is used
627 $this->mPrinter = $module->getCustomPrinter();
628 if ( is_null( $this->mPrinter ) ) {
629 // Create an appropriate printer
630 $this->mPrinter = $this->createPrinterByName( $params['format'] );
631 }
632
633 if ( $this->mPrinter->getNeedsRawData() ) {
634 $this->getResult()->setRawMode();
635 }
636 }
637
638 /**
639 * Execute the actual module, without any error handling
640 */
641 protected function executeAction() {
642 $params = $this->setupExecuteAction();
643 $module = $this->setupModule();
644
645 $this->checkExecutePermissions( $module );
646
647 if ( !$this->checkMaxLag( $module, $params ) ) return;
648
649 if ( !$this->mInternalMode ) {
650 $this->setupExternalResponse( $module, $params );
651 }
652
653 // Execute
654 $module->profileIn();
655 $module->execute();
656 wfRunHooks( 'APIAfterExecute', array( &$module ) );
657 $module->profileOut();
658
659 if ( !$this->mInternalMode ) {
660 // Print result data
661 $this->printResult( false );
662 }
663 }
664
665 /**
666 * Print results using the current printer
667 */
668 protected function printResult( $isError ) {
669 $this->getResult()->cleanUpUTF8();
670 $printer = $this->mPrinter;
671 $printer->profileIn();
672
673 /**
674 * If the help message is requested in the default (xmlfm) format,
675 * tell the printer not to escape ampersands so that our links do
676 * not break.
677 */
678 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
679 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
680
681 $printer->initPrinter( $isError );
682
683 $printer->execute();
684 $printer->closePrinter();
685 $printer->profileOut();
686 }
687
688 public function isReadMode() {
689 return false;
690 }
691
692 /**
693 * See ApiBase for description.
694 */
695 public function getAllowedParams() {
696 return array(
697 'format' => array(
698 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
699 ApiBase::PARAM_TYPE => $this->mFormatNames
700 ),
701 'action' => array(
702 ApiBase::PARAM_DFLT => 'help',
703 ApiBase::PARAM_TYPE => $this->mModuleNames
704 ),
705 'version' => false,
706 'maxlag' => array(
707 ApiBase::PARAM_TYPE => 'integer'
708 ),
709 'smaxage' => array(
710 ApiBase::PARAM_TYPE => 'integer',
711 ApiBase::PARAM_DFLT => 0
712 ),
713 'maxage' => array(
714 ApiBase::PARAM_TYPE => 'integer',
715 ApiBase::PARAM_DFLT => 0
716 ),
717 'requestid' => null,
718 'servedby' => false,
719 );
720 }
721
722 /**
723 * See ApiBase for description.
724 */
725 public function getParamDescription() {
726 return array(
727 'format' => 'The format of the output',
728 'action' => 'What action you would like to perform. See below for module help',
729 'version' => 'When showing help, include version for each module',
730 'maxlag' => 'Maximum lag',
731 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
732 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
733 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
734 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
735 );
736 }
737
738 /**
739 * See ApiBase for description.
740 */
741 public function getDescription() {
742 return array(
743 '',
744 '',
745 '******************************************************************',
746 '** **',
747 '** This is an auto-generated MediaWiki API documentation page **',
748 '** **',
749 '** Documentation and Examples: **',
750 '** http://www.mediawiki.org/wiki/API **',
751 '** **',
752 '******************************************************************',
753 '',
754 'Status: All features shown on this page should be working, but the API',
755 ' is still in active development, and may change at any time.',
756 ' Make sure to monitor our mailing list for any updates',
757 '',
758 'Documentation: http://www.mediawiki.org/wiki/API',
759 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
760 'Api Announcements: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
761 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
762 '',
763 '',
764 '',
765 '',
766 '',
767 );
768 }
769
770 public function getPossibleErrors() {
771 return array_merge( parent::getPossibleErrors(), array(
772 array( 'readonlytext' ),
773 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
774 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
775 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
776 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
777 ) );
778 }
779
780 /**
781 * Returns an array of strings with credits for the API
782 */
783 protected function getCredits() {
784 return array(
785 'API developers:',
786 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
787 ' Victor Vasiliev - vasilvv at gee mail dot com',
788 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
789 ' Sam Reed - sam @ reedyboy . net',
790 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
791 '',
792 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
793 'or file a bug report at http://bugzilla.wikimedia.org/'
794 );
795 }
796 /**
797 * Sets whether the pretty-printer should format *bold* and $italics$
798 */
799 public function setHelp( $help = true ) {
800 $this->mPrinter->setHelp( $help );
801 }
802
803 /**
804 * Override the parent to generate help messages for all available modules.
805 */
806 public function makeHelpMsg() {
807 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
808 $this->setHelp();
809 // Get help text from cache if present
810 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
811 SpecialVersion::getVersion( 'nodb' ) .
812 $this->getMain()->getShowVersions() );
813 if ( $wgAPICacheHelp ) {
814 $cached = $wgMemc->get( $key );
815 if ( $cached ) {
816 return $cached;
817 }
818 }
819 $retval = $this->reallyMakeHelpMsg();
820 if ( $wgAPICacheHelp ) {
821 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
822 }
823 return $retval;
824 }
825
826 public function reallyMakeHelpMsg() {
827 $this->setHelp();
828
829 // Use parent to make default message for the main module
830 $msg = parent::makeHelpMsg();
831
832 $astriks = str_repeat( '*** ', 10 );
833 $msg .= "\n\n$astriks Modules $astriks\n\n";
834 foreach ( $this->mModules as $moduleName => $unused ) {
835 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
836 $msg .= self::makeHelpMsgHeader( $module, 'action' );
837 $msg2 = $module->makeHelpMsg();
838 if ( $msg2 !== false ) {
839 $msg .= $msg2;
840 }
841 $msg .= "\n";
842 }
843
844 $msg .= "\n$astriks Permissions $astriks\n\n";
845 foreach ( self::$mRights as $right => $rightMsg ) {
846 $groups = User::getGroupsWithPermission( $right );
847 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
848 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
849
850 }
851
852 $msg .= "\n$astriks Formats $astriks\n\n";
853 foreach ( $this->mFormats as $formatName => $unused ) {
854 $module = $this->createPrinterByName( $formatName );
855 $msg .= self::makeHelpMsgHeader( $module, 'format' );
856 $msg2 = $module->makeHelpMsg();
857 if ( $msg2 !== false ) {
858 $msg .= $msg2;
859 }
860 $msg .= "\n";
861 }
862
863 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
864
865 return $msg;
866 }
867
868 public static function makeHelpMsgHeader( $module, $paramName ) {
869 $modulePrefix = $module->getModulePrefix();
870 if ( strval( $modulePrefix ) !== '' ) {
871 $modulePrefix = "($modulePrefix) ";
872 }
873
874 return "* $paramName={$module->getModuleName()} $modulePrefix*";
875 }
876
877 private $mIsBot = null;
878 private $mIsSysop = null;
879 private $mCanApiHighLimits = null;
880
881 /**
882 * Returns true if the currently logged in user is a bot, false otherwise
883 * OBSOLETE, use canApiHighLimits() instead
884 */
885 public function isBot() {
886 if ( !isset( $this->mIsBot ) ) {
887 global $wgUser;
888 $this->mIsBot = $wgUser->isAllowed( 'bot' );
889 }
890 return $this->mIsBot;
891 }
892
893 /**
894 * Similar to isBot(), this method returns true if the logged in user is
895 * a sysop, and false if not.
896 * OBSOLETE, use canApiHighLimits() instead
897 */
898 public function isSysop() {
899 if ( !isset( $this->mIsSysop ) ) {
900 global $wgUser;
901 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups() );
902 }
903
904 return $this->mIsSysop;
905 }
906
907 /**
908 * Check whether the current user is allowed to use high limits
909 * @return bool
910 */
911 public function canApiHighLimits() {
912 if ( !isset( $this->mCanApiHighLimits ) ) {
913 global $wgUser;
914 $this->mCanApiHighLimits = $wgUser->isAllowed( 'apihighlimits' );
915 }
916
917 return $this->mCanApiHighLimits;
918 }
919
920 /**
921 * Check whether the user wants us to show version information in the API help
922 * @return bool
923 */
924 public function getShowVersions() {
925 return $this->mShowVersions;
926 }
927
928 /**
929 * Returns the version information of this file, plus it includes
930 * the versions for all files that are not callable proper API modules
931 */
932 public function getVersion() {
933 $vers = array ();
934 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
935 $vers[] = __CLASS__ . ': $Id$';
936 $vers[] = ApiBase::getBaseVersion();
937 $vers[] = ApiFormatBase::getBaseVersion();
938 $vers[] = ApiQueryBase::getBaseVersion();
939 return $vers;
940 }
941
942 /**
943 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
944 * classes who wish to add their own modules to their lexicon or override the
945 * behavior of inherent ones.
946 *
947 * @param $mdlName String The identifier for this module.
948 * @param $mdlClass String The class where this module is implemented.
949 */
950 protected function addModule( $mdlName, $mdlClass ) {
951 $this->mModules[$mdlName] = $mdlClass;
952 }
953
954 /**
955 * Add or overwrite an output format for this ApiMain. Intended for use by extending
956 * classes who wish to add to or modify current formatters.
957 *
958 * @param $fmtName The identifier for this format.
959 * @param $fmtClass The class implementing this format.
960 */
961 protected function addFormat( $fmtName, $fmtClass ) {
962 $this->mFormats[$fmtName] = $fmtClass;
963 }
964
965 /**
966 * Get the array mapping module names to class names
967 */
968 function getModules() {
969 return $this->mModules;
970 }
971 }
972
973 /**
974 * This exception will be thrown when dieUsage is called to stop module execution.
975 * The exception handling code will print a help screen explaining how this API may be used.
976 *
977 * @ingroup API
978 */
979 class UsageException extends Exception {
980
981 private $mCodestr;
982 private $mExtraData;
983
984 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
985 parent::__construct( $message, $code );
986 $this->mCodestr = $codestr;
987 $this->mExtraData = $extradata;
988 }
989
990 public function getCodeString() {
991 return $this->mCodestr;
992 }
993
994 public function getMessageArray() {
995 $result = array(
996 'code' => $this->mCodestr,
997 'info' => $this->getMessage()
998 );
999 if ( is_array( $this->mExtraData ) ) {
1000 $result = array_merge( $result, $this->mExtraData );
1001 }
1002 return $result;
1003 }
1004
1005 public function __toString() {
1006 return "{$this->getCodeString()}: {$this->getMessage()}";
1007 }
1008 }