summaryrefslogtreecommitdiff
path: root/includes/CacheHelper.php
blob: f0ae5a313faa46c6d8c6519adba2b4cba5deb129 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<?php
/**
 * Cache of various elements in a single cache entry.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @license GNU GPL v2 or later
 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
 */

/**
 * Interface for all classes implementing CacheHelper functionality.
 *
 * @since 1.20
 */
interface ICacheHelper {

	/**
	 * Sets if the cache should be enabled or not.
	 *
	 * @since 1.20
	 * @param boolean $cacheEnabled
	 */
	function setCacheEnabled( $cacheEnabled );

	/**
	 * Initializes the caching.
	 * Should be called before the first time anything is added via addCachedHTML.
	 *
	 * @since 1.20
	 *
	 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
	 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
	 */
	function startCache( $cacheExpiry = null, $cacheEnabled = null );

	/**
	 * Get a cached value if available or compute it if not and then cache it if possible.
	 * The provided $computeFunction is only called when the computation needs to happen
	 * and should return a result value. $args are arguments that will be passed to the
	 * compute function when called.
	 *
	 * @since 1.20
	 *
	 * @param {function} $computeFunction
	 * @param array|mixed $args
	 * @param string|null $key
	 *
	 * @return mixed
	 */
	function getCachedValue( $computeFunction, $args = array(), $key = null );

	/**
	 * Saves the HTML to the cache in case it got recomputed.
	 * Should be called after the last time anything is added via addCachedHTML.
	 *
	 * @since 1.20
	 */
	function saveCache();

	/**
	 * Sets the time to live for the cache, in seconds or a unix timestamp
	 * indicating the point of expiry...
	 *
	 * @since 1.20
	 *
	 * @param integer $cacheExpiry
	 */
	function setExpiry( $cacheExpiry );

}

/**
 * Helper class for caching various elements in a single cache entry.
 *
 * To get a cached value or compute it, use getCachedValue like this:
 * $this->getCachedValue( $callback );
 *
 * To add HTML that should be cached, use addCachedHTML like this:
 * $this->addCachedHTML( $callback );
 *
 * The callback function is only called when needed, so do all your expensive
 * computations here. This function should returns the HTML to be cached.
 * It should not add anything to the PageOutput object!
 *
 * Before the first addCachedHTML call, you should call $this->startCache();
 * After adding the last HTML that should be cached, call $this->saveCache();
 *
 * @since 1.20
 */
class CacheHelper implements ICacheHelper {

	/**
	 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
	 *
	 * @since 1.20
	 * @var integer
	 */
	protected $cacheExpiry = 3600;

	/**
	 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
	 * If not cached already, then the newly computed chunks are added here,
	 * if it as cached already, chunks are removed from this list as they are needed.
	 *
	 * @since 1.20
	 * @var array
	 */
	protected $cachedChunks;

	/**
	 * Indicates if the to be cached content was already cached.
	 * Null if this information is not available yet.
	 *
	 * @since 1.20
	 * @var boolean|null
	 */
	protected $hasCached = null;

	/**
	 * If the cache is enabled or not.
	 *
	 * @since 1.20
	 * @var boolean
	 */
	protected $cacheEnabled = true;

	/**
	 * Function that gets called when initialization is done.
	 *
	 * @since 1.20
	 * @var callable
	 */
	protected $onInitHandler = false;

	/**
	 * Elements to build a cache key with.
	 *
	 * @since 1.20
	 * @var array
	 */
	protected $cacheKey = array();

	/**
	 * Sets if the cache should be enabled or not.
	 *
	 * @since 1.20
	 * @param boolean $cacheEnabled
	 */
	public function setCacheEnabled( $cacheEnabled ) {
		$this->cacheEnabled = $cacheEnabled;
	}

	/**
	 * Initializes the caching.
	 * Should be called before the first time anything is added via addCachedHTML.
	 *
	 * @since 1.20
	 *
	 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
	 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
	 */
	public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
		if ( is_null( $this->hasCached ) ) {
			if ( !is_null( $cacheExpiry ) ) {
				$this->cacheExpiry = $cacheExpiry;
			}

			if ( !is_null( $cacheEnabled ) ) {
				$this->setCacheEnabled( $cacheEnabled );
			}

			$this->initCaching();
		}
	}

	/**
	 * Returns a message that notifies the user he/she is looking at
	 * a cached version of the page, including a refresh link.
	 *
	 * @since 1.20
	 *
	 * @param IContextSource $context
	 * @param boolean $includePurgeLink
	 *
	 * @return string
	 */
	public function getCachedNotice( IContextSource $context, $includePurgeLink = true ) {
		if ( $this->cacheExpiry < 86400 * 3650 ) {
			$message = $context->msg(
				'cachedspecial-viewing-cached-ttl',
				$context->getLanguage()->formatDuration( $this->cacheExpiry )
			)->escaped();
		}
		else {
			$message = $context->msg(
				'cachedspecial-viewing-cached-ts'
			)->escaped();
		}

		if ( $includePurgeLink ) {
			$refreshArgs = $context->getRequest()->getQueryValues();
			unset( $refreshArgs['title'] );
			$refreshArgs['action'] = 'purge';

			$subPage = $context->getTitle()->getFullText();
			$subPage = explode( '/', $subPage, 2 );
			$subPage = count( $subPage ) > 1 ? $subPage[1] : false;

			$message .= ' ' . Linker::link(
				$context->getTitle( $subPage ),
				$context->msg( 'cachedspecial-refresh-now' )->escaped(),
				array(),
				$refreshArgs
			);
		}

		return $message;
	}

	/**
	 * Initializes the caching if not already done so.
	 * Should be called before any of the caching functionality is used.
	 *
	 * @since 1.20
	 */
	protected function initCaching() {
		if ( $this->cacheEnabled && is_null( $this->hasCached ) ) {
			$cachedChunks = wfGetCache( CACHE_ANYTHING )->get( $this->getCacheKeyString() );

			$this->hasCached = is_array( $cachedChunks );
			$this->cachedChunks = $this->hasCached ? $cachedChunks : array();

			if ( $this->onInitHandler !== false ) {
				call_user_func( $this->onInitHandler, $this->hasCached );
			}
		}
	}

	/**
	 * Get a cached value if available or compute it if not and then cache it if possible.
	 * The provided $computeFunction is only called when the computation needs to happen
	 * and should return a result value. $args are arguments that will be passed to the
	 * compute function when called.
	 *
	 * @since 1.20
	 *
	 * @param {function} $computeFunction
	 * @param array|mixed $args
	 * @param string|null $key
	 *
	 * @return mixed
	 */
	public function getCachedValue( $computeFunction, $args = array(), $key = null ) {
		$this->initCaching();

		if ( $this->cacheEnabled && $this->hasCached ) {
			$value = null;

			if ( is_null( $key ) ) {
				$itemKey = array_keys( array_slice( $this->cachedChunks, 0, 1 ) );
				$itemKey = array_shift( $itemKey );

				if ( !is_integer( $itemKey ) ) {
					wfWarn( "Attempted to get item with non-numeric key while the next item in the queue has a key ($itemKey) in " . __METHOD__ );
				}
				elseif ( is_null( $itemKey ) ) {
					wfWarn( "Attempted to get an item while the queue is empty in " . __METHOD__ );
				}
				else {
					$value = array_shift( $this->cachedChunks );
				}
			}
			else {
				if ( array_key_exists( $key, $this->cachedChunks ) ) {
					$value = $this->cachedChunks[$key];
					unset( $this->cachedChunks[$key] );
				}
				else {
					wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__ );
				}
			}
		}
		else {
			if ( !is_array( $args ) ) {
				$args = array( $args );
			}

			$value = call_user_func_array( $computeFunction, $args );

			if ( $this->cacheEnabled ) {
				if ( is_null( $key ) ) {
					$this->cachedChunks[] = $value;
				}
				else {
					$this->cachedChunks[$key] = $value;
				}
			}
		}

		return $value;
	}

	/**
	 * Saves the HTML to the cache in case it got recomputed.
	 * Should be called after the last time anything is added via addCachedHTML.
	 *
	 * @since 1.20
	 */
	public function saveCache() {
		if ( $this->cacheEnabled && $this->hasCached === false && !empty( $this->cachedChunks ) ) {
			wfGetCache( CACHE_ANYTHING )->set( $this->getCacheKeyString(), $this->cachedChunks, $this->cacheExpiry );
		}
	}

	/**
	 * Sets the time to live for the cache, in seconds or a unix timestamp
	 * indicating the point of expiry...
	 *
	 * @since 1.20
	 *
	 * @param integer $cacheExpiry
	 */
	public function setExpiry( $cacheExpiry ) {
		$this->cacheExpiry = $cacheExpiry;
	}

	/**
	 * Returns the cache key to use to cache this page's HTML output.
	 * Is constructed from the special page name and language code.
	 *
	 * @since 1.20
	 *
	 * @return string
	 * @throws MWException
	 */
	protected function getCacheKeyString() {
		if ( $this->cacheKey === array() ) {
			throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
		}

		return call_user_func_array( 'wfMemcKey', $this->cacheKey );
	}

	/**
	 * Sets the cache key that should be used.
	 *
	 * @since 1.20
	 *
	 * @param array $cacheKey
	 */
	public function setCacheKey( array $cacheKey ) {
		$this->cacheKey = $cacheKey;
	}

	/**
	 * Rebuild the content, even if it's already cached.
	 * This effectively has the same effect as purging the cache,
	 * since it will be overridden with the new value on the next request.
	 *
	 * @since 1.20
	 */
	public function rebuildOnDemand() {
		$this->hasCached = false;
	}

	/**
	 * Sets a function that gets called when initialization of the cache is done.
	 *
	 * @since 1.20
	 *
	 * @param $handlerFunction
	 */
	public function setOnInitializedHandler( $handlerFunction ) {
		$this->onInitHandler = $handlerFunction;
	}

}