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