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