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