<?php
define('URLOK_KEY_LENGTH_IN_CHARACTERS',14); //Minus the length of the prefix
define('URLOK_PREFIX_LENGTH',1);
define('URLOK_PREFIX','u'); //This makes it visually easier to work with but takes away a little bit of randomness

class URLO extends HashManager{
	public function __construct(string $URLO){
		if(empty($URLO))
			throw new Exception('Invalid URLO: empty.');
		$url = $this->stripHash($URLO);
		if($url !== false)
			$this->URLO = $url;
		else
			throw new Exception('Unable to process URL='.$url.', likely a problem with the querystring/hash fragments');
	}
	private function stripHash(string $url){ //Strip any hash fragment from the url, e.g. #print
		$hash_pos = mb_strripos($url,'#'); //Last position (not first but it likely doesn't matter)
		if($hash_pos===FALSE)
			return $url;
		else{
			$query_pos = mb_strripos($url,'?'); //Last position (not first but it likely doesn't matter)
			//Is the querystring not present?
			if($query_pos === FALSE){
				//If there's no querystring, just return up till the hash mark in the URL
				return mb_substr($url,0,$hash_pos);
			}else{
				if($hash_pos > $query_pos)
					return mb_substr($url,0,$hash_pos);
				else{
					//The hash position is less than the querystring position, this is an invalid URL
					throw new Exception('Invalid URL because hash position is before querystring position: '.$url); //Something is wrong
				}
			}
		}
		return false;
	}
	public function URLOK(){
		$hash = self::hash($this->URLO);
		//Can save a bit of effort by not base62-encoding the entire string since it's being truncated anyway
		//But the performance gain is very minor so not worth making this more complicated
		$base62 = self::base16to62($hash);
		return URLOK_PREFIX.substr($base62,0,URLOK_KEY_LENGTH_IN_CHARACTERS-URLOK_PREFIX_LENGTH);
	}
}
?>
