MediaWiki  master
HTMLFileCache.php
Go to the documentation of this file.
1 <?php
28 
37  public const MODE_NORMAL = 0; // normal cache mode
38  public const MODE_OUTAGE = 1; // fallback cache for DB outages
39  public const MODE_REBUILD = 2; // background cache rebuild mode
40 
47  public function __construct( $page, $action ) {
48  parent::__construct();
49 
50  if ( !in_array( $action, self::cacheablePageActions() ) ) {
51  throw new InvalidArgumentException( 'Invalid file cache type given.' );
52  }
53 
54  $this->mKey = CacheKeyHelper::getKeyForPage( $page );
55  $this->mType = (string)$action;
56  $this->mExt = 'html';
57  }
58 
63  protected static function cacheablePageActions() {
64  return [ 'view', 'history' ];
65  }
66 
71  protected function cacheDirectory() {
72  return $this->baseCacheDirectory(); // no subdir for b/c with old cache files
73  }
74 
81  protected function typeSubdirectory() {
82  if ( $this->mType === 'view' ) {
83  return ''; // b/c to not skip existing cache
84  } else {
85  return $this->mType . '/';
86  }
87  }
88 
95  public static function useFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
96  $config = MediaWikiServices::getInstance()->getMainConfig();
97 
98  if ( !$config->get( MainConfigNames::UseFileCache ) && $mode !== self::MODE_REBUILD ) {
99  return false;
100  }
101 
102  // Get all query values
103  $queryVals = $context->getRequest()->getValues();
104  foreach ( $queryVals as $query => $val ) {
105  if ( $query === 'title' || $query === 'curid' ) {
106  continue; // note: curid sets title
107  // Normal page view in query form can have action=view.
108  } elseif ( $query === 'action' && in_array( $val, self::cacheablePageActions() ) ) {
109  continue;
110  // Below are header setting params
111  } elseif ( $query === 'maxage' || $query === 'smaxage' ) {
112  continue;
113  // Uselang value is checked below
114  } elseif ( $query === 'uselang' ) {
115  continue;
116  }
117 
118  return false;
119  }
120 
121  $user = $context->getUser();
122  // Check for non-standard user language; this covers uselang,
123  // and extensions for auto-detecting user language.
124  $ulang = $context->getLanguage();
125 
126  // Check that there are no other sources of variation
127  if ( $user->isRegistered() ||
128  !$ulang->equals( MediaWikiServices::getInstance()->getContentLanguage() ) ) {
129  return false;
130  }
131 
132  $userHasNewMessages = MediaWikiServices::getInstance()
133  ->getTalkPageNotificationManager()->userHasNewMessages( $user );
134  if ( ( $mode === self::MODE_NORMAL ) && $userHasNewMessages ) {
135  return false;
136  }
137 
138  // Allow extensions to disable caching
139  return Hooks::runner()->onHTMLFileCache__useFileCache( $context );
140  }
141 
148  public function loadFromFileCache( IContextSource $context, $mode = self::MODE_NORMAL ) {
149  wfDebug( __METHOD__ . "()" );
150  $filename = $this->cachePath();
151 
152  if ( $mode === self::MODE_OUTAGE ) {
153  // Avoid DB errors for queries in sendCacheControl()
154  $context->getTitle()->resetArticleID( 0 );
155  }
156 
157  $context->getOutput()->sendCacheControl();
158  header( "Content-Type: {$this->options->get( MainConfigNames::MimeType )}; charset=UTF-8" );
159  header( 'Content-Language: ' .
160  MediaWikiServices::getInstance()->getContentLanguage()->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" );
168  readgzfile( $filename );
169  }
170  } else {
171  readfile( $filename );
172  }
173 
174  $context->getOutput()->disable(); // tell $wgOut that output is taken care of
175  }
176 
189  public function saveToFileCache( $text ) {
190  if ( strlen( $text ) < 512 ) {
191  // Disabled or empty/broken output (OOM and PHP errors)
192  return $text;
193  }
194 
195  wfDebug( __METHOD__ . "()\n", 'private' );
196 
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 );
204  }
205 
206  // Store text to FS...
207  $compressed = $this->saveText( $text );
208  if ( $compressed === false ) {
209  return $text; // error
210  }
211 
212  // gzip output to buffer as needed and set headers...
213  // @todo Ugly wfClientAcceptsGzip() function - use context!
214  if ( $this->useGzip() && wfClientAcceptsGzip() ) {
215  header( 'Content-Encoding: gzip' );
216 
217  return $compressed;
218  }
219 
220  return $text;
221  }
222 
229  public static function clearFileCache( $page ) {
230  $config = MediaWikiServices::getInstance()->getMainConfig();
231  if ( !$config->get( MainConfigNames::UseFileCache ) ) {
232  return false;
233  }
234 
235  foreach ( self::cacheablePageActions() as $type ) {
236  $fc = new self( $page, $type );
237  $fc->clearCache();
238  }
239 
240  return true;
241  }
242 }
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.
useGzip()
Check if the cache is gzipped.
cachePath()
Get the path to the cache file.
saveText( $text)
Save and compress text to the cache.
baseCacheDirectory()
Get the base file cache directory.
Page view caching in the file system.
static useFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Check if pages can be cached for this request/user.
__construct( $page, $action)
loadFromFileCache(IContextSource $context, $mode=self::MODE_NORMAL)
Read from cache to context output.
static clearFileCache( $page)
Clear the file caches for a page for all actions.
saveToFileCache( $text)
Save this cache object with the given text.
cacheDirectory()
Get the base file cache directory.
typeSubdirectory()
Get the cache type subdirectory (with the trailing slash) or the empty string Alter the type -> direc...
static cacheablePageActions()
Cacheable actions.
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:173
Helper class for mapping value objects representing basic entities to cache keys.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Interface for objects which can provide a MediaWiki context on request.
Interface for objects (potentially) representing an editable wiki page.