Merge "Rewrite pref cleanup script"
[lhc/web/wiklou.git] / includes / cache / CacheHelper.php
1 <?php
2 /**
3 * Cache of various elements in a single cache entry.
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 * @license GNU GPL v2 or later
22 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
23 */
24
25 /**
26 * Interface for all classes implementing CacheHelper functionality.
27 *
28 * @since 1.20
29 */
30 interface ICacheHelper {
31 /**
32 * Sets if the cache should be enabled or not.
33 *
34 * @since 1.20
35 * @param bool $cacheEnabled
36 */
37 function setCacheEnabled( $cacheEnabled );
38
39 /**
40 * Initializes the caching.
41 * Should be called before the first time anything is added via addCachedHTML.
42 *
43 * @since 1.20
44 *
45 * @param int|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
46 * @param bool|null $cacheEnabled Sets if the cache should be enabled or not.
47 */
48 function startCache( $cacheExpiry = null, $cacheEnabled = null );
49
50 /**
51 * Get a cached value if available or compute it if not and then cache it if possible.
52 * The provided $computeFunction is only called when the computation needs to happen
53 * and should return a result value. $args are arguments that will be passed to the
54 * compute function when called.
55 *
56 * @since 1.20
57 *
58 * @param callable $computeFunction
59 * @param array|mixed $args
60 * @param string|null $key
61 *
62 * @return mixed
63 */
64 function getCachedValue( $computeFunction, $args = [], $key = null );
65
66 /**
67 * Saves the HTML to the cache in case it got recomputed.
68 * Should be called after the last time anything is added via addCachedHTML.
69 *
70 * @since 1.20
71 */
72 function saveCache();
73
74 /**
75 * Sets the time to live for the cache, in seconds or a unix timestamp
76 * indicating the point of expiry...
77 *
78 * @since 1.20
79 *
80 * @param int $cacheExpiry
81 */
82 function setExpiry( $cacheExpiry );
83 }
84
85 use MediaWiki\MediaWikiServices;
86
87 /**
88 * Helper class for caching various elements in a single cache entry.
89 *
90 * To get a cached value or compute it, use getCachedValue like this:
91 * $this->getCachedValue( $callback );
92 *
93 * To add HTML that should be cached, use addCachedHTML like this:
94 * $this->addCachedHTML( $callback );
95 *
96 * The callback function is only called when needed, so do all your expensive
97 * computations here. This function should returns the HTML to be cached.
98 * It should not add anything to the PageOutput object!
99 *
100 * Before the first addCachedHTML call, you should call $this->startCache();
101 * After adding the last HTML that should be cached, call $this->saveCache();
102 *
103 * @since 1.20
104 */
105 class CacheHelper implements ICacheHelper {
106 /**
107 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
108 *
109 * @since 1.20
110 * @var int
111 */
112 protected $cacheExpiry = 3600;
113
114 /**
115 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
116 * If not cached already, then the newly computed chunks are added here,
117 * if it as cached already, chunks are removed from this list as they are needed.
118 *
119 * @since 1.20
120 * @var array
121 */
122 protected $cachedChunks;
123
124 /**
125 * Indicates if the to be cached content was already cached.
126 * Null if this information is not available yet.
127 *
128 * @since 1.20
129 * @var bool|null
130 */
131 protected $hasCached = null;
132
133 /**
134 * If the cache is enabled or not.
135 *
136 * @since 1.20
137 * @var bool
138 */
139 protected $cacheEnabled = true;
140
141 /**
142 * Function that gets called when initialization is done.
143 *
144 * @since 1.20
145 * @var callable
146 */
147 protected $onInitHandler = false;
148
149 /**
150 * Elements to build a cache key with.
151 *
152 * @since 1.20
153 * @var array
154 */
155 protected $cacheKey = [];
156
157 /**
158 * Sets if the cache should be enabled or not.
159 *
160 * @since 1.20
161 * @param bool $cacheEnabled
162 */
163 public function setCacheEnabled( $cacheEnabled ) {
164 $this->cacheEnabled = $cacheEnabled;
165 }
166
167 /**
168 * Initializes the caching.
169 * Should be called before the first time anything is added via addCachedHTML.
170 *
171 * @since 1.20
172 *
173 * @param int|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
174 * @param bool|null $cacheEnabled Sets if the cache should be enabled or not.
175 */
176 public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
177 if ( is_null( $this->hasCached ) ) {
178 if ( !is_null( $cacheExpiry ) ) {
179 $this->cacheExpiry = $cacheExpiry;
180 }
181
182 if ( !is_null( $cacheEnabled ) ) {
183 $this->setCacheEnabled( $cacheEnabled );
184 }
185
186 $this->initCaching();
187 }
188 }
189
190 /**
191 * Returns a message that notifies the user he/she is looking at
192 * a cached version of the page, including a refresh link.
193 *
194 * @since 1.20
195 *
196 * @param IContextSource $context
197 * @param bool $includePurgeLink
198 *
199 * @return string
200 */
201 public function getCachedNotice( IContextSource $context, $includePurgeLink = true ) {
202 if ( $this->cacheExpiry < 86400 * 3650 ) {
203 $message = $context->msg(
204 'cachedspecial-viewing-cached-ttl',
205 $context->getLanguage()->formatDuration( $this->cacheExpiry )
206 )->escaped();
207 } else {
208 $message = $context->msg(
209 'cachedspecial-viewing-cached-ts'
210 )->escaped();
211 }
212
213 if ( $includePurgeLink ) {
214 $refreshArgs = $context->getRequest()->getQueryValues();
215 unset( $refreshArgs['title'] );
216 $refreshArgs['action'] = 'purge';
217
218 $subPage = $context->getTitle()->getFullText();
219 $subPage = explode( '/', $subPage, 2 );
220 $subPage = count( $subPage ) > 1 ? $subPage[1] : false;
221
222 $message .= ' ' . MediaWikiServices::getInstance()->getLinkRenderer()->makeLink(
223 $context->getTitle( $subPage ),
224 $context->msg( 'cachedspecial-refresh-now' )->text(),
225 [],
226 $refreshArgs
227 );
228 }
229
230 return $message;
231 }
232
233 /**
234 * Initializes the caching if not already done so.
235 * Should be called before any of the caching functionality is used.
236 *
237 * @since 1.20
238 */
239 protected function initCaching() {
240 if ( $this->cacheEnabled && is_null( $this->hasCached ) ) {
241 $cachedChunks = wfGetCache( CACHE_ANYTHING )->get( $this->getCacheKeyString() );
242
243 $this->hasCached = is_array( $cachedChunks );
244 $this->cachedChunks = $this->hasCached ? $cachedChunks : [];
245
246 if ( $this->onInitHandler !== false ) {
247 call_user_func( $this->onInitHandler, $this->hasCached );
248 }
249 }
250 }
251
252 /**
253 * Get a cached value if available or compute it if not and then cache it if possible.
254 * The provided $computeFunction is only called when the computation needs to happen
255 * and should return a result value. $args are arguments that will be passed to the
256 * compute function when called.
257 *
258 * @since 1.20
259 *
260 * @param callable $computeFunction
261 * @param array|mixed $args
262 * @param string|null $key
263 *
264 * @return mixed
265 */
266 public function getCachedValue( $computeFunction, $args = [], $key = null ) {
267 $this->initCaching();
268
269 if ( $this->cacheEnabled && $this->hasCached ) {
270 $value = null;
271
272 if ( is_null( $key ) ) {
273 $itemKey = array_keys( array_slice( $this->cachedChunks, 0, 1 ) );
274 $itemKey = array_shift( $itemKey );
275
276 if ( !is_int( $itemKey ) ) {
277 wfWarn( "Attempted to get item with non-numeric key while " .
278 "the next item in the queue has a key ($itemKey) in " . __METHOD__ );
279 } elseif ( is_null( $itemKey ) ) {
280 wfWarn( "Attempted to get an item while the queue is empty in " . __METHOD__ );
281 } else {
282 $value = array_shift( $this->cachedChunks );
283 }
284 } else {
285 if ( array_key_exists( $key, $this->cachedChunks ) ) {
286 $value = $this->cachedChunks[$key];
287 unset( $this->cachedChunks[$key] );
288 } else {
289 wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ );
290 }
291 }
292 } else {
293 if ( !is_array( $args ) ) {
294 $args = [ $args ];
295 }
296
297 $value = call_user_func_array( $computeFunction, $args );
298
299 if ( $this->cacheEnabled ) {
300 if ( is_null( $key ) ) {
301 $this->cachedChunks[] = $value;
302 } else {
303 $this->cachedChunks[$key] = $value;
304 }
305 }
306 }
307
308 return $value;
309 }
310
311 /**
312 * Saves the HTML to the cache in case it got recomputed.
313 * Should be called after the last time anything is added via addCachedHTML.
314 *
315 * @since 1.20
316 */
317 public function saveCache() {
318 if ( $this->cacheEnabled && $this->hasCached === false && !empty( $this->cachedChunks ) ) {
319 wfGetCache( CACHE_ANYTHING )->set(
320 $this->getCacheKeyString(),
321 $this->cachedChunks,
322 $this->cacheExpiry
323 );
324 }
325 }
326
327 /**
328 * Sets the time to live for the cache, in seconds or a unix timestamp
329 * indicating the point of expiry...
330 *
331 * @since 1.20
332 *
333 * @param int $cacheExpiry
334 */
335 public function setExpiry( $cacheExpiry ) {
336 $this->cacheExpiry = $cacheExpiry;
337 }
338
339 /**
340 * Returns the cache key to use to cache this page's HTML output.
341 * Is constructed from the special page name and language code.
342 *
343 * @since 1.20
344 *
345 * @return string
346 * @throws MWException
347 */
348 protected function getCacheKeyString() {
349 if ( $this->cacheKey === [] ) {
350 throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
351 }
352
353 return call_user_func_array( 'wfMemcKey', $this->cacheKey );
354 }
355
356 /**
357 * Sets the cache key that should be used.
358 *
359 * @since 1.20
360 *
361 * @param array $cacheKey
362 */
363 public function setCacheKey( array $cacheKey ) {
364 $this->cacheKey = $cacheKey;
365 }
366
367 /**
368 * Rebuild the content, even if it's already cached.
369 * This effectively has the same effect as purging the cache,
370 * since it will be overridden with the new value on the next request.
371 *
372 * @since 1.20
373 */
374 public function rebuildOnDemand() {
375 $this->hasCached = false;
376 }
377
378 /**
379 * Sets a function that gets called when initialization of the cache is done.
380 *
381 * @since 1.20
382 *
383 * @param callable $handlerFunction
384 */
385 public function setOnInitializedHandler( $handlerFunction ) {
386 $this->onInitHandler = $handlerFunction;
387 }
388 }