0
0

Template.php 47 KB

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