Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / cache / HTMLFileCache.php
blob7c6a3127d2aee09e141a5faf538de939dd884da6
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\Cache\CacheKeyHelper;
25 use MediaWiki\Cache\FileCacheBase;
26 use MediaWiki\Context\IContextSource;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\MainConfigNames;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\Page\PageIdentity;
32 /**
33 * Page view caching in the file system.
34 * The only cacheable actions are "view" and "history". Also special pages
35 * will not be cached.
37 * @ingroup Cache
39 class HTMLFileCache extends FileCacheBase {
40 public const MODE_NORMAL = 0; // normal cache mode
41 public const MODE_OUTAGE = 1; // fallback cache for DB outages
42 public const MODE_REBUILD = 2; // background cache rebuild mode
44 private const CACHEABLE_ACTIONS = [
45 'view',
46 'history',
49 /**
50 * @param PageIdentity|string $page PageIdentity object or prefixed DB key string
51 * @param string $action
53 public function __construct( $page, $action ) {
54 parent::__construct();
56 if ( !in_array( $action, self::CACHEABLE_ACTIONS ) ) {
57 throw new InvalidArgumentException( 'Invalid file cache type given.' );
60 $this->mKey = CacheKeyHelper::getKeyForPage( $page );
61 $this->mType = (string)$action;
62 $this->mExt = 'html';
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 int $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 $services = MediaWikiServices::getInstance();
95 $config = $services->getMainConfig();
97 if ( !$config->get( MainConfigNames::UseFileCache ) && $mode !== self::MODE_REBUILD ) {
98 return false;
101 // Get all query values
102 $queryVals = $context->getRequest()->getValues();
103 foreach ( $queryVals as $query => $val ) {
104 if ( $query === 'title' || $query === 'curid' ) {
105 continue; // note: curid sets title
106 // Normal page view in query form can have action=view.
107 } elseif ( $query === 'action' && in_array( $val, self::CACHEABLE_ACTIONS ) ) {
108 continue;
109 // Below are header setting params
110 } elseif ( $query === 'maxage' || $query === 'smaxage' ) {
111 continue;
112 // Uselang value is checked below
113 } elseif ( $query === 'uselang' ) {
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->isRegistered() ||
127 !$ulang->equals( $services->getContentLanguage() ) ) {
128 return false;
131 $userHasNewMessages = $services->getTalkPageNotificationManager()->userHasNewMessages( $user );
132 if ( ( $mode === self::MODE_NORMAL ) && $userHasNewMessages ) {
133 return false;
136 // Allow extensions to disable caching
137 return ( new HookRunner( $services->getHookContainer() ) )->onHTMLFileCache__useFileCache( $context );
141 * Read from cache to context output
142 * @param IContextSource $context
143 * @param int $mode One of the HTMLFileCache::MODE_* constants
144 * @return void
146 public function loadFromFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
147 wfDebug( __METHOD__ . "()" );
148 $filename = $this->cachePath();
150 if ( $mode === self::MODE_OUTAGE ) {
151 // Avoid DB errors for queries in sendCacheControl()
152 $context->getTitle()->resetArticleID( 0 );
155 $context->getOutput()->sendCacheControl();
156 header( "Content-Type: {$this->options->get( MainConfigNames::MimeType )}; charset=UTF-8" );
157 header( 'Content-Language: ' .
158 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
159 if ( $this->useGzip() ) {
160 if ( wfClientAcceptsGzip() ) {
161 header( 'Content-Encoding: gzip' );
162 readfile( $filename );
163 } else {
164 /* Send uncompressed */
165 wfDebug( __METHOD__ . " uncompressing cache file and sending it" );
166 readgzfile( $filename );
168 } else {
169 readfile( $filename );
172 $context->getOutput()->disable(); // tell $wgOut that output is taken care of
176 * Save this cache object with the given text.
177 * Use this as an ob_start() handler.
179 * Normally this is only registered as a handler if $wgUseFileCache is on.
180 * If can be explicitly called by rebuildFileCache.php when it takes over
181 * handling file caching itself, disabling any automatic handling the
182 * process.
184 * @param string $text
185 * @return string|bool The annotated $text or false on error
187 public function saveToFileCache( $text ) {
188 if ( strlen( $text ) < 512 ) {
189 // Disabled or empty/broken output (OOM and PHP errors)
190 return $text;
193 wfDebug( __METHOD__ . "()\n", 'private' );
195 $now = wfTimestampNow();
196 if ( $this->useGzip() ) {
197 $text = str_replace(
198 '</html>', '<!-- Cached/compressed ' . $now . " -->\n</html>", $text );
199 } else {
200 $text = str_replace(
201 '</html>', '<!-- Cached ' . $now . " -->\n</html>", $text );
204 // Store text to FS...
205 $compressed = $this->saveText( $text );
206 if ( $compressed === false ) {
207 return $text; // error
210 // gzip output to buffer as needed and set headers...
211 // @todo Ugly wfClientAcceptsGzip() function - use context!
212 if ( $this->useGzip() && wfClientAcceptsGzip() ) {
213 header( 'Content-Encoding: gzip' );
215 return $compressed;
218 return $text;
222 * Clear the file caches for a page for all actions
224 * @param PageIdentity|string $page PageIdentity object or prefixed DB key string
225 * @return bool Whether $wgUseFileCache is enabled
227 public static function clearFileCache( $page ) {
228 $config = MediaWikiServices::getInstance()->getMainConfig();
229 if ( !$config->get( MainConfigNames::UseFileCache ) ) {
230 return false;
233 foreach ( self::CACHEABLE_ACTIONS as $type ) {
234 $fc = new self( $page, $type );
235 $fc->clearCache();
238 return true;