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