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