CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.3
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs