Merge "Ensure that User::getId() returns int"
[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 /** @var BagOStuff */
30 private $mMemc;
31 /**
32 * Get an instance of this object
33 *
34 * @return ParserCache
35 */
36 public static function singleton() {
37 static $instance;
38 if ( !isset( $instance ) ) {
39 global $parserMemc;
40 $instance = new ParserCache( $parserMemc );
41 }
42 return $instance;
43 }
44
45 /**
46 * Setup a cache pathway with a given back-end storage mechanism.
47 *
48 * This class use an invalidation strategy that is compatible with
49 * MultiWriteBagOStuff in async replication mode.
50 *
51 * @param BagOStuff $memCached
52 * @throws MWException
53 */
54 protected function __construct( BagOStuff $memCached ) {
55 $this->mMemc = $memCached;
56 }
57
58 /**
59 * @param WikiPage $article
60 * @param string $hash
61 * @return mixed|string
62 */
63 protected function getParserOutputKey( $article, $hash ) {
64 global $wgRequest;
65
66 // idhash seem to mean 'page id' + 'rendering hash' (r3710)
67 $pageid = $article->getId();
68 $renderkey = (int)( $wgRequest->getVal( 'action' ) == 'render' );
69
70 $key = wfMemcKey( 'pcache', 'idhash', "{$pageid}-{$renderkey}!{$hash}" );
71 return $key;
72 }
73
74 /**
75 * @param WikiPage $article
76 * @return mixed|string
77 */
78 protected function getOptionsKey( $article ) {
79 $pageid = $article->getId();
80 return wfMemcKey( 'pcache', 'idoptions', "{$pageid}" );
81 }
82
83 /**
84 * Provides an E-Tag suitable for the whole page. Note that $article
85 * is just the main wikitext. The E-Tag has to be unique to the whole
86 * page, even if the article itself is the same, so it uses the
87 * complete set of user options. We don't want to use the preference
88 * of a different user on a message just because it wasn't used in
89 * $article. For example give a Chinese interface to a user with
90 * English preferences. That's why we take into account *all* user
91 * options. (r70809 CR)
92 *
93 * @param WikiPage $article
94 * @param ParserOptions $popts
95 * @return string
96 */
97 public function getETag( $article, $popts ) {
98 return 'W/"' . $this->getParserOutputKey( $article,
99 $popts->optionsHash( ParserOptions::legacyOptions(), $article->getTitle() ) ) .
100 "--" . $article->getTouched() . '"';
101 }
102
103 /**
104 * Retrieve the ParserOutput from ParserCache, even if it's outdated.
105 * @param WikiPage $article
106 * @param ParserOptions $popts
107 * @return ParserOutput|bool False on failure
108 */
109 public function getDirty( $article, $popts ) {
110 $value = $this->get( $article, $popts, true );
111 return is_object( $value ) ? $value : false;
112 }
113
114 /**
115 * Generates a key for caching the given article considering
116 * the given parser options.
117 *
118 * @note Which parser options influence the cache key
119 * is controlled via ParserOutput::recordOption() or
120 * ParserOptions::addExtraKey().
121 *
122 * @note Used by Article to provide a unique id for the PoolCounter.
123 * It would be preferable to have this code in get()
124 * instead of having Article looking in our internals.
125 *
126 * @todo Document parameter $useOutdated
127 *
128 * @param WikiPage $article
129 * @param ParserOptions $popts
130 * @param bool $useOutdated (default true)
131 * @return bool|mixed|string
132 */
133 public function getKey( $article, $popts, $useOutdated = true ) {
134 global $wgCacheEpoch;
135
136 if ( $popts instanceof User ) {
137 wfWarn( "Use of outdated prototype ParserCache::getKey( &\$article, &\$user )\n" );
138 $popts = ParserOptions::newFromUser( $popts );
139 }
140
141 // Determine the options which affect this article
142 $casToken = null;
143 $optionsKey = $this->mMemc->get(
144 $this->getOptionsKey( $article ), $casToken, BagOStuff::READ_VERIFIED );
145 if ( $optionsKey instanceof CacheTime ) {
146 if ( !$useOutdated && $optionsKey->expired( $article->getTouched() ) ) {
147 wfIncrStats( "pcache.miss.expired" );
148 $cacheTime = $optionsKey->getCacheTime();
149 wfDebug( "Parser options key expired, touched " . $article->getTouched()
150 . ", epoch $wgCacheEpoch, cached $cacheTime\n" );
151 return false;
152 } elseif ( $optionsKey->isDifferentRevision( $article->getLatest() ) ) {
153 wfIncrStats( "pcache.miss.revid" );
154 $revId = $article->getLatest();
155 $cachedRevId = $optionsKey->getCacheRevisionId();
156 wfDebug( "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n" );
157 return false;
158 }
159
160 // $optionsKey->mUsedOptions is set by save() by calling ParserOutput::getUsedOptions()
161 $usedOptions = $optionsKey->mUsedOptions;
162 wfDebug( "Parser cache options found.\n" );
163 } else {
164 if ( !$useOutdated ) {
165 return false;
166 }
167 $usedOptions = ParserOptions::legacyOptions();
168 }
169
170 return $this->getParserOutputKey(
171 $article,
172 $popts->optionsHash( $usedOptions, $article->getTitle() )
173 );
174 }
175
176 /**
177 * Retrieve the ParserOutput from ParserCache.
178 * false if not found or outdated.
179 *
180 * @param WikiPage|Article $article
181 * @param ParserOptions $popts
182 * @param bool $useOutdated (default false)
183 *
184 * @return ParserOutput|bool False on failure
185 */
186 public function get( $article, $popts, $useOutdated = false ) {
187 global $wgCacheEpoch;
188
189 $canCache = $article->checkTouched();
190 if ( !$canCache ) {
191 // It's a redirect now
192 return false;
193 }
194
195 $touched = $article->getTouched();
196
197 $parserOutputKey = $this->getKey( $article, $popts, $useOutdated );
198 if ( $parserOutputKey === false ) {
199 wfIncrStats( 'pcache.miss.absent' );
200 return false;
201 }
202
203 $casToken = null;
204 $value = $this->mMemc->get( $parserOutputKey, $casToken, BagOStuff::READ_VERIFIED );
205 if ( !$value ) {
206 wfDebug( "ParserOutput cache miss.\n" );
207 wfIncrStats( "pcache.miss.absent" );
208 return false;
209 }
210
211 wfDebug( "ParserOutput cache found.\n" );
212
213 // The edit section preference may not be the appropiate one in
214 // the ParserOutput, as we are not storing it in the parsercache
215 // key. Force it here. See bug 31445.
216 $value->setEditSectionTokens( $popts->getEditSection() );
217
218 $wikiPage = method_exists( $article, 'getPage' )
219 ? $article->getPage()
220 : $article;
221
222 if ( !$useOutdated && $value->expired( $touched ) ) {
223 wfIncrStats( "pcache.miss.expired" );
224 $cacheTime = $value->getCacheTime();
225 wfDebug( "ParserOutput key expired, touched $touched, "
226 . "epoch $wgCacheEpoch, cached $cacheTime\n" );
227 $value = false;
228 } elseif ( $value->isDifferentRevision( $article->getLatest() ) ) {
229 wfIncrStats( "pcache.miss.revid" );
230 $revId = $article->getLatest();
231 $cachedRevId = $value->getCacheRevisionId();
232 wfDebug(
233 "ParserOutput key is for an old revision, latest $revId, cached $cachedRevId\n"
234 );
235 $value = false;
236 } elseif (
237 Hooks::run( 'RejectParserCacheValue', [ $value, $wikiPage, $popts ] ) === false
238 ) {
239 wfIncrStats( 'pcache.miss.rejected' );
240 wfDebug(
241 "ParserOutput key valid, but rejected by RejectParserCacheValue hook handler.\n"
242 );
243 $value = false;
244 } else {
245 wfIncrStats( "pcache.hit" );
246 }
247
248 return $value;
249 }
250
251 /**
252 * @param ParserOutput $parserOutput
253 * @param WikiPage $page
254 * @param ParserOptions $popts
255 * @param string $cacheTime Time when the cache was generated
256 * @param int $revId Revision ID that was parsed
257 */
258 public function save( $parserOutput, $page, $popts, $cacheTime = null, $revId = null ) {
259 $expire = $parserOutput->getCacheExpiry();
260 if ( $expire > 0 ) {
261 $cacheTime = $cacheTime ?: wfTimestampNow();
262 if ( !$revId ) {
263 $revision = $page->getRevision();
264 $revId = $revision ? $revision->getId() : null;
265 }
266
267 $optionsKey = new CacheTime;
268 $optionsKey->mUsedOptions = $parserOutput->getUsedOptions();
269 $optionsKey->updateCacheExpiry( $expire );
270
271 $optionsKey->setCacheTime( $cacheTime );
272 $parserOutput->setCacheTime( $cacheTime );
273 $optionsKey->setCacheRevisionId( $revId );
274 $parserOutput->setCacheRevisionId( $revId );
275
276 $parserOutputKey = $this->getParserOutputKey( $page,
277 $popts->optionsHash( $optionsKey->mUsedOptions, $page->getTitle() ) );
278
279 // Save the timestamp so that we don't have to load the revision row on view
280 $parserOutput->setTimestamp( $page->getTimestamp() );
281
282 $msg = "Saved in parser cache with key $parserOutputKey" .
283 " and timestamp $cacheTime" .
284 " and revision id $revId" .
285 "\n";
286
287 $parserOutput->mText .= "\n<!-- $msg -->\n";
288 wfDebug( $msg );
289
290 // Save the parser output
291 $this->mMemc->set( $parserOutputKey, $parserOutput, $expire );
292
293 // ...and its pointer
294 $this->mMemc->set( $this->getOptionsKey( $page ), $optionsKey, $expire );
295
296 Hooks::run(
297 'ParserCacheSaveComplete',
298 [ $this, $parserOutput, $page->getTitle(), $popts, $revId ]
299 );
300 } else {
301 wfDebug( "Parser output was marked as uncacheable and has not been saved.\n" );
302 }
303 }
304 }