TokenBuildBehavior.class.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. // +--------------------------------------------------------------------------
  3. // | Senthot [ DEVELOPED BY ME ]
  4. // +--------------------------------------------------------------------------
  5. // | Copyright (c) 2010 http://www.senthot.com All rights reserved.
  6. // | License ( http://www.apache.org/licenses/LICENSE-2.0 )
  7. // | Author: ms134n ( [email protected] )
  8. // +--------------------------------------------------------------------------
  9. defined('SEN_PATH') or exit();
  10. /**
  11. * System behavior extension : Form token generation
  12. * @category Sen
  13. * @package Sen
  14. * @subpackage Behavior
  15. * @author ms134n <[email protected]>
  16. */
  17. class TokenBuildBehavior extends Behavior {
  18. // Parameter defines the behavior
  19. protected $options = array(
  20. 'TOKEN_ON' => false, // Open Token Authentication
  21. 'TOKEN_NAME' => '__hash__', // Token authentication hidden form field names
  22. 'TOKEN_TYPE' => 'md5', // Token authentication hash rule
  23. 'TOKEN_RESET' => true, // Tokens are reset after an error
  24. );
  25. public function run(&$content){
  26. if(C('TOKEN_ON')) {
  27. if(strpos($content,'{__TOKEN__}')) {
  28. // Token hidden form fields specified location
  29. $content = str_replace('{__TOKEN__}',$this->buildToken(),$content);
  30. }elseif(preg_match('/<\/form(\s*)>/is',$content,$match)) {
  31. // Smart token generated form hidden fields
  32. $content = str_replace($match[0],$this->buildToken().$match[0],$content);
  33. }
  34. }else{
  35. $content = str_replace('{__TOKEN__}','',$content);
  36. }
  37. }
  38. // Create a form token
  39. private function buildToken() {
  40. $tokenName = C('TOKEN_NAME');
  41. $tokenType = C('TOKEN_TYPE');
  42. if(!isset($_SESSION[$tokenName])) {
  43. $_SESSION[$tokenName] = array();
  44. }
  45. // Uniqueness identifies the current page
  46. $tokenKey = md5($_SERVER['REQUEST_URI']);
  47. if(isset($_SESSION[$tokenName][$tokenKey])) {// Repeat the same page does not generate session
  48. $tokenValue = $_SESSION[$tokenName][$tokenKey];
  49. }else{
  50. $tokenValue = $tokenType(microtime(TRUE));
  51. $_SESSION[$tokenName][$tokenKey] = $tokenValue;
  52. }
  53. $token = '<input type="hidden" name="'.$tokenName.'" value="'.$tokenKey.'_'.$tokenValue.'" />';
  54. return $token;
  55. }
  56. }