search

Discuz template engine

Discuz’s template engine is a relatively good template engine class. I found it on the Internet a long time ago. Visually, this Discuz’s template engine should be very old. It is a version before DZ7.2. I also use it very smoothly. Share it. Download this template class.

There are two files. A template class, a function that needs to be used in template replacement
Original address: http://blog.qita.in

  1. ?/**
  2. * Template class - parsed using Discuz template engine
  3. * http://blog.qita.in
  4. */
  5. require_once (DIR_ROOT . '/../function/template.func.php');
  6. class Template {
  7. const DIR_SEP = DIRECTORY_SEPARATOR;
  8. /**
  9. * Template instance
  10. *
  11. * @staticvar
  12. * @var object Template
  13. */
  14. protected static $_instance;
  15. /**
  16. * Template parameter information
  17. *
  18. * @var array
  19. */
  20. protected $_options = array();
  21. /**
  22. * Singleton mode calling method
  23. *
  24. * @static
  25. * @return object Template
  26. */
  27. public static function getInstance( ) {
  28. if (!self :: $_instance instanceof self)
  29. self :: $_instance = new self();
  30. return self :: $_instance;
  31. }
  32. /**
  33. * Constructor
  34. *
  35. * @return void
  36. */
  37. private function __construct () {
  38. $this -> _options = array('template_dir' => 'templates' . self :: DIR_SEP, // The directory where the template file is located
  39. 'cache_dir' => 'templates' . self :: DIR_SEP . 'cache' . self :: DIR_SEP, // Directory where cache files are stored
  40. 'auto_update' => false, // Whether to regenerate the cache when the template file is changed
  41. 'cache_lifetime' => 0, // Cache life cycle ( minutes), 0 means permanent
  42. );
  43. }
  44. /**
  45. * Set template parameter information
  46. *
  47. * @param array $options parameter array
  48. * @return void
  49. */
  50. public function setOptions(array $options) {
  51. foreach ($options as $name => $value)
  52. $this - > set($name, $value);
  53. }
  54. /**
  55. * Set template parameters
  56. *
  57. * @param string $name parameter name
  58. * @param mixed $value parameter value
  59. * @return void
  60. */
  61. public function set($name, $value) {
  62. switch ($name) {
  63. case 'template_dir':
  64. $ value = $this -> _trimpath($value);
  65. if (!file_exists($value))
  66. $this -> _throwException("The specified template directory "$value"" was not found);
  67. $this -> ; _options['template_dir'] = $value;
  68. break;
  69. case 'cache_dir':
  70. $value = $this -> _trimpath($value);
  71. if (!file_exists($value))
  72. $this -> ; _throwException("The specified cache directory "$value"" was not found);
  73. $this -> _options['cache_dir'] = $value;
  74. break;
  75. case 'auto_update':
  76. $this -> _options[ 'auto_update'] = (boolean) $value;
  77. break;
  78. case 'cache_lifetime':
  79. $this -> _options['cache_lifetime'] = (float) $value;
  80. break;
  81. default:
  82. $this -> ; _throwException("Unknown template configuration option "$name"");
  83. }
  84. }
  85. /**
  86. * Set template parameters through magic method
  87. *
  88. * @see Template::set()
  89. * @param string $name parameter name
  90. * @param mixed $value parameter value
  91. * @return void
  92. */
  93. public function __set($name, $value) {
  94. $this -> set( $name, $value);
  95. }
  96. /**
  97. * Get template file
  98. *
  99. * @param string $file template file name
  100. * @return string
  101. */
  102. public function getfile($file) {
  103. $cachefile = $this -> _getCacheFile($file);
  104. if (!file_exists($ cachefile))
  105. $this -> cache($file);
  106. return $cachefile;
  107. }
  108. /**
  109. * Check whether the template file needs to update the cache
  110. *
  111. * @param string $file template file name
  112. * @param string $md5data template file md5 verification information
  113. * @param integer $md5data template file expiration time verification information
  114. * @return void
  115. */
  116. public function check($file, $md5data, $expireTime) {
  117. if ( $this -> _options['auto_update'] && md5_file($this -> _getTplFile($file)) != $md5data)
  118. $this -> cache($file);
  119. if ($this -> _options['cache_lifetime'] != 0 && (time() - $expireTime >= $this -> _options['cache_lifetime'] * 60))
  120. $this -> cache($file);
  121. }
  122. /**
  123. * Cache template files
  124. *
  125. * @param string $file template file name
  126. * @return void
  127. */
  128. public function cache($file) {
  129. $tplfile = $this -> _getTplFile($file);
  130. if (!is_readable($tplfile)) {
  131. $this -> ; _throwException("Template file "$tplfile" was not found or could not be opened");
  132. }
  133. // Get template content
  134. $template = file_get_contents($tplfile);
  135. // Filter/s", "{\1}", $template);
  136. // Replace language pack variables
  137. // $template = preg_replace("/{langs+(.+?)}/ies", "languagevar('\1')", $template);
  138. // Replace PHP newline character
  139. $template = str_replace("{LF}", "="\n"?>", $template);
  140. // Replace direct variable output
  141. $varRegexp = "((\$[a-zA-Z_x7f-xff][a-zA- Z0-9_x7f-xff]*)"
  142. . "([[a-zA-Z0-9_-."'[]$x7f-xff]+])*)";
  143. $template = preg_replace("/{( \$[a-zA-Z0-9_[]'"$.x7f-xff]+)}/s", "=\1?>", $template);
  144. $template = preg_replace(" /$varRegexp/es", "addquote('=\1?>')", $template);
  145. $template = preg_replace("/==$varRegexp?>? >/es", "addquote('=\1?>')", $template);
  146. // Replace template loading command
  147. $template = preg_replace("/[nrt]*{templates+( [a-z0-9_]+)}[nrt]*/is",
  148. "rn include($template->getfile('\1')); ?>rn",
  149. $template
  150. ) ;
  151. $template = preg_replace("/[nrt]*{templates+(.+?)}[nrt]*/is",
  152. "rn include($template->getfile(\1)); ?> ;rn",
  153. $template
  154. );
  155. // Replace specific function
  156. $template = preg_replace("/[nrt]*{evals+(.+?)}[nrt]*/ies",
  157. "stripvtags('< ;? \1 ?>','')",
  158. $template
  159. );
  160. $template = preg_replace("/[nrt]*{echos+(.+?)}[nrt]*/ies",
  161. " stripvtags(' echo \1; ?>','')",
  162. $template
  163. );
  164. $template = preg_replace("/([nrt]*){elseifs+(.+?)}([ nrt]*)/ies",
  165. "stripvtags('\1 } elseif(\2) { ?>\3','')",
  166. $template
  167. );
  168. $template = preg_replace("/ ([nrt]*){else}([nrt]*)/is",
  169. "\1 } else { ?>\2",
  170. $template
  171. );
  172. // Replace loop function and conditional judgment Statement
  173. $nest = 5;
  174. for ($i = 0; $i $template = preg_replace("/[nrt]*{loops+(S+)s+(S+)}[nr ]*(.+?)[nr]*{/loop}[nrt]*/ies",
  175. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2) { ? >','\3 } } ?>')",
  176. $template
  177. );
  178. $template = preg_replace("/[nrt]*{loops+(S+)s+(S+)s+(S+)} [nrt]*(.+?)[nrt]*{/loop}[nrt]*/ies",
  179. "stripvtags(' if(is_array(\1)) { foreach(\1 as \2 = > \3) { ?>','\4 } } ?>')",
  180. $template
  181. );
  182. $template = preg_replace("/([nrt]*){ifs+(.+ ?)}([nr]*)(.+?)([nr]*){/if}([nrt]*)/ies",
  183. "stripvtags('\1 if(\2) { ? >\3','\4\5 } ?>\6')",
  184. $template
  185. );
  186. }
  187. // Constant replacement
  188. $template = preg_replace("/{([a-zA -Z_x7f-xff][a-zA-Z0-9_x7f-xff]*)}/s",
  189. "=\1?>",
  190. $template
  191. );
  192. // Delete PHP code break Extra spaces and line breaks
  193. $template = preg_replace("/ ?>[nr]* /s", " ", $template);
  194. // Other replacements
  195. $template = preg_replace("/"(http )?[w./:]+?[^"]+?&[^"]+?"/e",
  196. "transamp('\0')",
  197. $template
  198. );
  199. $template = preg_replace ("/<script>]*?src="(.+?)".*?>s*</script>/ise",
  200. "stripscriptamp('\1')",
  201. $template
  202. );
  203. $template = preg_replace("/[nrt]*{blocks+([a-zA-Z0-9_]+)}(.+?){/block}/ies",
  204. "stripblock(' \1', '\2')",
  205. $template
  206. );
  207. // Add md5 and expiration check
  208. $md5data = md5_file($tplfile);
  209. $expireTime = time();
  210. $template = "< ;? if (!class_exists('template')) die('Access Denied');"
  211. . "$template->getInstance()->check('$file', '$md5data', $expireTime) ;"
  212. . "?>rn$template";
  213. // Write cache file
  214. $cachefile = $this -> _getCacheFile($file);
  215. $makepath = $this -> _makepath($cachefile);
  216. if ($makepath !== true)
  217. $this -> _throwException("Unable to create cache directory "$makepath"");
  218. file_put_contents($cachefile, $template);
  219. }
  220. /**
  221. * Correct the path to a form suitable for the operating system
  222. *
  223. * @param string $path path name
  224. * @return string
  225. */
  226. protected function _trimpath($path) {
  227. return str_replace(array('/', '\', '//', '\\'), self :: DIR_SEP, $path);
  228. }
  229. / **
  230. * Get the template file name and path
  231. *
  232. * @param string $file template file name
  233. * @return string
  234. */
  235. protected function _getTplFile($file) {
  236. return $this -> _trimpath($this -> _options['template_dir'] . self :: DIR_SEP . $file);
  237. }
  238. /**
  239. * Get the template cache file name and path
  240. *
  241. * @param string $file template file name
  242. * @return string
  243. */
  244. protected function _getCacheFile($file) {
  245. $file = preg_replace('/.[a-z0-9-_]+$/i', '.cache.php', $file);
  246. return $this -> _trimpath($this -> _options['cache_dir'] . self :: DIR_SEP . $file);
  247. }
  248. /**
  249. * Create a non-existing folder based on the specified path
  250. *
  251. * @param string $path path/folder name
  252. * @return string
  253. */
  254. protected function _makepath($path) {
  255. $dirs = explode(self :: DIR_SEP, dirname($this -> _trimpath($path)));
  256. $tmp = '';
  257. foreach ($dirs as $dir) {
  258. $tmp .= $dir . self :: DIR_SEP;
  259. if (!file_exists($tmp) && !@mkdir($tmp, 0777))
  260. return $tmp;
  261. }
  262. return true;
  263. }
  264. /**
  265. * Throw an error message
  266. *
  267. * @param string $message
  268. * @return void
  269. */
  270. protected function _throwException($message) {
  271. throw new Exception($message);
  272. }
  273. }
  274. ?>
复制代码
  1. 模板函数文件
  2. /**
  3. * Functions needed for template replacement
  4. * http://blog.qita.in
  5. */
  6. function transamp($template) {
  7. $template = str_replace('&', '&', $template);
  8. $template = str_replace('&', '&', $template);
  9. $template = str_replace('"', '"', $template);
  10. return $template;
  11. }
  12. function stripvtags($expr, $statement) {
  13. $expr = str_replace("\"", """, preg_replace("/=(\$.+?)?>/s", "\1", $expr));
  14. $statement = str_replace("\"", """, $statement);
  15. return $expr . $statement;
  16. }
  17. function addquote($var) {
  18. return str_replace("\"", """, preg_replace("/[([a-zA-Z0-9_-.x7f-xff]+)]/s", "['\1']", $var));
  19. }
  20. function stripscriptamp($s) {
  21. $s = str_replace('&', '&', $s);
  22. return "";
  23. }
  24. function stripblock($var, $s) {
  25. $s = str_replace('\"', '"', $s);
  26. $s = preg_replace("/=\$(.+?)?>/", "{$\1}", $s);
  27. preg_match_all("/=(.+?)?>/e", $s, $constary);
  28. $constadd = '';
  29. $constary[1] = array_unique($constary[1]);
  30. foreach($constary[1] as $const) {
  31. $constadd .= '$__' . $const .' = ' . $const . ';';
  32. }
  33. $s = preg_replace("/=(.+?)?>/", "{$__\1}", $s);
  34. $s = str_replace('?>', "n$$var .= $s = str_replace('', "nEOF;n", $s);
  35. return "";
  36. }
  37. ?>
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.