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.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 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 2005-2012, 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-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 14:  * @link          http://cakephp.org CakePHP(tm) Project
 15:  * @package       Cake.View.Helper
 16:  * @since         CakePHP(tm) v 1.0.0.2277
 17:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 18:  */
 19: 
 20: App::uses('AppHelper', 'View/Helper');
 21: 
 22: /**
 23:  * CacheHelper helps create full page view caching.
 24:  *
 25:  * When using CacheHelper you don't call any of its methods, they are all automatically
 26:  * called by View, and use the $cacheAction settings set in the controller.
 27:  *
 28:  * @package       Cake.View.Helper
 29:  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
 30:  */
 31: class CacheHelper extends AppHelper {
 32: 
 33: /**
 34:  * Array of strings replaced in cached views.
 35:  * The strings are found between `<!--nocache--><!--/nocache-->` in views
 36:  *
 37:  * @var array
 38:  */
 39:     protected $_replace = array();
 40: 
 41: /**
 42:  * Array of string that are replace with there var replace above.
 43:  * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
 44:  *
 45:  * @var array
 46:  */
 47:     protected $_match = array();
 48: 
 49: /**
 50:  * Counter used for counting nocache section tags.
 51:  *
 52:  * @var integer
 53:  */
 54:     protected $_counter = 0;
 55: 
 56: /**
 57:  * Is CacheHelper enabled? should files + output be parsed.
 58:  *
 59:  * @return boolean
 60:  */
 61:     protected function _enabled() {
 62:         return (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
 63:     }
 64: 
 65: /**
 66:  * Parses the view file and stores content for cache file building.
 67:  *
 68:  * @param string $viewFile
 69:  * @return void
 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 ouput
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:         $cache = strtolower(Inflector::slug($path));
285: 
286:         if (empty($cache)) {
287:             return;
288:         }
289:         $cache = $cache . '.php';
290:         $file = '<!--cachetime:' . $cacheTime . '--><?php';
291: 
292:         if (empty($this->_View->plugin)) {
293:             $file .= "
294:             App::uses('{$this->_View->name}Controller', 'Controller');
295:             ";
296:         } else {
297:             $file .= "
298:             App::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');
299:             App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
300:             ";
301:         }
302: 
303:         $file .= '
304:                 $request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\'));
305:                 $response = new CakeResponse(array("charset" => Configure::read("App.encoding")));
306:                 $controller = new ' . $this->_View->name . 'Controller($request, $response);
307:                 $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
308:                 $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
309:                 $controller->layout = $this->layout = \'' . $this->_View->layout . '\';
310:                 $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
311:                 $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
312:                 Router::setRequestInfo($controller->request);
313:                 $this->request = $request;';
314: 
315:         if ($useCallbacks == true) {
316:             $file .= '
317:                 $controller->constructClasses();
318:                 $controller->startupProcess();';
319:         }
320: 
321:         $file .= '
322:                 $this->viewVars = $controller->viewVars;
323:                 $this->loadHelpers();
324:                 extract($this->viewVars, EXTR_SKIP);
325:         ?>';
326:         $content = preg_replace("/(<\\?xml)/", "<?php echo '$1'; ?>", $content);
327:         $file .= $content;
328:         return cache('views' . DS . $cache, $file, $timestamp);
329:     }
330: 
331: }
332: 
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