<?php
require_once 'dbPDO.php';
// PHP 5.4 has a hex2bin function, the version on Yorktown doesn't
if (!version_compare(phpversion(), '5.4.0', '>=')) {
    function hex2bin($hex) {
    if (strlen($hex) % 2)
        $hex = "0".$hex;
    $bin = '';
    for ($i = 0; $i < strlen($hex); $i += 2) {
        $bin .= chr(hexdec(substr($hex, $i, 2)));
    }
       return $bin;
    }
		function hash_equals($s1, $s2) {
			// Not secure against timing attacks, but what are you going to do when the functions you use don't exist in a older version of pspell_check
			return $s1 == $s2;
		}
}
$userUUID = false;
$userCustID = 0;
$hmacPasswordSecret = 'ts1f5SD4THOuUPo+89f/5XgZwYSs5nt5MIOOu1Csu3x9zP7bEdLuu7VBY8BhCW5XD5Tw4dm9vSlV451eY+mDzFJf02T2UofoZbt/u9Nb9Fy1rOznFqVpg+RuiN76xSSI40mwZGms1YVZQKcQQiVYjMcgDV6IxqH6lUY1rCs9w5o=';
if (isset($_COOKIE['userUUID'])) {
	$cookie64 = $_COOKIE['userUUID'];
	$cookie = base64_decode($cookie64);
	$cookieSplit = explode('|', $cookie);
	$uuid = $cookieSplit[0];
	$cookieHash = $cookieSplit[1];
	if (hash_equals($cookieHash, hash_hmac('sha256', $uuid, 'DvtP7ImVfpSNCSsgqeu0'))) {
		$user = $db->prepare('SELECT hex(uuid) AS uuid, custID FROM bookuuidcustomers WHERE uuid = ?;');
		$user->execute(array(hex2bin($uuid)));
		if ($user->rowCount() == 1) {
			$result = $user->fetch();
			$userUUID = $result['uuid'];
			$userCustID = $result['custID'];
		} else {
			setcookie("userUUID", null, time() - 60 * 60 * 48);
			header("location: $_SERVER[REQUEST_URI]");
			exit();
		}
	} else {
		setcookie("userUUID", null, time() - 60 * 60 * 48);
		header("location: $_SERVER[REQUEST_URI]");
		exit();
	}
} else {
	$newUUID = bin2hex(openssl_random_pseudo_bytes(16));
	$check = $db->prepare('SELECT hex(uuid) FROM bookuuidcustomers WHERE uuid = ?;');
	$check->execute(array(hex2bin($newUUID)));
	$number = $check->rowCount();
	if ($number == 0) {
		$db->beginTransaction();
		$insert = $db->prepare("INSERT INTO bookuuidcustomers (uuid) VALUES (unhex(?));");
		$insert->execute(array($newUUID));
        $cookieHash = hash_hmac('sha256', $newUUID, 'DvtP7ImVfpSNCSsgqeu0'); // Last param is the secret key, don't read that
        $cookie = base64_encode("$newUUID|$cookieHash");
        setcookie('userUUID', $cookie, time() + 15552000); // time + 60 * 60 * 24 * 180 (180 days for expire)
        $db->commit();
        header("location: $_SERVER[REQUEST_URI]");
        exit();
    }
}
?>
