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