Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
/**
3
 * CacheHelper helps create full page view caching.
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://cakephp.org CakePHP(tm) Project
14
 * @package       Cake.View.Helper
15
 * @since         CakePHP(tm) v 1.0.0.2277
16
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
17
 */
18
 
19
App::uses('AppHelper', 'View/Helper');
20
 
21
/**
22
 * CacheHelper helps create full page view caching.
23
 *
24
 * When using CacheHelper you don't call any of its methods, they are all automatically
25
 * called by View, and use the $cacheAction settings set in the controller.
26
 *
27
 * @package       Cake.View.Helper
28
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
29
 */
30
class CacheHelper extends AppHelper {
31
 
32
/**
33
 * Array of strings replaced in cached views.
34
 * The strings are found between `<!--nocache--><!--/nocache-->` in views
35
 *
36
 * @var array
37
 */
38
	protected $_replace = array();
39
 
40
/**
41
 * Array of string that are replace with there var replace above.
42
 * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
43
 *
44
 * @var array
45
 */
46
	protected $_match = array();
47
 
48
/**
49
 * Counter used for counting nocache section tags.
50
 *
51
 * @var integer
52
 */
53
	protected $_counter = 0;
54
 
55
/**
56
 * Is CacheHelper enabled? should files + output be parsed.
57
 *
58
 * @return boolean
59
 */
60
	protected function _enabled() {
61
		return $this->_View->cacheAction && (Configure::read('Cache.check') === true);
62
	}
63
 
64
/**
65
 * Parses the view file and stores content for cache file building.
66
 *
67
 * @param string $viewFile
68
 * @param string $output The output for the file.
69
 * @return string Updated content.
70
 */
71
	public function afterRenderFile($viewFile, $output) {
72
		if ($this->_enabled()) {
73
			return $this->_parseContent($viewFile, $output);
74
		}
75
	}
76
 
77
/**
78
 * Parses the layout file and stores content for cache file building.
79
 *
80
 * @param string $layoutFile
81
 * @return void
82
 */
83
	public function afterLayout($layoutFile) {
84
		if ($this->_enabled()) {
85
			$this->_View->output = $this->cache($layoutFile, $this->_View->output);
86
		}
87
		$this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output);
88
	}
89
 
90
/**
91
 * Parse a file + output. Matches nocache tags between the current output and the current file
92
 * stores a reference of the file, so the generated can be swapped back with the file contents when
93
 * writing the cache file.
94
 *
95
 * @param string $file The filename to process.
96
 * @param string $out The output for the file.
97
 * @return string Updated content.
98
 */
99
	protected function _parseContent($file, $out) {
100
		$out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out);
101
		$this->_parseFile($file, $out);
102
		return $out;
103
	}
104
 
105
/**
106
 * Main method used to cache a view
107
 *
108
 * @param string $file File to cache
109
 * @param string $out output to cache
110
 * @return string view output
111
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
112
 */
113
	public function cache($file, $out) {
114
		$cacheTime = 0;
115
		$useCallbacks = false;
116
		$cacheAction = $this->_View->cacheAction;
117
 
118
		if (is_array($cacheAction)) {
119
			$keys = array_keys($cacheAction);
120
			$index = null;
121
 
122
			foreach ($keys as $action) {
123
				if ($action == $this->request->params['action']) {
124
					$index = $action;
125
					break;
126
				}
127
			}
128
 
129
			if (!isset($index) && $this->request->params['action'] === 'index') {
130
				$index = 'index';
131
			}
132
 
133
			$options = $cacheAction;
134
			if (isset($cacheAction[$index])) {
135
				if (is_array($cacheAction[$index])) {
136
					$options = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]);
137
				} else {
138
					$cacheTime = $cacheAction[$index];
139
				}
140
			}
141
			if (isset($options['duration'])) {
142
				$cacheTime = $options['duration'];
143
			}
144
			if (isset($options['callbacks'])) {
145
				$useCallbacks = $options['callbacks'];
146
			}
147
		} else {
148
			$cacheTime = $cacheAction;
149
		}
150
 
151
		if ($cacheTime && $cacheTime > 0) {
152
			$cached = $this->_parseOutput($out);
153
			try {
154
				$this->_writeFile($cached, $cacheTime, $useCallbacks);
155
			} catch (Exception $e) {
156
				$message = __d(
157
					'cake_dev',
158
					'Unable to write view cache file: "%s" for "%s"',
159
					$e->getMessage(),
160
					$this->request->here
161
				);
162
				$this->log($message, 'error');
163
			}
164
			$out = $this->_stripTags($out);
165
		}
166
		return $out;
167
	}
168
 
169
/**
170
 * Parse file searching for no cache tags
171
 *
172
 * @param string $file The filename that needs to be parsed.
173
 * @param string $cache The cached content
174
 * @return void
175
 */
176
	protected function _parseFile($file, $cache) {
177
		if (is_file($file)) {
178
			$file = file_get_contents($file);
179
		} elseif ($file = fileExistsInPath($file)) {
180
			$file = file_get_contents($file);
181
		}
182
		preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
183
		preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
184
		$fileResult = $fileResult[0];
185
		$outputResult = $outputResult[0];
186
 
187
		if (!empty($this->_replace)) {
188
			foreach ($outputResult as $i => $element) {
189
				$index = array_search($element, $this->_match);
190
				if ($index !== false) {
191
					unset($outputResult[$i]);
192
				}
193
			}
194
			$outputResult = array_values($outputResult);
195
		}
196
 
197
		if (!empty($fileResult)) {
198
			$i = 0;
199
			foreach ($fileResult as $cacheBlock) {
200
				if (isset($outputResult[$i])) {
201
					$this->_replace[] = $cacheBlock;
202
					$this->_match[] = $outputResult[$i];
203
				}
204
				$i++;
205
			}
206
		}
207
	}
208
 
209
/**
210
 * Munges the output from a view with cache tags, and numbers the sections.
211
 * This helps solve issues with empty/duplicate content.
212
 *
213
 * @return string The content with cake:nocache tags replaced.
214
 */
215
	protected function _replaceSection() {
216
		$this->_counter += 1;
217
		return sprintf('<!--nocache:%03d-->', $this->_counter);
218
	}
219
 
220
/**
221
 * Strip cake:nocache tags from a string. Since View::render()
222
 * only removes un-numbered nocache tags, remove all the numbered ones.
223
 * This is the complement to _replaceSection.
224
 *
225
 * @param string $content String to remove tags from.
226
 * @return string String with tags removed.
227
 */
228
	protected function _stripTags($content) {
229
		return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
230
	}
231
 
232
/**
233
 * Parse the output and replace cache tags
234
 *
235
 * @param string $cache Output to replace content in.
236
 * @return string with all replacements made to <!--nocache--><!--nocache-->
237
 */
238
	protected function _parseOutput($cache) {
239
		$count = 0;
240
		if (!empty($this->_match)) {
241
			foreach ($this->_match as $found) {
242
				$original = $cache;
243
				$length = strlen($found);
244
				$position = 0;
245
 
246
				for ($i = 1; $i <= 1; $i++) {
247
					$position = strpos($cache, $found, $position);
248
 
249
					if ($position !== false) {
250
						$cache = substr($original, 0, $position);
251
						$cache .= $this->_replace[$count];
252
						$cache .= substr($original, $position + $length);
253
					} else {
254
						break;
255
					}
256
				}
257
				$count++;
258
			}
259
			return $cache;
260
		}
261
		return $cache;
262
	}
263
 
264
/**
265
 * Write a cached version of the file
266
 *
267
 * @param string $content view content to write to a cache file.
268
 * @param string $timestamp Duration to set for cache file.
269
 * @param boolean $useCallbacks
270
 * @return boolean success of caching view.
271
 */
272
	protected function _writeFile($content, $timestamp, $useCallbacks = false) {
273
		$now = time();
274
 
275
		if (is_numeric($timestamp)) {
276
			$cacheTime = $now + $timestamp;
277
		} else {
278
			$cacheTime = strtotime($timestamp, $now);
279
		}
280
		$path = $this->request->here();
281
		if ($path === '/') {
282
			$path = 'home';
283
		}
284
		$prefix = Configure::read('Cache.viewPrefix');
285
		if ($prefix) {
286
			$path = $prefix . '_' . $path;
287
		}
288
		$cache = strtolower(Inflector::slug($path));
289
 
290
		if (empty($cache)) {
291
			return;
292
		}
293
		$cache = $cache . '.php';
294
		$file = '<!--cachetime:' . $cacheTime . '--><?php';
295
 
296
		if (empty($this->_View->plugin)) {
297
			$file .= "
298
			App::uses('{$this->_View->name}Controller', 'Controller');
299
			";
300
		} else {
301
			$file .= "
302
			App::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');
303
			App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
304
			";
305
		}
306
 
307
		$file .= '
308
				$request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\'));
309
				$response->type(\'' . $this->_View->response->type() . '\');
310
				$controller = new ' . $this->_View->name . 'Controller($request, $response);
311
				$controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
312
				$controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
313
				$controller->layout = $this->layout = \'' . $this->_View->layout . '\';
314
				$controller->theme = $this->theme = \'' . $this->_View->theme . '\';
315
				$controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
316
				Router::setRequestInfo($controller->request);
317
				$this->request = $request;';
318
 
319
		if ($useCallbacks) {
320
			$file .= '
321
				$controller->constructClasses();
322
				$controller->startupProcess();';
323
		}
324
 
325
		$file .= '
326
				$this->viewVars = $controller->viewVars;
327
				$this->loadHelpers();
328
				extract($this->viewVars, EXTR_SKIP);
329
		?>';
330
		$content = preg_replace("/(<\\?xml)/", "<?php echo '$1'; ?>", $content);
331
		$file .= $content;
332
		return cache('views' . DS . $cache, $file, $timestamp);
333
	}
334
 
335
}