Template.php 45 KB

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