3 * Cache of various elements in a single cache entry.
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
21 * @license GNU GPL v2 or later
22 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
26 * Interface for all classes implementing CacheHelper functionality.
30 interface ICacheHelper
{
32 * Sets if the cache should be enabled or not.
35 * @param bool $cacheEnabled
37 function setCacheEnabled( $cacheEnabled );
40 * Initializes the caching.
41 * Should be called before the first time anything is added via addCachedHTML.
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.
48 function startCache( $cacheExpiry = null, $cacheEnabled = null );
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.
58 * @param callable $computeFunction
59 * @param array|mixed $args
60 * @param string|null $key
64 function getCachedValue( $computeFunction, $args = array(), $key = null );
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.
75 * Sets the time to live for the cache, in seconds or a unix timestamp
76 * indicating the point of expiry...
80 * @param int $cacheExpiry
82 function setExpiry( $cacheExpiry );
86 * Helper class for caching various elements in a single cache entry.
88 * To get a cached value or compute it, use getCachedValue like this:
89 * $this->getCachedValue( $callback );
91 * To add HTML that should be cached, use addCachedHTML like this:
92 * $this->addCachedHTML( $callback );
94 * The callback function is only called when needed, so do all your expensive
95 * computations here. This function should returns the HTML to be cached.
96 * It should not add anything to the PageOutput object!
98 * Before the first addCachedHTML call, you should call $this->startCache();
99 * After adding the last HTML that should be cached, call $this->saveCache();
103 class CacheHelper
implements ICacheHelper
{
105 * The time to live for the cache, in seconds or a unix timestamp indicating the point of expiry.
110 protected $cacheExpiry = 3600;
113 * List of HTML chunks to be cached (if !hasCached) or that where cached (of hasCached).
114 * If not cached already, then the newly computed chunks are added here,
115 * if it as cached already, chunks are removed from this list as they are needed.
120 protected $cachedChunks;
123 * Indicates if the to be cached content was already cached.
124 * Null if this information is not available yet.
129 protected $hasCached = null;
132 * If the cache is enabled or not.
137 protected $cacheEnabled = true;
140 * Function that gets called when initialization is done.
145 protected $onInitHandler = false;
148 * Elements to build a cache key with.
153 protected $cacheKey = array();
156 * Sets if the cache should be enabled or not.
159 * @param bool $cacheEnabled
161 public function setCacheEnabled( $cacheEnabled ) {
162 $this->cacheEnabled
= $cacheEnabled;
166 * Initializes the caching.
167 * Should be called before the first time anything is added via addCachedHTML.
171 * @param int|null $cacheExpiry Sets the cache expiry, either ttl in seconds or unix timestamp.
172 * @param bool|null $cacheEnabled Sets if the cache should be enabled or not.
174 public function startCache( $cacheExpiry = null, $cacheEnabled = null ) {
175 if ( is_null( $this->hasCached
) ) {
176 if ( !is_null( $cacheExpiry ) ) {
177 $this->cacheExpiry
= $cacheExpiry;
180 if ( !is_null( $cacheEnabled ) ) {
181 $this->setCacheEnabled( $cacheEnabled );
184 $this->initCaching();
189 * Returns a message that notifies the user he/she is looking at
190 * a cached version of the page, including a refresh link.
194 * @param IContextSource $context
195 * @param bool $includePurgeLink
199 public function getCachedNotice( IContextSource
$context, $includePurgeLink = true ) {
200 if ( $this->cacheExpiry
< 86400 * 3650 ) {
201 $message = $context->msg(
202 'cachedspecial-viewing-cached-ttl',
203 $context->getLanguage()->formatDuration( $this->cacheExpiry
)
206 $message = $context->msg(
207 'cachedspecial-viewing-cached-ts'
211 if ( $includePurgeLink ) {
212 $refreshArgs = $context->getRequest()->getQueryValues();
213 unset( $refreshArgs['title'] );
214 $refreshArgs['action'] = 'purge';
216 $subPage = $context->getTitle()->getFullText();
217 $subPage = explode( '/', $subPage, 2 );
218 $subPage = count( $subPage ) > 1 ?
$subPage[1] : false;
220 $message .= ' ' . Linker
::link(
221 $context->getTitle( $subPage ),
222 $context->msg( 'cachedspecial-refresh-now' )->escaped(),
232 * Initializes the caching if not already done so.
233 * Should be called before any of the caching functionality is used.
237 protected function initCaching() {
238 if ( $this->cacheEnabled
&& is_null( $this->hasCached
) ) {
239 $cachedChunks = wfGetCache( CACHE_ANYTHING
)->get( $this->getCacheKeyString() );
241 $this->hasCached
= is_array( $cachedChunks );
242 $this->cachedChunks
= $this->hasCached ?
$cachedChunks : array();
244 if ( $this->onInitHandler
!== false ) {
245 call_user_func( $this->onInitHandler
, $this->hasCached
);
251 * Get a cached value if available or compute it if not and then cache it if possible.
252 * The provided $computeFunction is only called when the computation needs to happen
253 * and should return a result value. $args are arguments that will be passed to the
254 * compute function when called.
258 * @param callable $computeFunction
259 * @param array|mixed $args
260 * @param string|null $key
264 public function getCachedValue( $computeFunction, $args = array(), $key = null ) {
265 $this->initCaching();
267 if ( $this->cacheEnabled
&& $this->hasCached
) {
270 if ( is_null( $key ) ) {
271 $itemKey = array_keys( array_slice( $this->cachedChunks
, 0, 1 ) );
272 $itemKey = array_shift( $itemKey );
274 if ( !is_integer( $itemKey ) ) {
275 wfWarn( "Attempted to get item with non-numeric key while " .
276 "the next item in the queue has a key ($itemKey) in " . __METHOD__
);
277 } elseif ( is_null( $itemKey ) ) {
278 wfWarn( "Attempted to get an item while the queue is empty in " . __METHOD__
);
280 $value = array_shift( $this->cachedChunks
);
283 if ( array_key_exists( $key, $this->cachedChunks
) ) {
284 $value = $this->cachedChunks
[$key];
285 unset( $this->cachedChunks
[$key] );
287 wfWarn( "There is no item with key '$key' in this->cachedChunks in " . __METHOD__
);
291 if ( !is_array( $args ) ) {
292 $args = array( $args );
295 $value = call_user_func_array( $computeFunction, $args );
297 if ( $this->cacheEnabled
) {
298 if ( is_null( $key ) ) {
299 $this->cachedChunks
[] = $value;
301 $this->cachedChunks
[$key] = $value;
310 * Saves the HTML to the cache in case it got recomputed.
311 * Should be called after the last time anything is added via addCachedHTML.
315 public function saveCache() {
316 if ( $this->cacheEnabled
&& $this->hasCached
=== false && !empty( $this->cachedChunks
) ) {
317 wfGetCache( CACHE_ANYTHING
)->set(
318 $this->getCacheKeyString(),
326 * Sets the time to live for the cache, in seconds or a unix timestamp
327 * indicating the point of expiry...
331 * @param int $cacheExpiry
333 public function setExpiry( $cacheExpiry ) {
334 $this->cacheExpiry
= $cacheExpiry;
338 * Returns the cache key to use to cache this page's HTML output.
339 * Is constructed from the special page name and language code.
344 * @throws MWException
346 protected function getCacheKeyString() {
347 if ( $this->cacheKey
=== array() ) {
348 throw new MWException( 'No cache key set, so cannot obtain or save the CacheHelper values.' );
351 return call_user_func_array( 'wfMemcKey', $this->cacheKey
);
355 * Sets the cache key that should be used.
359 * @param array $cacheKey
361 public function setCacheKey( array $cacheKey ) {
362 $this->cacheKey
= $cacheKey;
366 * Rebuild the content, even if it's already cached.
367 * This effectively has the same effect as purging the cache,
368 * since it will be overridden with the new value on the next request.
372 public function rebuildOnDemand() {
373 $this->hasCached
= false;
377 * Sets a function that gets called when initialization of the cache is done.
381 * @param callable $handlerFunction
383 public function setOnInitializedHandler( $handlerFunction ) {
384 $this->onInitHandler
= $handlerFunction;