HTMLFileCache.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. <?php
  2. /**
  3. * Contain the HTMLFileCache class
  4. * @file
  5. * @ingroup Cache
  6. */
  7. /**
  8. * Handles talking to the file cache, putting stuff in and taking it back out.
  9. * Mostly called from Article.php, also from DatabaseFunctions.php for the
  10. * emergency abort/fallback to cache.
  11. *
  12. * Global options that affect this module:
  13. * - $wgCachePages
  14. * - $wgCacheEpoch
  15. * - $wgUseFileCache
  16. * - $wgFileCacheDirectory
  17. * - $wgUseGzip
  18. *
  19. * @ingroup Cache
  20. */
  21. class HTMLFileCache {
  22. var $mTitle, $mFileCache, $mType;
  23. public function __construct( &$title, $type = 'view' ) {
  24. $this->mTitle = $title;
  25. $this->mType = ($type == 'raw' || $type == 'view' ) ? $type : false;
  26. $this->fileCacheName(); // init name
  27. }
  28. public function fileCacheName() {
  29. if( !$this->mFileCache ) {
  30. global $wgFileCacheDirectory, $wgRequest;
  31. # Store raw pages (like CSS hits) elsewhere
  32. $subdir = ($this->mType === 'raw') ? 'raw/' : '';
  33. $key = $this->mTitle->getPrefixedDbkey();
  34. $hash = md5( $key );
  35. # Avoid extension confusion
  36. $key = str_replace( '.', '%2E', urlencode( $key ) );
  37. $hash1 = substr( $hash, 0, 1 );
  38. $hash2 = substr( $hash, 0, 2 );
  39. $this->mFileCache = "{$wgFileCacheDirectory}/{$subdir}{$hash1}/{$hash2}/{$key}.html";
  40. if( $this->useGzip() )
  41. $this->mFileCache .= '.gz';
  42. wfDebug( " fileCacheName() - {$this->mFileCache}\n" );
  43. }
  44. return $this->mFileCache;
  45. }
  46. public function isFileCached() {
  47. if( $this->mType === false ) return false;
  48. return file_exists( $this->fileCacheName() );
  49. }
  50. public function fileCacheTime() {
  51. return wfTimestamp( TS_MW, filemtime( $this->fileCacheName() ) );
  52. }
  53. /**
  54. * Check if pages can be cached for this request/user
  55. * @return bool
  56. */
  57. public static function useFileCache() {
  58. global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
  59. if( !$wgUseFileCache ) return false;
  60. // Get all query values
  61. $queryVals = $wgRequest->getValues();
  62. foreach( $queryVals as $query => $val ) {
  63. if( $query == 'title' || $query == 'curid' ) continue;
  64. // Normal page view in query form can have action=view.
  65. // Raw hits for pages also stored, like .css pages for example.
  66. else if( $query == 'action' && ($val == 'view' || $val == 'raw') ) continue;
  67. else if( $query == 'usemsgcache' && $val == 'yes' ) continue;
  68. // Below are header setting params
  69. else if( $query == 'maxage' || $query == 'smaxage' || $query == 'ctype' || $query == 'gen' )
  70. continue;
  71. else
  72. return false;
  73. }
  74. // Check for non-standard user language; this covers uselang,
  75. // and extensions for auto-detecting user language.
  76. $ulang = $wgLang->getCode();
  77. $clang = $wgContLang->getCode();
  78. // Check that there are no other sources of variation
  79. return !$wgShowIPinHeader && !$wgUser->getId() && !$wgUser->getNewtalk() && $ulang == $clang;
  80. }
  81. /*
  82. * Check if up to date cache file exists
  83. * @param $timestamp string
  84. */
  85. public function isFileCacheGood( $timestamp = '' ) {
  86. global $wgCacheEpoch;
  87. if( !$this->isFileCached() ) return false;
  88. if( !$timestamp ) return true; // should be invalidated on change
  89. $cachetime = $this->fileCacheTime();
  90. $good = $timestamp <= $cachetime && $wgCacheEpoch <= $cachetime;
  91. wfDebug(" isFileCacheGood() - cachetime $cachetime, touched '{$timestamp}' epoch {$wgCacheEpoch}, good $good\n");
  92. return $good;
  93. }
  94. public function useGzip() {
  95. global $wgUseGzip;
  96. return $wgUseGzip;
  97. }
  98. /* In handy string packages */
  99. public function fetchRawText() {
  100. return file_get_contents( $this->fileCacheName() );
  101. }
  102. public function fetchPageText() {
  103. if( $this->useGzip() ) {
  104. /* Why is there no gzfile_get_contents() or gzdecode()? */
  105. return implode( '', gzfile( $this->fileCacheName() ) );
  106. } else {
  107. return $this->fetchRawText();
  108. }
  109. }
  110. /* Working directory to/from output */
  111. public function loadFromFileCache() {
  112. global $wgOut, $wgMimeType, $wgOutputEncoding, $wgContLanguageCode;
  113. wfDebug(" loadFromFileCache()\n");
  114. $filename = $this->fileCacheName();
  115. // Raw pages should handle cache control on their own,
  116. // even when using file cache. This reduces hits from clients.
  117. if( $this->mType !== 'raw' ) {
  118. $wgOut->sendCacheControl();
  119. header( "Content-Type: $wgMimeType; charset={$wgOutputEncoding}" );
  120. header( "Content-Language: $wgContLanguageCode" );
  121. }
  122. if( $this->useGzip() ) {
  123. if( wfClientAcceptsGzip() ) {
  124. header( 'Content-Encoding: gzip' );
  125. } else {
  126. /* Send uncompressed */
  127. readgzfile( $filename );
  128. return;
  129. }
  130. }
  131. readfile( $filename );
  132. $wgOut->disable(); // tell $wgOut that output is taken care of
  133. }
  134. protected function checkCacheDirs() {
  135. $filename = $this->fileCacheName();
  136. $mydir2 = substr($filename,0,strrpos($filename,'/')); # subdirectory level 2
  137. $mydir1 = substr($mydir2,0,strrpos($mydir2,'/')); # subdirectory level 1
  138. wfMkdirParents( $mydir1 );
  139. wfMkdirParents( $mydir2 );
  140. }
  141. public function saveToFileCache( $text ) {
  142. global $wgUseFileCache;
  143. if( !$wgUseFileCache || strlen( $text ) < 512 ) {
  144. // Disabled or empty/broken output (OOM and PHP errors)
  145. return $text;
  146. }
  147. wfDebug(" saveToFileCache()\n", false);
  148. $this->checkCacheDirs();
  149. $f = fopen( $this->fileCacheName(), 'w' );
  150. if($f) {
  151. $now = wfTimestampNow();
  152. if( $this->useGzip() ) {
  153. $rawtext = str_replace( '</html>',
  154. '<!-- Cached/compressed '.$now." -->\n</html>",
  155. $text );
  156. $text = gzencode( $rawtext );
  157. } else {
  158. $text = str_replace( '</html>',
  159. '<!-- Cached '.$now." -->\n</html>",
  160. $text );
  161. }
  162. fwrite( $f, $text );
  163. fclose( $f );
  164. if( $this->useGzip() ) {
  165. if( wfClientAcceptsGzip() ) {
  166. header( 'Content-Encoding: gzip' );
  167. return $text;
  168. } else {
  169. return $rawtext;
  170. }
  171. } else {
  172. return $text;
  173. }
  174. }
  175. return $text;
  176. }
  177. public static function clearFileCache( $title ) {
  178. global $wgUseFileCache;
  179. if( !$wgUseFileCache ) return false;
  180. $fc = new self( $title, 'view' );
  181. @unlink( $fc->fileCacheName() );
  182. $fc = new self( $title, 'raw' );
  183. @unlink( $fc->fileCacheName() );
  184. return true;
  185. }
  186. }