Route.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2014 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. /**
  13. * ThinkPHP路由解析类
  14. */
  15. class Route
  16. {
  17. /**
  18. * 路由检测
  19. * @param array $paths path_info数组
  20. * @return boolean
  21. */
  22. public static function check($paths = array())
  23. {
  24. $rules = self::ruleCache();
  25. if (!empty($paths)) {
  26. $regx = implode('/', $paths);
  27. } else {
  28. $depr = C('URL_PATHINFO_DEPR');
  29. $regx = preg_replace('/\.' . __EXT__ . '$/i', '', trim($_SERVER['PATH_INFO'], $depr));
  30. if (!$regx) {
  31. return false;
  32. }
  33. // 分隔符替换 确保路由定义使用统一的分隔符
  34. if ('/' != $depr) {
  35. $regx = str_replace($depr, '/', $regx);
  36. }
  37. }
  38. // 静态路由检查
  39. if (isset($rules[0][$regx])) {
  40. $route = $rules[0][$regx];
  41. $_SERVER['PATH_INFO'] = $route[0];
  42. $args = array_pop($route);
  43. if (!empty($route[1])) {
  44. $args = array_merge($args, $route[1]);
  45. }
  46. $_GET = array_merge($args, $_GET);
  47. return true;
  48. }
  49. // 动态路由检查
  50. if (!empty($rules[1])) {
  51. foreach ($rules[1] as $rule => $route) {
  52. $args = array_pop($route);
  53. if (isset($route[2])) {
  54. // 路由参数检查
  55. if (!self::checkOption($route[2], __EXT__)) {
  56. continue;
  57. }
  58. }
  59. if ($matches = self::checkUrlMatch($rule, $args, $regx)) {
  60. if ($route[0] instanceof \Closure) {
  61. // 执行闭包
  62. $result = self::invoke($route[0], $matches);
  63. // 如果返回布尔值 则继续执行
  64. return is_bool($result) ? $result : exit;
  65. } else {
  66. // 存在动态变量
  67. if (strpos($route[0], ':')) {
  68. $matches = array_values($matches);
  69. $route[0] = preg_replace_callback('/:(\d+)/', function ($match) use (&$matches) {
  70. return $matches[$match[1] - 1];
  71. }, $route[0]);
  72. }
  73. // 路由参数关联$matches
  74. if ('/' == substr($rule, 0, 1)) {
  75. $rule_params = array();
  76. foreach ($route[1] as $param_key => $param) {
  77. list($param_name, $param_value) = explode('=', $param, 2);
  78. if (!is_null($param_value)) {
  79. if (preg_match('/^:(\d*)$/', $param_value, $match_index)) {
  80. $match_index = $match_index[1] - 1;
  81. $param_value = $matches[$match_index];
  82. }
  83. $rule_params[$param_name] = $param_value;
  84. unset($route[1][$param_key]);
  85. }
  86. }
  87. $route[1] = $rule_params;
  88. }
  89. // 重定向
  90. if ('/' == substr($route[0], 0, 1)) {
  91. header("Location: $route[0]", true, $route[1]);
  92. exit;
  93. } else {
  94. $depr = C('URL_PATHINFO_DEPR');
  95. if ('/' != $depr) {
  96. $route[0] = str_replace('/', $depr, $route[0]);
  97. }
  98. $_SERVER['PATH_INFO'] = $route[0];
  99. if (!empty($route[1])) {
  100. $_GET = array_merge($route[1], $_GET);
  101. }
  102. return true;
  103. }
  104. }
  105. }
  106. }
  107. }
  108. return false;
  109. }
  110. /**
  111. * 路由反向解析
  112. * @param string $path 控制器/方法
  113. * @param array $vars url参数
  114. * @param string $depr 分隔符
  115. * @param string|true $suffix url后缀
  116. * @return string|false
  117. */
  118. public static function reverse($path, &$vars, $depr, $suffix = true)
  119. {
  120. static $_rules;
  121. if (is_null($_rules)) {
  122. if ($rules = self::ruleCache()) {
  123. foreach ($rules as $i => $rules2) {
  124. foreach ($rules2 as $rule => $route) {
  125. if (is_array($route) && is_string($route[0]) && '/' != substr($route[0], 0, 1)) {
  126. $_rules[$i][$route[0]][$rule] = $route;
  127. }
  128. }
  129. }
  130. }
  131. }
  132. // 静态路由
  133. if (isset($_rules[0][$path])) {
  134. foreach ($_rules[0][$path] as $rule => $route) {
  135. $args = array_pop($route);
  136. if (count($vars) == count($args) && !empty($vars) && !array_diff($vars, $args)) {
  137. return str_replace('/', $depr, $rule);
  138. }
  139. }
  140. }
  141. if (isset($_rules[1][$path])) {
  142. foreach ($_rules[1][$path] as $rule => $route) {
  143. $args = array_pop($route);
  144. $array = array();
  145. if (isset($route[2])) {
  146. // 路由参数检查
  147. if (!self::checkOption($route[2], $suffix)) {
  148. continue;
  149. }
  150. }
  151. if ('/' != substr($rule, 0, 1)) {
  152. // 规则路由
  153. foreach ($args as $key => $val) {
  154. $flag = false;
  155. if ($val[0] == 0) {
  156. // 静态变量值
  157. $array[$key] = $key;
  158. continue;
  159. }
  160. if (isset($vars[$key])) {
  161. // 是否有过滤条件
  162. if (!empty($val[2])) {
  163. if ($val[2] == 'int') {
  164. // 是否为数字
  165. if (!is_numeric($vars[$key]) || !preg_match('/^\d*$/', $vars[$key])) {
  166. break;
  167. }
  168. } else {
  169. // 排除的名称
  170. if (in_array($vars[$key], $val[2])) {
  171. break;
  172. }
  173. }
  174. }
  175. $flag = true;
  176. $array[$key] = $vars[$key];
  177. } elseif ($val[0] == 1) {
  178. // 如果是必选项
  179. break;
  180. }
  181. }
  182. // 匹配成功
  183. if (!empty($flag)) {
  184. foreach (array_keys($array) as $key) {
  185. $array[$key] = urlencode($array[$key]);
  186. unset($vars[$key]);
  187. }
  188. return implode($depr, $array);
  189. }
  190. } else {
  191. // 正则路由
  192. $keys = !empty($args) ? array_keys($args) : array_keys($vars);
  193. $temp_vars = $vars;
  194. $str = preg_replace_callback('/\(.*?\)/', function ($match) use (&$temp_vars, &$keys) {
  195. $k = array_shift($keys);
  196. $re_var = '';
  197. if (isset($temp_vars[$k])) {
  198. $re_var = $temp_vars[$k];
  199. unset($temp_vars[$k]);
  200. }
  201. return urlencode($re_var);
  202. }, $rule);
  203. $str = substr($str, 1, -1);
  204. $str = rtrim(ltrim($str, '^'), '$');
  205. $str = str_replace('\\', '', $str);
  206. if (preg_match($rule, $str, $matches)) {
  207. // 匹配成功
  208. $vars = $temp_vars;
  209. return str_replace('/', $depr, $str);
  210. }
  211. }
  212. }
  213. }
  214. return false;
  215. }
  216. // 规则路由定义方法:
  217. // '路由规则'=>'[控制器/操作]?额外参数1=值1&额外参数2=值2...'
  218. // '路由规则'=>array('[控制器/操作]','额外参数1=值1&额外参数2=值2...')
  219. // '路由规则'=>'外部地址'
  220. // '路由规则'=>array('外部地址','重定向代码')
  221. // 路由规则中 :开头 表示动态变量
  222. // 外部地址中可以用动态变量 采用 :1 :2 的方式
  223. // 'news/:month/:day/:id'=>array('News/read?cate=1','status=1'),
  224. // 'new/:id'=>array('/new.php?id=:1',301), 重定向
  225. // 正则路由定义方法:
  226. // '路由正则'=>'[控制器/操作]?参数1=值1&参数2=值2...'
  227. // '路由正则'=>array('[控制器/操作]?参数1=值1&参数2=值2...','额外参数1=值1&额外参数2=值2...')
  228. // '路由正则'=>'外部地址'
  229. // '路由正则'=>array('外部地址','重定向代码')
  230. // 参数值和外部地址中可以用动态变量 采用 :1 :2 的方式
  231. // '/new\/(\d+)\/(\d+)/'=>array('News/read?id=:1&page=:2&cate=1','status=1'),
  232. // '/new\/(\d+)/'=>array('/new.php?id=:1&page=:2&status=1','301'), 重定向
  233. /**
  234. * 读取规则缓存
  235. * @param boolean $update 是否更新
  236. * @return array
  237. */
  238. public static function ruleCache($update = false)
  239. {
  240. $result = array();
  241. $module = defined('MODULE_NAME') ? '_' . MODULE_NAME : '';
  242. if (APP_DEBUG || $update || !$result = S('url_route_rules' . $module)) {
  243. // 静态路由
  244. $result[0] = C('URL_MAP_RULES');
  245. if (!empty($result[0])) {
  246. foreach ($result[0] as $rule => $route) {
  247. if (!is_array($route)) {
  248. $route = array($route);
  249. }
  250. if (strpos($route[0], '?')) {
  251. // 分离参数
  252. list($route[0], $args) = explode('?', $route[0], 2);
  253. parse_str($args, $args);
  254. } else {
  255. $args = array();
  256. }
  257. if (!empty($route[1]) && is_string($route[1])) {
  258. // 额外参数
  259. parse_str($route[1], $route[1]);
  260. }
  261. $route[] = $args;
  262. $result[0][$rule] = $route;
  263. }
  264. }
  265. // 动态路由
  266. $result[1] = C('URL_ROUTE_RULES');
  267. if (!empty($result[1])) {
  268. foreach ($result[1] as $rule => $route) {
  269. if (!is_array($route)) {
  270. $route = array($route);
  271. } elseif (is_numeric($rule)) {
  272. // 支持 array('rule','adddress',...) 定义路由
  273. $rule = array_shift($route);
  274. }
  275. if (!empty($route)) {
  276. $args = array();
  277. if (is_string($route[0])) {
  278. if (0 === strpos($route[0], '/') || 0 === strpos($route[0], 'http')) {
  279. // 重定向
  280. if (!isset($route[1])) {
  281. $route[1] = 301;
  282. }
  283. } else {
  284. if (!empty($route[1]) && is_string($route[1])) {
  285. // 额外参数
  286. parse_str($route[1], $route[1]);
  287. }
  288. if (strpos($route[0], '?')) {
  289. // 分离参数
  290. list($route[0], $params) = explode('?', $route[0], 2);
  291. if (!empty($params)) {
  292. foreach (explode('&', $params) as $key => $val) {
  293. if (0 === strpos($val, ':')) {
  294. // 动态参数
  295. $val = substr($val, 1);
  296. $args[$key] = strpos($val, '|') ? explode('|', $val, 2) : array($val);
  297. } else {
  298. $route[1][$key] = $val;
  299. }
  300. }
  301. }
  302. }
  303. }
  304. }
  305. if ('/' != substr($rule, 0, 1)) {
  306. // 规则路由
  307. foreach (explode('/', rtrim($rule, '$')) as $item) {
  308. $filter = $fun = '';
  309. $type = 0;
  310. if (0 === strpos($item, '[:')) {
  311. // 可选变量
  312. $type = 2;
  313. $item = substr($item, 1, -1);
  314. }
  315. if (0 === strpos($item, ':')) {
  316. // 动态变量获取
  317. $type = $type ?: 1;
  318. if ($pos = strpos($item, '|')) {
  319. // 支持函数过滤
  320. $fun = substr($item, $pos + 1);
  321. $item = substr($item, 1, $pos - 1);
  322. }
  323. if ($pos = strpos($item, '^')) {
  324. // 排除项
  325. $filter = explode('-', substr($item, $pos + 1));
  326. $item = substr($item, 1, $pos - 1);
  327. } elseif (strpos($item, '\\')) {
  328. // \d表示限制为数字
  329. if ('d' == substr($item, -1)) {
  330. $filter = 'int';
  331. }
  332. $item = substr($item, 1, -2);
  333. } else {
  334. $item = substr($item, 1);
  335. }
  336. }
  337. $args[$item] = array($type, $fun, $filter);
  338. }
  339. }
  340. $route[] = $args;
  341. $result[1][$rule] = $route;
  342. } else {
  343. unset($result[1][$rule]);
  344. }
  345. }
  346. }
  347. S('url_route_rules' . $module, $result);
  348. }
  349. return $result;
  350. }
  351. /**
  352. * 路由参数检测
  353. * @param array $options 路由参数
  354. * @param string|true $suffix URL后缀
  355. * @return boolean
  356. */
  357. private static function checkOption($options, $suffix = true)
  358. {
  359. // URL后缀检测
  360. if (isset($options['ext'])) {
  361. if ($suffix) {
  362. $suffix = $suffix === true ? C('URL_HTML_SUFFIX') : $suffix;
  363. if ($pos = strpos($suffix, '|')) {
  364. $suffix = substr($suffix, 0, $pos);
  365. }
  366. }
  367. if ($suffix != $options['ext']) {
  368. return false;
  369. }
  370. }
  371. if (isset($options['method']) && REQUEST_METHOD != strtoupper($options['method'])) {
  372. // 请求类型检测
  373. return false;
  374. }
  375. // 自定义检测
  376. if (!empty($options['callback']) && is_callable($options['callback'])) {
  377. if (false === call_user_func($options['callback'])) {
  378. return false;
  379. }
  380. }
  381. return true;
  382. }
  383. /**
  384. * 检测URL和路由规则是否匹配
  385. * @param string $rule 路由规则
  386. * @param array $args 路由动态变量
  387. * @param string $regx URL地址
  388. * @return array|false
  389. */
  390. private static function checkUrlMatch(&$rule, &$args, &$regx)
  391. {
  392. $params = array();
  393. if ('/' == substr($rule, 0, 1)) {
  394. // 正则路由
  395. if (preg_match($rule, $regx, $matches)) {
  396. if ($args) { // 存在动态变量
  397. foreach ($args as $key => $val) {
  398. $params[$key] = isset($val[1]) ? $val[1]($matches[$val[0]]) : $matches[$val[0]];
  399. }
  400. $regx = substr_replace($regx, '', 0, strlen($matches[0]));
  401. }
  402. array_shift($matches);
  403. return $matches;
  404. } else {
  405. return false;
  406. }
  407. } else {
  408. $paths = explode('/', $regx);
  409. // $结尾则要求完整匹配
  410. if ('$' == substr($rule, -1) && count($args) != count($paths)) {
  411. return false;
  412. }
  413. foreach ($args as $key => $val) {
  414. $var = array_shift($paths) ?: '';
  415. if ($val[0] == 0) {
  416. // 静态变量
  417. if (0 !== strcasecmp($key, $var)) {
  418. return false;
  419. }
  420. } else {
  421. if (isset($val[2])) {
  422. // 设置了过滤条件
  423. if ($val[2] == 'int') {
  424. // 如果值不为整数
  425. if (!preg_match('/^\d*$/', $var)) {
  426. return false;
  427. }
  428. } else {
  429. // 如果值在排除的名单里
  430. if (in_array($var, $val[2])) {
  431. return false;
  432. }
  433. }
  434. }
  435. if (!empty($var)) {
  436. $params[$key] = !empty($val[1]) ? $val[1]($var) : $var;
  437. } elseif ($val[0] == 1) {
  438. // 不是可选的
  439. return false;
  440. }
  441. }
  442. }
  443. $matches = $params;
  444. $regx = implode('/', $paths);
  445. }
  446. // 解析剩余的URL参数
  447. if ($regx) {
  448. preg_replace_callback('/(\w+)\/([^\/]+)/', function ($match) use (&$params) {
  449. $params[strtolower($match[1])] = strip_tags($match[2]);
  450. }, $regx);
  451. }
  452. $_GET = array_merge($params, $_GET);
  453. // 成功匹配后返回URL中的动态变量数组
  454. return $matches;
  455. }
  456. /**
  457. * 执行闭包方法 支持参数调用
  458. * @param function $closure 闭包函数
  459. * @param array $var 传给闭包的参数
  460. * @return boolean
  461. */
  462. private static function invoke($closure, $var = array())
  463. {
  464. $reflect = new \ReflectionFunction($closure);
  465. $params = $reflect->getParameters();
  466. $args = array();
  467. foreach ($params as $i => $param) {
  468. $name = $param->getName();
  469. if (isset($var[$name])) {
  470. $args[] = $var[$name];
  471. } elseif (isset($var[$i])) {
  472. $args[] = $var[$i];
  473. } elseif ($param->isDefaultValueAvailable()) {
  474. $args[] = $param->getDefaultValue();
  475. }
  476. }
  477. return $reflect->invokeArgs($args);
  478. }
  479. }