<?php

	function show_403(){
		if ((isset($_SERVER["HTTP_X_REQUESTED_WITH"]) and strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") or strpos($_SERVER["HTTP_ACCEPT"], "application/json") !== false) {
			http_response_code(403);
			echo json_encode([
				"status" => "error",
				"message" => "ERRO 403: Acesso negado, você não tem autorização para acessar esta página!"
			]);
			exit();
		}
		else{
			throw new Exception("Access denied.", 403);
		}
	}

	function show_404(){
		if ((isset($_SERVER["HTTP_X_REQUESTED_WITH"]) and strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") or strpos($_SERVER["HTTP_ACCEPT"], "application/json") !== false) {
			http_response_code(404);
			echo json_encode([
				"status" => "error",
				"message" => "ERRO 404: A página que você está procurando não foi encontrada!"
			]);
			exit();
		}
		else{
			throw new Exception("This page does not exist.", 404);
		}
	}

	function show_500($message = "Erro interno no sistema!"){
		if ((isset($_SERVER["HTTP_X_REQUESTED_WITH"]) and strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") or strpos($_SERVER["HTTP_ACCEPT"], "application/json") !== false) {
			http_response_code(500);
			echo json_encode([
				"status" => "error",
				"message" => "ERRO 500: {$message}"
			]);
			exit();
		}
		else{
			throw new Exception("{$message}", 500);
		}
	}

	function show_503(){
		if ((isset($_SERVER["HTTP_X_REQUESTED_WITH"]) and strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") or strpos($_SERVER["HTTP_ACCEPT"], "application/json") !== false) {
			http_response_code(503);
			echo json_encode([
				"status" => "error",
				"message" => "ERRO 503: Estamos em manutenção neste exato momento, tente mais tarde!"
			]);
			exit();
		}
		else{
			throw new Exception("We are under maintenance.", 503);
		}
	}

	function get_title($title, $separator = "|", $order = true){
		if ($order == true) {
			return $title." ".$separator." ".PROJECT_NAME;
		}
		else{
			return PROJECT_NAME." ".$separator." ".$title;
		}
	}

	function show_title($title, $separator = "|", $order = true){
		echo get_title($title, $separator, $order);
	}

	function show($var){
		if (gettype($var) == "array") {
			echo "<pre>".print_r($var, true)."</pre>";
		}
		else{
			echo $var;
		}
	}

	function convert_date($data, $type=null){
		if (strpos($data, "/") != "") {
			if (strpos($data, ":") != "" and strpos($data, " ") != ""){
				$aux = explode(" ", $data);
				$d = $aux[0];
				$h = $aux[1];

				$aux = explode("/", $d);
				return $aux[2]."-".$aux[1]."-".$aux[0]." ".$h;
			}
			else{
				$aux = explode("/", $data);
				return $aux[2]."-".$aux[1]."-".$aux[0];
			}
		}
		else if (strpos($data, "-") != "") {
			if (strpos($data, ":") != "" and strpos($data, " ") != ""){
				$aux = explode(" ", $data);
				$d = $aux[0];
				$h = $aux[1];

				$aux = explode("-", $d);
				return $aux[2]."/".$aux[1]."/".$aux[0]." ".$h;
			}
			else{
				$aux = explode("-", $data);
				return $aux[2]."/".$aux[1]."/".$aux[0];
			}
		}
		else{
			return $data;
		}
	}

	function first_name($name){
		$array = explode(" ", $name);

		if (count($array) > 1) {
			return $array[0];
		}
		else{
			return $name;
		}
	}

	function first_last_name($name){
		$array = explode(" ", $name);

		if (count($array) == 1) {
			return $array[0];
		}
		else if (count($array) >= 2) {
			if (empty($array[1]) or in_array(mb_strtolower($array[1]), ["de", "di", "da", "do", "dos", "das"])) {
				return $array[0];
			}
			return $array[0]." ".$array[1];
		}
		else{
			return $name;
		}
	}

	function validate_cpf($cpf){
		if (empty($cpf)) {
			return false;
		}

		$cpf = preg_replace("/[^0-9]/", "", $cpf);
		$cpf = str_pad($cpf, 11, '0', STR_PAD_LEFT);
	
		if (strlen($cpf) != 11) {
			return false;
		}
		elseif (
			$cpf == "00000000000" or 
			$cpf == "11111111111" or 
			$cpf == "22222222222" or 
			$cpf == "33333333333" or 
			$cpf == "44444444444" or 
			$cpf == "55555555555" or 
			$cpf == "66666666666" or 
			$cpf == "77777777777" or 
			$cpf == "88888888888" or 
			$cpf == "99999999999" or 
			$cpf == "12345678909"
		) {
			return false;
		}
		else{   
			for ($t = 9; $t < 11; $t++) {
				for ($d = 0, $c = 0; $c < $t; $c++) {
					$d += $cpf[$c] * (($t + 1) - $c);
				}
				$d = ((10 * $d) % 11) % 10;
				if ($cpf[$c] != $d) {
					return false;
				}
			}
			return true;
		}
	}

	function validate_cnpj($cnpj){ 
		if (empty($cnpj)) {
			return false;
		}

		$cnpj = preg_replace("/[^0-9]/", "", $cnpj);
		$cnpj = str_pad($cnpj, 14, '0', STR_PAD_LEFT);
		
		if (strlen($cnpj) != 14) {
			return false;
		}
		else if (
			$cnpj == "00000000000000" or 
			$cnpj == "11111111111111" or 
			$cnpj == "22222222222222" or 
			$cnpj == "33333333333333" or 
			$cnpj == "44444444444444" or 
			$cnpj == "55555555555555" or 
			$cnpj == "66666666666666" or 
			$cnpj == "77777777777777" or 
			$cnpj == "88888888888888" or 
			$cnpj == "99999999999999"
		) {
			return false;
		}
		else {   
			$j = 5;
			$k = 6;
			$soma1 = 0;
			$soma2 = 0;

			for ($i = 0; $i < 13; $i++) {
				$j = $j == 1 ? 9 : $j;
				$k = $k == 1 ? 9 : $k;

				$soma2 += ($cnpj[$i] * $k);

				if ($i < 12) {
					$soma1 += ($cnpj[$i] * $j);
				}

				$k--;
				$j--;
			}

			$digito1 = $soma1 % 11 < 2 ? 0 : 11 - $soma1 % 11;
			$digito2 = $soma2 % 11 < 2 ? 0 : 11 - $soma2 % 11;

			if ($cnpj[12] == $digito1 and $cnpj[13] == $digito2){
				return true;
			}
			else{
				return false;
			}
		}
	}

	function validate_cnh($cnh){
		$cnh = strval($cnh);
		$chart1 = $cnh[0];

		if (strlen(preg_replace("/[^\d]/", "", $cnh)) !== 11 || str_repeat($chart1, 11) == $cnh) {
			return false;
		} 

		for ($i = 0, $j = 9, $v = 0; $i < 9; ++$i, --$j) {
			$v += +($cnh[$i] * $j);
		}

		$dsc = 0;
		$vl1 = $v % 11;

		if ($vl1 >= 10) {
			$vl1 = 0;
			$dsc = 2;
		}

		for ($i = 0, $j = 1, $v = 0; $i < 9; ++$i, ++$j) {
			$v += +($cnh[$i] * $j);
		}

		$x = $v % 11;
		$vl2 = ($x >= 10) ? 0 : $x - $dsc;

		return ("".$vl1.$vl2) === substr($cnh, -2);
	}


	function validate_cep($cep){
		if (preg_match("/[0-9]{5}-[0-9]{3}/", $cep) == 1) {
			if (preg_replace("/[0-9]{5}-[0-9]{3}/", "", $cep) != "") {
				return false;
			}           
			return true;
		}
		else{
			return false;
		}
	}

	function validate_date($date){
		if (preg_match("/(\d{2})\/(\d{2})\/(\d{4})/", $date, $aux) == 1) {
			$d = $aux[1];
			$m = $aux[2];
			$y = $aux[3];
		}
		elseif (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date, $aux) == 1) {
			$d = $aux[3];
			$m = $aux[2];
			$y = $aux[1];
		}
		else{
			return false;
		}
	
		if (checkdate($m, $d, $y) == 1){
			return true;
		}
		else{
			return false;
		}
	}

	function validate_birth_date($date){
		if (validate_date($date)) {
			if (preg_match("/(\d{2})\/(\d{2})\/(\d{4})/", $date) == 1){
				$date = convert_date($date);
			}
			
			return (date("Y-m-d") >= $date and $date >= date("Y-m-d", strtotime("-125 years", strtotime(date("Y-m-d"))))) ? true : false;
		}
		else{
			return false;
		}
	}

	function validate_email($email){
		if (preg_match("/([A-z\_\.0-9]{1,64})\@([A-z\.\_0-9]{1,254})/", $email) == 1){
			if (preg_replace("/([A-z\_\.0-9]{1,64})\@([A-z\.\_0-9]{1,254})/", "", $email) != "") {
				return false;
			}
			return true;
		}
		else{
			return false;
		}
	}

	function validate_url($url){
		if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
			return true;
		}
		else{
			return false;
		}
	}

	function validate_ip($ip){
		if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
			return true;
		}
		else{
			return false;
		}
	}

	function import_file($path, $vars = [], $once=true){
		if (preg_match("/[\/]$/", $path) == 1) {
			$path = substr($path, 1);
		}

		if (preg_match("/[.php]$/", $path) == 0) {
			$path .= ".php";
		}

		if (!file_exists($path)) {
			throw new Exception("The $path file does not exist.", 500);
		}

		if (gettype($vars) == "array" and count($vars) > 0) {
			foreach ($vars as $key => $value) {
				$$key = $value;
			}
		}

		if ($once == true) {
			require_once($path);
		}
		else{	
			require($path);
		}
	}

	function import_action($path, $vars = [], $once=true){
		return import_file(DIR_ACTIONS.$path, $vars, $once);
	}

	function import_view($path, $vars = [], $once=true){
		return import_file(DIR_VIEWS.$path, $vars, $once);
	}

	function import_template($path, $vars = [], $once=true){
		return import_file(DIR_TEMPLATES.$path, $vars, $once);
	}

	function import_page($path, $vars = [], $once=true){
		return import_file(DIR_PAGES.$path, $vars, $once);
	}

	function import_library($path, $vars = [], $once=true){
		return import_file(DIR_LIBRARIES.$path, $vars, $once);
	}

	function get_slug($string) {
		$search = ["ä","ã","à","á","â","ê","ë","è","é","ï","ì","í","ö","õ","ò","ó","ô","ü","ù","ú","û","À","Á","É","Í","Ó","Ú","ñ","Ñ","ç","Ç"," ","-","(",")",",",";",":","|","!",'"',"#","$","%","&","/","=","?","~","^",">","<","ª","º","+","*",".",",",";","'",'"'];

		$replace = ["a","a","a","a","a","e","e","e","e","i","i","i","o","o","o","o","o","u","u","u","u","A","A","E","I","O","U","n","n","c","C","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","","","","","","",""];

		return strtolower(str_replace($search, $replace, $string));
	}

	function show_slug($string) {
		echo get_slug();
	}

	function encrypt_encode($string){
		return Encryption::encode($string);
	}

	function encrypt_decode($string){
		return Encryption::decode($string);
	}

	function get_session($param = null){
		if (empty($param)) {
			return Session::getAll();
		}
		else{
			return Session::get($param);
		}
	}

	function set_session($param, $value){
		Session::set($param, $value);
	}

	function exist_session($param){
		return Session::exist($param);
	}

	function unset_session(){
		return Session::unset();
	}

	function destroy_session($reset_id = true){
		return Session::destroy($reset_id);
	}

	function get_path(){
		return Controller::getPath();
	}

	function get_page($path = null){
		return Controller::getPage($path);
	}

	function have_method_permission($path = null){
		return Controller::haveMethodPermission($path);
	}

	function have_authentication_permission($path = null){
		return Controller::haveAuthenticationPermission($path);
	}

	function validate_csrf($path = null){
		return Controller::validateCSRF($path);
	}

	function set_headers_configs($path = null){
		Controller::setHeadersConfigs($path);
	}
	
	function exist_page($path = null){
		return Controller::existPage($path);
	}

	function get_link($string = null){
		return Controller::getLink($string);
	}

	function show_link($string = null){
		echo Controller::getLink($string);
	}

	function get_file_link($link){
		return get_link($link."?v=".filemtime(get_dir($link)));
	}

	function show_file_link($link){
		echo get_link($link."?v=".filemtime(get_dir($link)));
	}

	function get_dir($dir){
		return $_SERVER["DOCUMENT_ROOT"].get_link($dir);
	}

	function show_dir($dir){
		echo $_SERVER["DOCUMENT_ROOT"].get_link($dir);
	}

	function get_url($link = null){
		return ((isset($_SERVER["HTTPS"]) or $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https" : "http")."://".$_SERVER["HTTP_HOST"].get_link($link);
	}

	function show_url($link = null){
		echo ((isset($_SERVER["HTTPS"]) or $_SERVER["HTTP_X_FORWARDED_PROTO"] == "https") ? "https" : "http")."://".$_SERVER["HTTP_HOST"].get_link($link);
	}

	function get_error_page($code){
		return Controller::getErrorPage($code);
	}

	function prepare_directory($dir, $option = true){
		return File::prepareDirectory($dir, $option);
	}

	function upload_file($files, $dir, $filter=[], $subfolder=true, $file_name=null, $reduce=true){
		return File::upload($files, $dir, $filter, $subfolder, $file_name, $reduce);
	}

	function delete_file($dir_file, $report_error=false){
		return File::delete($dir_file, $report_error);
	}

	function filter($variable, $filter){
		if (is_array($variable) == false and is_object($variable) == false) {
			switch (strtoupper($filter)) {
				case "STRING":
					return strip_tags(preg_replace("/[\'\"\`]/i", "", preg_replace("#([\s\t\n]on.*=\".*?\")|([\s\t\n]on.*=\'.*?\')#is", "", preg_replace("#<script.*</script>#is", "", strval($variable)))));
					break; 
				case "NUMBER_INT":
					return intval(((strval($variable)[0] == "-") ? "-" : "").(preg_replace("/\D/i", "", strval($variable))));
					break; 
				case "NUMBER_FLOAT":
					return floatval(((strval($variable)[0] == "-") ? "-" : "").(preg_replace("#[^0-9\.,]#", "", strval($variable))));
					break; 
				case "EMAIL":
					return preg_replace("/[^A-z0-9\!\#\$\%\&\'\*\+\-\=\?\^\_\`\{\|\}\~\@\.\[\]]/i", "", strval($variable));
					break; 
				case "URL":
					return preg_replace("/[^A-z0-9\$\-\_\.\+\!\*\'\(\)\,\{\}\|\\\^\~\[\]\`\<\>\#\%\"\;\/\?\:\@\&\=]/i", "", strval($variable));
					break; 
				case "HTML":
					return strip_tags(preg_replace("#([\s\t\n]on.*=\".*?\")|([\s\t\n]on.*=\'.*?\')#is", "", preg_replace("#<script.*</script>#is", "", strval($variable))), "<p><b><strong><i><h1><h2><h3><h4><h5><h6><ul><ol><li><span><div><a><u><iframe><img><video><audio><hr><br><code><small><table><thead><tbody><tr><td><th><sub><sup>");
					break;
				case "DEFAULT":
					return $variable;
					break;
				default:
					throw new Exception("Non-existing filter.", 500);
					break;
			}
		}
		else{
			foreach ($variable as $key => $value) {
				$variable[$key] = filter($value, $filter);
			}

			return $variable;
		}
	}

	function get_input($method, $name, $filter="DEFAULT"){
		switch (strtoupper($method)) {
			case "GET":
				return filter($_GET[$name], $filter);
				break;
			case "POST":
				return filter($_POST[$name], $filter);
				break;
			case "PUT":
				return filter($_PUT[$name], $filter);
				break;
			case "DELETE":
				return filter($_DELETE[$name], $filter);
				break;
			case "HEAD":
				return filter($_HEAD[$name], $filter);
				break;
			case "OPTIONS":
				return filter($_OPTIONS[$name], $filter);
				break;
			default:
				throw new Exception("Non-existing method.", 500);
				break;
		}
	}

	function money_mask($money, $dollar_sign = "R$", $abbreviated = false){
		if ($abbreviated == false) {
			return !empty($dollar_sign) ? $dollar_sign." ".number_format($money, 2, ",", ".") : number_format($money, 2, ",", ".");
		}
		else{
			if ($money != 0) {
				if ($money >= 1000000000 or $money <= -1000000000) {
					return !empty($dollar_sign) ? $dollar_sign." ".number_format(($money/1000000000), 1,".",",")."B" : number_format(($money/1000000000), 1,".",",")."B";
				} 
				else if ($money >= 1000000 or $money <= -1000000) {
					return !empty($dollar_sign) ? $dollar_sign." ".number_format(($money/1000000), 1,".",",")."M" : number_format(($money/1000000), 1,".",",")."M";
				} 
				else if ($money >= 1000 or $money <= -1000) {
					return !empty($dollar_sign) ? $dollar_sign." ".number_format(($money/1000), 1,".",",")."K" : number_format(($money/1000000), 1,".",",")."K";
				} 
				else{
					return !empty($dollar_sign) ? $dollar_sign." ".number_format($money, 2, ",", ".") : number_format($money, 2, ",", ".");
				}
			}
			else{
				return !empty($dollar_sign) ? $dollar_sign." ".number_format($money, 2, ",", ".") : number_format($money, 2, ",", ".");
			}
		}
	}

	function unmask_money($money){
		return floatval(str_replace(",", ".", preg_replace("/[^\d\,]/i", "", $money)));
	}

	function mask($string, $mask){
		$string_maskared = "";
		$count = 0;

		for ($i = 0; $i < strlen($mask); $i++) {
			if ($mask[$i] == "#") {
				if (isset($string[$count])) {
					$string_maskared .= $string[$count];
					$count++;
				}
			} 
			else {
				if (isset($mask[$i])) {
					$string_maskared .= $mask[$i];
				}
			}
		}

		return $string_maskared;
	}

	function pct($val){
		$aux = intval(str_replace("%", "", $val));
		return ($aux/100);
	}

	function generate_password($number = 12){
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#$%&+-!";

		$password = "";

		for ($i = 0; $i < $number; $i++) { 
			$password .= $chars[rand(0, strlen($chars)-1)];
		}

		return $password;
	}

	function delete_folder($folder){ 
		$dir_folder = $_SERVER["DOCUMENT_ROOT"].show_link($folder);

		$iterator = new RecursiveDirectoryIterator($dir_folder, FilesystemIterator::SKIP_DOTS);
		$rec_iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST);

		foreach($rec_iterator as $file){ 
			if ($file->isFile()) {
				unlink($file->getPathname());
			}
			else{
				rmdir($file->getPathname()); 
			}
		}

		rmdir($dir_folder); 
	}

	function hex_rgba($hex, $a=1){
		if (strlen($hex) == 7 and is_numeric($a) and $a <= 1) {
			$str = str_replace("#", "", $hex);
			$aux = str_split($str, 2);

			$r = hexdec($aux[0]);
			$g = hexdec($aux[1]);
			$b = hexdec($aux[2]);

			return "rgba(".$r.",".$g.",".$b.",".$a.")";
		}
		return false;
	}

	function is_color_light($hex){
		if (strlen($hex) == 7) {
			$str = str_replace("#", "", $hex);
			$aux = str_split($str, 2);

			$r = intval(hexdec($aux[0]));
			$g = intval(hexdec($aux[1]));
			$b = intval(hexdec($aux[2]));

			$lum = ($r*299 + $g*587 + $b*114)/1000;

			if ($lum > 128) {
				return true;
			}
			else{
				return false;
			}
		}
		return null;
	}

	function color_scale($hex, $grau){
		if (strlen($hex) == 7 and strpos($grau, "%") !== false and (strpos($grau, "+") !== false or strpos($grau, "-") !== false)) {
			$str = str_replace("#", "", $hex);
			$aux = str_split($str, 2);
			
			$r = intval(hexdec($aux[0]));
			$g = intval(hexdec($aux[1]));
			$b = intval(hexdec($aux[2]));
			
			if (strpos($grau, "+") !== false) {
				$num = intval(str_replace("+", "", str_replace("%", "", $grau)));
				$pct = pct($num);

				$vr = ($r == 0) ? ceil(255*$pct) : ceil($r*$pct);
				$vg = ($g == 0) ? ceil(255*$pct) : ceil($g*$pct);
				$vb = ($b == 0) ? ceil(255*$pct) : ceil($b*$pct);
		
				if ($r == 255) {
					if ($g == 0 and $b == 0) {
						$vb += $vr;
					}
					$vg += $vr;
					$new_r = 255;
				}
				else if (($r+$vr) > 255) {
					$new_r = 255;
					$aux = ($r+$vr) - 255;
					if ($g == 0 and $b == 0) {
						$vb += $aux;
					}
					$vg += $aux;
				}
				else{
					$new_r = $r+$vr;
				}
				
				$vr = 0;
				
				if ($g == 255) {
					if ($r == 0 and $b == 0) {
						$vr += $vg;
					}
					$vb += $vg;
					$new_g = 255;
				}
				else if (($g+$vg) > 255) {
					$new_g = 255;
					$aux = ($g+$vg) - 255;
					if ($r == 0 and $b == 0) {
						$vr += $aux;
					}
					$vb += $aux;
				}
				else{
					$new_g = $g+$vg;
				}
				
				$vg = 0;
				
				if ($b == 255) {
					if ($r == 0 and $g == 0) {
						$vg += $vb;
					}
					$vr += $vb;
					$new_b = 255;
				}
				else if (($b+$vb) > 255) {
					$new_b = 255;
					$aux = ($b+$vb) - 255;
					if ($r == 0 and $g == 0) {
						$vg += $aux;
					}
					$vr += $aux;
				}
				else{
					$new_b = $b+$vb;
				}
				
				$vb = 0;
				
				if (($new_r+$vr) <= 255) {
					$new_r += $vr;
				}
				else{
					$new_r = 255;
					$vg += ($new_r+$vr) - 255;
				}
				
				if (($new_g+$vg) <= 255) {
					$new_g += $vg;
				}
				else{
					$new_g = 255;
					$vb += ($new_g+$vg) - 255;
				}
				
				if (($new_b+$vb) <= 255) {
					$new_b += $vb;
				}
				else{
					$new_b = 255;
				}
			}
			else{
				$num = intval(str_replace("-", "", str_replace("%", "", $grau)));
				$pct = pct($num);
				
				$vr = ceil($r*$pct);
				$vg = ceil($g*$pct);
				$vb = ceil($b*$pct);

				if ($r == 0) {
					$new_r = 0;
				}
				else if (($r-$vr) < 0) {
					$new_r = 0;
				}
				else{
					$new_r = $r-$vr;
				}

				if ($g == 0) {
					$new_g = 0;
				}
				else if (($g-$vg) < 0) {
					$new_g = 0;
				}
				else{
					$new_g = $g-$vg;
				}

				if ($b == 0) {
					$new_b = 0;
				}
				else if (($b-$vb) < 0) {
					$new_b = 0;
				}
				else{
					$new_b = $b-$vb;
				}
			}
			
			$pr = dechex($new_r);
			$pr = (strlen($pr) == 1) ? "0".$pr : $pr;
			$pg = dechex($new_g);
			$pg = (strlen($pg) == 1) ? "0".$pg : $pg;
			$pb = dechex($new_b);
			$pb = (strlen($pb) == 1) ? "0".$pb : $pb;
			
			return "#".$pr.$pg.$pb;
		}
		return false;
	}

	function anti_injection($string){
		$string = preg_replace("/(?i)[\;\'\"]|(from|select|insert|delete|where|drop|table|show|tables|database|#|\*|--|\\\\)/i", "" , $string);
		$string = trim($string);
		$string = strip_tags($string);
		
		if (get_magic_quotes_gpc()) {
			return $string;
		}
		else{
			return addslashes($string);
		}
	}

	function compress_string($string, $length, $break = false){
		if (strlen($string) <= $length) {
			$new_string = $string;
		}
		else{
			if ($break == true) { 
				$new_string = trim(mb_substr($string, 0, $length))."...";
			}
			else{
				$last_space = strrpos(mb_substr($string, 0, $length), " ");
				$new_string = trim(mb_substr($string, 0, $last_space))."...";
			}
		}

		return ($new_string == "...") ? $string : $new_string;
	}
	
	function get_client_access(){
		$ip = $_SERVER["REMOTE_ADDR"];

		$user_agent = $_SERVER["HTTP_USER_AGENT"];
		$browser = "";
		$platform = "";

		if (preg_match("/windows phone/i", $user_agent)) {
			$platform = "Windows Phone";
		}
		elseif (preg_match("/iphone/i", $user_agent)) {
			$platform = "iPhone";
		}
		elseif (preg_match("/android/i", $user_agent)) {
			$platform = "Android";
		}
		elseif (preg_match("/blackberry/i", $user_agent)) {
			$platform = "BlackBerry";
		}
		elseif (preg_match("/webos/i", $user_agent)) {
			$platform = "Mobile";
		}
		elseif (preg_match("/ipod/i", $user_agent)) {
			$platform = "iPod";
		}
		elseif (preg_match("/ipad/i", $user_agent)) {
			$platform = "iPad";
		}
		elseif (preg_match("/linux/i", $user_agent)) {
			if (preg_match("/ubuntu/i", $user_agent)) {
				$platform = "Linux Ubuntu";
			}
			elseif (preg_match("/debian/i", $user_agent)) {
				$platform = "Linux Debian";
			}
			elseif (preg_match("/slackware/i", $user_agent)) {
				$platform = "Linux Slackware";
			}
			elseif (preg_match("/kali/i", $user_agent)) {
				$platform = "Linux Kali";
			}
			elseif (preg_match("/fedora/i", $user_agent)) {
				$platform = "Linux Fedora";
			}
			elseif (preg_match("/mint/i", $user_agent)) {
				$platform = "Linux Mint";
			}
			elseif (preg_match("/centos/i", $user_agent)) {
				$platform = "Linux CentOS";
			}
			else{
				$platform = "Linux";
			}
		}
		elseif (preg_match("/macintosh|mac os x/i", $user_agent)) {
			if (preg_match("/macintosh/i", $user_agent)) {
				$platform = "Mac OS X";
			}
			elseif (preg_match("/mac_powerpc/i", $user_agent)) {
				$platform = "Mac OS 9";
			}
			else{
				$platform = "Mac";
			}
		}
		elseif (preg_match("/windows|win32/i", $user_agent)) {
			if (preg_match("/Windows NT 13.0/i", $user_agent)) {
				$platform = "Windows 11";
			}
			elseif (preg_match("/Windows NT 10.0/i", $user_agent)) {
				$platform = "Windows 10";
			}
			elseif (preg_match("/Windows NT 6.3/i", $user_agent)) {
				$platform = "Windows 8.1";
			}
			elseif (preg_match("/Windows NT 6.2/i", $user_agent)) {
				$platform = "Windows 8";
			}
			elseif (preg_match("/Windows NT 6.1/i", $user_agent)) {
				$platform = "Windows 7";
			}
			elseif (preg_match("/Windows NT 6.0/i", $user_agent)) {
				$platform = "Windows Vista";
			}
			elseif (preg_match("/Windows NT 5.2/i", $user_agent)) {
				$platform = "Windows Server 2003";
			}
			elseif (preg_match("/Windows NT 5.1/i", $user_agent)) {
				$platform = "Windows XP";
			}
			elseif (preg_match("/Windows NT 5.0/i", $user_agent)) {
				$platform = "Windows 2000";
			}
			elseif (preg_match("/Windows ME/i", $user_agent)) {
				$platform = "Windows ME";
			}
			elseif (preg_match("/Win98/i", $user_agent)) {
				$platform = "Windows 98";
			}
			elseif (preg_match("/Win95/i", $user_agent)) {
				$platform = "Windows 95";
			}
			elseif (preg_match("/Win16/i", $user_agent)) {
				$platform = "Windows 3.11";
			}
			else{
				$platform = "Windows";
			}

			if (preg_match("/x86/i", $user_agent)) {
				$platform .= " x86";
			}
			elseif (preg_match("/x64/i", $user_agent)) {
				$platform .= " x64";
			}
			elseif (preg_match("/WOW64/i", $user_agent)) {
				$platform .= " x64";
			}
			elseif (preg_match("/WOW86/i", $user_agent)) {
				$platform .= " x86";
			}
		}
		else{
			$platform = "Desconhecida";
		}

		if (preg_match("/MSIE/i", $user_agent) or (preg_match("/WOW/i", $user_agent) and preg_match("/Trident/i", $user_agent))) {
			$browser = "Internet Explorer";
		}
		elseif (preg_match("/Firefox/i", $user_agent)) {
			$browser = "Firefox";
		}
		elseif (preg_match("/Edg/i", $user_agent)) {
			$browser = "Microsoft Edge";
		}
		elseif (preg_match("/OPR/i", $user_agent) or preg_match("/Presto/i", $user_agent)) {
			$browser = "Opera";
		}
		elseif (preg_match("/Chrome/i", $user_agent)) {
			$browser = "Google Chrome";
		}
		elseif (preg_match("/AppleWebKit/i", $user_agent)) {
			$browser = "AppleWebKit";
		}
		elseif (preg_match("/Safari/i", $user_agent)) {
			$browser = "Apple Safari";
		}
		elseif (preg_match("/Netscape/i", $user_agent)) {
			$browser = "Netscape";
		}
		else{
			$browser = "Desconhecido";
		}

		return [
			"ip" => $ip, 
			"browser" => $browser, 
			"platform" => $platform,
			"user_agent" => $user_agent 
		];
	}

	function add_working_days($date, $period) {
		$days = 0;
		$working_days = 0;

		while ($working_days < $period) {
			$days++;
			$weekdays = date("w", strtotime("+".$days." days", strtotime($date)));

			if ($weekdays != "0" && $weekdays != "6") {
				$working_days++;
			}
		}

		return date("Y-m-d", strtotime("+".$days." days", strtotime($date)));
	}

	function get_request_url($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$data = curl_exec($ch);
		curl_close($ch);
		
		return $data;
	}

	function password($password){
		return hash("sha256", SECRET_KEY."+".$password);
	}

	function create_htaccess($update = false){
		if (@filemtime(get_dir("/.htaccess")) < @filemtime(get_dir("/.env")) or $update == true) {
			@unlink(get_dir("/.htaccess"));

			$file = fopen(get_dir("/.htaccess"), "a+");

			$content = "RewriteEngine on

				Options -Indexes

				RewriteCond $1 !^(index.php|resources|robots.txt)
				RewriteCond %{REQUEST_FILENAME} !-f
				RewriteCond %{REQUEST_FILENAME} !-d
				RewriteRule ^(.*)$ index.php/$1 [L,QSA]

				RewriteRule (.*\.(env|ENV|secret_key|SECRET_KEY)|JCphp)$ ".ROOT_DIRECTORY."/__application__/views/errors_pages/403.html [L]

				ErrorDocument 400 ".ROOT_DIRECTORY."/__application__/views/errors_pages/400.html
				ErrorDocument 401 ".ROOT_DIRECTORY."/__application__/views/errors_pages/401.html
				ErrorDocument 403 ".ROOT_DIRECTORY."/__application__/views/errors_pages/403.html
				ErrorDocument 404 ".ROOT_DIRECTORY."/__application__/views/errors_pages/404.html
				ErrorDocument 408 ".ROOT_DIRECTORY."/__application__/views/errors_pages/408.html
				ErrorDocument 500 ".ROOT_DIRECTORY."/__application__/views/errors_pages/500.html
				ErrorDocument 503 ".ROOT_DIRECTORY."/__application__/views/errors_pages/503.html

				<Files .htaccess>
				    order allow,deny
				    deny from all
				</Files>";

			fwrite($file, str_replace("\t", "", $content));
			fclose($file);

			unset($file, $content);	
		}
	}

	function create_manifest_json($update = false){
		if (@filemtime(get_dir("/manifest.json")) < @filemtime(get_dir("/.env")) or $update == true) {
			@unlink(get_dir("/manifest.json"));

			$file = fopen(get_dir("/manifest.json"), "a+");

			$content = "{
			    \"name\": \"".PROJECT_NAME."\",
			    \"short_name\": \"".PROJECT_NAME."\",
			    \"theme_color\": \"#ffffff\",
			    \"background_color\": \"#ffffff\",
			    \"display\": \"standalone\",
			    \"start_url\": \"".get_url("/")."\",
			    \"icons\": [
			        {
			            \"src\": \"".get_url(PROJECT_ICON)."\",
			            \"sizes\": \"72x72\",
			            \"type\": \"image/".pathinfo(get_url(PROJECT_ICON))["extension"]."\"
			        }
			    ],
			    \"url\": \"".get_url("/")."\",
			    \"lang\": \"Portuguese\",
			    \"screenshots\": []
			}";

			fwrite($file, str_replace("\t", "", $content));
			fclose($file);

			unset($file, $content);	
		}
	}

	function create_secret_key($update = false){
		if (!file_exists(get_dir("/.secret_key")) or $update == true) {
			@unlink(get_dir("/.secret_key"));

			$file = fopen(get_dir("/.secret_key"), "a+");

			$content = "SECRET_KEY=".hash("sha256", time().rand(1, 99999));

			fwrite($file, $content);
			fclose($file);

			unset($file, $content);	
		}
	}

	function create_log($code, $message, $file = null, $line = null){
		$directory = prepare_directory("/__logs__/");

		$data_client = get_client_access();

		$datetime = date("Y-m-d H:i:s");

		$content = "IP: {$data_client['ip']} 
			BROWSER: {$data_client['browser']} 
			PLATFORM: {$data_client['platform']} 
			HTTP_USER_AGENT: {$data_client['user_agent']} 
			DATETIME: {$datetime} 
			--
			CODE: {$code} 
			MESSAGE: \"{$message}\"
			FILE: {$file}
			LINE: {$line}";

		file_put_contents(get_dir("/".$directory.time().".txt"), str_replace("\t", "", $content));

		unset($directory, $content, $data_client, $datetime);	
	}

	function create_token($algorithm = "sha256"){
		return hash($algorithm, SECRET_KEY.time());
	}

	function input_csrf_token(){
		echo '<input type="hidden" name="csrf_token" id="csrf-token" value="'.get_session("CSRF_TOKEN").'">';
	}

	function request_csrf_token(){
		switch ($_SERVER["REQUEST_METHOD"]) {
			case "GET":
				return $_GET["csrf_token"];
				break;
			case "POST":
				return $_POST["csrf_token"];
				break;
			case "PUT":
				return $_PUT["csrf_token"];
				break;
			case "DELETE":
				return $_DELETE["csrf_token"];
				break;
			default:
				return null;
				break;
		}
	}

	function get_csrf_token(){
		return get_session("CSRF_TOKEN");
	}

	function reset_csrf_token(){
		$token = create_token();

		set_session("CSRF_TOKEN", $token);

		return $token;
	}

	function send_email($to, $subject, $message){
		if (is_array($to)) {
			if (is_array($to["name"]) and is_array($to["email"])) {
				if (count($to["name"]) == count($to["email"])) {
					$emails = "";
					$tags = "";

					for ($i = 0; $i < count($to["name"]); $i++) {
						if (isset($to["email"][$i+1]) and !empty($to["email"][$i+1])) {
							$emails .= $to["email"][$i].", ";
							$tags .= $to["name"][$i]." <".$to["email"][$i].">, ";
						}
						else{
							$emails .= $to["email"][$i];
							$tags .= $to["name"][$i]." <".$to["email"][$i].">";
						}
					}
				}
				else{
					return false;
				}
			}
			else{
				$tags = ((!is_array($to["name"])) ? $to["name"] : $to["name"][0])." <".((!is_array($to["email"])) ? $to["email"] : $to["email"][0]).">";
				$emails = (!is_array($to["email"])) ? $to["email"] : $to["email"][0];
			}

			$headers  = "To: ".$tags."\r\n";
			$headers .= "From: ".EMAIL_USERNAME." <".EMAIL_ADDRESS.">"."\r\n";
			$headers .= "Reply-To: ".EMAIL_USERNAME." <".EMAIL_ADDRESS.">"."\r\n";
			$headers .= "Content-type: text/html; charset=UTF-8"."\r\n";
			$headers .= "Content-Language: pt-br"."\r\n";
			$headers .= "MIME-Version: 1.0"."\r\n";
			$headers .= "X-Mailer: PHP/".phpversion()."\r\n";

			return mail($emails, $subject, $message, $headers);
		}
		else{
			return false;
		}
	}

?>