<?php
	class Security {
		
		public $csrfTokenName;
		public $passwordMinLength;
		private $session;
		private $config;
		
		function __construct() {
			global $session, $config;
			
			$this->csrfTokenName = 'csrf_token';
			$this->session = $session;
			$this->config = $config;
			$this->passwordMinLength = $this->config['settings']['password-min-lenght'];
		}
		
		public function setCSRFToken() {
				
			//if ($this->session->sessionExists($this->csrfTokenName)) {
				
				if (function_exists('random_bytes')) { //Only PHP 7
					$this->session->refreshSession($this->csrfTokenName, bin2hex(random_bytes(32)));
				} else {
					$this->session->refreshSession($this->csrfTokenName, bin2hex(openssl_random_pseudo_bytes(32)));
				}
			
			//}
						
			return $this->session->getSessionValue($this->csrfTokenName);
		}
		
		public function getCSRFToken() {
			return $this->session->getSessionValue($this->csrfTokenName);
		}
		
		public function compareCSRFToken($token=null) {
			
			$sessionToken = $this->getCSRFToken();
			
			if ($sessionToken !== false) {
				return hash_equals($sessionToken, $token);
			}
			
			return false;
		}
		
		public function secureString($string, $action='e') {
			    $output = false;

			    $encryptMethod = "AES-256-CBC";
			    $secretKey = $this->config['settings']['secret-key'];
			    $secretIv = $this->config['settings']['secret-iv'];
			

			    $key = hash('sha256', $secretKey);
			
			    $iv = substr(hash('sha256', $secretIv), 0, 16);
			
			    if ($action == 'e') {
			        $output = openssl_encrypt($string, $encryptMethod, $key, 0, $iv);
			        $output = base64_encode($output);
			    } else if ($action == 'd') {
			        $output = openssl_decrypt(base64_decode($string), $encryptMethod, $key, 0, $iv);
			    }
			
			    return $output;
		}
		
		public function validatePassword($password='') {
			if(!preg_match( '/[^A-Za-z0-9]+/', $password) || strlen($password) < $this->passwordMinLength) {
				return false;
			}

			return true;
		}
		
		public function getGUID() {
		    if (function_exists('com_create_guid') === true) {
		        return trim(com_create_guid(), '{}');
		    }
		
		    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
		}

	}