Merge "docs: Fix typo"
[mediawiki.git] / includes / parser / CacheTime.php
blobcf7c7ac60938ddc30bc277fcbd05447b3dcf70a8
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 namespace MediaWiki\Parser;
26 use MediaWiki\Json\JsonDeserializable;
27 use MediaWiki\Json\JsonDeserializableTrait;
28 use MediaWiki\Json\JsonDeserializer;
29 use MediaWiki\MainConfigNames;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Utils\MWTimestamp;
32 use Wikimedia\Reflection\GhostFieldAccessTrait;
34 /**
35 * Parser cache specific expiry check.
37 * @ingroup Parser
39 class CacheTime implements ParserCacheMetadata, JsonDeserializable {
40 use GhostFieldAccessTrait;
41 use JsonDeserializableTrait;
43 /**
44 * @var true[] ParserOptions which have been taken into account
45 * to produce output, option names stored in array keys.
47 protected $mParseUsedOptions = [];
49 /**
50 * @var string|int TS_MW timestamp when this object was generated, or -1 for not cacheable. Used
51 * in ParserCache.
53 protected $mCacheTime = '';
55 /**
56 * @var int|null Seconds after which the object should expire, use 0 for not cacheable. Used in
57 * ParserCache.
59 protected $mCacheExpiry = null;
61 /**
62 * @var int|null Revision ID that was parsed
64 protected $mCacheRevisionId = null;
66 /**
67 * @return string|int TS_MW timestamp
69 public function getCacheTime() {
70 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
71 if ( $this->mCacheTime === '' ) {
72 $this->mCacheTime = MWTimestamp::now();
74 return $this->mCacheTime;
77 /**
78 * @return bool true if a cache time has been set
80 public function hasCacheTime(): bool {
81 return $this->mCacheTime !== '';
84 /**
85 * setCacheTime() sets the timestamp expressing when the page has been rendered.
86 * This does not control expiry, see updateCacheExpiry() for that!
87 * @param string $t TS_MW timestamp
88 * @return string
90 public function setCacheTime( $t ) {
91 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
92 if ( is_string( $t ) && $t !== '-1' ) {
93 $t = MWTimestamp::convert( TS_MW, $t );
96 if ( $t === -1 || $t === '-1' ) {
97 wfDeprecatedMsg( __METHOD__ . ' called with -1 as an argument', '1.36' );
100 return wfSetVar( $this->mCacheTime, $t );
104 * @since 1.23
105 * @return int|null Revision id, if any was set
107 public function getCacheRevisionId(): ?int {
108 return $this->mCacheRevisionId;
112 * @since 1.23
113 * @param int|null $id Revision ID
115 public function setCacheRevisionId( $id ) {
116 $this->mCacheRevisionId = $id;
120 * Sets the number of seconds after which this object should expire.
122 * This value is used with the ParserCache.
123 * If called with a value greater than the value provided at any previous call,
124 * the new call has no effect. The value returned by getCacheExpiry is smaller
125 * or equal to the smallest number that was provided as an argument to
126 * updateCacheExpiry().
128 * Avoid using 0 if at all possible. Consider JavaScript for highly dynamic content.
130 * NOTE: Beware that reducing the TTL for reasons that do not relate to "dynamic content",
131 * may have the side-effect of incurring more RefreshLinksJob executions.
132 * See also WikiPage::triggerOpportunisticLinksUpdate.
134 * @param int $seconds
136 public function updateCacheExpiry( $seconds ) {
137 $seconds = (int)$seconds;
139 if ( $this->mCacheExpiry === null || $this->mCacheExpiry > $seconds ) {
140 $this->mCacheExpiry = $seconds;
145 * Returns the number of seconds after which this object should expire.
146 * This method is used by ParserCache to determine how long the ParserOutput can be cached.
147 * The timestamp of expiry can be calculated by adding getCacheExpiry() to getCacheTime().
148 * The value returned by getCacheExpiry is smaller or equal to the smallest number
149 * that was provided to a call of updateCacheExpiry(), and smaller or equal to the
150 * value of $wgParserCacheExpireTime.
152 public function getCacheExpiry(): int {
153 $parserCacheExpireTime = MediaWikiServices::getInstance()->getMainConfig()
154 ->get( MainConfigNames::ParserCacheExpireTime );
156 // NOTE: keep support for undocumented used of -1 to mean "not cacheable".
157 if ( $this->mCacheTime !== '' && $this->mCacheTime < 0 ) {
158 return 0;
161 $expire = min( $this->mCacheExpiry ?? $parserCacheExpireTime, $parserCacheExpireTime );
162 return $expire > 0 ? $expire : 0;
166 * @return bool
168 public function isCacheable() {
169 return $this->getCacheExpiry() > 0;
173 * Return true if this cached output object predates the global or
174 * per-article cache invalidation timestamps, or if it comes from
175 * an incompatible older version.
177 * @param string $touched The affected article's last touched timestamp
178 * @return bool
180 public function expired( $touched ) {
181 $cacheEpoch = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::CacheEpoch );
183 $expiry = MWTimestamp::convert( TS_MW, MWTimestamp::time() - $this->getCacheExpiry() );
185 return !$this->isCacheable() // parser says it's not cacheable
186 || $this->getCacheTime() < $touched
187 || $this->getCacheTime() <= $cacheEpoch
188 || $this->getCacheTime() < $expiry; // expiry period has passed
192 * Return true if this cached output object is for a different revision of
193 * the page.
195 * @todo We always return false if $this->getCacheRevisionId() is null;
196 * this prevents invalidating the whole parser cache when this change is
197 * deployed. Someday that should probably be changed.
199 * @since 1.23
200 * @param int $id The affected article's current revision id
201 * @return bool
203 public function isDifferentRevision( $id ) {
204 $cached = $this->getCacheRevisionId();
205 return $cached !== null && $id !== $cached;
209 * Returns the options from its ParserOptions which have been taken
210 * into account to produce the output.
211 * @since 1.36
212 * @return string[]
214 public function getUsedOptions(): array {
215 return array_keys( $this->mParseUsedOptions );
219 * Tags a parser option for use in the cache key for this parser output.
220 * Registered as a watcher at ParserOptions::registerWatcher() by Parser::clearState().
221 * The information gathered here is available via getUsedOptions(),
222 * and is used by ParserCache::save().
224 * @see ParserCache::getMetadata
225 * @see ParserCache::save
226 * @see ParserOptions::addExtraKey
227 * @see ParserOptions::optionsHash
228 * @param string $option
230 public function recordOption( string $option ) {
231 $this->mParseUsedOptions[$option] = true;
235 * Tags a list of parser option names for use in the cache key for this parser output.
237 * @see recordOption()
238 * @param string[] $options
240 public function recordOptions( array $options ) {
241 $this->mParseUsedOptions = array_merge(
242 $this->mParseUsedOptions,
243 array_fill_keys( $options, true )
248 * Returns a JSON serializable structure representing this CacheTime instance.
249 * @see newFromJson()
251 * @return array
253 protected function toJsonArray(): array {
254 // WARNING: When changing how this class is serialized, follow the instructions
255 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
257 return [
258 'ParseUsedOptions' => $this->mParseUsedOptions,
259 'CacheExpiry' => $this->mCacheExpiry,
260 'CacheTime' => $this->mCacheTime,
261 'CacheRevisionId' => $this->mCacheRevisionId,
265 public static function newFromJsonArray( JsonDeserializer $deserializer, array $json ) {
266 $cacheTime = new CacheTime();
267 $cacheTime->initFromJson( $deserializer, $json );
268 return $cacheTime;
272 * Initialize member fields from an array returned by jsonSerialize().
273 * @param JsonDeserializer $deserializer Unused
274 * @param array $jsonData
276 protected function initFromJson( JsonDeserializer $deserializer, array $jsonData ) {
277 // WARNING: When changing how this class is serialized, follow the instructions
278 // at <https://www.mediawiki.org/wiki/Manual:Parser_cache/Serialization_compatibility>!
280 if ( array_key_exists( 'AccessedOptions', $jsonData ) ) {
281 // Backwards compatibility for ParserOutput
282 $this->mParseUsedOptions = $jsonData['AccessedOptions'] ?: [];
283 } elseif ( array_key_exists( 'UsedOptions', $jsonData ) ) {
284 // Backwards compatibility
285 $this->recordOptions( $jsonData['UsedOptions'] ?: [] );
286 } else {
287 $this->mParseUsedOptions = $jsonData['ParseUsedOptions'] ?: [];
289 $this->mCacheExpiry = $jsonData['CacheExpiry'];
290 $this->mCacheTime = $jsonData['CacheTime'];
291 $this->mCacheRevisionId = $jsonData['CacheRevisionId'];
294 public function __wakeup() {
295 // Backwards compatibility, pre 1.36
296 $priorOptions = $this->getGhostFieldValue( 'mUsedOptions' );
297 if ( $priorOptions ) {
298 $this->recordOptions( $priorOptions );
302 public function __get( $name ) {
303 if ( property_exists( get_called_class(), $name ) ) {
304 // Direct access to a public property, deprecated.
305 wfDeprecatedMsg( "CacheTime::{$name} public read access deprecated", '1.38' );
306 return $this->$name;
307 } elseif ( property_exists( $this, $name ) ) {
308 // Dynamic property access, deprecated.
309 wfDeprecatedMsg( "CacheTime::{$name} dynamic property read access deprecated", '1.38' );
310 return $this->$name;
311 } else {
312 trigger_error( "Inaccessible property via __set(): $name" );
313 return null;
317 public function __set( $name, $value ) {
318 if ( property_exists( get_called_class(), $name ) ) {
319 // Direct access to a public property, deprecated.
320 wfDeprecatedMsg( "CacheTime::$name public write access deprecated", '1.38' );
321 $this->$name = $value;
322 } else {
323 // Dynamic property access, deprecated.
324 wfDeprecatedMsg( "CacheTime::$name dynamic property write access deprecated", '1.38' );
325 $this->$name = $value;
330 /** @deprecated class alias since 1.43 */
331 class_alias( CacheTime::class, 'CacheTime' );