統計
| ブランチ: | リビジョン:

pictcode_admin / lib / Cake / View / Helper / CacheHelper.php @ 5ad38a95

履歴 | 表示 | アノテート | ダウンロード (9.802 KB)

1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @package       Cake.View.Helper
13
 * @since         CakePHP(tm) v 1.0.0.2277
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16

    
17
App::uses('AppHelper', 'View/Helper');
18

    
19
/**
20
 * CacheHelper helps create full page view caching.
21
 *
22
 * When using CacheHelper you don't call any of its methods, they are all automatically
23
 * called by View, and use the $cacheAction settings set in the controller.
24
 *
25
 * @package Cake.View.Helper
26
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
27
 * @deprecated This class will be removed in 3.0. You should use a separate response cache
28
 * like Varnish instead.
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 int
52
 */
53
        protected $_counter = 0;
54

    
55
/**
56
 * Is CacheHelper enabled? should files + output be parsed.
57
 *
58
 * @return bool
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 View file name.
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 Layout file name.
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
 * @throws Exception If debug mode is enabled and writing to cache file fails.
113
 */
114
        public function cache($file, $out) {
115
                $cacheTime = 0;
116
                $useCallbacks = false;
117
                $cacheAction = $this->_View->cacheAction;
118

    
119
                if (is_array($cacheAction)) {
120
                        $keys = array_keys($cacheAction);
121
                        $index = null;
122

    
123
                        foreach ($keys as $action) {
124
                                if ($action === $this->request->params['action']) {
125
                                        $index = $action;
126
                                        break;
127
                                }
128
                        }
129

    
130
                        if (!isset($index) && $this->request->params['action'] === 'index') {
131
                                $index = 'index';
132
                        }
133

    
134
                        $options = $cacheAction;
135
                        if (isset($cacheAction[$index])) {
136
                                if (is_array($cacheAction[$index])) {
137
                                        $options = $cacheAction[$index] + array('duration' => 0, 'callbacks' => false);
138
                                } else {
139
                                        $cacheTime = $cacheAction[$index];
140
                                }
141
                        }
142
                        if (isset($options['duration'])) {
143
                                $cacheTime = $options['duration'];
144
                        }
145
                        if (isset($options['callbacks'])) {
146
                                $useCallbacks = $options['callbacks'];
147
                        }
148
                } else {
149
                        $cacheTime = $cacheAction;
150
                }
151

    
152
                if ($cacheTime && $cacheTime > 0) {
153
                        $cached = $this->_parseOutput($out);
154
                        try {
155
                                $this->_writeFile($cached, $cacheTime, $useCallbacks);
156
                        } catch (Exception $e) {
157
                                if (Configure::read('debug')) {
158
                                        throw $e;
159
                                }
160

    
161
                                $message = __d(
162
                                        'cake_dev',
163
                                        'Unable to write view cache file: "%s" for "%s"',
164
                                        $e->getMessage(),
165
                                        $this->request->here
166
                                );
167
                                $this->log($message, 'error');
168
                        }
169
                        $out = $this->_stripTags($out);
170
                }
171
                return $out;
172
        }
173

    
174
/**
175
 * Parse file searching for no cache tags
176
 *
177
 * @param string $file The filename that needs to be parsed.
178
 * @param string $cache The cached content
179
 * @return void
180
 */
181
        protected function _parseFile($file, $cache) {
182
                if (is_file($file)) {
183
                        $file = file_get_contents($file);
184
                } elseif ($file = fileExistsInPath($file)) {
185
                        $file = file_get_contents($file);
186
                }
187
                preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
188
                preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
189
                $fileResult = $fileResult[0];
190
                $outputResult = $outputResult[0];
191

    
192
                if (!empty($this->_replace)) {
193
                        foreach ($outputResult as $i => $element) {
194
                                $index = array_search($element, $this->_match);
195
                                if ($index !== false) {
196
                                        unset($outputResult[$i]);
197
                                }
198
                        }
199
                        $outputResult = array_values($outputResult);
200
                }
201

    
202
                if (!empty($fileResult)) {
203
                        $i = 0;
204
                        foreach ($fileResult as $cacheBlock) {
205
                                if (isset($outputResult[$i])) {
206
                                        $this->_replace[] = $cacheBlock;
207
                                        $this->_match[] = $outputResult[$i];
208
                                }
209
                                $i++;
210
                        }
211
                }
212
        }
213

    
214
/**
215
 * Munges the output from a view with cache tags, and numbers the sections.
216
 * This helps solve issues with empty/duplicate content.
217
 *
218
 * @return string The content with cake:nocache tags replaced.
219
 */
220
        protected function _replaceSection() {
221
                $this->_counter += 1;
222
                return sprintf('<!--nocache:%03d-->', $this->_counter);
223
        }
224

    
225
/**
226
 * Strip cake:nocache tags from a string. Since View::render()
227
 * only removes un-numbered nocache tags, remove all the numbered ones.
228
 * This is the complement to _replaceSection.
229
 *
230
 * @param string $content String to remove tags from.
231
 * @return string String with tags removed.
232
 */
233
        protected function _stripTags($content) {
234
                return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
235
        }
236

    
237
/**
238
 * Parse the output and replace cache tags
239
 *
240
 * @param string $cache Output to replace content in.
241
 * @return string with all replacements made to <!--nocache--><!--nocache-->
242
 */
243
        protected function _parseOutput($cache) {
244
                $count = 0;
245
                if (!empty($this->_match)) {
246
                        foreach ($this->_match as $found) {
247
                                $original = $cache;
248
                                $length = strlen($found);
249
                                $position = 0;
250

    
251
                                for ($i = 1; $i <= 1; $i++) {
252
                                        $position = strpos($cache, $found, $position);
253

    
254
                                        if ($position !== false) {
255
                                                $cache = substr($original, 0, $position);
256
                                                $cache .= $this->_replace[$count];
257
                                                $cache .= substr($original, $position + $length);
258
                                        } else {
259
                                                break;
260
                                        }
261
                                }
262
                                $count++;
263
                        }
264
                        return $cache;
265
                }
266
                return $cache;
267
        }
268

    
269
/**
270
 * Write a cached version of the file
271
 *
272
 * @param string $content view content to write to a cache file.
273
 * @param string $timestamp Duration to set for cache file.
274
 * @param bool|null $useCallbacks Whether to include statements in cached file which
275
 *   run callbacks, otherwise null.
276
 * @return bool success of caching view.
277
 */
278
        protected function _writeFile($content, $timestamp, $useCallbacks = false) {
279
                $now = time();
280

    
281
                if (is_numeric($timestamp)) {
282
                        $cacheTime = $now + $timestamp;
283
                } else {
284
                        $cacheTime = strtotime($timestamp, $now);
285
                }
286
                $path = $this->request->here();
287
                if ($path === '/') {
288
                        $path = 'home';
289
                }
290
                $prefix = Configure::read('Cache.viewPrefix');
291
                if ($prefix) {
292
                        $path = $prefix . '_' . $path;
293
                }
294
                $cache = strtolower(Inflector::slug($path));
295

    
296
                if (empty($cache)) {
297
                        return null;
298
                }
299
                $cache = $cache . '.php';
300
                $file = '<!--cachetime:' . $cacheTime . '--><?php';
301

    
302
                if (empty($this->_View->plugin)) {
303
                        $file .= "
304
                        App::uses('{$this->_View->name}Controller', 'Controller');
305
                        ";
306
                } else {
307
                        $file .= "
308
                        App::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');
309
                        App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
310
                        ";
311
                }
312

    
313
                $file .= '
314
                                $request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\'));
315
                                $response->type(\'' . $this->_View->response->type() . '\');
316
                                $controller = new ' . $this->_View->name . 'Controller($request, $response);
317
                                $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
318
                                $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
319
                                $controller->layout = $this->layout = \'' . $this->_View->layout . '\';
320
                                $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
321
                                $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
322
                                Router::setRequestInfo($controller->request);
323
                                $this->request = $request;';
324

    
325
                if ($useCallbacks) {
326
                        $file .= '
327
                                $controller->constructClasses();
328
                                $controller->startupProcess();';
329
                }
330

    
331
                $file .= '
332
                                $this->viewVars = $controller->viewVars;
333
                                $this->loadHelpers();
334
                                extract($this->viewVars, EXTR_SKIP);
335
                ?>';
336
                $content = preg_replace("/(<\\?xml)/", "<?php echo '$1'; ?>", $content);
337
                $file .= $content;
338
                return cache('views' . DS . $cache, $file, $timestamp);
339
        }
340

    
341
}