PageRenderTime 73ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/app/application/libraries/dwoo/Dwoo/Template/String.php

https://github.com/almonk/Deadweight-CMS-1
PHP | 497 lines | 206 code | 52 blank | 239 comment | 39 complexity | a7db2fe8ec5c573a65db4895ab0f3c7c MD5 | raw file
  1. <?php
  2. /**
  3. * represents a Dwoo template contained in a string
  4. *
  5. * This software is provided 'as-is', without any express or implied warranty.
  6. * In no event will the authors be held liable for any damages arising from the use of this software.
  7. *
  8. * @author Jordi Boggiano <j.boggiano@seld.be>
  9. * @copyright Copyright (c) 2008, Jordi Boggiano
  10. * @license http://dwoo.org/LICENSE Modified BSD License
  11. * @link http://dwoo.org/
  12. * @version 1.1.0
  13. * @date 2009-07-18
  14. * @package Dwoo
  15. */
  16. class Dwoo_Template_String implements Dwoo_ITemplate
  17. {
  18. /**
  19. * template name
  20. *
  21. * @var string
  22. */
  23. protected $name;
  24. /**
  25. * template compilation id
  26. *
  27. * @var string
  28. */
  29. protected $compileId;
  30. /**
  31. * template cache id, if not provided in the constructor, it is set to
  32. * the md4 hash of the request_uri. it is however highly recommended to
  33. * provide one that will fit your needs.
  34. *
  35. * in all cases, the compilation id is prepended to the cache id to separate
  36. * templates with similar cache ids from one another
  37. *
  38. * @var string
  39. */
  40. protected $cacheId;
  41. /**
  42. * validity duration of the generated cache file (in seconds)
  43. *
  44. * set to -1 for infinite cache, 0 to disable and null to inherit the Dwoo instance's cache time
  45. *
  46. * @var int
  47. */
  48. protected $cacheTime;
  49. /**
  50. * boolean flag that defines whether the compilation should be enforced (once) or
  51. * not use this if you have issues with the compiled templates not being updated
  52. * but if you do need this it's most likely that you should file a bug report
  53. *
  54. * @var bool
  55. */
  56. protected $compilationEnforced;
  57. /**
  58. * caches the results of the file checks to save some time when the same
  59. * templates is rendered several times
  60. *
  61. * @var array
  62. */
  63. protected static $cache = array('cached'=>array(), 'compiled'=>array());
  64. /**
  65. * holds the compiler that built this template
  66. *
  67. * @var Dwoo_ICompiler
  68. */
  69. protected $compiler;
  70. /**
  71. * chmod value for all files written (cached or compiled ones)
  72. *
  73. * set to null if you don't want any chmod operation to happen
  74. *
  75. * @var int
  76. */
  77. protected $chmod = 0777;
  78. /**
  79. * creates a template from a string
  80. *
  81. * @param string $templateString the template to use
  82. * @param int $cacheTime duration of the cache validity for this template,
  83. * if null it defaults to the Dwoo instance that will
  84. * render this template, set to -1 for infinite cache or 0 to disable
  85. * @param string $cacheId the unique cache identifier of this page or anything else that
  86. * makes this template's content unique, if null it defaults
  87. * to the current url
  88. * @param string $compileId the unique compiled identifier, which is used to distinguish this
  89. * template from others, if null it defaults to the md4 hash of the template
  90. */
  91. public function __construct($templateString, $cacheTime = null, $cacheId = null, $compileId = null)
  92. {
  93. $this->template = $templateString;
  94. if (function_exists('hash')) {
  95. $this->name = hash('md4', $templateString);
  96. } else {
  97. $this->name = md5($templateString);
  98. }
  99. $this->cacheTime = $cacheTime;
  100. if ($compileId !== null) {
  101. $this->compileId = str_replace('../', '__', strtr($compileId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'));
  102. }
  103. if ($cacheId !== null) {
  104. $this->cacheId = str_replace('../', '__', strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'));
  105. }
  106. }
  107. /**
  108. * returns the cache duration for this template
  109. *
  110. * defaults to null if it was not provided
  111. *
  112. * @return int|null
  113. */
  114. public function getCacheTime()
  115. {
  116. return $this->cacheTime;
  117. }
  118. /**
  119. * sets the cache duration for this template
  120. *
  121. * can be used to set it after the object is created if you did not provide
  122. * it in the constructor
  123. *
  124. * @param int $seconds duration of the cache validity for this template, if
  125. * null it defaults to the Dwoo instance's cache time. 0 = disable and
  126. * -1 = infinite cache
  127. */
  128. public function setCacheTime($seconds = null)
  129. {
  130. $this->cacheTime = $seconds;
  131. }
  132. /**
  133. * returns the chmod value for all files written (cached or compiled ones)
  134. *
  135. * defaults to 0777
  136. *
  137. * @return int|null
  138. */
  139. public function getChmod()
  140. {
  141. return $this->chmod;
  142. }
  143. /**
  144. * set the chmod value for all files written (cached or compiled ones)
  145. *
  146. * set to null if you don't want to do any chmod() operation
  147. *
  148. * @param int $mask new bitmask to use for all files
  149. */
  150. public function setChmod($mask = null)
  151. {
  152. $this->chmod = $mask;
  153. }
  154. /**
  155. * returns the template name
  156. *
  157. * @return string
  158. */
  159. public function getName()
  160. {
  161. return $this->name;
  162. }
  163. /**
  164. * returns the resource name for this template class
  165. *
  166. * @return string
  167. */
  168. public function getResourceName()
  169. {
  170. return 'string';
  171. }
  172. /**
  173. * returns the resource identifier for this template, false here as strings don't have identifiers
  174. *
  175. * @return false
  176. */
  177. public function getResourceIdentifier()
  178. {
  179. return false;
  180. }
  181. /**
  182. * returns the template source of this template
  183. *
  184. * @return string
  185. */
  186. public function getSource()
  187. {
  188. return $this->template;
  189. }
  190. /**
  191. * returns an unique value identifying the current version of this template,
  192. * in this case it's the md4 hash of the content
  193. *
  194. * @return string
  195. */
  196. public function getUid()
  197. {
  198. return $this->name;
  199. }
  200. /**
  201. * returns the compiler used by this template, if it was just compiled, or null
  202. *
  203. * @return Dwoo_ICompiler
  204. */
  205. public function getCompiler()
  206. {
  207. return $this->compiler;
  208. }
  209. /**
  210. * marks this template as compile-forced, which means it will be recompiled even if it
  211. * was already saved and wasn't modified since the last compilation. do not use this in production,
  212. * it's only meant to be used in development (and the development of dwoo particularly)
  213. */
  214. public function forceCompilation()
  215. {
  216. $this->compilationEnforced = true;
  217. }
  218. /**
  219. * returns the cached template output file name, true if it's cache-able but not cached
  220. * or false if it's not cached
  221. *
  222. * @param Dwoo $dwoo the dwoo instance that requests it
  223. * @return string|bool
  224. */
  225. public function getCachedTemplate(Dwoo $dwoo)
  226. {
  227. if ($this->cacheTime !== null) {
  228. $cacheLength = $this->cacheTime;
  229. } else {
  230. $cacheLength = $dwoo->getCacheTime();
  231. }
  232. // file is not cacheable
  233. if ($cacheLength === 0) {
  234. return false;
  235. }
  236. $cachedFile = $this->getCacheFilename($dwoo);
  237. if (isset(self::$cache['cached'][$this->cacheId]) === true && file_exists($cachedFile)) {
  238. // already checked, return cache file
  239. return $cachedFile;
  240. } elseif ($this->compilationEnforced !== true && file_exists($cachedFile) && ($cacheLength === -1 || filemtime($cachedFile) > ($_SERVER['REQUEST_TIME'] - $cacheLength))) {
  241. // cache is still valid and can be loaded
  242. self::$cache['cached'][$this->cacheId] = true;
  243. return $cachedFile;
  244. } else {
  245. // file is cacheable
  246. return true;
  247. }
  248. }
  249. /**
  250. * caches the provided output into the cache file
  251. *
  252. * @param Dwoo $dwoo the dwoo instance that requests it
  253. * @param string $output the template output
  254. * @return mixed full path of the cached file or false upon failure
  255. */
  256. public function cache(Dwoo $dwoo, $output)
  257. {
  258. $cacheDir = $dwoo->getCacheDir();
  259. $cachedFile = $this->getCacheFilename($dwoo);
  260. // the code below is courtesy of Rasmus Schultz,
  261. // thanks for his help on avoiding concurency issues
  262. $temp = tempnam($cacheDir, 'temp');
  263. if (!($file = @fopen($temp, 'wb'))) {
  264. $temp = $cacheDir . uniqid('temp');
  265. if (!($file = @fopen($temp, 'wb'))) {
  266. trigger_error('Error writing temporary file \''.$temp.'\'', E_USER_WARNING);
  267. return false;
  268. }
  269. }
  270. fwrite($file, $output);
  271. fclose($file);
  272. $this->makeDirectory(dirname($cachedFile), $cacheDir);
  273. if (!@rename($temp, $cachedFile)) {
  274. @unlink($cachedFile);
  275. @rename($temp, $cachedFile);
  276. }
  277. if ($this->chmod !== null) {
  278. chmod($cachedFile, $this->chmod);
  279. }
  280. self::$cache['cached'][$this->cacheId] = true;
  281. return $cachedFile;
  282. }
  283. /**
  284. * clears the cached template if it's older than the given time
  285. *
  286. * @param Dwoo $dwoo the dwoo instance that was used to cache that template
  287. * @param int $olderThan minimum time (in seconds) required for the cache to be cleared
  288. * @return bool true if the cache was not present or if it was deleted, false if it remains there
  289. */
  290. public function clearCache(Dwoo $dwoo, $olderThan = -1)
  291. {
  292. $cachedFile = $this->getCacheFilename($dwoo);
  293. return !file_exists($cachedFile) || (filectime($cachedFile) < (time() - $olderThan) && unlink($cachedFile));
  294. }
  295. /**
  296. * returns the compiled template file name
  297. *
  298. * @param Dwoo $dwoo the dwoo instance that requests it
  299. * @param Dwoo_ICompiler $compiler the compiler that must be used
  300. * @return string
  301. */
  302. public function getCompiledTemplate(Dwoo $dwoo, Dwoo_ICompiler $compiler = null)
  303. {
  304. $compiledFile = $this->getCompiledFilename($dwoo);
  305. if ($this->compilationEnforced !== true && isset(self::$cache['compiled'][$this->compileId]) === true) {
  306. // already checked, return compiled file
  307. } elseif ($this->compilationEnforced !== true && $this->isValidCompiledFile($compiledFile)) {
  308. // template is compiled
  309. self::$cache['compiled'][$this->compileId] = true;
  310. } else {
  311. // compiles the template
  312. $this->compilationEnforced = false;
  313. if ($compiler === null) {
  314. $compiler = $dwoo->getDefaultCompilerFactory($this->getResourceName());
  315. if ($compiler === null || $compiler === array('Dwoo_Compiler', 'compilerFactory')) {
  316. if (class_exists('Dwoo_Compiler', false) === false) {
  317. include DWOO_DIRECTORY . 'Dwoo/Compiler.php';
  318. }
  319. $compiler = Dwoo_Compiler::compilerFactory();
  320. } else {
  321. $compiler = call_user_func($compiler);
  322. }
  323. }
  324. $this->compiler = $compiler;
  325. $compiler->setCustomPlugins($dwoo->getCustomPlugins());
  326. $compiler->setSecurityPolicy($dwoo->getSecurityPolicy());
  327. $this->makeDirectory(dirname($compiledFile), $dwoo->getCompileDir());
  328. file_put_contents($compiledFile, $compiler->compile($dwoo, $this));
  329. if ($this->chmod !== null) {
  330. chmod($compiledFile, $this->chmod);
  331. }
  332. self::$cache['compiled'][$this->compileId] = true;
  333. }
  334. return $compiledFile;
  335. }
  336. /**
  337. * Checks if compiled file is valid (it exists)
  338. *
  339. * @param string file
  340. * @return boolean True cache file existance
  341. */
  342. protected function isValidCompiledFile($file) {
  343. return file_exists($file);
  344. }
  345. /**
  346. * returns a new template string object with the resource id being the template source code
  347. *
  348. * @param Dwoo $dwoo the dwoo instance requiring it
  349. * @param mixed $resourceId the filename (relative to this template's dir) of the template to include
  350. * @param int $cacheTime duration of the cache validity for this template,
  351. * if null it defaults to the Dwoo instance that will
  352. * render this template
  353. * @param string $cacheId the unique cache identifier of this page or anything else that
  354. * makes this template's content unique, if null it defaults
  355. * to the current url
  356. * @param string $compileId the unique compiled identifier, which is used to distinguish this
  357. * template from others, if null it defaults to the filename+bits of the path
  358. * @param Dwoo_ITemplate $parentTemplate the template that is requesting a new template object (through
  359. * an include, extends or any other plugin)
  360. * @return Dwoo_Template_String
  361. */
  362. public static function templateFactory(Dwoo $dwoo, $resourceId, $cacheTime = null, $cacheId = null, $compileId = null, Dwoo_ITemplate $parentTemplate = null)
  363. {
  364. return new self($resourceId, $cacheTime, $cacheId, $compileId);
  365. }
  366. /**
  367. * returns the full compiled file name and assigns a default value to it if
  368. * required
  369. *
  370. * @param Dwoo $dwoo the dwoo instance that requests the file name
  371. * @return string the full path to the compiled file
  372. */
  373. protected function getCompiledFilename(Dwoo $dwoo)
  374. {
  375. // no compile id was provided, set default
  376. if ($this->compileId===null) {
  377. $this->compileId = $this->name;
  378. }
  379. return $dwoo->getCompileDir() . $this->compileId.'.d'.Dwoo::RELEASE_TAG.'.php';
  380. }
  381. /**
  382. * returns the full cached file name and assigns a default value to it if
  383. * required
  384. *
  385. * @param Dwoo $dwoo the dwoo instance that requests the file name
  386. * @return string the full path to the cached file
  387. */
  388. protected function getCacheFilename(Dwoo $dwoo)
  389. {
  390. // no cache id provided, use request_uri as default
  391. if ($this->cacheId === null) {
  392. if (isset($_SERVER['REQUEST_URI']) === true) {
  393. $cacheId = $_SERVER['REQUEST_URI'];
  394. } elseif (isset($_SERVER['SCRIPT_FILENAME']) && isset($_SERVER['argv'])) {
  395. $cacheId = $_SERVER['SCRIPT_FILENAME'].'-'.implode('-', $_SERVER['argv']);
  396. } else {
  397. $cacheId = '';
  398. }
  399. // force compiled id generation
  400. $this->getCompiledFilename($dwoo);
  401. $this->cacheId = str_replace('../', '__', $this->compileId . strtr($cacheId, '\\%?=!:;'.PATH_SEPARATOR, '/-------'));
  402. }
  403. return $dwoo->getCacheDir() . $this->cacheId.'.html';
  404. }
  405. /**
  406. * returns some php code that will check if this template has been modified or not
  407. *
  408. * if the function returns null, the template will be instanciated and then the Uid checked
  409. *
  410. * @return string
  411. */
  412. public function getIsModifiedCode()
  413. {
  414. return null;
  415. }
  416. /**
  417. * ensures the given path exists
  418. *
  419. * @param string $path any path
  420. * @param string $baseDir the base directory where the directory is created
  421. * ($path must still contain the full path, $baseDir
  422. * is only used for unix permissions)
  423. */
  424. protected function makeDirectory($path, $baseDir = null)
  425. {
  426. if (is_dir($path) === true) {
  427. return;
  428. }
  429. if ($this->chmod === null) {
  430. $chmod = 0777;
  431. } else {
  432. $chmod = $this->chmod;
  433. }
  434. mkdir($path, $chmod, true);
  435. // enforce the correct mode for all directories created
  436. if (strpos(PHP_OS, 'WIN') !== 0 && $baseDir !== null) {
  437. $path = strtr(str_replace($baseDir, '', $path), '\\', '/');
  438. $folders = explode('/', trim($path, '/'));
  439. foreach ($folders as $folder) {
  440. $baseDir .= $folder . DIRECTORY_SEPARATOR;
  441. chmod($baseDir, $chmod);
  442. }
  443. }
  444. }
  445. }