MediaWiki REL1_34
Token.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
32class Token {
36 const SUFFIX = '+\\';
37
39 private $secret = '';
40
42 private $salt = '';
43
45 private $new = false;
46
52 public function __construct( $secret, $salt, $new = false ) {
53 $this->secret = $secret;
54 $this->salt = $salt;
55 $this->new = $new;
56 }
57
67 public static function getTimestamp( $token ) {
68 $suffixLen = strlen( self::SUFFIX );
69 $len = strlen( $token );
70 if ( $len <= 32 + $suffixLen ||
71 substr( $token, -$suffixLen ) !== self::SUFFIX ||
72 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
73 ) {
74 return null;
75 }
76
77 return hexdec( substr( $token, 32, -$suffixLen ) );
78 }
79
85 protected function toStringAtTimestamp( $timestamp ) {
86 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
87 dechex( $timestamp ) .
89 }
90
95 public function toString() {
96 return $this->toStringAtTimestamp( wfTimestamp() );
97 }
98
99 public function __toString() {
100 return $this->toString();
101 }
102
109 public function match( $userToken, $maxAge = null ) {
110 $timestamp = self::getTimestamp( $userToken );
111 if ( $timestamp === null ) {
112 return false;
113 }
114 if ( $maxAge !== null && $timestamp < wfTimestamp() - $maxAge ) {
115 // Expired token
116 return false;
117 }
118
119 $sessionToken = $this->toStringAtTimestamp( $timestamp );
120 return hash_equals( $sessionToken, $userToken );
121 }
122
127 public function wasNew() {
128 return $this->new;
129 }
130
131}
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Value object representing a CSRF token.
Definition Token.php:32
match( $userToken, $maxAge=null)
Test if the token-string matches this token.
Definition Token.php:109
__construct( $secret, $salt, $new=false)
Definition Token.php:52
toString()
Get the string representation of the token.
Definition Token.php:95
wasNew()
Indicate whether this token was just created.
Definition Token.php:127
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:85
const SUFFIX
CSRF token suffix.
Definition Token.php:36
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:67