Move remaining LoadBalancer classes to Rdbms
[mediawiki.git] / includes / cache / HTMLFileCache.php
blobb0a3a1c262d1ecafc05115520d5950d4ceb2d49a
1 <?php
2 /**
3 * Page view caching in the file system.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Cache
24 use MediaWiki\MediaWikiServices;
26 /**
27 * Page view caching in the file system.
28 * The only cacheable actions are "view" and "history". Also special pages
29 * will not be cached.
31 * @ingroup Cache
33 class HTMLFileCache extends FileCacheBase {
34 const MODE_NORMAL = 0; // normal cache mode
35 const MODE_OUTAGE = 1; // fallback cache for DB outages
36 const MODE_REBUILD = 2; // background cache rebuild mode
38 /**
39 * @param Title|string $title Title object or prefixed DB key string
40 * @param string $action
41 * @throws MWException
43 public function __construct( $title, $action ) {
44 parent::__construct();
46 $allowedTypes = self::cacheablePageActions();
47 if ( !in_array( $action, $allowedTypes ) ) {
48 throw new MWException( 'Invalid file cache type given.' );
50 $this->mKey = ( $title instanceof Title )
51 ? $title->getPrefixedDBkey()
52 : (string)$title;
53 $this->mType = (string)$action;
54 $this->mExt = 'html';
57 /**
58 * Cacheable actions
59 * @return array
61 protected static function cacheablePageActions() {
62 return [ 'view', 'history' ];
65 /**
66 * Get the base file cache directory
67 * @return string
69 protected function cacheDirectory() {
70 return $this->baseCacheDirectory(); // no subdir for b/c with old cache files
73 /**
74 * Get the cache type subdirectory (with the trailing slash) or the empty string
75 * Alter the type -> directory mapping to put action=view cache at the root.
77 * @return string
79 protected function typeSubdirectory() {
80 if ( $this->mType === 'view' ) {
81 return ''; // b/c to not skip existing cache
82 } else {
83 return $this->mType . '/';
87 /**
88 * Check if pages can be cached for this request/user
89 * @param IContextSource $context
90 * @param integer $mode One of the HTMLFileCache::MODE_* constants (since 1.28)
91 * @return bool
93 public static function useFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
94 $config = MediaWikiServices::getInstance()->getMainConfig();
96 if ( !$config->get( 'UseFileCache' ) && $mode !== self::MODE_REBUILD ) {
97 return false;
98 } elseif ( $config->get( 'DebugToolbar' ) ) {
99 wfDebug( "HTML file cache skipped. \$wgDebugToolbar on\n" );
101 return false;
104 // Get all query values
105 $queryVals = $context->getRequest()->getValues();
106 foreach ( $queryVals as $query => $val ) {
107 if ( $query === 'title' || $query === 'curid' ) {
108 continue; // note: curid sets title
109 // Normal page view in query form can have action=view.
110 } elseif ( $query === 'action' && in_array( $val, self::cacheablePageActions() ) ) {
111 continue;
112 // Below are header setting params
113 } elseif ( $query === 'maxage' || $query === 'smaxage' ) {
114 continue;
117 return false;
120 $user = $context->getUser();
121 // Check for non-standard user language; this covers uselang,
122 // and extensions for auto-detecting user language.
123 $ulang = $context->getLanguage();
125 // Check that there are no other sources of variation
126 if ( $user->getId() || $ulang->getCode() !== $config->get( 'LanguageCode' ) ) {
127 return false;
130 if ( $mode === self::MODE_NORMAL ) {
131 if ( $user->getNewtalk() ) {
132 return false;
136 // Allow extensions to disable caching
137 return Hooks::run( 'HTMLFileCache::useFileCache', [ $context ] );
141 * Read from cache to context output
142 * @param IContextSource $context
143 * @param integer $mode One of the HTMLFileCache::MODE_* constants
144 * @return void
146 public function loadFromFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
147 global $wgContLang;
148 $config = MediaWikiServices::getInstance()->getMainConfig();
150 wfDebug( __METHOD__ . "()\n" );
151 $filename = $this->cachePath();
153 if ( $mode === self::MODE_OUTAGE ) {
154 // Avoid DB errors for queries in sendCacheControl()
155 $context->getTitle()->resetArticleID( 0 );
158 $context->getOutput()->sendCacheControl();
159 header( "Content-Type: {$config->get( 'MimeType' )}; charset=UTF-8" );
160 header( "Content-Language: {$wgContLang->getHtmlCode()}" );
161 if ( $this->useGzip() ) {
162 if ( wfClientAcceptsGzip() ) {
163 header( 'Content-Encoding: gzip' );
164 readfile( $filename );
165 } else {
166 /* Send uncompressed */
167 wfDebug( __METHOD__ . " uncompressing cache file and sending it\n" );
168 readgzfile( $filename );
170 } else {
171 readfile( $filename );
174 $context->getOutput()->disable(); // tell $wgOut that output is taken care of
178 * Save this cache object with the given text.
179 * Use this as an ob_start() handler.
181 * Normally this is only registed as a handler if $wgUseFileCache is on.
182 * If can be explicitly called by rebuildFileCache.php when it takes over
183 * handling file caching itself, disabling any automatic handling the the
184 * process.
186 * @param string $text
187 * @return string|bool The annotated $text or false on error
189 public function saveToFileCache( $text ) {
190 if ( strlen( $text ) < 512 ) {
191 // Disabled or empty/broken output (OOM and PHP errors)
192 return $text;
195 wfDebug( __METHOD__ . "()\n", 'private' );
197 $now = wfTimestampNow();
198 if ( $this->useGzip() ) {
199 $text = str_replace(
200 '</html>', '<!-- Cached/compressed ' . $now . " -->\n</html>", $text );
201 } else {
202 $text = str_replace(
203 '</html>', '<!-- Cached ' . $now . " -->\n</html>", $text );
206 // Store text to FS...
207 $compressed = $this->saveText( $text );
208 if ( $compressed === false ) {
209 return $text; // error
212 // gzip output to buffer as needed and set headers...
213 if ( $this->useGzip() ) {
214 // @todo Ugly wfClientAcceptsGzip() function - use context!
215 if ( wfClientAcceptsGzip() ) {
216 header( 'Content-Encoding: gzip' );
218 return $compressed;
219 } else {
220 return $text;
222 } else {
223 return $text;
228 * Clear the file caches for a page for all actions
229 * @param Title $title
230 * @return bool Whether $wgUseFileCache is enabled
232 public static function clearFileCache( Title $title ) {
233 $config = MediaWikiServices::getInstance()->getMainConfig();
235 if ( !$config->get( 'UseFileCache' ) ) {
236 return false;
239 foreach ( self::cacheablePageActions() as $type ) {
240 $fc = new self( $title, $type );
241 $fc->clearCache();
244 return true;