]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiMain.php
MediaWiki 1.17.4
[autoinstalls/mediawiki.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                 '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                 if ( isset( $moduleParams['gettoken'] ) ) {
551                         $gettoken = $moduleParams['gettoken'];
552                 } else {
553                         $gettoken = false;
554                 }
555
556                 $salt = $module->getTokenSalt();
557                 if ( $salt !== false && !$gettoken ) {
558                         if ( !isset( $moduleParams['token'] ) ) {
559                                 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
560                         } else {
561                                 global $wgUser;
562                                 if ( !$wgUser->matchEditToken( $moduleParams['token'], $salt ) ) {
563                                         $this->dieUsageMsg( array( 'sessionfailure' ) );
564                                 }
565                         }
566                 }
567                 return $module;
568         }
569
570         /**
571          * Check the max lag if necessary
572          * @param $module ApiBase object: Api module being used
573          * @param $params Array an array containing the request parameters.
574          * @return boolean True on success, false should exit immediately
575          */
576         protected function checkMaxLag( $module, $params ) {
577                 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
578                         // Check for maxlag
579                         global $wgShowHostnames;
580                         $maxLag = $params['maxlag'];
581                         list( $host, $lag ) = wfGetLB()->getMaxLag();
582                         if ( $lag > $maxLag ) {
583                                 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
584                                 header( 'X-Database-Lag: ' . intval( $lag ) );
585                                 if ( $wgShowHostnames ) {
586                                         $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
587                                 } else {
588                                         $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
589                                 }
590                                 return false;
591                         }
592                 }
593                 return true;
594         }
595
596
597         /**
598          * Check for sufficient permissions to execute
599          * @param $module ApiBase An Api module
600          */
601         protected function checkExecutePermissions( $module ) {
602                 global $wgUser;
603                 if ( $module->isReadMode() && !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) &&
604                         !$wgUser->isAllowed( 'read' ) )
605                 {
606                         $this->dieUsageMsg( array( 'readrequired' ) );
607                 }
608                 if ( $module->isWriteMode() ) {
609                         if ( !$this->mEnableWrite ) {
610                                 $this->dieUsageMsg( array( 'writedisabled' ) );
611                         }
612                         if ( !$wgUser->isAllowed( 'writeapi' ) ) {
613                                 $this->dieUsageMsg( array( 'writerequired' ) );
614                         }
615                         if ( wfReadOnly() ) {
616                                 $this->dieReadOnly();
617                         }
618                 }
619         }
620
621         /**
622          * Check POST for external response and setup result printer
623          * @param $module ApiBase An Api module
624          * @param $params Array an array with the request parameters
625          */
626         protected function setupExternalResponse( $module, $params ) {
627                 // Ignore mustBePosted() for internal calls
628                 if ( $module->mustBePosted() && !$this->mRequest->wasPosted() ) {
629                         $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
630                 }
631
632                 // See if custom printer is used
633                 $this->mPrinter = $module->getCustomPrinter();
634                 if ( is_null( $this->mPrinter ) ) {
635                         // Create an appropriate printer
636                         $this->mPrinter = $this->createPrinterByName( $params['format'] );
637                 }
638
639                 if ( $this->mPrinter->getNeedsRawData() ) {
640                         $this->getResult()->setRawMode();
641                 }
642         }
643
644         /**
645          * Execute the actual module, without any error handling
646          */
647         protected function executeAction() {
648                 $params = $this->setupExecuteAction();
649                 $module = $this->setupModule();
650
651                 $this->checkExecutePermissions( $module );
652
653                 if ( !$this->checkMaxLag( $module, $params ) ) {
654                         return;
655                 }
656
657                 if ( !$this->mInternalMode ) {
658                         $this->setupExternalResponse( $module, $params );
659                 }
660
661                 // Execute
662                 $module->profileIn();
663                 $module->execute();
664                 wfRunHooks( 'APIAfterExecute', array( &$module ) );
665                 $module->profileOut();
666
667                 if ( !$this->mInternalMode ) {
668                         // Print result data
669                         $this->printResult( false );
670                 }
671         }
672
673         /**
674          * Print results using the current printer
675          */
676         protected function printResult( $isError ) {
677                 $this->getResult()->cleanUpUTF8();
678                 $printer = $this->mPrinter;
679                 $printer->profileIn();
680
681                 /**
682                  * If the help message is requested in the default (xmlfm) format,
683                  * tell the printer not to escape ampersands so that our links do
684                  * not break.
685                  */
686                 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
687                                 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
688
689                 $printer->initPrinter( $isError );
690
691                 $printer->execute();
692                 $printer->closePrinter();
693                 $printer->profileOut();
694         }
695
696         public function isReadMode() {
697                 return false;
698         }
699
700         /**
701          * See ApiBase for description.
702          */
703         public function getAllowedParams() {
704                 return array(
705                         'format' => array(
706                                 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
707                                 ApiBase::PARAM_TYPE => $this->mFormatNames
708                         ),
709                         'action' => array(
710                                 ApiBase::PARAM_DFLT => 'help',
711                                 ApiBase::PARAM_TYPE => $this->mModuleNames
712                         ),
713                         'version' => false,
714                         'maxlag'  => array(
715                                 ApiBase::PARAM_TYPE => 'integer'
716                         ),
717                         'smaxage' => array(
718                                 ApiBase::PARAM_TYPE => 'integer',
719                                 ApiBase::PARAM_DFLT => 0
720                         ),
721                         'maxage' => array(
722                                 ApiBase::PARAM_TYPE => 'integer',
723                                 ApiBase::PARAM_DFLT => 0
724                         ),
725                         'requestid' => null,
726                         'servedby'  => false,
727                 );
728         }
729
730         /**
731          * See ApiBase for description.
732          */
733         public function getParamDescription() {
734                 return array(
735                         'format' => 'The format of the output',
736                         'action' => 'What action you would like to perform. See below for module help',
737                         'version' => 'When showing help, include version for each module',
738                         'maxlag' => 'Maximum lag',
739                         'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
740                         'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
741                         'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
742                         'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
743                 );
744         }
745
746         /**
747          * See ApiBase for description.
748          */
749         public function getDescription() {
750                 return array(
751                         '',
752                         '',
753                         '******************************************************************************************',
754                         '**                                                                                      **',
755                         '**              This is an auto-generated MediaWiki API documentation page              **',
756                         '**                                                                                      **',
757                         '**                            Documentation and Examples:                               **',
758                         '**                         http://www.mediawiki.org/wiki/API                            **',
759                         '**                                                                                      **',
760                         '******************************************************************************************',
761                         '',
762                         'Status:                All features shown on this page should be working, but the API',
763                         '                       is still in active development, and  may change at any time.',
764                         '                       Make sure to monitor our mailing list for any updates',
765                         '',
766                         'Documentation:         http://www.mediawiki.org/wiki/API',
767                         'Mailing list:          http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
768                         'Api Announcements:     http://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
769                         'Bugs & Requests:       http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
770                         '',
771                         '',
772                         '',
773                         '',
774                         '',
775                 );
776         }
777
778         public function getPossibleErrors() {
779                 return array_merge( parent::getPossibleErrors(), array(
780                         array( 'readonlytext' ),
781                         array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
782                         array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
783                         array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
784                         array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
785                 ) );
786         }
787
788         /**
789          * Returns an array of strings with credits for the API
790          */
791         protected function getCredits() {
792                 return array(
793                         'API developers:',
794                         '    Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
795                         '    Victor Vasiliev - vasilvv at gee mail dot com',
796                         '    Bryan Tong Minh - bryan . tongminh @ gmail . com',
797                         '    Sam Reed - sam @ reedyboy . net',
798                         '    Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
799                         '',
800                         'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
801                         'or file a bug report at http://bugzilla.wikimedia.org/'
802                 );
803         }
804         /**
805          * Sets whether the pretty-printer should format *bold* and $italics$
806          */
807         public function setHelp( $help = true ) {
808                 $this->mPrinter->setHelp( $help );
809         }
810
811         /**
812          * Override the parent to generate help messages for all available modules.
813          */
814         public function makeHelpMsg() {
815                 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
816                 $this->setHelp();
817                 // Get help text from cache if present
818                 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
819                         SpecialVersion::getVersion( 'nodb' ) .
820                         $this->getMain()->getShowVersions() );
821                 if ( $wgAPICacheHelp ) {
822                         $cached = $wgMemc->get( $key );
823                         if ( $cached ) {
824                                 return $cached;
825                         }
826                 }
827                 $retval = $this->reallyMakeHelpMsg();
828                 if ( $wgAPICacheHelp ) {
829                         $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
830                 }
831                 return $retval;
832         }
833
834         public function reallyMakeHelpMsg() {
835                 $this->setHelp();
836
837                 // Use parent to make default message for the main module
838                 $msg = parent::makeHelpMsg();
839
840                 $astriks = str_repeat( '*** ', 10 );
841                 $msg .= "\n\n$astriks Modules  $astriks\n\n";
842                 foreach ( array_keys( $this->mModules ) as $moduleName ) {
843                         $module = new $this->mModules[$moduleName] ( $this, $moduleName );
844                         $msg .= self::makeHelpMsgHeader( $module, 'action' );
845                         $msg2 = $module->makeHelpMsg();
846                         if ( $msg2 !== false ) {
847                                 $msg .= $msg2;
848                         }
849                         $msg .= "\n";
850                 }
851
852                 $msg .= "\n$astriks Permissions $astriks\n\n";
853                 foreach ( self::$mRights as $right => $rightMsg ) {
854                         $groups = User::getGroupsWithPermission( $right );
855                         $msg .= "* " . $right . " *\n  " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
856                                                 "\nGranted to:\n  " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
857
858                 }
859
860                 $msg .= "\n$astriks Formats  $astriks\n\n";
861                 foreach ( array_keys( $this->mFormats ) as $formatName ) {
862                         $module = $this->createPrinterByName( $formatName );
863                         $msg .= self::makeHelpMsgHeader( $module, 'format' );
864                         $msg2 = $module->makeHelpMsg();
865                         if ( $msg2 !== false ) {
866                                 $msg .= $msg2;
867                         }
868                         $msg .= "\n";
869                 }
870
871                 $msg .= "\n*** Credits: ***\n   " . implode( "\n   ", $this->getCredits() ) . "\n";
872
873                 return $msg;
874         }
875
876         public static function makeHelpMsgHeader( $module, $paramName ) {
877                 $modulePrefix = $module->getModulePrefix();
878                 if ( strval( $modulePrefix ) !== '' ) {
879                         $modulePrefix = "($modulePrefix) ";
880                 }
881
882                 return "* $paramName={$module->getModuleName()} $modulePrefix*";
883         }
884
885         private $mIsBot = null;
886         private $mIsSysop = null;
887         private $mCanApiHighLimits = null;
888
889         /**
890          * Returns true if the currently logged in user is a bot, false otherwise
891          * OBSOLETE, use canApiHighLimits() instead
892          */
893         public function isBot() {
894                 if ( !isset( $this->mIsBot ) ) {
895                         global $wgUser;
896                         $this->mIsBot = $wgUser->isAllowed( 'bot' );
897                 }
898                 return $this->mIsBot;
899         }
900
901         /**
902          * Similar to isBot(), this method returns true if the logged in user is
903          * a sysop, and false if not.
904          * OBSOLETE, use canApiHighLimits() instead
905          */
906         public function isSysop() {
907                 if ( !isset( $this->mIsSysop ) ) {
908                         global $wgUser;
909                         $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups() );
910                 }
911
912                 return $this->mIsSysop;
913         }
914
915         /**
916          * Check whether the current user is allowed to use high limits
917          * @return bool
918          */
919         public function canApiHighLimits() {
920                 if ( !isset( $this->mCanApiHighLimits ) ) {
921                         global $wgUser;
922                         $this->mCanApiHighLimits = $wgUser->isAllowed( 'apihighlimits' );
923                 }
924
925                 return $this->mCanApiHighLimits;
926         }
927
928         /**
929          * Check whether the user wants us to show version information in the API help
930          * @return bool
931          */
932         public function getShowVersions() {
933                 return $this->mShowVersions;
934         }
935
936         /**
937          * Returns the version information of this file, plus it includes
938          * the versions for all files that are not callable proper API modules
939          */
940         public function getVersion() {
941                 $vers = array ();
942                 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n    http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
943                 $vers[] = __CLASS__ . ': $Id$';
944                 $vers[] = ApiBase::getBaseVersion();
945                 $vers[] = ApiFormatBase::getBaseVersion();
946                 $vers[] = ApiQueryBase::getBaseVersion();
947                 return $vers;
948         }
949
950         /**
951          * Add or overwrite a module in this ApiMain instance. Intended for use by extending
952          * classes who wish to add their own modules to their lexicon or override the
953          * behavior of inherent ones.
954          *
955          * @param $mdlName String The identifier for this module.
956          * @param $mdlClass String The class where this module is implemented.
957          */
958         protected function addModule( $mdlName, $mdlClass ) {
959                 $this->mModules[$mdlName] = $mdlClass;
960         }
961
962         /**
963          * Add or overwrite an output format for this ApiMain. Intended for use by extending
964          * classes who wish to add to or modify current formatters.
965          *
966          * @param $fmtName The identifier for this format.
967          * @param $fmtClass The class implementing this format.
968          */
969         protected function addFormat( $fmtName, $fmtClass ) {
970                 $this->mFormats[$fmtName] = $fmtClass;
971         }
972
973         /**
974          * Get the array mapping module names to class names
975          */
976         function getModules() {
977                 return $this->mModules;
978         }
979 }
980
981 /**
982  * This exception will be thrown when dieUsage is called to stop module execution.
983  * The exception handling code will print a help screen explaining how this API may be used.
984  *
985  * @ingroup API
986  */
987 class UsageException extends Exception {
988
989         private $mCodestr;
990         private $mExtraData;
991
992         public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
993                 parent::__construct( $message, $code );
994                 $this->mCodestr = $codestr;
995                 $this->mExtraData = $extradata;
996         }
997
998         public function getCodeString() {
999                 return $this->mCodestr;
1000         }
1001
1002         public function getMessageArray() {
1003                 $result = array(
1004                         'code' => $this->mCodestr,
1005                         'info' => $this->getMessage()
1006                 );
1007                 if ( is_array( $this->mExtraData ) ) {
1008                         $result = array_merge( $result, $this->mExtraData );
1009                 }
1010                 return $result;
1011         }
1012
1013         public function __toString() {
1014                 return "{$this->getCodeString()}: {$this->getMessage()}";
1015         }
1016 }