vendor/contao/core-bundle/src/Resources/contao/library/Contao/RequestToken.php line 15

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Contao.
  4.  *
  5.  * (c) Leo Feyer
  6.  *
  7.  * @license LGPL-3.0-or-later
  8.  */
  9. namespace Contao;
  10. use Symfony\Component\Security\Csrf\CsrfToken;
  11. trigger_deprecation('contao/core-bundle''4.0''Using the "Contao\RequestToken" class has been deprecated and will no longer work in Contao 5.0. Use the Symfony CSRF service via the container instead.');
  12. /**
  13.  * Generates and validates request tokens
  14.  *
  15.  * The class tries to read and validate the request token from the user session
  16.  * and creates a new token if there is none.
  17.  *
  18.  * Usage:
  19.  *
  20.  *     echo RequestToken::get();
  21.  *
  22.  *     if (!RequestToken::validate('TOKEN'))
  23.  *     {
  24.  *         throw new Exception("Invalid request token");
  25.  *     }
  26.  *
  27.  * @deprecated Deprecated since Contao 4.0, to be removed in Contao 5.0.
  28.  *             Use the Symfony CSRF service via the container instead.
  29.  */
  30. class RequestToken
  31. {
  32.     /**
  33.      * Read the token from the session or generate a new one
  34.      */
  35.     public static function initialize()
  36.     {
  37.         // ignore
  38.     }
  39.     /**
  40.      * Return the token
  41.      *
  42.      * @return string The request token
  43.      */
  44.     public static function get()
  45.     {
  46.         $container System::getContainer();
  47.         return $container->get('contao.csrf.token_manager')->getDefaultTokenValue();
  48.     }
  49.     /**
  50.      * Validate a token
  51.      *
  52.      * @param string $strToken The request token
  53.      *
  54.      * @return boolean True if the token matches the stored one
  55.      */
  56.     public static function validate($strToken)
  57.     {
  58.         // The feature has been disabled
  59.         if (\defined('BYPASS_TOKEN_CHECK') || Config::get('disableRefererCheck'))
  60.         {
  61.             return true;
  62.         }
  63.         // Check against the whitelist (thanks to Tristan Lins) (see #3164)
  64.         if (Config::get('requestTokenWhitelist'))
  65.         {
  66.             $strHostname gethostbyaddr($_SERVER['REMOTE_ADDR']);
  67.             foreach (Config::get('requestTokenWhitelist') as $strDomain)
  68.             {
  69.                 if ($strDomain == $strHostname || preg_match('/\.' preg_quote($strDomain'/') . '$/'$strHostname))
  70.                 {
  71.                     return true;
  72.                 }
  73.             }
  74.         }
  75.         $container System::getContainer();
  76.         return $container->get('contao.csrf.token_manager')->isTokenValid(new CsrfToken($container->getParameter('contao.csrf_token_name'), $strToken));
  77.     }
  78. }
  79. class_alias(RequestToken::class, 'RequestToken');