Merge "Link to existing login help page by default from helplogin-url"
[lhc/web/wiklou.git] / includes / 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 /**
33 * Sets if the cache should be enabled or not.
34 *
35 * @since 1.20
36 * @param boolean $cacheEnabled
37 */
38 function setCacheEnabled( $cacheEnabled );
39
40 /**
41 * Initializes the caching.
42 * Should be called before the first time anything is added via addCachedHTML.
43 *
44 * @since 1.20
45 *
46 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
47 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
48 */
49 function startCache( $cacheExpiry = null, $cacheEnabled = null );
50
51 /**
52 * Get a cached value if available or compute it if not and then cache it if possible.
53 * The provided $computeFunction is only called when the computation needs to happen
54 * and should return a result value. $args are arguments that will be passed to the
55 * compute function when called.
56 *
57 * @since 1.20
58 *
59 * @param {function} $computeFunction
60 * @param array|mixed $args
61 * @param string|null $key
62 *
63 * @return mixed
64 */
65 function getCachedValue( $computeFunction, $args = array(), $key = null );
66
67 /**
68 * Saves the HTML to the cache in case it got recomputed.
69 * Should be called after the last time anything is added via addCachedHTML.
70 *
71 * @since 1.20
72 */
73 function saveCache();
74
75 /**
76 * Sets the time to live for the cache, in seconds or a unix timestamp
77 * indicating the point of expiry...
78 *
79 * @since 1.20
80 *
81 * @param integer $cacheExpiry
82 */
83 function setExpiry( $cacheExpiry );
84
85 }
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 /**
108 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
109 *
110 * @since 1.20
111 * @var integer
112 */
113 protected $cacheExpiry = 3600;
114
115 /**
116 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
117 * If not cached already, then the newly computed chunks are added here,
118 * if it as cached already, chunks are removed from this list as they are needed.
119 *
120 * @since 1.20
121 * @var array
122 */
123 protected $cachedChunks;
124
125 /**
126 * Indicates if the to be cached content was already cached.
127 * Null if this information is not available yet.
128 *
129 * @since 1.20
130 * @var boolean|null
131 */
132 protected $hasCached = null;
133
134 /**
135 * If the cache is enabled or not.
136 *
137 * @since 1.20
138 * @var boolean
139 */
140 protected $cacheEnabled = true;
141
142 /**
143 * Function that gets called when initialization is done.
144 *
145 * @since 1.20
146 * @var callable
147 */
148 protected $onInitHandler = false;
149
150 /**
151 * Elements to build a cache key with.
152 *
153 * @since 1.20
154 * @var array
155 */
156 protected $cacheKey = array();
157
158 /**
159 * Sets if the cache should be enabled or not.
160 *
161 * @since 1.20
162 * @param boolean $cacheEnabled
163 */
164 public function setCacheEnabled( $cacheEnabled ) {
165 $this->cacheEnabled = $cacheEnabled;
166 }
167
168 /**
169 * Initializes the caching.
170 * Should be called before the first time anything is added via addCachedHTML.
171 *
172 * @since 1.20
173 *
174 * @param integer|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
175 * @param boolean|null $cacheEnabled Sets if the cache should be enabled or not.
176 */
177 public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
178 if ( is_null( $this->hasCached ) ) {
179 if ( !is_null( $cacheExpiry ) ) {
180 $this->cacheExpiry = $cacheExpiry;
181 }
182
183 if ( !is_null( $cacheEnabled ) ) {
184 $this->setCacheEnabled( $cacheEnabled );
185 }
186
187 $this->initCaching();
188 }
189 }
190
191 /**
192 * Returns a message that notifies the user he/she is looking at
193 * a cached version of the page, including a refresh link.
194 *
195 * @since 1.20
196 *
197 * @param IContextSource $context
198 * @param boolean $includePurgeLink
199 *
200 * @return string
201 */
202 public function getCachedNotice( IContextSource $context, $includePurgeLink = true ) {
203 if ( $this->cacheExpiry < 86400 * 3650 ) {
204 $message = $context->msg(
205 'cachedspecial-viewing-cached-ttl',
206 $context->getLanguage()->formatDuration( $this->cacheExpiry )
207 )->escaped();
208 } else {
209 $message = $context->msg(
210 'cachedspecial-viewing-cached-ts'
211 )->escaped();
212 }
213
214 if ( $includePurgeLink ) {
215 $refreshArgs = $context->getRequest()->getQueryValues();
216 unset( $refreshArgs['title'] );
217 $refreshArgs['action'] = 'purge';
218
219 $subPage = $context->getTitle()->getFullText();
220 $subPage = explode( '/', $subPage, 2 );
221 $subPage = count( $subPage ) > 1 ? $subPage[1] : false;
222
223 $message .= ' ' . Linker::link(
224 $context->getTitle( $subPage ),
225 $context->msg( 'cachedspecial-refresh-now' )->escaped(),
226 array(),
227 $refreshArgs
228 );
229 }
230
231 return $message;
232 }
233
234 /**
235 * Initializes the caching if not already done so.
236 * Should be called before any of the caching functionality is used.
237 *
238 * @since 1.20
239 */
240 protected function initCaching() {
241 if ( $this->cacheEnabled && is_null( $this->hasCached ) ) {
242 $cachedChunks = wfGetCache( CACHE_ANYTHING )->get( $this->getCacheKeyString() );
243
244 $this->hasCached = is_array( $cachedChunks );
245 $this->cachedChunks = $this->hasCached ? $cachedChunks : array();
246
247 if ( $this->onInitHandler !== false ) {
248 call_user_func( $this->onInitHandler, $this->hasCached );
249 }
250 }
251 }
252
253 /**
254 * Get a cached value if available or compute it if not and then cache it if possible.
255 * The provided $computeFunction is only called when the computation needs to happen
256 * and should return a result value. $args are arguments that will be passed to the
257 * compute function when called.
258 *
259 * @since 1.20
260 *
261 * @param {function} $computeFunction
262 * @param array|mixed $args
263 * @param string|null $key
264 *
265 * @return mixed
266 */
267 public function getCachedValue( $computeFunction, $args = array(), $key = null ) {
268 $this->initCaching();
269
270 if ( $this->cacheEnabled && $this->hasCached ) {
271 $value = null;
272
273 if ( is_null( $key ) ) {
274 $itemKey = array_keys( array_slice( $this->cachedChunks, 0, 1 ) );
275 $itemKey = array_shift( $itemKey );
276
277 if ( !is_integer( $itemKey ) ) {
278 wfWarn( "Attempted to get item with non-numeric key while 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 = array( $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( $this->getCacheKeyString(), $this->cachedChunks, $this->cacheExpiry );
320 }
321 }
322
323 /**
324 * Sets the time to live for the cache, in seconds or a unix timestamp
325 * indicating the point of expiry...
326 *
327 * @since 1.20
328 *
329 * @param integer $cacheExpiry
330 */
331 public function setExpiry( $cacheExpiry ) {
332 $this->cacheExpiry = $cacheExpiry;
333 }
334
335 /**
336 * Returns the cache key to use to cache this page's HTML output.
337 * Is constructed from the special page name and language code.
338 *
339 * @since 1.20
340 *
341 * @return string
342 * @throws MWException
343 */
344 protected function getCacheKeyString() {
345 if ( $this->cacheKey === array() ) {
346 throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
347 }
348
349 return call_user_func_array( 'wfMemcKey', $this->cacheKey );
350 }
351
352 /**
353 * Sets the cache key that should be used.
354 *
355 * @since 1.20
356 *
357 * @param array $cacheKey
358 */
359 public function setCacheKey( array $cacheKey ) {
360 $this->cacheKey = $cacheKey;
361 }
362
363 /**
364 * Rebuild the content, even if it's already cached.
365 * This effectively has the same effect as purging the cache,
366 * since it will be overridden with the new value on the next request.
367 *
368 * @since 1.20
369 */
370 public function rebuildOnDemand() {
371 $this->hasCached = false;
372 }
373
374 /**
375 * Sets a function that gets called when initialization of the cache is done.
376 *
377 * @since 1.20
378 *
379 * @param $handlerFunction
380 */
381 public function setOnInitializedHandler( $handlerFunction ) {
382 $this->onInitHandler = $handlerFunction;
383 }
384
385 }