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