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