
function base64_urlsafe_encode($val) {
  $val = base64_encode($val);
  return str_replace(array('+', '/', '='), array('_', '-', '.'), $val);
}

function base64_urlsafe_decode($val) {
  $val = str_replace(array('_','-', '.'), array('+', '/', '='), $val);
  return base64_decode($val);
}

function encode_token($book, $secret){
  $blob = serialize($book);
  $blob64 = base64_urlsafe_encode($blob);
  $cert = hash_hmac ("sha256", $blob64 , $secret ) ;
  return $cert.$blob64;
}

function decode_token($token, $secret,$default = false){
  if(strlen($token) < 40){return $default;}
  $cert = substr($token, 0, 64);
  $blob64 = substr($token, 64);
  $formal = hash_hmac ("sha256", $blob64 , $secret ) ;
  if($cert == $formal){
    return unserialize(base64_urlsafe_decode($blob64));
  }else{
    return $default;
  }
}

function check_token($token, $secret){
  if(strlen($token) < 40){return $default;}
  $cert = substr($token, 0, 64);
  $blob64 = substr($token, 64);
  $formal = hash_hmac ("sha256", $blob64 , $secret ) ;
  return $cert == $formal;
}

function app_token_secret()
{
  $keyfile = dirname(__FILE__) . "/_apptokensecret.php";

  if(!is_file($keyfile)){
    $key = bin2hex(openssl_random_pseudo_bytes(32));
    $phptext = '<?php function _AppTokenSecret(){ return "'. $key .'"; }';
    file_put_contents($keyfile, $phptext);
  }
  
  require_once($keyfile);
  
  return _AppTokenSecret();
}
