Source

joomla-platform / libraries / joomla / cache / cache.php

  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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<?php
/**
 * @package     Joomla.Platform
 * @subpackage  Cache
 *
 * @copyright   Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 */

defined('JPATH_PLATFORM') or die;

//Register the storage class with the loader
JLoader::register('JCacheStorage', dirname(__FILE__).DS.'storage.php');

//Register the controller class with the loader
JLoader::register('JCacheController', dirname(__FILE__).DS.'controller.php');

/**
 * Joomla! Cache base object
 *
 * @abstract
 * @package		Joomla.Platform
 * @subpackage	Cache
 * @since		11.1
 */

// ALMOST EVERYTHING MUST BE PUBLIC HERE TO ALLOW OVERLOADING!

class JCache extends JObject
{
	/**
	 *
	 * @var		object	Storage Handler
	 * @since	11.1
	 */
	public static $_handler = array();

	/**
	 * @since	11.1
	 */
	public $_options;

	/**
	 * Constructor
	 *
	 * @param	array	$options	options
	 */
	public function __construct($options)
	{
		$conf = JFactory::getConfig();

		$this->_options = array(
			'cachebase'		=> $conf->get('cache_path', JPATH_CACHE),
			'lifetime'		=> (int)$conf->get('cachetime'),
			'language'		=> $conf->get('language', 'en-GB'),
			'storage'		=> $conf->get('cache_handler',''),
			'defaultgroup'	=> 'default',
			'locking'		=> true,
			'locktime'		=> 15,
			'checkTime' 	=> true,
			'caching'		=> ($conf->get('caching') >= 1) ? true : false
		);

		// Overwrite default options with given options
		foreach ($options AS $option=>$value) {
			if (isset($options[$option]) && $options[$option] !== '') {
				$this->_options[$option] = $options[$option];
			}
		}

		if (empty($this->_options['storage'])) {
			$this->_options['caching'] = false;
		}
	}

	/**
	 * Returns a reference to a cache adapter object, always creating it
	 *
	 * @param	string	$type	The cache object type to instantiate
	 * @return	object	A JCache object
	 * @since	11.1
	 */
	public static function getInstance($type = 'output', $options = array())
	{
		return JCacheController::getInstance($type, $options);
	}

	/**
	 * Get the storage handlers
	 *
	 * @return	array	An array of available storage handlers
	 * @since	11.1
	 */
	public static function getStores()
	{
		jimport('joomla.filesystem.folder');
		$handlers = JFolder::files(dirname(__FILE__).DS.'storage', '.php');

		$names = array();
		foreach($handlers as $handler) {
			$name = substr($handler, 0, strrpos($handler, '.'));
			$class = 'JCacheStorage'.$name;

			if (!class_exists($class)) {
				require_once dirname(__FILE__).DS.'storage'.DS.$name.'.php';
			}

			if (call_user_func_array(array(trim($class), 'test'), array())) {
				$names[] = $name;
			}
		}

		return $names;
	}

	/**
	 * Set caching enabled state
	 *
	 * @param	boolean	$enabled	True to enable caching
	 * @return	void
	 * @since	11.1
	 */
	public function setCaching($enabled)
	{
		$this->_options['caching'] = $enabled;
	}

	/**
	 * Get caching state
	 *
	 * @return	boolean Caching state
	 * @since	11.1
	 */
	public function getCaching()
	{
		return $this->_options['caching'];
	}

	/**
	 * Set cache lifetime
	 *
	 * @param	int	$lt	Cache lifetime
	 * @return	void
	 * @since	11.1
	 */
	public function setLifeTime($lt)
	{
		$this->_options['lifetime'] = $lt;
	}

	/**
	 * Get cached data by id and group
	 *
	 * @param	string	$id		The cache data id
	 * @param	string	$group	The cache data group
	 * @return	mixed	Boolean false on failure or a cached data string
	 * @since	11.1
	 */
	public function get($id, $group=null)
	{
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		// Get the storage
		$handler = $this->_getStorage();
		if (!JError::isError($handler) && $this->_options['caching']) {
			return $handler->get($id, $group, $this->_options['checkTime']);
		}
		return false;
	}

	/**
	 * Get a list of all cached data
	 *
	 * @return	mixed	Boolean false on failure or an object with a list of cache groups and data
	 * @since	11.1
	 */
	public function getAll()
	{
		// Get the storage
		$handler = $this->_getStorage();
		if (!JError::isError($handler) && $this->_options['caching']) {
			return $handler->getAll();
		}
		return false;
	}

	/**
	 * Store the cached data by id and group
	 *
	 * @param	string	$id		The cache data id
	 * @param	string	$group	The cache data group
	 * @param	mixed	$data	The data to store
	 * @return	boolean	True if cache stored
	 * @since	11.1
	 */
	public function store($data, $id, $group=null)
	{
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		// Get the storage and store the cached data
		$handler = $this->_getStorage();
		if (!JError::isError($handler) && $this->_options['caching']) {
			$handler->_lifetime = $this->_options['lifetime'];
			return $handler->store($id, $group, $data);
		}
		return false;
	}

	/**
	 * Remove a cached data entry by id and group
	 *
	 * @param	string	$id		The cache data id
	 * @param	string	$group	The cache data group
	 * @return	boolean	True on success, false otherwise
	 * @since	11.1
	 */
	public function remove($id, $group=null)
	{
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		// Get the storage
		$handler = $this->_getStorage();
		if (!JError::isError($handler)) {
			return $handler->remove($id, $group);
		}
		return false;
	}

	/**
	 * Clean cache for a group given a mode.
	 *
	 * group mode		: cleans all cache in the group
	 * notgroup mode	: cleans all cache not in the group
	 *
	 * @param	string	$group	The cache data group
	 * @param	string	$mode	The mode for cleaning cache [group|notgroup]
	 * @return	boolean	True on success, false otherwise
	 * @since	11.1
	 */
	public function clean($group=null, $mode='group')
	{
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		// Get the storage handler
		$handler = $this->_getStorage();
		if (!JError::isError($handler)) {
			return $handler->clean($group, $mode);
		}
		return false;
	}

	/**
	 * Garbage collect expired cache data
	 *
	 * @return boolean  True on success, false otherwise.
	 * @since	11.1
	 */
	public function gc()
	{
		// Get the storage handler
		$handler = $this->_getStorage();
		if (!JError::isError($handler)) {
			return $handler->gc();
		}
		return false;
	}

	/**
	 * Set lock flag on cached item
	 *
	 * @param	string	$id		The cache data id
	 * @param	string	$group	The cache data group
	 * @return	boolean	True on success, false otherwise.
	 * @since	11.1
	 */
	public function lock($id,$group=null,$locktime=null)
	{
		$returning = new stdClass();
		$returning->locklooped = false;
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		// Get the default locktime
		$locktime = ($locktime) ? $locktime : $this->_options['locktime'];

		//allow storage handlers to perform locking on their own
		// NOTE drivers with lock need also unlock or unlocking will fail because of false $id
		$handler = $this->_getStorage();
		if (!JError::isError($handler) && $this->_options['locking'] == true && $this->_options['caching'] == true) {
			$locked = $handler->lock($id, $group, $locktime);
			if ($locked !== false) {
				return $locked;
			}
		}

		// fallback
		$curentlifetime = $this->_options['lifetime'];
		// set lifetime to locktime for storing in children
		$this->_options['lifetime'] = $locktime;

		$looptime 	= $locktime * 10;
		$id2 		= $id.'_lock';

		if ($this->_options['locking'] == true && $this->_options['caching'] == true ) {
			$data_lock = $this->get($id2, $group);

		} else {
			$data_lock = false;
			$returning->locked = false;
		}

		if ( $data_lock !== false ) {
			$lock_counter = 0;

			// loop until you find that the lock has been released.  that implies that data get from other thread has finished
			while ( $data_lock !== false ) {

				if ( $lock_counter > $looptime) {
					$returning->locked 		= false;
					$returning->locklooped 	= true;
					break;
				}

				usleep(100);
				$data_lock = $this->get($id2, $group);
				$lock_counter++;
			}
		}

		if ($this->_options['locking'] == true && $this->_options['caching'] == true ) {
			$returning->locked = $this->store(1, $id2, $group);
		}

		// revert lifetime to previuos one
		$this->_options['lifetime'] = $curentlifetime;

		//return $lock;
		return $returning;
	}

	/**
	 * Unset lock flag on cached item
	 *
	 * @param	string	$id		The cache data id
	 * @param	string	$group	The cache data group
	 * @return	boolean	True on success, false otherwise.
	 * @since	11.1
	 */
	public function unlock($id,$group=null)
	{
		$unlock = false;
		// Get the default group
		$group = ($group) ? $group : $this->_options['defaultgroup'];

		//allow handlers to perform unlocking on their own
		$handler = $this->_getStorage();
		if (!JError::isError($handler) && $this->_options['caching']) {
			$unlocked = $handler->unlock($id, $group);
			if ($unlocked !== false) return $unlocked;
		}

		// fallback
		if ($this->_options['caching']) {
			$unlock = $this->remove($id.'_lock', $group);
		}

		return $unlock;
	}

	/**
	 * Get the cache storage handler
	 *
	 * @return	object	A JCacheStorage object
	 * @since	11.1
	 */
	public function _getStorage()
	{
		if (isset(self::$_handler[$this->_options['storage']]) && self::$_handler[$this->_options['storage']] instanceof JCacheStorage) {
			return self::$_handler[$this->_options['storage']];
		}

		self::$_handler[$this->_options['storage']] = JCacheStorage::getInstance($this->_options['storage'], $this->_options);
		return self::$_handler[$this->_options['storage']];
	}

	/**
	 * Perform workarounds on retrieved cached data
	 *
	 * @param	string	$data		Cached data
	 * @return	string	$body		Body of cached data
	 * @since	11.1
	 */
	public static function getWorkarounds($data,$options=array()) {

		// Initialise variables.
		$app 		= JFactory::getApplication();
		$document	= JFactory::getDocument();
		$body 		= null;

		// Get the document head out of the cache.
		if (isset($options['mergehead']) && $options['mergehead'] == 1 && isset($data['head']) && !empty($data['head'])) {
			$document->mergeHeadData($data['head']);
		} else if (isset($data['head'])){
			$document->setHeadData($data['head']);
		}

		// If the pathway buffer is set in the cache data, get it.
		if (isset($data['pathway']) && is_array($data['pathway'])) {
			// Push the pathway data into the pathway object.
			$pathway = $app->getPathWay();
			$pathway->setPathway($data['pathway']);
		}

		// @todo chech if the following is needed, seems like it should be in page cache
		// If a module buffer is set in the cache data, get it.
		if (isset($data['module']) && is_array($data['module'])) {
			// Iterate through the module positions and push them into the document buffer.
			foreach ($data['module'] as $name => $contents) {
				$document->setBuffer($contents, 'module', $name);
			}
		}

		if (isset($data['body'])) {
			// the following code searches for a token in the cached page and replaces it with the
			// proper token.
			$token			= JUtility::getToken();
			$search 		= '#<input type="hidden" name="[0-9a-f]{32}" value="1" />#';
			$replacement 	= '<input type="hidden" name="'.$token.'" value="1" />';
			$data['body'] = preg_replace($search, $replacement, $data['body']);
			$body = $data['body'];
		}

		// Get the document body out of the cache.
		return $body;
	}

	/**
	 * Create workarounded data to be cached
	 *
	 * @param	string	$data		Cached data
	 * @return	string	$cached		Data to be cached
	 * @since	11.1
	 */
	public static function setWorkarounds($data,$options=array())
	{
		$loptions=array();
		$loptions['nopathway'] = 0;
		$loptions['nohead'] = 0;
		$loptions['nomodules'] = 0;
		$loptions['modulemode'] = 0;

		if (isset($options['nopathway'])) {
			$loptions['nopathway'] = $options['nopathway'];
		}

		if (isset($options['nohead'])) {
			$loptions['nohead'] = $options['nohead'];
		}

		if (isset($options['nomodules'])) {
			$loptions['nomodules'] = $options['nomodules'];
		}

		if (isset($options['modulemode'])) {
			$loptions['modulemode'] = $options['modulemode'];
		}

		// Initialise variables.
		$app 		= JFactory::getApplication();
		$document	= JFactory::getDocument();

		// Get the modules buffer before component execution.
		$buffer1 = $document->getBuffer();

		// Make sure the module buffer is an array.
		if (!isset($buffer1['module']) || !is_array($buffer1['module'])) {
			$buffer1['module'] = array();
		}

		// View body data
		$cached['body'] = $data;

		// Document head data
		if ($loptions['nohead'] != 1) {
			$cached['head'] = $document->getHeadData();

			if ($loptions['modulemode'] == 1) {
					unset($cached['head']['title']);
					unset($cached['head']['description']);
					unset($cached['head']['link']);
					unset($cached['head']['metaTags']);
			}
		}

		// Pathway data
		if ($app->isSite() && $loptions['nopathway'] != 1) {
			$pathway			= $app->getPathWay();
			$cached['pathway'] 	= isset($data['pathway']) ? $data['pathway'] : $pathway->getPathway();
		}

		if ($loptions['nomodules'] != 1) {
			// @todo chech if the following is needed, seems like it should be in page cache
			// Get the module buffer after component execution.
			$buffer2 = $document->getBuffer();

			// Make sure the module buffer is an array.
			if (!isset($buffer2['module']) || !is_array($buffer2['module'])) {
				$buffer2['module'] = array();
			}

			// Compare the second module buffer against the first buffer.
			$cached['module'] = array_diff_assoc($buffer2['module'], $buffer1['module']);
		}

		return $cached;
	}

	/**
	 * Create safe id for cached data from url parameters set by plugins and framework
	 *
	 * @return	string	md5 encoded cacheid
	 * @since	11.1
	 */
	public static function makeId()
	{
		$app = JFactory::getApplication();
		// get url parameters set by plugins
		$registeredurlparams = $app->get('registeredurlparams');

		if (empty($registeredurlparams)) {
			/*
			$registeredurlparams = new stdClass();
			$registeredurlparams->Itemid 	= 'INT';
			$registeredurlparams->catid 	= 'INT';
			$registeredurlparams->id 		= 'INT';
			*/

			return md5(serialize(JRequest::getURI()));   // provided for backwards compatibility - THIS IS NOT SAFE!!!!
		}
		// framework defaults
		$registeredurlparams->format 	= 'WORD';
		$registeredurlparams->option 	= 'WORD';
		$registeredurlparams->view		= 'WORD';
		$registeredurlparams->layout	= 'WORD';
		$registeredurlparams->tpl		= 'CMD';
		$registeredurlparams->id		= 'INT';

		$safeuriaddon = new stdClass();

		foreach ($registeredurlparams AS $key => $value) {
			$safeuriaddon->$key = JRequest::getVar($key, null, 'default', $value);
		}

		return md5(serialize($safeuriaddon));
	}

	/**
	 * Add a directory where JCache should search for handlers. You may
	 * either pass a string or an array of directories.
	 *
	 * @param	string	A path to search.
	 * @return	array	An array with directory elements
	 * @since	11.1
	 */
	public static function addIncludePath($path='')
	{
		static $paths;

		if (!isset($paths)) {
			$paths = array();
		}
		if (!empty($path) && !in_array($path, $paths)) {
			jimport('joomla.filesystem.path');
			array_unshift($paths, JPath::clean($path));
		}
		return $paths;
	}
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.