MediaWiki REL1_30
Token.php
Go to the documentation of this file.
1<?php
24namespace MediaWiki\Session;
25
32class Token {
35 const SUFFIX = '+\\';
36
37 private $secret = '';
38 private $salt = '';
39 private $new = false;
40
46 public function __construct( $secret, $salt, $new = false ) {
47 $this->secret = $secret;
48 $this->salt = $salt;
49 $this->new = $new;
50 }
51
61 public static function getTimestamp( $token ) {
62 $suffixLen = strlen( self::SUFFIX );
63 $len = strlen( $token );
64 if ( $len <= 32 + $suffixLen ||
65 substr( $token, -$suffixLen ) !== self::SUFFIX ||
66 strspn( $token, '0123456789abcdef' ) + $suffixLen !== $len
67 ) {
68 return null;
69 }
70
71 return hexdec( substr( $token, 32, -$suffixLen ) );
72 }
73
79 protected function toStringAtTimestamp( $timestamp ) {
80 return hash_hmac( 'md5', $timestamp . $this->salt, $this->secret, false ) .
81 dechex( $timestamp ) .
83 }
84
89 public function toString() {
90 return $this->toStringAtTimestamp( wfTimestamp() );
91 }
92
93 public function __toString() {
94 return $this->toString();
95 }
96
103 public function match( $userToken, $maxAge = null ) {
104 $timestamp = self::getTimestamp( $userToken );
105 if ( $timestamp === null ) {
106 return false;
107 }
108 if ( $maxAge !== null && $timestamp < wfTimestamp() - $maxAge ) {
109 // Expired token
110 return false;
111 }
112
113 $sessionToken = $this->toStringAtTimestamp( $timestamp );
114 return hash_equals( $sessionToken, $userToken );
115 }
116
121 public function wasNew() {
122 return $this->new;
123 }
124
125}
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:103
__construct( $secret, $salt, $new=false)
Definition Token.php:46
toString()
Get the string representation of the token.
Definition Token.php:89
wasNew()
Indicate whether this token was just created.
Definition Token.php:121
toStringAtTimestamp( $timestamp)
Get the string representation of the token at a timestamp.
Definition Token.php:79
const SUFFIX
CSRF token suffix.
Definition Token.php:35
static getTimestamp( $token)
Decode the timestamp from a token string.
Definition Token.php:61