Template.php 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use think\exception\TemplateNotFoundException;
  13. use think\template\TagLib;
  14. /**
  15. * ThinkPHP分离出来的模板引擎
  16. * 支持XML标签和普通标签的模板解析
  17. * 编译型模板引擎 支持动态缓存
  18. */
  19. class Template
  20. {
  21. // 模板变量
  22. protected $data = [];
  23. // 引擎配置
  24. protected $config = [
  25. 'view_path' => '', // 模板路径
  26. 'view_base' => '',
  27. 'view_suffix' => 'html', // 默认模板文件后缀
  28. 'view_depr' => DS,
  29. 'cache_suffix' => 'php', // 默认模板缓存后缀
  30. 'tpl_deny_func_list' => 'echo,exit', // 模板引擎禁用函数
  31. 'tpl_deny_php' => false, // 默认模板引擎是否禁用PHP原生代码
  32. 'tpl_begin' => '{', // 模板引擎普通标签开始标记
  33. 'tpl_end' => '}', // 模板引擎普通标签结束标记
  34. 'strip_space' => false, // 是否去除模板文件里面的html空格与换行
  35. 'tpl_cache' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译
  36. 'compile_type' => 'file', // 模板编译类型
  37. 'cache_prefix' => '', // 模板缓存前缀标识,可以动态改变
  38. 'cache_time' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒)
  39. 'layout_on' => false, // 布局模板开关
  40. 'layout_name' => 'layout', // 布局模板入口文件
  41. 'layout_item' => '{__CONTENT__}', // 布局模板的内容替换标识
  42. 'taglib_begin' => '{', // 标签库标签开始标记
  43. 'taglib_end' => '}', // 标签库标签结束标记
  44. 'taglib_load' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测
  45. 'taglib_build_in' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序
  46. 'taglib_pre_load' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔
  47. 'display_cache' => false, // 模板渲染缓存
  48. 'cache_id' => '', // 模板缓存ID
  49. 'tpl_replace_string' => [],
  50. 'tpl_var_identify' => 'array', // .语法变量识别,array|object|'', 为空时自动识别
  51. ];
  52. private $literal = [];
  53. private $includeFile = []; // 记录所有模板包含的文件路径及更新时间
  54. protected $storage;
  55. /**
  56. * 构造函数
  57. * @access public
  58. * @param array $config
  59. */
  60. public function __construct(array $config = [])
  61. {
  62. $this->config['cache_path'] = TEMP_PATH;
  63. $this->config = array_merge($this->config, $config);
  64. $this->config['taglib_begin_origin'] = $this->config['taglib_begin'];
  65. $this->config['taglib_end_origin'] = $this->config['taglib_end'];
  66. $this->config['taglib_begin'] = preg_quote($this->config['taglib_begin'], '/');
  67. $this->config['taglib_end'] = preg_quote($this->config['taglib_end'], '/');
  68. $this->config['tpl_begin'] = preg_quote($this->config['tpl_begin'], '/');
  69. $this->config['tpl_end'] = preg_quote($this->config['tpl_end'], '/');
  70. // 初始化模板编译存储器
  71. $type = $this->config['compile_type'] ? $this->config['compile_type'] : 'File';
  72. $class = false !== strpos($type, '\\') ? $type : '\\think\\template\\driver\\' . ucwords($type);
  73. $this->storage = new $class();
  74. }
  75. /**
  76. * 模板变量赋值
  77. * @access public
  78. * @param mixed $name
  79. * @param mixed $value
  80. * @return void
  81. */
  82. public function assign($name, $value = '')
  83. {
  84. if (is_array($name)) {
  85. $this->data = array_merge($this->data, $name);
  86. } else {
  87. $this->data[$name] = $value;
  88. }
  89. }
  90. /**
  91. * 模板引擎参数赋值
  92. * @access public
  93. * @param mixed $name
  94. * @param mixed $value
  95. */
  96. public function __set($name, $value)
  97. {
  98. $this->config[$name] = $value;
  99. }
  100. /**
  101. * 模板引擎配置项
  102. * @access public
  103. * @param array|string $config
  104. * @return string|void|array
  105. */
  106. public function config($config)
  107. {
  108. if (is_array($config)) {
  109. $this->config = array_merge($this->config, $config);
  110. } elseif (isset($this->config[$config])) {
  111. return $this->config[$config];
  112. } else {
  113. return;
  114. }
  115. }
  116. /**
  117. * 模板变量获取
  118. * @access public
  119. * @param string $name 变量名
  120. * @return mixed
  121. */
  122. public function get($name = '')
  123. {
  124. if ('' == $name) {
  125. return $this->data;
  126. } else {
  127. $data = $this->data;
  128. foreach (explode('.', $name) as $key => $val) {
  129. if (isset($data[$val])) {
  130. $data = $data[$val];
  131. } else {
  132. $data = null;
  133. break;
  134. }
  135. }
  136. return $data;
  137. }
  138. }
  139. /**
  140. * 渲染模板文件
  141. * @access public
  142. * @param string $template 模板文件
  143. * @param array $vars 模板变量
  144. * @param array $config 模板参数
  145. * @return void
  146. */
  147. public function fetch($template, $vars = [], $config = [])
  148. {
  149. if ($vars) {
  150. $this->data = $vars;
  151. }
  152. if ($config) {
  153. $this->config($config);
  154. }
  155. if (!empty($this->config['cache_id']) && $this->config['display_cache']) {
  156. // 读取渲染缓存
  157. $cacheContent = Cache::get($this->config['cache_id']);
  158. if (false !== $cacheContent) {
  159. echo $cacheContent;
  160. return;
  161. }
  162. }
  163. $template = $this->parseTemplateFile($template);
  164. if ($template) {
  165. $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($this->config['layout_name'] . $template) . '.' . ltrim($this->config['cache_suffix'], '.');
  166. if (!$this->checkCache($cacheFile)) {
  167. // 缓存无效 重新模板编译
  168. $content = file_get_contents($template);
  169. $this->compiler($content, $cacheFile);
  170. }
  171. // 页面缓存
  172. ob_start();
  173. ob_implicit_flush(0);
  174. // 读取编译存储
  175. $this->storage->read($cacheFile, $this->data);
  176. // 获取并清空缓存
  177. $content = ob_get_clean();
  178. if (!empty($this->config['cache_id']) && $this->config['display_cache']) {
  179. // 缓存页面输出
  180. Cache::set($this->config['cache_id'], $content, $this->config['cache_time']);
  181. }
  182. echo $content;
  183. }
  184. }
  185. /**
  186. * 渲染模板内容
  187. * @access public
  188. * @param string $content 模板内容
  189. * @param array $vars 模板变量
  190. * @param array $config 模板参数
  191. * @return void
  192. */
  193. public function display($content, $vars = [], $config = [])
  194. {
  195. if ($vars) {
  196. $this->data = $vars;
  197. }
  198. if ($config) {
  199. $this->config($config);
  200. }
  201. $cacheFile = $this->config['cache_path'] . $this->config['cache_prefix'] . md5($content) . '.' . ltrim($this->config['cache_suffix'], '.');
  202. if (!$this->checkCache($cacheFile)) {
  203. // 缓存无效 模板编译
  204. $this->compiler($content, $cacheFile);
  205. }
  206. // 读取编译存储
  207. $this->storage->read($cacheFile, $this->data);
  208. }
  209. /**
  210. * 设置布局
  211. * @access public
  212. * @param mixed $name 布局模板名称 false 则关闭布局
  213. * @param string $replace 布局模板内容替换标识
  214. * @return Template
  215. */
  216. public function layout($name, $replace = '')
  217. {
  218. if (false === $name) {
  219. // 关闭布局
  220. $this->config['layout_on'] = false;
  221. } else {
  222. // 开启布局
  223. $this->config['layout_on'] = true;
  224. // 名称必须为字符串
  225. if (is_string($name)) {
  226. $this->config['layout_name'] = $name;
  227. }
  228. if (!empty($replace)) {
  229. $this->config['layout_item'] = $replace;
  230. }
  231. }
  232. return $this;
  233. }
  234. /**
  235. * 检查编译缓存是否有效
  236. * 如果无效则需要重新编译
  237. * @access private
  238. * @param string $cacheFile 缓存文件名
  239. * @return boolean
  240. */
  241. private function checkCache($cacheFile)
  242. {
  243. // 未开启缓存功能
  244. if (!$this->config['tpl_cache']) {
  245. return false;
  246. }
  247. // 缓存文件不存在
  248. if (!is_file($cacheFile)) {
  249. return false;
  250. }
  251. // 读取缓存文件失败
  252. if (!$handle = @fopen($cacheFile, "r")) {
  253. return false;
  254. }
  255. // 读取第一行
  256. preg_match('/\/\*(.+?)\*\//', fgets($handle), $matches);
  257. if (!isset($matches[1])) {
  258. return false;
  259. }
  260. $includeFile = unserialize($matches[1]);
  261. if (!is_array($includeFile)) {
  262. return false;
  263. }
  264. // 检查模板文件是否有更新
  265. foreach ($includeFile as $path => $time) {
  266. if (is_file($path) && filemtime($path) > $time) {
  267. // 模板文件如果有更新则缓存需要更新
  268. return false;
  269. }
  270. }
  271. // 检查编译存储是否有效
  272. return $this->storage->check($cacheFile, $this->config['cache_time']);
  273. }
  274. /**
  275. * 检查编译缓存是否存在
  276. * @access public
  277. * @param string $cacheId 缓存的id
  278. * @return boolean
  279. */
  280. public function isCache($cacheId)
  281. {
  282. if ($cacheId && $this->config['display_cache']) {
  283. // 缓存页面输出
  284. return Cache::has($cacheId);
  285. }
  286. return false;
  287. }
  288. /**
  289. * 编译模板文件内容
  290. * @access private
  291. * @param string $content 模板内容
  292. * @param string $cacheFile 缓存文件名
  293. * @return void
  294. */
  295. private function compiler(&$content, $cacheFile)
  296. {
  297. // 判断是否启用布局
  298. if ($this->config['layout_on']) {
  299. if (false !== strpos($content, '{__NOLAYOUT__}')) {
  300. // 可以单独定义不使用布局
  301. $content = str_replace('{__NOLAYOUT__}', '', $content);
  302. } else {
  303. // 读取布局模板
  304. $layoutFile = $this->parseTemplateFile($this->config['layout_name']);
  305. if ($layoutFile) {
  306. // 替换布局的主体内容
  307. $content = str_replace($this->config['layout_item'], $content, file_get_contents($layoutFile));
  308. }
  309. }
  310. } else {
  311. $content = str_replace('{__NOLAYOUT__}', '', $content);
  312. }
  313. // 模板解析
  314. $this->parse($content);
  315. if ($this->config['strip_space']) {
  316. /* 去除html空格与换行 */
  317. $find = ['~>\s+<~', '~>(\s+\n|\r)~'];
  318. $replace = ['><', '>'];
  319. $content = preg_replace($find, $replace, $content);
  320. }
  321. // 优化生成的php代码
  322. $content = preg_replace('/\?>\s*<\?php\s(?!echo\b)/s', '', $content);
  323. // 模板过滤输出
  324. $replace = $this->config['tpl_replace_string'];
  325. $content = str_replace(array_keys($replace), array_values($replace), $content);
  326. // 添加安全代码及模板引用记录
  327. $content = '<?php if (!defined(\'THINK_PATH\')) exit(); /*' . serialize($this->includeFile) . '*/ ?>' . "\n" . $content;
  328. // 编译存储
  329. $this->storage->write($cacheFile, $content);
  330. $this->includeFile = [];
  331. return;
  332. }
  333. /**
  334. * 模板解析入口
  335. * 支持普通标签和TagLib解析 支持自定义标签库
  336. * @access public
  337. * @param string $content 要解析的模板内容
  338. * @return void
  339. */
  340. public function parse(&$content)
  341. {
  342. // 内容为空不解析
  343. if (empty($content)) {
  344. return;
  345. }
  346. // 替换literal标签内容
  347. $this->parseLiteral($content);
  348. // 解析继承
  349. $this->parseExtend($content);
  350. // 解析布局
  351. $this->parseLayout($content);
  352. // 检查include语法
  353. $this->parseInclude($content);
  354. // 替换包含文件中literal标签内容
  355. $this->parseLiteral($content);
  356. // 检查PHP语法
  357. $this->parsePhp($content);
  358. // 获取需要引入的标签库列表
  359. // 标签库只需要定义一次,允许引入多个一次
  360. // 一般放在文件的最前面
  361. // 格式:<taglib name="html,mytag..." />
  362. // 当TAGLIB_LOAD配置为true时才会进行检测
  363. if ($this->config['taglib_load']) {
  364. $tagLibs = $this->getIncludeTagLib($content);
  365. if (!empty($tagLibs)) {
  366. // 对导入的TagLib进行解析
  367. foreach ($tagLibs as $tagLibName) {
  368. $this->parseTagLib($tagLibName, $content);
  369. }
  370. }
  371. }
  372. // 预先加载的标签库 无需在每个模板中使用taglib标签加载 但必须使用标签库XML前缀
  373. if ($this->config['taglib_pre_load']) {
  374. $tagLibs = explode(',', $this->config['taglib_pre_load']);
  375. foreach ($tagLibs as $tag) {
  376. $this->parseTagLib($tag, $content);
  377. }
  378. }
  379. // 内置标签库 无需使用taglib标签导入就可以使用 并且不需使用标签库XML前缀
  380. $tagLibs = explode(',', $this->config['taglib_build_in']);
  381. foreach ($tagLibs as $tag) {
  382. $this->parseTagLib($tag, $content, true);
  383. }
  384. // 解析普通模板标签 {$tagName}
  385. $this->parseTag($content);
  386. // 还原被替换的Literal标签
  387. $this->parseLiteral($content, true);
  388. return;
  389. }
  390. /**
  391. * 检查PHP语法
  392. * @access private
  393. * @param string $content 要解析的模板内容
  394. * @return void
  395. * @throws \think\Exception
  396. */
  397. private function parsePhp(&$content)
  398. {
  399. // 短标签的情况要将<?标签用echo方式输出 否则无法正常输出xml标识
  400. $content = preg_replace('/(<\?(?!php|=|$))/i', '<?php echo \'\\1\'; ?>' . "\n", $content);
  401. // PHP语法检查
  402. if ($this->config['tpl_deny_php'] && false !== strpos($content, '<?php')) {
  403. throw new Exception('not allow php tag', 11600);
  404. }
  405. return;
  406. }
  407. /**
  408. * 解析模板中的布局标签
  409. * @access private
  410. * @param string $content 要解析的模板内容
  411. * @return void
  412. */
  413. private function parseLayout(&$content)
  414. {
  415. // 读取模板中的布局标签
  416. if (preg_match($this->getRegex('layout'), $content, $matches)) {
  417. // 替换Layout标签
  418. $content = str_replace($matches[0], '', $content);
  419. // 解析Layout标签
  420. $array = $this->parseAttr($matches[0]);
  421. if (!$this->config['layout_on'] || $this->config['layout_name'] != $array['name']) {
  422. // 读取布局模板
  423. $layoutFile = $this->parseTemplateFile($array['name']);
  424. if ($layoutFile) {
  425. $replace = isset($array['replace']) ? $array['replace'] : $this->config['layout_item'];
  426. // 替换布局的主体内容
  427. $content = str_replace($replace, $content, file_get_contents($layoutFile));
  428. }
  429. }
  430. } else {
  431. $content = str_replace('{__NOLAYOUT__}', '', $content);
  432. }
  433. return;
  434. }
  435. /**
  436. * 解析模板中的include标签
  437. * @access private
  438. * @param string $content 要解析的模板内容
  439. * @return void
  440. */
  441. private function parseInclude(&$content)
  442. {
  443. $regex = $this->getRegex('include');
  444. $func = function ($template) use (&$func, &$regex, &$content) {
  445. if (preg_match_all($regex, $template, $matches, PREG_SET_ORDER)) {
  446. foreach ($matches as $match) {
  447. $array = $this->parseAttr($match[0]);
  448. $file = $array['file'];
  449. unset($array['file']);
  450. // 分析模板文件名并读取内容
  451. $parseStr = $this->parseTemplateName($file);
  452. foreach ($array as $k => $v) {
  453. // 以$开头字符串转换成模板变量
  454. if (0 === strpos($v, '$')) {
  455. $v = $this->get(substr($v, 1));
  456. }
  457. $parseStr = str_replace('[' . $k . ']', $v, $parseStr);
  458. }
  459. $content = str_replace($match[0], $parseStr, $content);
  460. // 再次对包含文件进行模板分析
  461. $func($parseStr);
  462. }
  463. unset($matches);
  464. }
  465. };
  466. // 替换模板中的include标签
  467. $func($content);
  468. return;
  469. }
  470. /**
  471. * 解析模板中的extend标签
  472. * @access private
  473. * @param string $content 要解析的模板内容
  474. * @return void
  475. */
  476. private function parseExtend(&$content)
  477. {
  478. $regex = $this->getRegex('extend');
  479. $array = $blocks = $baseBlocks = [];
  480. $extend = '';
  481. $func = function ($template) use (&$func, &$regex, &$array, &$extend, &$blocks, &$baseBlocks) {
  482. if (preg_match($regex, $template, $matches)) {
  483. if (!isset($array[$matches['name']])) {
  484. $array[$matches['name']] = 1;
  485. // 读取继承模板
  486. $extend = $this->parseTemplateName($matches['name']);
  487. // 读取包含文件
  488. $this->parseInclude($extend);
  489. // 递归检查继承
  490. $func($extend);
  491. // 取得block标签内容
  492. $blocks = array_merge($blocks, $this->parseBlock($template));
  493. return;
  494. }
  495. } else {
  496. // 取得顶层模板block标签内容
  497. $baseBlocks = $this->parseBlock($template, true);
  498. if (empty($extend)) {
  499. // 无extend标签但有block标签的情况
  500. $extend = $template;
  501. }
  502. }
  503. };
  504. $func($content);
  505. if (!empty($extend)) {
  506. if ($baseBlocks) {
  507. $children = [];
  508. foreach ($baseBlocks as $name => $val) {
  509. $replace = $val['content'];
  510. if (!empty($children[$name])) {
  511. // 如果包含有子block标签
  512. foreach ($children[$name] as $key) {
  513. $replace = str_replace($baseBlocks[$key]['begin'] . $baseBlocks[$key]['content'] . $baseBlocks[$key]['end'], $blocks[$key]['content'], $replace);
  514. }
  515. }
  516. if (isset($blocks[$name])) {
  517. // 带有{__block__}表示与所继承模板的相应标签合并,而不是覆盖
  518. $replace = str_replace(['{__BLOCK__}', '{__block__}'], $replace, $blocks[$name]['content']);
  519. if (!empty($val['parent'])) {
  520. // 如果不是最顶层的block标签
  521. $parent = $val['parent'];
  522. if (isset($blocks[$parent])) {
  523. $blocks[$parent]['content'] = str_replace($blocks[$name]['begin'] . $blocks[$name]['content'] . $blocks[$name]['end'], $replace, $blocks[$parent]['content']);
  524. }
  525. $blocks[$name]['content'] = $replace;
  526. $children[$parent][] = $name;
  527. continue;
  528. }
  529. } elseif (!empty($val['parent'])) {
  530. // 如果子标签没有被继承则用原值
  531. $children[$val['parent']][] = $name;
  532. $blocks[$name] = $val;
  533. }
  534. if (!$val['parent']) {
  535. // 替换模板中的顶级block标签
  536. $extend = str_replace($val['begin'] . $val['content'] . $val['end'], $replace, $extend);
  537. }
  538. }
  539. }
  540. $content = $extend;
  541. unset($blocks, $baseBlocks);
  542. }
  543. return;
  544. }
  545. /**
  546. * 替换页面中的literal标签
  547. * @access private
  548. * @param string $content 模板内容
  549. * @param boolean $restore 是否为还原
  550. * @return void
  551. */
  552. private function parseLiteral(&$content, $restore = false)
  553. {
  554. $regex = $this->getRegex($restore ? 'restoreliteral' : 'literal');
  555. if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
  556. if (!$restore) {
  557. $count = count($this->literal);
  558. // 替换literal标签
  559. foreach ($matches as $match) {
  560. $this->literal[] = substr($match[0], strlen($match[1]), -strlen($match[2]));
  561. $content = str_replace($match[0], "<!--###literal{$count}###-->", $content);
  562. $count++;
  563. }
  564. } else {
  565. // 还原literal标签
  566. foreach ($matches as $match) {
  567. $content = str_replace($match[0], $this->literal[$match[1]], $content);
  568. }
  569. // 清空literal记录
  570. $this->literal = [];
  571. }
  572. unset($matches);
  573. }
  574. return;
  575. }
  576. /**
  577. * 获取模板中的block标签
  578. * @access private
  579. * @param string $content 模板内容
  580. * @param boolean $sort 是否排序
  581. * @return array
  582. */
  583. private function parseBlock(&$content, $sort = false)
  584. {
  585. $regex = $this->getRegex('block');
  586. $result = [];
  587. if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
  588. $right = $keys = [];
  589. foreach ($matches as $match) {
  590. if (empty($match['name'][0])) {
  591. if (count($right) > 0) {
  592. $tag = array_pop($right);
  593. $start = $tag['offset'] + strlen($tag['tag']);
  594. $length = $match[0][1] - $start;
  595. $result[$tag['name']] = [
  596. 'begin' => $tag['tag'],
  597. 'content' => substr($content, $start, $length),
  598. 'end' => $match[0][0],
  599. 'parent' => count($right) ? end($right)['name'] : '',
  600. ];
  601. $keys[$tag['name']] = $match[0][1];
  602. }
  603. } else {
  604. // 标签头压入栈
  605. $right[] = [
  606. 'name' => $match[2][0],
  607. 'offset' => $match[0][1],
  608. 'tag' => $match[0][0],
  609. ];
  610. }
  611. }
  612. unset($right, $matches);
  613. if ($sort) {
  614. // 按block标签结束符在模板中的位置排序
  615. array_multisort($keys, $result);
  616. }
  617. }
  618. return $result;
  619. }
  620. /**
  621. * 搜索模板页面中包含的TagLib库
  622. * 并返回列表
  623. * @access private
  624. * @param string $content 模板内容
  625. * @return array|null
  626. */
  627. private function getIncludeTagLib(&$content)
  628. {
  629. // 搜索是否有TagLib标签
  630. if (preg_match($this->getRegex('taglib'), $content, $matches)) {
  631. // 替换TagLib标签
  632. $content = str_replace($matches[0], '', $content);
  633. return explode(',', $matches['name']);
  634. }
  635. return;
  636. }
  637. /**
  638. * TagLib库解析
  639. * @access public
  640. * @param string $tagLib 要解析的标签库
  641. * @param string $content 要解析的模板内容
  642. * @param boolean $hide 是否隐藏标签库前缀
  643. * @return void
  644. */
  645. public function parseTagLib($tagLib, &$content, $hide = false)
  646. {
  647. if (false !== strpos($tagLib, '\\')) {
  648. // 支持指定标签库的命名空间
  649. $className = $tagLib;
  650. $tagLib = substr($tagLib, strrpos($tagLib, '\\') + 1);
  651. } else {
  652. $className = '\\think\\template\\taglib\\' . ucwords($tagLib);
  653. }
  654. /** @var Taglib $tLib */
  655. $tLib = new $className($this);
  656. $tLib->parseTag($content, $hide ? '' : $tagLib);
  657. return;
  658. }
  659. /**
  660. * 分析标签属性
  661. * @access public
  662. * @param string $str 属性字符串
  663. * @param string $name 不为空时返回指定的属性名
  664. * @return array
  665. */
  666. public function parseAttr($str, $name = null)
  667. {
  668. $regex = '/\s+(?>(?P<name>[\w-]+)\s*)=(?>\s*)([\"\'])(?P<value>(?:(?!\\2).)*)\\2/is';
  669. $array = [];
  670. if (preg_match_all($regex, $str, $matches, PREG_SET_ORDER)) {
  671. foreach ($matches as $match) {
  672. $array[$match['name']] = $match['value'];
  673. }
  674. unset($matches);
  675. }
  676. if (!empty($name) && isset($array[$name])) {
  677. return $array[$name];
  678. } else {
  679. return $array;
  680. }
  681. }
  682. /**
  683. * 模板标签解析
  684. * 格式: {TagName:args [|content] }
  685. * @access private
  686. * @param string $content 要解析的模板内容
  687. * @return void
  688. */
  689. private function parseTag(&$content)
  690. {
  691. $regex = $this->getRegex('tag');
  692. if (preg_match_all($regex, $content, $matches, PREG_SET_ORDER)) {
  693. foreach ($matches as $match) {
  694. $str = stripslashes($match[1]);
  695. $flag = substr($str, 0, 1);
  696. switch ($flag) {
  697. case '$':
  698. // 解析模板变量 格式 {$varName}
  699. // 是否带有?号
  700. if (false !== $pos = strpos($str, '?')) {
  701. $array = preg_split('/([!=]={1,2}|(?<!-)[><]={0,1})/', substr($str, 0, $pos), 2, PREG_SPLIT_DELIM_CAPTURE);
  702. $name = $array[0];
  703. $this->parseVar($name);
  704. $this->parseVarFunction($name);
  705. $str = trim(substr($str, $pos + 1));
  706. $this->parseVar($str);
  707. $first = substr($str, 0, 1);
  708. if (strpos($name, ')')) {
  709. // $name为对象或是自动识别,或者含有函数
  710. if (isset($array[1])) {
  711. $this->parseVar($array[2]);
  712. $name .= $array[1] . $array[2];
  713. }
  714. switch ($first) {
  715. case '?':
  716. $str = '<?php echo (' . $name . ') ? ' . $name . ' : ' . substr($str, 1) . '; ?>';
  717. break;
  718. case '=':
  719. $str = '<?php if(' . $name . ') echo ' . substr($str, 1) . '; ?>';
  720. break;
  721. default:
  722. $str = '<?php echo ' . $name . '?' . $str . '; ?>';
  723. }
  724. } else {
  725. if (isset($array[1])) {
  726. $this->parseVar($array[2]);
  727. $express = $name . $array[1] . $array[2];
  728. } else {
  729. $express = false;
  730. }
  731. // $name为数组
  732. switch ($first) {
  733. case '?':
  734. // {$varname??'xxx'} $varname有定义则输出$varname,否则输出xxx
  735. $str = '<?php echo ' . ($express ?: 'isset(' . $name . ')') . '?' . $name . ':' . substr($str, 1) . '; ?>';
  736. break;
  737. case '=':
  738. // {$varname?='xxx'} $varname为真时才输出xxx
  739. $str = '<?php if(' . ($express ?: '!empty(' . $name . ')') . ') echo ' . substr($str, 1) . '; ?>';
  740. break;
  741. case ':':
  742. // {$varname?:'xxx'} $varname为真时输出$varname,否则输出xxx
  743. $str = '<?php echo ' . ($express ?: '!empty(' . $name . ')') . '?' . $name . $str . '; ?>';
  744. break;
  745. default:
  746. $str = '<?php echo ' . ($express ?: '!empty(' . $name . ')') . '?' . $str . '; ?>';
  747. }
  748. }
  749. } else {
  750. $this->parseVar($str);
  751. $this->parseVarFunction($str);
  752. $str = '<?php echo ' . $str . '; ?>';
  753. }
  754. break;
  755. case ':':
  756. // 输出某个函数的结果
  757. $str = substr($str, 1);
  758. $this->parseVar($str);
  759. $str = '<?php echo ' . $str . '; ?>';
  760. break;
  761. case '~':
  762. // 执行某个函数
  763. $str = substr($str, 1);
  764. $this->parseVar($str);
  765. $str = '<?php ' . $str . '; ?>';
  766. break;
  767. case '-':
  768. case '+':
  769. // 输出计算
  770. $this->parseVar($str);
  771. $str = '<?php echo ' . $str . '; ?>';
  772. break;
  773. case '/':
  774. // 注释标签
  775. $flag2 = substr($str, 1, 1);
  776. if ('/' == $flag2 || ('*' == $flag2 && substr(rtrim($str), -2) == '*/')) {
  777. $str = '';
  778. }
  779. break;
  780. default:
  781. // 未识别的标签直接返回
  782. $str = $this->config['tpl_begin'] . $str . $this->config['tpl_end'];
  783. break;
  784. }
  785. $content = str_replace($match[0], $str, $content);
  786. }
  787. unset($matches);
  788. }
  789. return;
  790. }
  791. /**
  792. * 模板变量解析,支持使用函数
  793. * 格式: {$varname|function1|function2=arg1,arg2}
  794. * @access public
  795. * @param string $varStr 变量数据
  796. * @return void
  797. */
  798. public function parseVar(&$varStr)
  799. {
  800. $varStr = trim($varStr);
  801. if (preg_match_all('/\$[a-zA-Z_](?>\w*)(?:[:\.][0-9a-zA-Z_](?>\w*))+/', $varStr, $matches, PREG_OFFSET_CAPTURE)) {
  802. static $_varParseList = [];
  803. while ($matches[0]) {
  804. $match = array_pop($matches[0]);
  805. //如果已经解析过该变量字串,则直接返回变量值
  806. if (isset($_varParseList[$match[0]])) {
  807. $parseStr = $_varParseList[$match[0]];
  808. } else {
  809. if (strpos($match[0], '.')) {
  810. $vars = explode('.', $match[0]);
  811. $first = array_shift($vars);
  812. if ('$Think' == $first) {
  813. // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出
  814. $parseStr = $this->parseThinkVar($vars);
  815. } elseif ('$Request' == $first) {
  816. // 获取Request请求对象参数
  817. $method = array_shift($vars);
  818. if (!empty($vars)) {
  819. $params = implode('.', $vars);
  820. if ('true' != $params) {
  821. $params = '\'' . $params . '\'';
  822. }
  823. } else {
  824. $params = '';
  825. }
  826. $parseStr = '\think\Request::instance()->' . $method . '(' . $params . ')';
  827. } else {
  828. switch ($this->config['tpl_var_identify']) {
  829. case 'array': // 识别为数组
  830. $parseStr = $first . '[\'' . implode('\'][\'', $vars) . '\']';
  831. break;
  832. case 'obj': // 识别为对象
  833. $parseStr = $first . '->' . implode('->', $vars);
  834. break;
  835. default: // 自动判断数组或对象
  836. $parseStr = '(is_array(' . $first . ')?' . $first . '[\'' . implode('\'][\'', $vars) . '\']:' . $first . '->' . implode('->', $vars) . ')';
  837. }
  838. }
  839. } else {
  840. $parseStr = str_replace(':', '->', $match[0]);
  841. }
  842. $_varParseList[$match[0]] = $parseStr;
  843. }
  844. $varStr = substr_replace($varStr, $parseStr, $match[1], strlen($match[0]));
  845. }
  846. unset($matches);
  847. }
  848. return;
  849. }
  850. /**
  851. * 对模板中使用了函数的变量进行解析
  852. * 格式 {$varname|function1|function2=arg1,arg2}
  853. * @access public
  854. * @param string $varStr 变量字符串
  855. * @return void
  856. */
  857. public function parseVarFunction(&$varStr)
  858. {
  859. if (false == strpos($varStr, '|')) {
  860. return;
  861. }
  862. static $_varFunctionList = [];
  863. $_key = md5($varStr);
  864. //如果已经解析过该变量字串,则直接返回变量值
  865. if (isset($_varFunctionList[$_key])) {
  866. $varStr = $_varFunctionList[$_key];
  867. } else {
  868. $varArray = explode('|', $varStr);
  869. // 取得变量名称
  870. $name = array_shift($varArray);
  871. // 对变量使用函数
  872. $length = count($varArray);
  873. // 取得模板禁止使用函数列表
  874. $template_deny_funs = explode(',', $this->config['tpl_deny_func_list']);
  875. for ($i = 0; $i < $length; $i++) {
  876. $args = explode('=', $varArray[$i], 2);
  877. // 模板函数过滤
  878. $fun = trim($args[0]);
  879. switch ($fun) {
  880. case 'default': // 特殊模板函数
  881. if (false === strpos($name, '(')) {
  882. $name = '(isset(' . $name . ') && (' . $name . ' !== \'\')?' . $name . ':' . $args[1] . ')';
  883. } else {
  884. $name = '(' . $name . ' ?: ' . $args[1] . ')';
  885. }
  886. break;
  887. default: // 通用模板函数
  888. if (!in_array($fun, $template_deny_funs)) {
  889. if (isset($args[1])) {
  890. if (strstr($args[1], '###')) {
  891. $args[1] = str_replace('###', $name, $args[1]);
  892. $name = "$fun($args[1])";
  893. } else {
  894. $name = "$fun($name,$args[1])";
  895. }
  896. } else {
  897. if (!empty($args[0])) {
  898. $name = "$fun($name)";
  899. }
  900. }
  901. }
  902. }
  903. }
  904. $_varFunctionList[$_key] = $name;
  905. $varStr = $name;
  906. }
  907. return;
  908. }
  909. /**
  910. * 特殊模板变量解析
  911. * 格式 以 $Think. 打头的变量属于特殊模板变量
  912. * @access public
  913. * @param array $vars 变量数组
  914. * @return string
  915. */
  916. public function parseThinkVar($vars)
  917. {
  918. $type = strtoupper(trim(array_shift($vars)));
  919. $param = implode('.', $vars);
  920. if ($vars) {
  921. switch ($type) {
  922. case 'SERVER':
  923. $parseStr = '\\think\\Request::instance()->server(\'' . $param . '\')';
  924. break;
  925. case 'GET':
  926. $parseStr = '\\think\\Request::instance()->get(\'' . $param . '\')';
  927. break;
  928. case 'POST':
  929. $parseStr = '\\think\\Request::instance()->post(\'' . $param . '\')';
  930. break;
  931. case 'COOKIE':
  932. $parseStr = '\\think\\Cookie::get(\'' . $param . '\')';
  933. break;
  934. case 'SESSION':
  935. $parseStr = '\\think\\Session::get(\'' . $param . '\')';
  936. break;
  937. case 'ENV':
  938. $parseStr = '\\think\\Request::instance()->env(\'' . $param . '\')';
  939. break;
  940. case 'REQUEST':
  941. $parseStr = '\\think\\Request::instance()->request(\'' . $param . '\')';
  942. break;
  943. case 'CONST':
  944. $parseStr = strtoupper($param);
  945. break;
  946. case 'LANG':
  947. $parseStr = '\\think\\Lang::get(\'' . $param . '\')';
  948. break;
  949. case 'CONFIG':
  950. $parseStr = '\\think\\Config::get(\'' . $param . '\')';
  951. break;
  952. default:
  953. $parseStr = '\'\'';
  954. break;
  955. }
  956. } else {
  957. switch ($type) {
  958. case 'NOW':
  959. $parseStr = "date('Y-m-d g:i a',time())";
  960. break;
  961. case 'VERSION':
  962. $parseStr = 'THINK_VERSION';
  963. break;
  964. case 'LDELIM':
  965. $parseStr = '\'' . ltrim($this->config['tpl_begin'], '\\') . '\'';
  966. break;
  967. case 'RDELIM':
  968. $parseStr = '\'' . ltrim($this->config['tpl_end'], '\\') . '\'';
  969. break;
  970. default:
  971. if (defined($type)) {
  972. $parseStr = $type;
  973. } else {
  974. $parseStr = '';
  975. }
  976. }
  977. }
  978. return $parseStr;
  979. }
  980. /**
  981. * 分析加载的模板文件并读取内容 支持多个模板文件读取
  982. * @access private
  983. * @param string $templateName 模板文件名
  984. * @return string
  985. */
  986. private function parseTemplateName($templateName)
  987. {
  988. $array = explode(',', $templateName);
  989. $parseStr = '';
  990. foreach ($array as $templateName) {
  991. if (empty($templateName)) {
  992. continue;
  993. }
  994. if (0 === strpos($templateName, '$')) {
  995. //支持加载变量文件名
  996. $templateName = $this->get(substr($templateName, 1));
  997. }
  998. $template = $this->parseTemplateFile($templateName);
  999. if ($template) {
  1000. // 获取模板文件内容
  1001. $parseStr .= file_get_contents($template);
  1002. }
  1003. }
  1004. return $parseStr;
  1005. }
  1006. /**
  1007. * 解析模板文件名
  1008. * @access private
  1009. * @param string $template 文件名
  1010. * @return string|false
  1011. */
  1012. private function parseTemplateFile($template)
  1013. {
  1014. if ('' == pathinfo($template, PATHINFO_EXTENSION)) {
  1015. if (strpos($template, '@')) {
  1016. list($module, $template) = explode('@', $template);
  1017. }
  1018. if (0 !== strpos($template, '/')) {
  1019. $template = str_replace(['/', ':'], $this->config['view_depr'], $template);
  1020. } else {
  1021. $template = str_replace(['/', ':'], $this->config['view_depr'], substr($template, 1));
  1022. }
  1023. if ($this->config['view_base']) {
  1024. $module = isset($module) ? $module : Request::instance()->module();
  1025. $path = $this->config['view_base'] . ($module ? $module . DS : '');
  1026. } else {
  1027. $path = isset($module) ? APP_PATH . $module . DS . basename($this->config['view_path']) . DS : $this->config['view_path'];
  1028. }
  1029. $template = realpath($path . $template . '.' . ltrim($this->config['view_suffix'], '.'));
  1030. }
  1031. if (is_file($template)) {
  1032. // 记录模板文件的更新时间
  1033. $this->includeFile[$template] = filemtime($template);
  1034. return $template;
  1035. } else {
  1036. throw new TemplateNotFoundException('template not exists:' . $template, $template);
  1037. }
  1038. }
  1039. /**
  1040. * 按标签生成正则
  1041. * @access private
  1042. * @param string $tagName 标签名
  1043. * @return string
  1044. */
  1045. private function getRegex($tagName)
  1046. {
  1047. $regex = '';
  1048. if ('tag' == $tagName) {
  1049. $begin = $this->config['tpl_begin'];
  1050. $end = $this->config['tpl_end'];
  1051. if (strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1) {
  1052. $regex = $begin . '((?:[\$]{1,2}[a-wA-w_]|[\:\~][\$a-wA-w_]|[+]{2}[\$][a-wA-w_]|[-]{2}[\$][a-wA-w_]|\/[\*\/])(?>[^' . $end . ']*))' . $end;
  1053. } else {
  1054. $regex = $begin . '((?:[\$]{1,2}[a-wA-w_]|[\:\~][\$a-wA-w_]|[+]{2}[\$][a-wA-w_]|[-]{2}[\$][a-wA-w_]|\/[\*\/])(?>(?:(?!' . $end . ').)*))' . $end;
  1055. }
  1056. } else {
  1057. $begin = $this->config['taglib_begin'];
  1058. $end = $this->config['taglib_end'];
  1059. $single = strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1 ? true : false;
  1060. switch ($tagName) {
  1061. case 'block':
  1062. if ($single) {
  1063. $regex = $begin . '(?:' . $tagName . '\b(?>(?:(?!name=).)*)\bname=([\'\"])(?P<name>[\$\w\-\/\.]+)\\1(?>[^' . $end . ']*)|\/' . $tagName . ')' . $end;
  1064. } else {
  1065. $regex = $begin . '(?:' . $tagName . '\b(?>(?:(?!name=).)*)\bname=([\'\"])(?P<name>[\$\w\-\/\.]+)\\1(?>(?:(?!' . $end . ').)*)|\/' . $tagName . ')' . $end;
  1066. }
  1067. break;
  1068. case 'literal':
  1069. if ($single) {
  1070. $regex = '(' . $begin . $tagName . '\b(?>[^' . $end . ']*)' . $end . ')';
  1071. $regex .= '(?:(?>[^' . $begin . ']*)(?>(?!' . $begin . '(?>' . $tagName . '\b[^' . $end . ']*|\/' . $tagName . ')' . $end . ')' . $begin . '[^' . $begin . ']*)*)';
  1072. $regex .= '(' . $begin . '\/' . $tagName . $end . ')';
  1073. } else {
  1074. $regex = '(' . $begin . $tagName . '\b(?>(?:(?!' . $end . ').)*)' . $end . ')';
  1075. $regex .= '(?:(?>(?:(?!' . $begin . ').)*)(?>(?!' . $begin . '(?>' . $tagName . '\b(?>(?:(?!' . $end . ').)*)|\/' . $tagName . ')' . $end . ')' . $begin . '(?>(?:(?!' . $begin . ').)*))*)';
  1076. $regex .= '(' . $begin . '\/' . $tagName . $end . ')';
  1077. }
  1078. break;
  1079. case 'restoreliteral':
  1080. $regex = '<!--###literal(\d+)###-->';
  1081. break;
  1082. case 'include':
  1083. $name = 'file';
  1084. case 'taglib':
  1085. case 'layout':
  1086. case 'extend':
  1087. if (empty($name)) {
  1088. $name = 'name';
  1089. }
  1090. if ($single) {
  1091. $regex = $begin . $tagName . '\b(?>(?:(?!' . $name . '=).)*)\b' . $name . '=([\'\"])(?P<name>[\$\w\-\/\.\:@,\\\\]+)\\1(?>[^' . $end . ']*)' . $end;
  1092. } else {
  1093. $regex = $begin . $tagName . '\b(?>(?:(?!' . $name . '=).)*)\b' . $name . '=([\'\"])(?P<name>[\$\w\-\/\.\:@,\\\\]+)\\1(?>(?:(?!' . $end . ').)*)' . $end;
  1094. }
  1095. break;
  1096. }
  1097. }
  1098. return '/' . $regex . '/is';
  1099. }
  1100. }