TokenBuildBehavior.class.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | TOPThink [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2010 http://topthink.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Behavior;
  12. /**
  13. * 系统行为扩展:表单令牌生成
  14. */
  15. class TokenBuildBehavior {
  16. public function run(&$content){
  17. if(C('TOKEN_ON')) {
  18. list($tokenName,$tokenKey,$tokenValue)=$this->getToken();
  19. $input_token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />';
  20. $meta_token = '<meta name="'.$tokenName.'" content="'.$tokenKey.'_'.$tokenValue.'" />';
  21. if(strpos($content,'{__TOKEN__}')) {
  22. // 指定表单令牌隐藏域位置
  23. $content = str_replace('{__TOKEN__}',$input_token,$content);
  24. }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
  25. // 智能生成表单令牌隐藏域
  26. $content = str_replace($match[0],$input_token.$match[0],$content);
  27. }
  28. $content = str_ireplace('</head>',$meta_token.'</head>',$content);
  29. }else{
  30. $content = str_replace('{__TOKEN__}','',$content);
  31. }
  32. }
  33. //获得token
  34. private function getToken(){
  35. $tokenName = C('TOKEN_NAME',null,'__hash__');
  36. $tokenType = C('TOKEN_TYPE',null,'md5');
  37. if(!isset($_SESSION[$tokenName])) {
  38. $_SESSION[$tokenName] = array();
  39. }
  40. // 标识当前页面唯一性
  41. $tokenKey = md5($_SERVER['REQUEST_URI']);
  42. if(isset($_SESSION[$tokenName][$tokenKey])) {// 相同页面不重复生成session
  43. $tokenValue = $_SESSION[$tokenName][$tokenKey];
  44. }else{
  45. $tokenValue = is_callable($tokenType) ? $tokenType(microtime(true)) : md5(microtime(true));
  46. $_SESSION[$tokenName][$tokenKey] = $tokenValue;
  47. if(IS_AJAX && C('TOKEN_RESET',null,true))
  48. header($tokenName.': '.$tokenKey.'_'.$tokenValue); //ajax需要获得这个header并替换页面中meta中的token值
  49. }
  50. return array($tokenName,$tokenKey,$tokenValue);
  51. }
  52. }