<?php
$accepted_origins = array("http://localhost", "https://localhost", "https://brrsolucoesdigitais.com");
$imageFolder 			= '../uploads/upload_tinymce/';

reset($_FILES);

$temp = current($_FILES);

if(is_uploaded_file($temp['tmp_name'])) {
	if(isset($_SERVER['HTTP_ORIGIN'])) {
		if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
			header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
		}else{
			header("Erro 403: Origem não permitida.");
			return;
		}
	}

	if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])){
		header("Erro 400: Nome de arquivo não parmitido.");
		return;
	}

	if(!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))){
		header("Erro 400: Extensão de arquivo não permitida..");
		return;
	}

	$protocol 		= isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
	$actual_link 	= $protocol."{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
	
	$newName 			= md5(date('Y-m-d H:i:s'));
	$mod 					= explode('painel-cms', $_POST['mudulo']);
	$mod 					= explode('/', $mod[1]);
	
	$path_parts 	= pathinfo($temp['name']);
	$ext 					= $path_parts['extension'];
	
	$temp['name'] = $mod[1].'_'.$newName.'.'.$ext;
	$filetowrite = $imageFolder . $temp['name'];

	$return = move_uploaded_file($temp['tmp_name'], $filetowrite);

	if($return == 1) {
		$BASE_URL 	= $protocol."{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
		$BASE_URL 	= str_replace('php/upload_tinymce.php', '', $BASE_URL);
		$BASE_URL 	= $BASE_URL.'uploads/upload_tinymce/'.$temp['name'];

		echo json_encode(array('location' => $BASE_URL));
	} else {
		header("Erro 501: Ops... Tente novamente.");
	}
} else {
	header("Erro 500: Ops... Tente novamente.");
}
?>