Update git submodules
[mediawiki.git] / includes / parser / CacheTime.php
blob75242691bbd169a64049fa3341a583b7db7a715e
1 <?php
2 /**
3 * Parser cache specific expiry check.
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.
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.
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
20 * @file
21 * @ingroup Parser
24 use MediaWiki\Json\JsonUnserializable;
25 use MediaWiki\Json\JsonUnserializableTrait;
26 use MediaWiki\Json\JsonUnserializer;
27 use MediaWiki\MainConfigNames;
28 use MediaWiki\MediaWikiServices;
29 use MediaWiki\Parser\ParserCacheMetadata;
30 use MediaWiki\Utils\MWTimestamp;
31 use Wikimedia\Reflection\GhostFieldAccessTrait;
33 /**
34 * Parser cache specific expiry check.
36 * @ingroup Parser
38 class CacheTime implements ParserCacheMetadata, JsonUnserializable {
39 use GhostFieldAccessTrait;
40 use JsonUnserializableTrait;
42 /**
43 * @var true[] ParserOptions which have been taken into account
44 * to produce output, option names stored in array keys.
46 protected $mParseUsedOptions = [];
48 /**
49 * @var string|int TS_MW timestamp when this object was generated, or -1 for not cacheable. Used
50 * in ParserCache.
52 protected $mCacheTime = '';
54 /**
55 * @var int|null Seconds after which the object should expire, use 0 for not cacheable. Used in
56 * ParserCache.
58 protected $mCacheExpiry = null;
60 /**
61 * @var int|null Revision ID that was parsed
63 protected $mCacheRevisionId = null;
65 /**
66 * @return string|int TS_MW timestamp
68 public function getCacheTime() {
69 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
70 if ( $this->mCacheTime === '' ) {
71 $this->mCacheTime = MWTimestamp::now();
73 return $this->mCacheTime;
76 /**
77 * setCacheTime() sets the timestamp expressing when the page has been rendered.
78 * This does not control expiry, see updateCacheExpiry() for that!
79 * @param string $t TS_MW timestamp
80 * @return string
82 public function setCacheTime( $t ) {
83 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
84 if ( is_string( $t ) && $t !== '-1' ) {
85 $t = MWTimestamp::convert( TS_MW, $t );
88 if ( $t === -1 || $t === '-1' ) {
89 wfDeprecatedMsg( __METHOD__ . ' called with -1 as an argument', '1.36' );
92 return wfSetVar( $this->mCacheTime, $t );
95 /**
96 * @since 1.23
97 * @return int|null Revision id, if any was set
99 public function getCacheRevisionId(): ?int {
100 return $this->mCacheRevisionId;
104 * @since 1.23
105 * @param int|null $id Revision ID
107 public function setCacheRevisionId( $id ) {
108 $this->mCacheRevisionId = $id;
112 * Sets the number of seconds after which this object should expire.
114 * This value is used with the ParserCache.
115 * If called with a value greater than the value provided at any previous call,
116 * the new call has no effect. The value returned by getCacheExpiry is smaller
117 * or equal to the smallest number that was provided as an argument to
118 * updateCacheExpiry().
120 * Avoid using 0 if at all possible. Consider JavaScript for highly dynamic content.
122 * NOTE: Beware that reducing the TTL for reasons that do not relate to "dynamic content",
123 * may have the side-effect of incurring more RefreshLinksJob executions.
124 * See also WikiPage::triggerOpportunisticLinksUpdate.
126 * @param int $seconds
128 public function updateCacheExpiry( $seconds ) {
129 $seconds = (int)$seconds;
131 if ( $this->mCacheExpiry === null || $this->mCacheExpiry > $seconds ) {
132 $this->mCacheExpiry = $seconds;
137 * Returns the number of seconds after which this object should expire.
138 * This method is used by ParserCache to determine how long the ParserOutput can be cached.
139 * The timestamp of expiry can be calculated by adding getCacheExpiry() to getCacheTime().
140 * The value returned by getCacheExpiry is smaller or equal to the smallest number
141 * that was provided to a call of updateCacheExpiry(), and smaller or equal to the
142 * value of $wgParserCacheExpireTime.
143 * @return int
145 public function getCacheExpiry(): int {
146 $parserCacheExpireTime = MediaWikiServices::getInstance()->getMainConfig()
147 ->get( MainConfigNames::ParserCacheExpireTime );
149 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
150 if ( $this->mCacheTime !== '' && $this->mCacheTime < 0 ) {
151 return 0;
154 $expire = $this->mCacheExpiry;
156 if ( $expire === null ) {
157 $expire = $parserCacheExpireTime;
158 } else {
159 $expire = min( $expire, $parserCacheExpireTime );
162 if ( $expire <= 0 ) {
163 return 0; // not cacheable
164 } else {
165 return $expire;
170 * @return bool
172 public function isCacheable() {
173 return $this->getCacheExpiry() > 0;
177 * Return true if this cached output object predates the global or
178 * per-article cache invalidation timestamps, or if it comes from
179 * an incompatible older version.
181 * @param string $touched The affected article's last touched timestamp
182 * @return bool
184 public function expired( $touched ) {
185 $cacheEpoch = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::CacheEpoch );
187 $expiry = MWTimestamp::convert( TS_MW, MWTimestamp::time() - $this->getCacheExpiry() );
189 return !$this->isCacheable() // parser says it's not cacheable
190 || $this->getCacheTime() < $touched
191 || $this->getCacheTime() <= $cacheEpoch
192 || $this->getCacheTime() < $expiry; // expiry period has passed
196 * Return true if this cached output object is for a different revision of
197 * the page.
199 * @todo We always return false if $this->getCacheRevisionId() is null;
200 * this prevents invalidating the whole parser cache when this change is
201 * deployed. Someday that should probably be changed.
203 * @since 1.23
204 * @param int $id The affected article's current revision id
205 * @return bool
207 public function isDifferentRevision( $id ) {
208 $cached = $this->getCacheRevisionId();
209 return $cached !== null && $id !== $cached;
213 * Returns the options from its ParserOptions which have been taken
214 * into account to produce the output.
215 * @since 1.36
216 * @return string[]
218 public function getUsedOptions(): array {
219 return array_keys( $this->mParseUsedOptions );
223 * Tags a parser option for use in the cache key for this parser output.
224 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
225 * The information gathered here is available via getUsedOptions(),
226 * and is used by ParserCache::save().
228 * @see ParserCache::getMetadata
229 * @see ParserCache::save
230 * @see ParserOptions::addExtraKey
231 * @see ParserOptions::optionsHash
232 * @param string $option
234 public function recordOption( string $option ) {
235 $this->mParseUsedOptions[$option] = true;
239 * Tags a list of parser option names for use in the cache key for this parser output.
241 * @see recordOption()
242 * @param string[] $options
244 public function recordOptions( array $options ) {
245 $this->mParseUsedOptions = array_merge(
246 $this->mParseUsedOptions,
247 array_fill_keys( $options, true )
252 * Returns a JSON serializable structure representing this CacheTime instance.
253 * @see newFromJson()
255 * @return array
257 protected function toJsonArray(): array {
258 // WARNING: When changing how this class is serialized, follow the instructions
259 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
261 return [
262 'ParseUsedOptions' => $this->mParseUsedOptions,
263 'CacheExpiry' => $this->mCacheExpiry,
264 'CacheTime' => $this->mCacheTime,
265 'CacheRevisionId' => $this->mCacheRevisionId,
269 public static function newFromJsonArray( JsonUnserializer $unserializer, array $json ) {
270 $cacheTime = new CacheTime();
271 $cacheTime->initFromJson( $unserializer, $json );
272 return $cacheTime;
276 * Initialize member fields from an array returned by jsonSerialize().
277 * @param JsonUnserializer $unserializer
278 * @param array $jsonData
280 protected function initFromJson( JsonUnserializer $unserializer, array $jsonData ) {
281 // WARNING: When changing how this class is serialized, follow the instructions
282 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
284 if ( array_key_exists( 'AccessedOptions', $jsonData ) ) {
285 // Backwards compatibility for ParserOutput
286 $this->mParseUsedOptions = $jsonData['AccessedOptions'] ?: [];
287 } elseif ( array_key_exists( 'UsedOptions', $jsonData ) ) {
288 // Backwards compatibility
289 $this->recordOptions( $jsonData['UsedOptions'] ?: [] );
290 } else {
291 $this->mParseUsedOptions = $jsonData['ParseUsedOptions'] ?: [];
293 $this->mCacheExpiry = $jsonData['CacheExpiry'];
294 $this->mCacheTime = $jsonData['CacheTime'];
295 $this->mCacheRevisionId = $jsonData['CacheRevisionId'];
298 public function __wakeup() {
299 // Backwards compatibility, pre 1.36
300 $priorOptions = $this->getGhostFieldValue( 'mUsedOptions' );
301 if ( $priorOptions ) {
302 $this->recordOptions( $priorOptions );
306 public function __get( $name ) {
307 if ( property_exists( get_called_class(), $name ) ) {
308 // Direct access to a public property, deprecated.
309 wfDeprecatedMsg( "CacheTime::{$name} public read access deprecated", '1.38' );
310 return $this->$name;
311 } elseif ( property_exists( $this, $name ) ) {
312 // Dynamic property access, deprecated.
313 wfDeprecatedMsg( "CacheTime::{$name} dynamic property read access deprecated", '1.38' );
314 return $this->$name;
315 } else {
316 trigger_error( "Inaccessible property via __set(): $name" );
317 return null;
321 public function __set( $name, $value ) {
322 if ( property_exists( get_called_class(), $name ) ) {
323 // Direct access to a public property, deprecated.
324 wfDeprecatedMsg( "CacheTime::$name public write access deprecated", '1.38' );
325 $this->$name = $value;
326 } else {
327 // Dynamic property access, deprecated.
328 wfDeprecatedMsg( "CacheTime::$name dynamic property write access deprecated", '1.38' );
329 $this->$name = $value;