source: Dev/branches/cakephp/cake/libs/view/helpers/cache.php @ 126

Last change on this file since 126 was 126, checked in by fpvanagthoven, 14 years ago

Cakephp branch.

File size: 8.7 KB
Line 
1<?php
2/**
3 * CacheHelper helps create full page view caching.
4 *
5 * PHP versions 4 and 5
6 *
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
9 *
10 * Licensed under The MIT License
11 * Redistributions of files must retain the above copyright notice.
12 *
13 * @copyright     Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link          http://cakephp.org CakePHP(tm) Project
15 * @package       cake
16 * @subpackage    cake.cake.libs.view.helpers
17 * @since         CakePHP(tm) v 1.0.0.2277
18 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
19 */
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
28 * @subpackage    cake.cake.libs.view.helpers
29 * @link http://book.cakephp.org/view/1376/Cache
30 */
31class CacheHelper extends AppHelper {
32
33/**
34 * Array of strings replaced in cached views.
35 * The strings are found between <cake:nocache><cake:nocache> in views
36 *
37 * @var array
38 * @access private
39 */
40        var $__replace = array();
41
42/**
43 * Array of string that are replace with there var replace above.
44 * The strings are any content inside <cake:nocache><cake:nocache> and includes the tags in views
45 *
46 * @var array
47 * @access private
48 */
49        var $__match = array();
50
51/**
52 * cache action time
53 *
54 * @var object
55 * @access public
56 */
57        var $cacheAction;
58
59/**
60 * Counter used for counting nocache section tags.
61 *
62 * @var integer
63 */
64        var $_counter = 0;
65
66/**
67 * Main method used to cache a view
68 *
69 * @param string $file File to cache
70 * @param string $out output to cache
71 * @param boolean $cache Whether or not a cache file should be written.
72 * @return string view ouput
73 */
74        function cache($file, $out, $cache = false) {
75                $cacheTime = 0;
76                $useCallbacks = false;
77                if (is_array($this->cacheAction)) {
78                        $keys = array_keys($this->cacheAction);
79                        $index = null;
80
81                        foreach ($keys as $action) {
82                                if ($action == $this->params['action']) {
83                                        $index = $action;
84                                        break;
85                                }
86                        }
87
88                        if (!isset($index) && $this->action == 'index') {
89                                $index = 'index';
90                        }
91
92                        $options = $this->cacheAction;
93                        if (isset($this->cacheAction[$index])) {
94                                if (is_array($this->cacheAction[$index])) {
95                                        $options = array_merge(array('duration' => 0, 'callbacks' => false), $this->cacheAction[$index]);
96                                } else {
97                                        $cacheTime = $this->cacheAction[$index];
98                                }
99                        }
100                        if (isset($options['duration'])) {
101                                $cacheTime = $options['duration'];
102                        }
103                        if (isset($options['callbacks'])) {
104                                $useCallbacks = $options['callbacks'];
105                        }
106                } else {
107                        $cacheTime = $this->cacheAction;
108                }
109
110                if ($cacheTime != '' && $cacheTime > 0) {
111                        $out = preg_replace_callback('/<cake\:nocache>/', array($this, '_replaceSection'), $out);
112
113                        $this->__parseFile($file, $out);
114                        if ($cache === true) {
115                                $cached = $this->__parseOutput($out);
116                                $this->__writeFile($cached, $cacheTime, $useCallbacks);
117                                $out = $this->_stripTags($out);
118                        }
119                        return $out;
120                } else {
121                        return $out;
122                }
123        }
124
125/**
126 * Parse file searching for no cache tags
127 *
128 * @param string $file The filename that needs to be parsed.
129 * @param string $cache The cached content
130 * @access private
131 */
132        function __parseFile($file, $cache) {
133                if (is_file($file)) {
134                        $file = file_get_contents($file);
135                } elseif ($file = fileExistsInPath($file)) {
136                        $file = file_get_contents($file);
137                }
138
139                preg_match_all('/(<cake:nocache:\d{3}>(?<=<cake:nocache:\d{3}>)[\\s\\S]*?(?=<\/cake:nocache>)<\/cake:nocache>)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
140                preg_match_all('/(?<=<cake:nocache>)([\\s\\S]*?)(?=<\/cake:nocache>)/i', $file, $fileResult, PREG_PATTERN_ORDER);
141                $fileResult = $fileResult[0];
142                $outputResult = $outputResult[0];
143
144                if (!empty($this->__replace)) {
145                        foreach ($outputResult as $i => $element) {
146                                $index = array_search($element, $this->__match);
147                                if ($index !== false) {
148                                        unset($outputResult[$i]);
149                                }
150                        }
151                        $outputResult = array_values($outputResult);
152                }
153
154                if (!empty($fileResult)) {
155                        $i = 0;
156                        foreach ($fileResult as $cacheBlock) {
157                                if (isset($outputResult[$i])) {
158                                        $this->__replace[] = $cacheBlock;
159                                        $this->__match[] = $outputResult[$i];
160                                }
161                                $i++;
162                        }
163                }
164        }
165
166/**
167 * Munges the output from a view with cache tags, and numbers the sections.
168 * This helps solve issues with empty/duplicate content.
169 *
170 * @param string $content The content to munge.
171 * @return string The content with cake:nocache tags replaced.
172 */
173        function _replaceSection($matches) {
174                $this->_counter += 1;
175                return sprintf('<cake:nocache:%03d>', $this->_counter);
176        }
177
178/**
179 * Strip cake:nocache tags from a string. Since View::render()
180 * only removes un-numbered nocache tags, remove all the numbered ones.
181 * This is the complement to _replaceSection.
182 *
183 * @param string $content String to remove tags from.
184 * @return string String with tags removed.
185 */
186        function _stripTags($content) {
187                return preg_replace('#<\/?cake\:nocache(\:\d{3})?>#', '', $content);
188        }
189
190/**
191 * Parse the output and replace cache tags
192 *
193 * @param string $cache Output to replace content in.
194 * @return string with all replacements made to <cake:nocache><cake:nocache>
195 * @access private
196 */
197        function __parseOutput($cache) {
198                $count = 0;
199                if (!empty($this->__match)) {
200                        foreach ($this->__match as $found) {
201                                $original = $cache;
202                                $length = strlen($found);
203                                $position = 0;
204
205                                for ($i = 1; $i <= 1; $i++) {
206                                        $position = strpos($cache, $found, $position);
207
208                                        if ($position !== false) {
209                                                $cache = substr($original, 0, $position);
210                                                $cache .= $this->__replace[$count];
211                                                $cache .= substr($original, $position + $length);
212                                        } else {
213                                                break;
214                                        }
215                                }
216                                $count++;
217                        }
218                        return $cache;
219                }
220                return $cache;
221        }
222
223/**
224 * Write a cached version of the file
225 *
226 * @param string $content view content to write to a cache file.
227 * @param sting $timestamp Duration to set for cache file.
228 * @return boolean success of caching view.
229 * @access private
230 */
231        function __writeFile($content, $timestamp, $useCallbacks = false) {
232                $now = time();
233
234                if (is_numeric($timestamp)) {
235                        $cacheTime = $now + $timestamp;
236                } else {
237                        $cacheTime = strtotime($timestamp, $now);
238                }
239                $path = $this->here;
240                if ($this->here == '/') {
241                        $path = 'home';
242                }
243                $cache = strtolower(Inflector::slug($path));
244
245                if (empty($cache)) {
246                        return;
247                }
248                $cache = $cache . '.php';
249                $file = '<!--cachetime:' . $cacheTime . '--><?php';
250
251                if (empty($this->plugin)) {
252                        $file .= '
253                        App::import(\'Controller\', \'' . $this->controllerName. '\');
254                        ';
255                } else {
256                        $file .= '
257                        App::import(\'Controller\', \'' . $this->plugin . '.' . $this->controllerName. '\');
258                        ';
259                }
260
261                $file .= '$controller =& new ' . $this->controllerName . 'Controller();
262                                $controller->plugin = $this->plugin = \''.$this->plugin.'\';
263                                $controller->helpers = $this->helpers = unserialize(\'' . serialize($this->helpers) . '\');
264                                $controller->base = $this->base = \'' . $this->base . '\';
265                                $controller->layout = $this->layout = \'' . $this->layout. '\';
266                                $controller->webroot = $this->webroot = \'' . $this->webroot . '\';
267                                $controller->here = $this->here = \'' . $this->here . '\';
268                                $controller->params = $this->params = unserialize(stripslashes(\'' . addslashes(serialize($this->params)) . '\'));
269                                $controller->action = $this->action = unserialize(\'' . serialize($this->action) . '\');
270                                $controller->data = $this->data = unserialize(stripslashes(\'' . addslashes(serialize($this->data)) . '\'));
271                                $controller->viewVars = $this->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->viewVars)) . '\'));
272                                $controller->theme = $this->theme = \'' . $this->theme . '\';
273                                Router::setRequestInfo(array($this->params, array(\'base\' => $this->base, \'webroot\' => $this->webroot)));';
274
275                if ($useCallbacks == true) {
276                        $file .= '
277                                $controller->constructClasses();
278                                $controller->Component->initialize($controller);
279                                $controller->beforeFilter();
280                                $controller->Component->startup($controller);
281                                $this->params = $controller->params;';
282                }
283
284                $file .= '
285                                $loadedHelpers = array();
286                                $loadedHelpers = $this->_loadHelpers($loadedHelpers, $this->helpers);
287                                foreach (array_keys($loadedHelpers) as $helper) {
288                                        $camelBackedHelper = Inflector::variable($helper);
289                                        ${$camelBackedHelper} =& $loadedHelpers[$helper];
290                                        $this->loaded[$camelBackedHelper] =& ${$camelBackedHelper};
291                                        $this->{$helper} =& $loadedHelpers[$helper];
292                                }
293                                extract($this->viewVars, EXTR_SKIP);
294                ?>';
295                $content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>",$content);
296                $file .= $content;
297                return cache('views' . DS . $cache, $file, $timestamp);
298        }
299}
Note: See TracBrowser for help on using the repository browser.