Adding apihighlimits permission. Users with this permission can request 10 times...
[lhc/web/wiklou.git] / includes / api / ApiMain.php
index a03b503..acf3e50 100644 (file)
@@ -54,6 +54,8 @@ class ApiMain extends ApiBase {
        private static $Modules = array (
                'login' => 'ApiLogin',
                'query' => 'ApiQuery',
+               'expandtemplates' => 'ApiExpandTemplates',
+               'render' => 'ApiRender',
                'opensearch' => 'ApiOpenSearch',
                'feedwatchlist' => 'ApiFeedWatchlist',
                'help' => 'ApiHelp',
@@ -96,8 +98,8 @@ class ApiMain extends ApiBase {
                        
                        // Impose module restrictions.
                        // If the current user cannot read, 
-                       // Remove all modules other than login & help
-                       global $wgUser, $wgWhitelistRead;
+                       // Remove all modules other than login
+                       global $wgUser;
                        if (!$wgUser->isAllowed('read')) {
                                self::$Modules = array(
                                        'login' => self::$Modules['login'],
@@ -106,7 +108,9 @@ class ApiMain extends ApiBase {
                        }
                }
 
-               $this->mModules = self :: $Modules;
+               global $wgAPIModules; // extension modules
+               $this->mModules = $wgAPIModules + self :: $Modules;
+
                $this->mModuleNames = array_keys($this->mModules); // todo: optimize
                $this->mFormats = self :: $Formats;
                $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
@@ -120,6 +124,13 @@ class ApiMain extends ApiBase {
                $this->mSquidMaxage = 0;
        }
 
+       /**
+        * Return true if the API was started by other PHP code using FauxRequest
+        */
+       public function isInternalMode() {
+               return $this->mInternalMode;
+       }
+
        /**
         * Return the request object that contains client's request
         */
@@ -188,9 +199,43 @@ class ApiMain extends ApiBase {
                        // handler will process and log it.
                        //
 
+                       $errCode = $this->substituteResultWithError($e);
+
                        // Error results should not be cached
                        $this->setCacheMaxAge(0);
 
+                       $headerStr = 'MediaWiki-API-Error: ' . $errCode;
+                       if ($e->getCode() === 0)
+                               header($headerStr, true);
+                       else
+                               header($headerStr, true, $e->getCode());
+
+                       // Reset and print just the error message
+                       ob_clean();
+
+                       // If the error occured during printing, do a printer->profileOut()
+                       $this->mPrinter->safeProfileOut();
+                       $this->printResult(true);
+               }
+
+               // Set the cache expiration at the last moment, as any errors may change the expiration.
+               // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
+               $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
+               header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
+               header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
+
+               if($this->mPrinter->getIsHtml())
+                       echo wfReportTime();
+
+               ob_end_flush();
+       }
+
+       /**
+        * Replace the result data with the information about an exception.
+        * Returns the error code 
+        */
+       protected function substituteResultWithError($e) {
+       
                        // Printer may not be initialized if the extractRequestParams() fails for the main module
                        if (!isset ($this->mPrinter)) {
                                // The printer has not been created yet. Try to manually get formatter value.
@@ -208,7 +253,8 @@ class ApiMain extends ApiBase {
                                // User entered incorrect parameters - print usage screen
                                //
                                $errMessage = array (
-                               'code' => $e->getCodeString(), 'info' => $e->getMessage());
+                               'code' => $e->getCodeString(),
+                               'info' => $e->getMessage());
                                
                                // Only print the help message when this is for the developer, not runtime
                                if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
@@ -219,38 +265,16 @@ class ApiMain extends ApiBase {
                                // Something is seriously wrong
                                //
                                $errMessage = array (
-                                       'code' => 'internal_api_error',
+                                       'code' => 'internal_api_error_'. get_class($e),
                                        'info' => "Exception Caught: {$e->getMessage()}"
                                );
                                ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
                        }
 
-                       $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
-                       if ($e->getCode() === 0)
-                               header($headerStr, true);
-                       else
-                               header($headerStr, true, $e->getCode());
-
-                       // Reset and print just the error message
-                       ob_clean();
                        $this->getResult()->reset();
                        $this->getResult()->addValue(null, 'error', $errMessage);
 
-                       // If the error occured during printing, do a printer->profileOut()
-                       $this->mPrinter->safeProfileOut();
-                       $this->printResult(true);
-               }
-
-               // Set the cache expiration at the last moment, as any errors may change the expiration.
-               // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
-               $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
-               header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
-               header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
-
-               if($this->mPrinter->getIsHtml())
-                       echo wfReportTime();
-
-               ob_end_flush();
+               return $errMessage['code'];
        }
 
        /**
@@ -265,6 +289,21 @@ class ApiMain extends ApiBase {
 
                // Instantiate the module requested by the user
                $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
+               
+               if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
+                       // Check for maxlag
+                       global $wgLoadBalancer, $wgShowHostnames;
+                       $maxLag = $params['maxlag'];
+                       list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
+                       if ( $lag > $maxLag ) {
+                               if( $wgShowHostnames ) {
+                                       ApiBase :: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
+                               } else {
+                                       ApiBase :: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
+                               }
+                               return;
+                       }
+               }
 
                if (!$this->mInternalMode) {
 
@@ -296,7 +335,16 @@ class ApiMain extends ApiBase {
        protected function printResult($isError) {
                $printer = $this->mPrinter;
                $printer->profileIn();
+       
+               /* If the help message is requested in the default (xmlfm) format,
+                * tell the printer not to escape ampersands so that our links do
+                * not break. */
+               $params = $this->extractRequestParams();
+               $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError ) 
+                               && $params['format'] == ApiMain::API_DEFAULT_FORMAT );
+
                $printer->initPrinter($isError);
+
                $printer->execute();
                $printer->closePrinter();
                $printer->profileOut();
@@ -315,7 +363,10 @@ class ApiMain extends ApiBase {
                                ApiBase :: PARAM_DFLT => 'help',
                                ApiBase :: PARAM_TYPE => $this->mModuleNames
                        ),
-                       'version' => false
+                       'version' => false,
+                       'maxlag'  => array (
+                               ApiBase :: PARAM_TYPE => 'integer'
+                       ),
                );
        }
 
@@ -326,7 +377,8 @@ class ApiMain extends ApiBase {
                return array (
                        'format' => 'The format of the output',
                        'action' => 'What action you would like to perform',
-                       'version' => 'When showing help, include version for each module'
+                       'version' => 'When showing help, include version for each module',
+                       'maxlag' => 'Maximum lag'
                );
        }
 
@@ -415,11 +467,12 @@ class ApiMain extends ApiBase {
        } 
 
        private $mIsBot = null;
-       
        private $mIsSysop = null;
+       private $mCanApiHighLimits = null;
        
        /**
         * Returns true if the currently logged in user is a bot, false otherwise
+        * OBSOLETE, use canApiHighLimits() instead
         */
        public function isBot() {
                if (!isset ($this->mIsBot)) {
@@ -432,16 +485,25 @@ class ApiMain extends ApiBase {
        /**
         * Similar to isBot(), this method returns true if the logged in user is
         * a sysop, and false if not.
+        * OBSOLETE, use canApiHighLimits() instead
         */
        public function isSysop() {
                if (!isset ($this->mIsSysop)) {
                        global $wgUser;
-                       $this->mIsSysop = in_array( 'sysop',
-                               $wgUser->getGroups());
+                       $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
                }
 
                return $this->mIsSysop;
        }
+       
+       public function canApiHighLimits() {
+               if (!is_null ($this->mCanApiHighLimits)) {
+                       global $wgUser;
+                       $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
+               }
+
+               return $this->mCanApiHighLimits;
+       }
 
        public function getShowVersions() {
                return $this->mShowVersions;
@@ -461,6 +523,31 @@ class ApiMain extends ApiBase {
                $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
                return $vers;
        }
+
+       /**
+        * Add or overwrite a module in this ApiMain instance. Intended for use by extending
+        * classes who wish to add their own modules to their lexicon or override the 
+        * behavior of inherent ones.
+        *
+        * @access protected
+        * @param $mdlName String The identifier for this module.
+        * @param $mdlClass String The class where this module is implemented.
+        */
+       protected function addModule( $mdlName, $mdlClass ) {
+               $this->mModules[$mdlName] = $mdlClass;
+       }
+
+       /**
+        * Add or overwrite an output format for this ApiMain. Intended for use by extending
+        * classes who wish to add to or modify current formatters.
+        *
+        * @access protected
+        * @param $fmtName The identifier for this format.
+        * @param $fmtClass The class implementing this format.
+        */
+       protected function addFormat( $fmtName, $fmtClass ) {
+               $this->mFormats[$fmtName] = $fmtClass;
+       }
 }
 
 /**
@@ -485,3 +572,4 @@ class UsageException extends Exception {
        }
 }
 
+