Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[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 use MediaWiki\MediaWikiServices;
25
26 /**
27 * @ingroup Cache Parser
28 * @todo document
29 */
30 class ParserCache {
31 /**
32 * Constants for self::getKey()
33 * @since 1.30
34 */
35
36 /** Use only current data */
37 const USE_CURRENT_ONLY = 0;
38
39 /** Use expired data if current data is unavailable */
40 const USE_EXPIRED = 1;
41
42 /** Use expired data or data from different revisions if current data is unavailable */
43 const USE_OUTDATED = 2;
44
45 /**
46 * Use expired data and data from different revisions, and if all else
47 * fails vary on all variable options
48 */
49 const USE_ANYTHING = 3;
50
51 /** @var BagOStuff */
52 private $mMemc;
53
54 /**
55 * Anything cached prior to this is invalidated
56 *
57 * @var string
58 */
59 private $cacheEpoch;
60 /**
61 * Get an instance of this object
62 *
63 * @deprecated since 1.30, use MediaWikiServices instead
64 * @return ParserCache
65 */
66 public static function singleton() {
67 return MediaWikiServices::getInstance()->getParserCache();
68 }
69
70 /**
71 * Setup a cache pathway with a given back-end storage mechanism.
72 *
73 * This class use an invalidation strategy that is compatible with
74 * MultiWriteBagOStuff in async replication mode.
75 *
76 * @param BagOStuff $cache
77 * @param string $cacheEpoch Anything before this timestamp is invalidated
78 * @throws MWException
79 */
80 public function __construct( BagOStuff $cache, $cacheEpoch = '20030516000000' ) {
81 $this->mMemc = $cache;
82 $this->cacheEpoch = $cacheEpoch;
83 }
84
85 /**
86 * @param WikiPage $article
87 * @param string $hash
88 * @return mixed|string
89 */
90 protected function getParserOutputKey( $article, $hash ) {
91 global $wgRequest;
92
93 // idhash seem to mean 'page id' + 'rendering hash' (r3710)
94 $pageid = $article->getId();
95 $renderkey = (int)( $wgRequest->getVal( 'action' ) == 'render' );
96
97 $key = $this->mMemc->makeKey( 'pcache', 'idhash', "{$pageid}-{$renderkey}!{$hash}" );
98 return $key;
99 }
100
101 /**
102 * @param WikiPage $page
103 * @return mixed|string
104 */
105 protected function getOptionsKey( $page ) {
106 return $this->mMemc->makeKey( 'pcache', 'idoptions', $page->getId() );
107 }
108
109 /**
110 * @param WikiPage $page
111 * @since 1.28
112 */
113 public function deleteOptionsKey( $page ) {
114 $this->mMemc->delete( $this->getOptionsKey( $page ) );
115 }
116
117 /**
118 * Provides an E-Tag suitable for the whole page. Note that $article
119 * is just the main wikitext. The E-Tag has to be unique to the whole
120 * page, even if the article itself is the same, so it uses the
121 * complete set of user options. We don't want to use the preference
122 * of a different user on a message just because it wasn't used in
123 * $article. For example give a Chinese interface to a user with
124 * English preferences. That's why we take into account *all* user
125 * options. (r70809 CR)
126 *
127 * @param WikiPage $article
128 * @param ParserOptions $popts
129 * @return string
130 */
131 public function getETag( $article, $popts ) {
132 return 'W/"' . $this->getParserOutputKey( $article,
133 $popts->optionsHash( ParserOptions::allCacheVaryingOptions(), $article->getTitle() ) ) .
134 "--" . $article->getTouched() . '"';
135 }
136
137 /**
138 * Retrieve the ParserOutput from ParserCache, even if it's outdated.
139 * @param WikiPage $article
140 * @param ParserOptions $popts
141 * @return ParserOutput|bool False on failure
142 */
143 public function getDirty( $article, $popts ) {
144 $value = $this->get( $article, $popts, true );
145 return is_object( $value ) ? $value : false;
146 }
147
148 /**
149 * @param WikiPage $article
150 * @param string $metricSuffix
151 */
152 private function incrementStats( $article, $metricSuffix ) {
153 // old style global metric (can be removed once no longer used)
154 wfIncrStats( 'pcache.' . $metricSuffix );
155 // new per content model metric
156 $contentModel = str_replace( '.', '_', $article->getContentModel() );
157 $metricSuffix = str_replace( '.', '_', $metricSuffix );
158 wfIncrStats( 'pcache.' . $contentModel . '.' . $metricSuffix );
159 }
160
161 /**
162 * Generates a key for caching the given article considering
163 * the given parser options.
164 *
165 * @note Which parser options influence the cache key
166 * is controlled via ParserOutput::recordOption() or
167 * ParserOptions::addExtraKey().
168 *
169 * @note Used by Article to provide a unique id for the PoolCounter.
170 * It would be preferable to have this code in get()
171 * instead of having Article looking in our internals.
172 *
173 * @param WikiPage $article
174 * @param ParserOptions $popts
175 * @param int|bool $useOutdated One of the USE constants. For backwards
176 * compatibility, boolean false is treated as USE_CURRENT_ONLY and
177 * boolean true is treated as USE_ANYTHING.
178 * @return bool|mixed|string
179 * @since 1.30 Changed $useOutdated to an int and added the non-boolean values
180 */
181 public function getKey( $article, $popts, $useOutdated = self::USE_ANYTHING ) {
182 if ( is_bool( $useOutdated ) ) {
183 $useOutdated = $useOutdated ? self::USE_ANYTHING : self::USE_CURRENT_ONLY;
184 }
185
186 if ( $popts instanceof User ) {
187 wfWarn( "Use of outdated prototype ParserCache::getKey( &\$article, &\$user )\n" );
188 $popts = ParserOptions::newFromUser( $popts );
189 }
190
191 // Determine the options which affect this article
192 $optionsKey = $this->mMemc->get(
193 $this->getOptionsKey( $article ), BagOStuff::READ_VERIFIED );
194 if ( $optionsKey instanceof CacheTime ) {
195 if ( $useOutdated < self::USE_EXPIRED && $optionsKey->expired( $article->getTouched() ) ) {
196 $this->incrementStats( $article, "miss.expired" );
197 $cacheTime = $optionsKey->getCacheTime();
198 wfDebugLog( "ParserCache",
199 "Parser options key expired, touched " . $article->getTouched()
200 . ", epoch {$this->cacheEpoch}, cached $cacheTime\n" );
201 return false;
202 } elseif ( $useOutdated < self::USE_OUTDATED &&
203 $optionsKey->isDifferentRevision( $article->getLatest() )
204 ) {
205 $this->incrementStats( $article, "miss.revid" );
206 $revId = $article->getLatest();
207 $cachedRevId = $optionsKey->getCacheRevisionId();
208 wfDebugLog( "ParserCache",
209 "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
210 );
211 return false;
212 }
213
214 // $optionsKey->mUsedOptions is set by save() by calling ParserOutput::getUsedOptions()
215 $usedOptions = $optionsKey->mUsedOptions;
216 wfDebug( "Parser cache options found.\n" );
217 } else {
218 if ( $useOutdated < self::USE_ANYTHING ) {
219 return false;
220 }
221 $usedOptions = ParserOptions::allCacheVaryingOptions();
222 }
223
224 return $this->getParserOutputKey(
225 $article,
226 $popts->optionsHash( $usedOptions, $article->getTitle() )
227 );
228 }
229
230 /**
231 * Retrieve the ParserOutput from ParserCache.
232 * false if not found or outdated.
233 *
234 * @param WikiPage|Article $article
235 * @param ParserOptions $popts
236 * @param bool $useOutdated (default false)
237 *
238 * @return ParserOutput|bool False on failure
239 */
240 public function get( $article, $popts, $useOutdated = false ) {
241 $canCache = $article->checkTouched();
242 if ( !$canCache ) {
243 // It's a redirect now
244 return false;
245 }
246
247 $touched = $article->getTouched();
248
249 $parserOutputKey = $this->getKey( $article, $popts,
250 $useOutdated ? self::USE_OUTDATED : self::USE_CURRENT_ONLY
251 );
252 if ( $parserOutputKey === false ) {
253 $this->incrementStats( $article, 'miss.absent' );
254 return false;
255 }
256
257 $casToken = null;
258 /** @var ParserOutput $value */
259 $value = $this->mMemc->get( $parserOutputKey, BagOStuff::READ_VERIFIED );
260 if ( !$value ) {
261 wfDebug( "ParserOutput cache miss.\n" );
262 $this->incrementStats( $article, "miss.absent" );
263 return false;
264 }
265
266 wfDebug( "ParserOutput cache found.\n" );
267
268 $wikiPage = method_exists( $article, 'getPage' )
269 ? $article->getPage()
270 : $article;
271
272 if ( !$useOutdated && $value->expired( $touched ) ) {
273 $this->incrementStats( $article, "miss.expired" );
274 $cacheTime = $value->getCacheTime();
275 wfDebugLog( "ParserCache",
276 "ParserOutput key expired, touched $touched, "
277 . "epoch {$this->cacheEpoch}, cached $cacheTime\n" );
278 $value = false;
279 } elseif ( !$useOutdated && $value->isDifferentRevision( $article->getLatest() ) ) {
280 $this->incrementStats( $article, "miss.revid" );
281 $revId = $article->getLatest();
282 $cachedRevId = $value->getCacheRevisionId();
283 wfDebugLog( "ParserCache",
284 "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
285 );
286 $value = false;
287 } elseif (
288 Hooks::run( 'RejectParserCacheValue', [ $value, $wikiPage, $popts ] ) === false
289 ) {
290 $this->incrementStats( $article, 'miss.rejected' );
291 wfDebugLog( "ParserCache",
292 "ParserOutput key valid, but rejected by RejectParserCacheValue hook handler.\n"
293 );
294 $value = false;
295 } else {
296 $this->incrementStats( $article, "hit" );
297 }
298
299 return $value;
300 }
301
302 /**
303 * @param ParserOutput $parserOutput
304 * @param WikiPage $page
305 * @param ParserOptions $popts
306 * @param string|null $cacheTime TS_MW timestamp when the cache was generated
307 * @param int|null $revId Revision ID that was parsed
308 */
309 public function save(
310 ParserOutput $parserOutput,
311 $page,
312 $popts,
313 $cacheTime = null,
314 $revId = null
315 ) {
316 if ( !$parserOutput->hasText() ) {
317 throw new InvalidArgumentException( 'Attempt to cache a ParserOutput with no text set!' );
318 }
319
320 $expire = $parserOutput->getCacheExpiry();
321 if ( $expire > 0 && !$this->mMemc instanceof EmptyBagOStuff ) {
322 $cacheTime = $cacheTime ?: wfTimestampNow();
323 if ( !$revId ) {
324 $revision = $page->getRevision();
325 $revId = $revision ? $revision->getId() : null;
326 }
327
328 $optionsKey = new CacheTime;
329 $optionsKey->mUsedOptions = $parserOutput->getUsedOptions();
330 $optionsKey->updateCacheExpiry( $expire );
331
332 $optionsKey->setCacheTime( $cacheTime );
333 $parserOutput->setCacheTime( $cacheTime );
334 $optionsKey->setCacheRevisionId( $revId );
335 $parserOutput->setCacheRevisionId( $revId );
336
337 $parserOutputKey = $this->getParserOutputKey( $page,
338 $popts->optionsHash( $optionsKey->mUsedOptions, $page->getTitle() ) );
339
340 // Save the timestamp so that we don't have to load the revision row on view
341 $parserOutput->setTimestamp( $page->getTimestamp() );
342
343 $msg = "Saved in parser cache with key $parserOutputKey" .
344 " and timestamp $cacheTime" .
345 " and revision id $revId" .
346 "\n";
347
348 $parserOutput->mText .= "\n<!-- $msg -->\n";
349 wfDebug( $msg );
350
351 // Save the parser output
352 $this->mMemc->set( $parserOutputKey, $parserOutput, $expire );
353
354 // ...and its pointer
355 $this->mMemc->set( $this->getOptionsKey( $page ), $optionsKey, $expire );
356
357 Hooks::run(
358 'ParserCacheSaveComplete',
359 [ $this, $parserOutput, $page->getTitle(), $popts, $revId ]
360 );
361 } elseif ( $expire <= 0 ) {
362 wfDebug( "Parser output was marked as uncacheable and has not been saved.\n" );
363 }
364 }
365
366 /**
367 * Get the backend BagOStuff instance that
368 * powers the parser cache
369 *
370 * @since 1.30
371 * @return BagOStuff
372 */
373 public function getCacheStorage() {
374 return $this->mMemc;
375 }
376 }