<?php

/**
 * CSRF
 *
 * This implements CSRF security for sites
 *
 * @category Core
 * @package  Mtc_Core
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @license  GPLv3 http://www.gnu.org/licenses/gpl.html
 * @version  CVS: 1.0
 * @link     http://www.mtcmedia.co.uk
 */


/**
 * Class CSRF
 *
 * This class implements CSRF token creation and check to increase site security
 *
 * @category Plugins
 * @package  Mtc_Plugins
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 * @license  GPLv3 http://www.gnu.org/licenses/gpl.html
 * @version  Release: 1.0
 * @link     http://www.mtcmedia.co.uk
 */
class CSRF
{
    /**
     * CSRF::token()
     *
     * Generates and returns a random token. Saves also in $_SESSION for later usage
     *
     * @access public
     * @static
     * @param  mixed $form_name Form name for which this token is created
     *
     * @return string Token field as a hidden input
     */
    public static function token($form_name = false)
    {
        if ($form_name) {
            // Check if a token already exists for the given form
            if (isset($_SESSION['csrf'][$form_name])) {
                $token = $_SESSION['csrf'][$form_name];
            } else {
                // Generate a new token if none exists
                $token = md5(uniqid(rand(), true));
                $_SESSION['csrf'][$form_name] = $token;
            }
            return '<input type="hidden" name="csrf" value="'.$token.'" />';
        }
    }

    /**
     * CSRF::checkToken()
     *
     * Checks if token matches the one stored on server.
     * Also checks whether HTTP_ORIGIN matches site.
     *
     * @access public
     * @static
     * @param  mixed $form_name Form name for which this token is created
     *
     * @return bool Whether token check was successful or failed attempt
     */
    public static function checkToken($form_name=false)
    {
        if (DEV_MODE) {
            return true;
        } // Disable security checks for staging and not yet ready sites
        if (isset($_SERVER['HTTP_ORIGIN']) 
            && strpos($_SERVER['HTTP_ORIGIN'], $_SERVER['HTTP_HOST']) === false
        ) {
            return false;
        }
        if ($_REQUEST['csrf'] && $_SESSION['csrf'][$form_name]) {
            if ($_SESSION['csrf'][$form_name] == $_REQUEST['csrf']) {
                unset($_SESSION['csrf'][$form_name]);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
