PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/CacheHelper.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 305 lines | 179 code | 27 blank | 99 comment | 39 complexity | d946a37233be752786a89ccc771e3e09 MD5 | raw file
  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-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.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. App::uses('AppHelper', 'View/Helper');
  20. /**
  21. * CacheHelper helps create full page view caching.
  22. *
  23. * When using CacheHelper you don't call any of its methods, they are all automatically
  24. * called by View, and use the $cacheAction settings set in the controller.
  25. *
  26. * @package Cake.View.Helper
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  28. */
  29. class CacheHelper extends AppHelper {
  30. /**
  31. * Array of strings replaced in cached views.
  32. * The strings are found between `<!--nocache--><!--/nocache-->` in views
  33. *
  34. * @var array
  35. */
  36. protected $_replace = array();
  37. /**
  38. * Array of string that are replace with there var replace above.
  39. * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
  40. *
  41. * @var array
  42. */
  43. protected $_match = array();
  44. /**
  45. * Counter used for counting nocache section tags.
  46. *
  47. * @var integer
  48. */
  49. protected $_counter = 0;
  50. /**
  51. * Parses the view file and stores content for cache file building.
  52. *
  53. * @param string $viewFile
  54. * @return void
  55. */
  56. public function afterRender($viewFile) {
  57. $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
  58. if ($caching) {
  59. $this->_View->output = $this->cache($viewFile, $this->_View->output, false);
  60. }
  61. }
  62. /**
  63. * Parses the layout file and stores content for cache file building.
  64. *
  65. * @param string $layoutFile
  66. * @return void
  67. */
  68. public function afterLayout($layoutFile) {
  69. $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
  70. if ($caching) {
  71. $this->_View->output = $this->cache($layoutFile, $this->_View->output, true);
  72. }
  73. $this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output);
  74. }
  75. /**
  76. * Main method used to cache a view
  77. *
  78. * @param string $file File to cache
  79. * @param string $out output to cache
  80. * @param boolean $cache Whether or not a cache file should be written.
  81. * @return string view output
  82. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  83. */
  84. public function cache($file, $out, $cache = false) {
  85. $cacheTime = 0;
  86. $useCallbacks = false;
  87. $cacheAction = $this->_View->cacheAction;
  88. if (is_array($cacheAction)) {
  89. $keys = array_keys($cacheAction);
  90. $index = null;
  91. foreach ($keys as $action) {
  92. if ($action == $this->request->params['action']) {
  93. $index = $action;
  94. break;
  95. }
  96. }
  97. if (!isset($index) && $this->request->params['action'] == 'index') {
  98. $index = 'index';
  99. }
  100. $options = $cacheAction;
  101. if (isset($cacheAction[$index])) {
  102. if (is_array($cacheAction[$index])) {
  103. $options = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]);
  104. } else {
  105. $cacheTime = $cacheAction[$index];
  106. }
  107. }
  108. if (isset($options['duration'])) {
  109. $cacheTime = $options['duration'];
  110. }
  111. if (isset($options['callbacks'])) {
  112. $useCallbacks = $options['callbacks'];
  113. }
  114. } else {
  115. $cacheTime = $cacheAction;
  116. }
  117. if ($cacheTime != '' && $cacheTime > 0) {
  118. $out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out);
  119. $this->_parseFile($file, $out);
  120. if ($cache === true) {
  121. $cached = $this->_parseOutput($out);
  122. $this->_writeFile($cached, $cacheTime, $useCallbacks);
  123. $out = $this->_stripTags($out);
  124. }
  125. return $out;
  126. } else {
  127. return $out;
  128. }
  129. }
  130. /**
  131. * Parse file searching for no cache tags
  132. *
  133. * @param string $file The filename that needs to be parsed.
  134. * @param string $cache The cached content
  135. * @return void
  136. */
  137. protected function _parseFile($file, $cache) {
  138. if (is_file($file)) {
  139. $file = file_get_contents($file);
  140. } elseif ($file = fileExistsInPath($file)) {
  141. $file = file_get_contents($file);
  142. }
  143. preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
  144. preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
  145. $fileResult = $fileResult[0];
  146. $outputResult = $outputResult[0];
  147. if (!empty($this->_replace)) {
  148. foreach ($outputResult as $i => $element) {
  149. $index = array_search($element, $this->_match);
  150. if ($index !== false) {
  151. unset($outputResult[$i]);
  152. }
  153. }
  154. $outputResult = array_values($outputResult);
  155. }
  156. if (!empty($fileResult)) {
  157. $i = 0;
  158. foreach ($fileResult as $cacheBlock) {
  159. if (isset($outputResult[$i])) {
  160. $this->_replace[] = $cacheBlock;
  161. $this->_match[] = $outputResult[$i];
  162. }
  163. $i++;
  164. }
  165. }
  166. }
  167. /**
  168. * Munges the output from a view with cache tags, and numbers the sections.
  169. * This helps solve issues with empty/duplicate content.
  170. *
  171. * @return string The content with cake:nocache tags replaced.
  172. */
  173. protected function _replaceSection() {
  174. $this->_counter += 1;
  175. return sprintf('<!--nocache:%03d-->', $this->_counter);
  176. }
  177. /**
  178. * Strip cake:nocache tags from a string. Since View::render()
  179. * only removes un-numbered nocache tags, remove all the numbered ones.
  180. * This is the complement to _replaceSection.
  181. *
  182. * @param string $content String to remove tags from.
  183. * @return string String with tags removed.
  184. */
  185. protected function _stripTags($content) {
  186. return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
  187. }
  188. /**
  189. * Parse the output and replace cache tags
  190. *
  191. * @param string $cache Output to replace content in.
  192. * @return string with all replacements made to <!--nocache--><!--nocache-->
  193. */
  194. protected function _parseOutput($cache) {
  195. $count = 0;
  196. if (!empty($this->_match)) {
  197. foreach ($this->_match as $found) {
  198. $original = $cache;
  199. $length = strlen($found);
  200. $position = 0;
  201. for ($i = 1; $i <= 1; $i++) {
  202. $position = strpos($cache, $found, $position);
  203. if ($position !== false) {
  204. $cache = substr($original, 0, $position);
  205. $cache .= $this->_replace[$count];
  206. $cache .= substr($original, $position + $length);
  207. } else {
  208. break;
  209. }
  210. }
  211. $count++;
  212. }
  213. return $cache;
  214. }
  215. return $cache;
  216. }
  217. /**
  218. * Write a cached version of the file
  219. *
  220. * @param string $content view content to write to a cache file.
  221. * @param string $timestamp Duration to set for cache file.
  222. * @param boolean $useCallbacks
  223. * @return boolean success of caching view.
  224. */
  225. protected function _writeFile($content, $timestamp, $useCallbacks = false) {
  226. $now = time();
  227. if (is_numeric($timestamp)) {
  228. $cacheTime = $now + $timestamp;
  229. } else {
  230. $cacheTime = strtotime($timestamp, $now);
  231. }
  232. $path = $this->request->here();
  233. if ($path == '/') {
  234. $path = 'home';
  235. }
  236. $cache = strtolower(Inflector::slug($path));
  237. if (empty($cache)) {
  238. return;
  239. }
  240. $cache = $cache . '.php';
  241. $file = '<!--cachetime:' . $cacheTime . '--><?php';
  242. if (empty($this->_View->plugin)) {
  243. $file .= "
  244. App::uses('{$this->_View->name}Controller', 'Controller');
  245. ";
  246. } else {
  247. $file .= "
  248. App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
  249. ";
  250. }
  251. $file .= '
  252. $request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\');
  253. $response = new CakeResponse(array("charset" => Configure::read("App.encoding")));
  254. $controller = new ' . $this->_View->name . 'Controller($request, $response);
  255. $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
  256. $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
  257. $controller->layout = $this->layout = \'' . $this->_View->layout . '\';
  258. $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
  259. $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
  260. Router::setRequestInfo($controller->request);
  261. $this->request = $request;';
  262. if ($useCallbacks == true) {
  263. $file .= '
  264. $controller->constructClasses();
  265. $controller->startupProcess();';
  266. }
  267. $file .= '
  268. $this->viewVars = $controller->viewVars;
  269. $this->loadHelpers();
  270. extract($this->viewVars, EXTR_SKIP);
  271. ?>';
  272. $content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>", $content);
  273. $file .= $content;
  274. return cache('views' . DS . $cache, $file, $timestamp);
  275. }
  276. }