SpecialNewFiles: Swap from/to date serverside
[lhc/web/wiklou.git] / includes / parser / ParserCache.php
1 <?php
2 /**
3 * Cache for outputs of the PHP parser
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Cache Parser
22 */
23
24 /**
25 * @ingroup Cache Parser
26 * @todo document
27 */
28 class ParserCache {
29 /**
30 * Constants for self::getKey()
31 * @since 1.30
32 */
33
34 /** Use only current data */
35 const USE_CURRENT_ONLY = 0;
36
37 /** Use expired data if current data is unavailable */
38 const USE_EXPIRED = 1;
39
40 /** Use expired data or data from different revisions if current data is unavailable */
41 const USE_OUTDATED = 2;
42
43 /**
44 * Use expired data and data from different revisions, and if all else
45 * fails vary on all variable options
46 */
47 const USE_ANYTHING = 3;
48
49 /** @var BagOStuff */
50 private $mMemc;
51 /**
52 * Get an instance of this object
53 *
54 * @return ParserCache
55 */
56 public static function singleton() {
57 static $instance;
58 if ( !isset( $instance ) ) {
59 global $parserMemc;
60 $instance = new ParserCache( $parserMemc );
61 }
62 return $instance;
63 }
64
65 /**
66 * Setup a cache pathway with a given back-end storage mechanism.
67 *
68 * This class use an invalidation strategy that is compatible with
69 * MultiWriteBagOStuff in async replication mode.
70 *
71 * @param BagOStuff $memCached
72 * @throws MWException
73 */
74 protected function __construct( BagOStuff $memCached ) {
75 $this->mMemc = $memCached;
76 }
77
78 /**
79 * @param WikiPage $article
80 * @param string $hash
81 * @return mixed|string
82 */
83 protected function getParserOutputKey( $article, $hash ) {
84 global $wgRequest;
85
86 // idhash seem to mean 'page id' + 'rendering hash' (r3710)
87 $pageid = $article->getId();
88 $renderkey = (int)( $wgRequest->getVal( 'action' ) == 'render' );
89
90 $key = $this->mMemc->makeKey( 'pcache', 'idhash', "{$pageid}-{$renderkey}!{$hash}" );
91 return $key;
92 }
93
94 /**
95 * @param WikiPage $page
96 * @return mixed|string
97 */
98 protected function getOptionsKey( $page ) {
99 return $this->mMemc->makeKey( 'pcache', 'idoptions', $page->getId() );
100 }
101
102 /**
103 * @param WikiPage $page
104 * @since 1.28
105 */
106 public function deleteOptionsKey( $page ) {
107 $this->mMemc->delete( $this->getOptionsKey( $page ) );
108 }
109
110 /**
111 * Provides an E-Tag suitable for the whole page. Note that $article
112 * is just the main wikitext. The E-Tag has to be unique to the whole
113 * page, even if the article itself is the same, so it uses the
114 * complete set of user options. We don't want to use the preference
115 * of a different user on a message just because it wasn't used in
116 * $article. For example give a Chinese interface to a user with
117 * English preferences. That's why we take into account *all* user
118 * options. (r70809 CR)
119 *
120 * @param WikiPage $article
121 * @param ParserOptions $popts
122 * @return string
123 */
124 public function getETag( $article, $popts ) {
125 return 'W/"' . $this->getParserOutputKey( $article,
126 $popts->optionsHash( ParserOptions::allCacheVaryingOptions(), $article->getTitle() ) ) .
127 "--" . $article->getTouched() . '"';
128 }
129
130 /**
131 * Retrieve the ParserOutput from ParserCache, even if it's outdated.
132 * @param WikiPage $article
133 * @param ParserOptions $popts
134 * @return ParserOutput|bool False on failure
135 */
136 public function getDirty( $article, $popts ) {
137 $value = $this->get( $article, $popts, true );
138 return is_object( $value ) ? $value : false;
139 }
140
141 /**
142 * Generates a key for caching the given article considering
143 * the given parser options.
144 *
145 * @note Which parser options influence the cache key
146 * is controlled via ParserOutput::recordOption() or
147 * ParserOptions::addExtraKey().
148 *
149 * @note Used by Article to provide a unique id for the PoolCounter.
150 * It would be preferable to have this code in get()
151 * instead of having Article looking in our internals.
152 *
153 * @param WikiPage $article
154 * @param ParserOptions $popts
155 * @param int|bool $useOutdated One of the USE constants. For backwards
156 * compatibility, boolean false is treated as USE_CURRENT_ONLY and
157 * boolean true is treated as USE_ANYTHING.
158 * @return bool|mixed|string
159 * @since 1.30 Changed $useOutdated to an int and added the non-boolean values
160 */
161 public function getKey( $article, $popts, $useOutdated = self::USE_ANYTHING ) {
162 global $wgCacheEpoch;
163
164 if ( is_bool( $useOutdated ) ) {
165 $useOutdated = $useOutdated ? self::USE_ANYTHING : self::USE_CURRENT_ONLY;
166 }
167
168 if ( $popts instanceof User ) {
169 wfWarn( "Use of outdated prototype ParserCache::getKey( &\$article, &\$user )\n" );
170 $popts = ParserOptions::newFromUser( $popts );
171 }
172
173 // Determine the options which affect this article
174 $casToken = null;
175 $optionsKey = $this->mMemc->get(
176 $this->getOptionsKey( $article ), $casToken, BagOStuff::READ_VERIFIED );
177 if ( $optionsKey instanceof CacheTime ) {
178 if ( $useOutdated < self::USE_EXPIRED && $optionsKey->expired( $article->getTouched() ) ) {
179 wfIncrStats( "pcache.miss.expired" );
180 $cacheTime = $optionsKey->getCacheTime();
181 wfDebugLog( "ParserCache",
182 "Parser options key expired, touched " . $article->getTouched()
183 . ", epoch $wgCacheEpoch, cached $cacheTime\n" );
184 return false;
185 } elseif ( $useOutdated < self::USE_OUTDATED &&
186 $optionsKey->isDifferentRevision( $article->getLatest() )
187 ) {
188 wfIncrStats( "pcache.miss.revid" );
189 $revId = $article->getLatest();
190 $cachedRevId = $optionsKey->getCacheRevisionId();
191 wfDebugLog( "ParserCache",
192 "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
193 );
194 return false;
195 }
196
197 // $optionsKey->mUsedOptions is set by save() by calling ParserOutput::getUsedOptions()
198 $usedOptions = $optionsKey->mUsedOptions;
199 wfDebug( "Parser cache options found.\n" );
200 } else {
201 if ( $useOutdated < self::USE_ANYTHING ) {
202 return false;
203 }
204 $usedOptions = ParserOptions::allCacheVaryingOptions();
205 }
206
207 return $this->getParserOutputKey(
208 $article,
209 $popts->optionsHash( $usedOptions, $article->getTitle() )
210 );
211 }
212
213 /**
214 * Retrieve the ParserOutput from ParserCache.
215 * false if not found or outdated.
216 *
217 * @param WikiPage|Article $article
218 * @param ParserOptions $popts
219 * @param bool $useOutdated (default false)
220 *
221 * @return ParserOutput|bool False on failure
222 */
223 public function get( $article, $popts, $useOutdated = false ) {
224 global $wgCacheEpoch;
225
226 $canCache = $article->checkTouched();
227 if ( !$canCache ) {
228 // It's a redirect now
229 return false;
230 }
231
232 $touched = $article->getTouched();
233
234 $parserOutputKey = $this->getKey( $article, $popts,
235 $useOutdated ? self::USE_OUTDATED : self::USE_CURRENT_ONLY
236 );
237 if ( $parserOutputKey === false ) {
238 wfIncrStats( 'pcache.miss.absent' );
239 return false;
240 }
241
242 $casToken = null;
243 /** @var ParserOutput $value */
244 $value = $this->mMemc->get( $parserOutputKey, $casToken, BagOStuff::READ_VERIFIED );
245 if ( !$value ) {
246 wfDebug( "ParserOutput cache miss.\n" );
247 wfIncrStats( "pcache.miss.absent" );
248 return false;
249 }
250
251 wfDebug( "ParserOutput cache found.\n" );
252
253 // The edit section preference may not be the appropiate one in
254 // the ParserOutput, as we are not storing it in the parsercache
255 // key. Force it here. See T33445.
256 $value->setEditSectionTokens( $popts->getEditSection() );
257
258 $wikiPage = method_exists( $article, 'getPage' )
259 ? $article->getPage()
260 : $article;
261
262 if ( !$useOutdated && $value->expired( $touched ) ) {
263 wfIncrStats( "pcache.miss.expired" );
264 $cacheTime = $value->getCacheTime();
265 wfDebugLog( "ParserCache",
266 "ParserOutput key expired, touched $touched, "
267 . "epoch $wgCacheEpoch, cached $cacheTime\n" );
268 $value = false;
269 } elseif ( !$useOutdated && $value->isDifferentRevision( $article->getLatest() ) ) {
270 wfIncrStats( "pcache.miss.revid" );
271 $revId = $article->getLatest();
272 $cachedRevId = $value->getCacheRevisionId();
273 wfDebugLog( "ParserCache",
274 "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
275 );
276 $value = false;
277 } elseif (
278 Hooks::run( 'RejectParserCacheValue', [ $value, $wikiPage, $popts ] ) === false
279 ) {
280 wfIncrStats( 'pcache.miss.rejected' );
281 wfDebugLog( "ParserCache",
282 "ParserOutput key valid, but rejected by RejectParserCacheValue hook handler.\n"
283 );
284 $value = false;
285 } else {
286 wfIncrStats( "pcache.hit" );
287 }
288
289 return $value;
290 }
291
292 /**
293 * @param ParserOutput $parserOutput
294 * @param WikiPage $page
295 * @param ParserOptions $popts
296 * @param string $cacheTime Time when the cache was generated
297 * @param int $revId Revision ID that was parsed
298 */
299 public function save( $parserOutput, $page, $popts, $cacheTime = null, $revId = null ) {
300 $expire = $parserOutput->getCacheExpiry();
301 if ( $expire > 0 && !$this->mMemc instanceof EmptyBagOStuff ) {
302 $cacheTime = $cacheTime ?: wfTimestampNow();
303 if ( !$revId ) {
304 $revision = $page->getRevision();
305 $revId = $revision ? $revision->getId() : null;
306 }
307
308 $optionsKey = new CacheTime;
309 $optionsKey->mUsedOptions = $parserOutput->getUsedOptions();
310 $optionsKey->updateCacheExpiry( $expire );
311
312 $optionsKey->setCacheTime( $cacheTime );
313 $parserOutput->setCacheTime( $cacheTime );
314 $optionsKey->setCacheRevisionId( $revId );
315 $parserOutput->setCacheRevisionId( $revId );
316
317 $parserOutputKey = $this->getParserOutputKey( $page,
318 $popts->optionsHash( $optionsKey->mUsedOptions, $page->getTitle() ) );
319
320 // Save the timestamp so that we don't have to load the revision row on view
321 $parserOutput->setTimestamp( $page->getTimestamp() );
322
323 $msg = "Saved in parser cache with key $parserOutputKey" .
324 " and timestamp $cacheTime" .
325 " and revision id $revId" .
326 "\n";
327
328 $parserOutput->mText .= "\n<!-- $msg -->\n";
329 wfDebug( $msg );
330
331 // Save the parser output
332 $this->mMemc->set( $parserOutputKey, $parserOutput, $expire );
333
334 // ...and its pointer
335 $this->mMemc->set( $this->getOptionsKey( $page ), $optionsKey, $expire );
336
337 Hooks::run(
338 'ParserCacheSaveComplete',
339 [ $this, $parserOutput, $page->getTitle(), $popts, $revId ]
340 );
341 } elseif ( $expire <= 0 ) {
342 wfDebug( "Parser output was marked as uncacheable and has not been saved.\n" );
343 }
344 }
345 }