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