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