MediaWiki master
HTMLFileCache.php
Go to the documentation of this file.
1<?php
9
10namespace MediaWiki\Cache;
11
12use InvalidArgumentException;
13use MediaWiki\Context\IContextSource;
14use MediaWiki\HookContainer\HookRunner;
15use MediaWiki\MainConfigNames;
16use MediaWiki\MediaWikiServices;
17use MediaWiki\Page\CacheKeyHelper;
18use MediaWiki\Page\PageIdentity;
19use Wikimedia\Http\HttpHeader;
20
29 public const MODE_NORMAL = 0; // normal cache mode
30 public const MODE_OUTAGE = 1; // fallback cache for DB outages
31 public const MODE_REBUILD = 2; // background cache rebuild mode
32
33 private const CACHEABLE_ACTIONS = [
34 'view',
35 'history',
36 ];
37
42 public function __construct( $page, $action ) {
43 parent::__construct();
44
45 if ( !in_array( $action, self::CACHEABLE_ACTIONS ) ) {
46 throw new InvalidArgumentException( 'Invalid file cache type given.' );
47 }
48
49 $this->mKey = CacheKeyHelper::getKeyForPage( $page );
50 $this->mType = (string)$action;
51 $this->mExt = 'html';
52 }
53
58 protected function cacheDirectory() {
59 return $this->baseCacheDirectory(); // no subdir for b/c with old cache files
60 }
61
68 protected function typeSubdirectory() {
69 if ( $this->mType === 'view' ) {
70 return ''; // b/c to not skip existing cache
71 } else {
72 return $this->mType . '/';
73 }
74 }
75
82 public static function useFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
84 $config = $services->getMainConfig();
85
86 if ( !$config->get( MainConfigNames::UseFileCache ) && $mode !== self::MODE_REBUILD ) {
87 return false;
88 }
89
90 // Get all query values
91 $queryVals = $context->getRequest()->getValues();
92 foreach ( $queryVals as $query => $val ) {
93 if ( $query === 'title' || $query === 'curid' ) {
94 continue; // note: curid sets title
95 // Normal page view in query form can have action=view.
96 } elseif ( $query === 'action' && in_array( $val, self::CACHEABLE_ACTIONS ) ) {
97 continue;
98 // Below are header setting params
99 } elseif ( $query === 'maxage' || $query === 'smaxage' ) {
100 continue;
101 // Uselang value is checked below
102 } elseif ( $query === 'uselang' ) {
103 continue;
104 }
105
106 return false;
107 }
108
109 $user = $context->getUser();
110 // Check for non-standard user language; this covers uselang,
111 // and extensions for auto-detecting user language.
112 $ulang = $context->getLanguage();
113
114 // Check that there are no other sources of variation
115 if ( $user->isRegistered() ||
116 !$ulang->equals( $services->getContentLanguage() ) ) {
117 return false;
118 }
119
120 $userHasNewMessages = $services->getTalkPageNotificationManager()->userHasNewMessages( $user );
121 if ( ( $mode === self::MODE_NORMAL ) && $userHasNewMessages ) {
122 return false;
123 }
124
125 // Allow extensions to disable caching
126 return ( new HookRunner( $services->getHookContainer() ) )->onHTMLFileCache__useFileCache( $context );
127 }
128
135 public function loadFromFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
136 wfDebug( __METHOD__ . "()" );
137 $filename = $this->cachePath();
138
139 if ( $mode === self::MODE_OUTAGE ) {
140 // Avoid DB errors for queries in sendCacheControl()
141 $context->getTitle()->resetArticleID( 0 );
142 }
143
144 $context->getOutput()->sendCacheControl();
145 HttpHeader::send( "Content-Type: {$this->options->get( MainConfigNames::MimeType )}; charset=UTF-8" );
146 HttpHeader::send( 'Content-Language: ' .
147 MediaWikiServices::getInstance()->getContentLanguage()->getHtmlCode() );
148 if ( $this->useGzip() ) {
149 if ( wfClientAcceptsGzip() ) {
150 HttpHeader::send( 'Content-Encoding: gzip' );
151 readfile( $filename );
152 } else {
153 /* Send uncompressed */
154 wfDebug( __METHOD__ . " uncompressing cache file and sending it" );
155 readgzfile( $filename );
156 }
157 } else {
158 readfile( $filename );
159 }
160
161 $context->getOutput()->disable(); // tell $wgOut that output is taken care of
162 }
163
176 public function saveToFileCache( $text ) {
177 if ( strlen( $text ) < 512 ) {
178 // Disabled or empty/broken output (OOM and PHP errors)
179 return $text;
180 }
181
182 wfDebug( __METHOD__ . "()\n", 'private' );
183
184 $now = wfTimestampNow();
185 if ( $this->useGzip() ) {
186 $text = str_replace(
187 '</html>', '<!-- Cached/compressed ' . $now . " -->\n</html>", $text );
188 } else {
189 $text = str_replace(
190 '</html>', '<!-- Cached ' . $now . " -->\n</html>", $text );
191 }
192
193 // Store text to FS...
194 $compressed = $this->saveText( $text );
195 if ( $compressed === false ) {
196 return $text; // error
197 }
198
199 // gzip output to buffer as needed and set headers...
200 // @todo Ugly wfClientAcceptsGzip() function - use context!
201 if ( $this->useGzip() && wfClientAcceptsGzip() ) {
202 HttpHeader::send( 'Content-Encoding: gzip' );
203
204 return $compressed;
205 }
206
207 return $text;
208 }
209
216 public static function clearFileCache( $page ) {
217 $config = MediaWikiServices::getInstance()->getMainConfig();
218 if ( !$config->get( MainConfigNames::UseFileCache ) ) {
219 return false;
220 }
221
222 foreach ( self::CACHEABLE_ACTIONS as $type ) {
223 $fc = new self( $page, $type );
224 $fc->clearCache();
225 }
226
227 return true;
228 }
229}
230
232class_alias( HTMLFileCache::class, 'HTMLFileCache' );
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfClientAcceptsGzip( $force=false)
Whether the client accept gzip encoding.
Base class for data storage in the file system.
saveText( $text)
Save and compress text to the cache.
baseCacheDirectory()
Get the base file cache directory.
cachePath()
Get the path to the cache file.
useGzip()
Check if the cache is gzipped.
Page view caching in the file system.
saveToFileCache( $text)
Save this cache object with the given text.
static clearFileCache( $page)
Clear the file caches for a page for all actions.
typeSubdirectory()
Get the cache type subdirectory (with the trailing slash) or the empty string Alter the type -> direc...
static useFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Check if pages can be cached for this request/user.
loadFromFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Read from cache to context output.
cacheDirectory()
Get the base file cache directory.
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
const UseFileCache
Name constant for the UseFileCache setting, for use with Config\get().
static getInstance()
Returns the global default instance of the top level service locator.
static send(string $header, bool $replace=true, int $responseCode=0)
Interface for objects which can provide a MediaWiki context on request.