<?php 

	define("ALL_FILES", 0);
	define("IMAGE_FILES", 1000);
	define("DOCUMENT_FILES", 2000);
	define("COMPRESSED_FILES", 3000);
	define("AUDIO_FILES", 4000);
	define("VIDEO_FILES", 5000);

	class File{
		private static function prepareDirectory($dir, $option = true){
			if (preg_match("/^[\/]/", $dir) == 1) {
				$dir = preg_replace("/^[\/]/", "", $dir);
			}

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

			$aux = explode("/", $dir);

			foreach ($aux as $value) {
				if ($value == "__application__" or $value == "__libraries__" or $value == "__settings__" or $value == "__models__" or $value == "__views__" or $value == "__controllers__" or $value == "__error__" or $value == "__templates__" or $value == "__internal__" or $value == "__classes__" or $value == "__functions__") {
					return false;
				}
			}

			if ($option == true) {
				$ano = date("Y");
				$mes = date("m");
				$dia = date("d");

				if (is_dir($dir.$ano."/")) {
					if (is_dir($dir.$ano."/".$mes."/")) {
						if (!is_dir($dir.$ano."/".$mes."/".$dia."/")) {
							mkdir($dir.$ano."/".$mes."/".$dia."/", 0777, true);
						}	
					}
					else{
						mkdir($dir.$ano."/".$mes."/".$dia."/", 0777, true);
					}
				}
				else{
					mkdir($dir.$ano."/".$mes."/".$dia."/", 0777, true);
				}

				return $dir.$ano."/".$mes."/".$dia."/";
			}
			else{
				if (!is_dir($dir)) {
					mkdir($dir, 0777, true);
				}

				return $dir;
			}
		}

		private static function filterFile($ext, $filter){
			switch ($filter) {
				case ALL_FILES:
					if ($ext != "php" and $ext != "html" and $ext != "css" and $ext != "js") {
						return true;
					}
					else{
						return false;
					}					
				case IMAGE_FILES:
					if ($ext == "png" or $ext == "jpeg" or $ext == "jpg" or $ext == "gif") {
						return true;
					}
					else{
						return false;
					}
				case DOCUMENT_FILES:
					if ($ext == "txt" or $ext == "pdf" or $ext == "doc" or $ext == "docx" or $ext == "xls" or $ext == "xlsx" or $ext == "ppt" or $ext == "pptx") {
						return true;
					}
					else{
						return false;
					}
				case COMPRESSED_FILES:
					if ($ext == "zip" or $ext == "rar" or $ext == "7z") {
						return true;
					}
					else{
						return false;
					}
				case AUDIO_FILES:
					if ($ext == "mp3" or $ext == "wma" or $ext == "ogg" or $ext == "aac") {
						return true;
					}
					else{
						return false;
					}
				case VIDEO_FILES:
					if ($ext == "mp4" or $ext == "mov" or $ext == "avi" or $ext == "wmv" or $ext == "flv") {
						return true;
					}
					else{
						return false;
					}
				default:
					throw new Exception("ERROR: This type of file filter does not exist.", 500);
			}
		}

		public static function upload($files, $dir, $filter=ALL_FILES, $subfolder=true, $file_name=null, $reduce=true){
			$response = [];
			$directory = self::prepareDirectory($dir, $subfolder);
			if ($directory != false) {
				if (gettype($files["error"]) == "array") {
					foreach ($files["error"] as $key => $error) {
						if ($error == UPLOAD_ERR_OK) {
							if ($filter != IMAGE_FILES or $reduce != true) {
								if ($file_name == null or empty($file_name)) {
									$nome = $files["name"][$key];
									$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
									$novo_nome = sha1($nome.strtotime(date("Y-m-d H:i:s")).rand(1000, 9999)).".".$ext;
								}
								else{
									$nome = $files["name"][$key];
									$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
									$novo_nome = $file_name.".".$ext;
								}

								$arquivo = $files["tmp_name"][$key];

								if (self::filterFile($ext, $filter)) {
									if (move_uploaded_file($arquivo, $directory.$novo_nome)) {
										$response[] = "/".$directory.$novo_nome;
									}
								}
							}
							else{
								if ($file_name == null or empty($file_name)) {
									$nome = $files["name"][$key];
									$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
									$novo_nome = sha1($nome.strtotime(date("Y-m-d H:i:s")).rand(1000, 9999)).".".$ext;
								}
								else{
									$nome = $files["name"][$key];
									$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
									$novo_nome = $file_name.".".$ext;
								}

								if (self::filterFile($ext, $filter)) {	
									if ($files["type"][$key] == "image/jpeg") {
										$imagem = imagecreatefromjpeg($files["tmp_name"][$key]);
									}
									elseif ($files["type"][$key] == "image/gif") {
										$imagem = imagecreatefromgif($files["tmp_name"][$key]);
									}
									elseif ($files["type"][$key] == "image/png") {
										$imagem = imagecreatefrompng($files["tmp_name"][$key]);
									}

									$x = imagesx($imagem);
									$y = imagesy($imagem);

									if ($files["size"][$key] >= 5242880) { 
										$autura = ceil($y / 3);
										$largura = ceil($x / 3);
									}
									elseif ($files["size"][$key] >= 1048576) {
										$autura = ceil($y / 2);
										$largura = ceil($x / 2);
									}
									else{
										$autura = $y;
										$largura = $x;
									}
									
									$nova_imagem = imagecreatetruecolor($largura, $autura);

									if ($files["type"][$key] == "image/png" or $files["type"][$key] == "image/gif") {
										imagealphablending($nova_imagem, false);
										imagesavealpha($nova_imagem, true);
										$transparencia = imagecolorallocatealpha($nova_imagem, 255, 255, 255, 127);
										imagefilledrectangle($nova_imagem, 0, 0, $largura, $autura, $transparencia);
									}

									imagecopyresampled($nova_imagem, $imagem, 0, 0, 0, 0, $largura, $autura, $x, $y);
									
									if ($files["type"][$key] == "image/jpeg") {
										imagejpeg($nova_imagem, $directory.$novo_nome);
									}
									elseif ($files["type"][$key] == "image/gif") {
										imagegif($nova_imagem, $directory.$novo_nome);
									}
									elseif ($files["type"][$key] == "image/png") {
										imagepng($nova_imagem, $directory.$novo_nome);
									}

									$response[] = "/".$directory.$novo_nome;
								
									imagedestroy($imagem);
									imagedestroy($nova_imagem);
								}
							}
						}
					}
				}
				else{
					if ($files["error"] == UPLOAD_ERR_OK) {
						if ($filter != IMAGE_FILES or $reduce != true) {
							if ($file_name == null or empty($file_name)) {
								$nome = $files["name"];
								$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
								$novo_nome = sha1($nome.strtotime(date("Y-m-d H:i:s")).rand(1000, 9999)).".".$ext;
							}
							else{
								$nome = $files["name"];
								$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
								$novo_nome = $file_name.".".$ext;
							}
							
							$arquivo = $files["tmp_name"];

							if (self::filterFile($ext, $filter)) {
								if (move_uploaded_file($arquivo, $directory.$novo_nome)) {
									$response[] = "/".$directory.$novo_nome;
								}
							}
						}
						else{
							if ($file_name == null or empty($file_name)) {
								$nome = $files["name"];
								$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
								$novo_nome = sha1($nome.strtotime(date("Y-m-d H:i:s")).rand(1000, 9999)).".".$ext;
							}
							else{
								$nome = $files["name"];
								$ext = strtolower(pathinfo($nome, PATHINFO_EXTENSION));
								$novo_nome = $file_name.".".$ext;
							}

							if (self::filterFile($ext, $filter)) {	
								if ($files["type"] == "image/jpeg") {
									$imagem = imagecreatefromjpeg($files["tmp_name"]);
								}
								elseif ($files["type"] == "image/gif") {
									$imagem = imagecreatefromgif($files["tmp_name"]);
								}
								elseif ($files["type"] == "image/png") {
									$imagem = imagecreatefrompng($files["tmp_name"]);
								}

								$x = imagesx($imagem);
								$y = imagesy($imagem);

								if ($files["size"] >= 5242880) { 
									$autura = ceil($y / 3);
									$largura = ceil($x / 3);
								}
								elseif ($files["size"] >= 1048576) {
									$autura = ceil($y / 2);
									$largura = ceil($x / 2);
								}
								else{
									$autura = $y;
									$largura = $x;
								}
								
								$nova_imagem = imagecreatetruecolor($largura, $autura);

								if ($files["type"] == "image/png" or $files["type"] == "image/gif") {
									imagealphablending($nova_imagem, false);
									imagesavealpha($nova_imagem, true);
									$transparencia = imagecolorallocatealpha($nova_imagem, 255, 255, 255, 127);
									imagefilledrectangle($nova_imagem, 0, 0, $largura, $autura, $transparencia);
								}

								imagecopyresampled($nova_imagem, $imagem, 0, 0, 0, 0, $largura, $autura, $x, $y);
								
								if ($files["type"] == "image/jpeg") {
									$result = imagejpeg($nova_imagem, $directory.$novo_nome);
								}
								elseif ($files["type"] == "image/gif") {
									$result = imagegif($nova_imagem, $directory.$novo_nome);
								}
								elseif ($files["type"] == "image/png") {
									$result = imagepng($nova_imagem, $directory.$novo_nome);
								}

								$response[] = "/".$directory.$novo_nome;
								
								imagedestroy($imagem);
								imagedestroy($nova_imagem);
							}
						}
					}
				}
				return $response;
			}
			else{
				throw new Exception("ERROR: Invalid directory, it is not possible to use reserved directories.", 500);	
			}
		}

		public static function delete($dir_file, $report_error=false){
			if (file_exists($_SERVER["DOCUMENT_ROOT"].show_link($dir_file))) {
				$aux = explode("/", $dir_file);

				foreach ($aux as $value) {
					if ($value == "__application__" or $value == "__libraries__" or $value == "__settings__" or $value == "__models__" or $value == "__views__" or $value == "__controllers__" or $value == "__error__" or $value == "__templates__" or $value == "__internal__" or $value == "__classes__" or $value == "__functions__" or $value == ".htaccess" or preg_match("/.?\.php$/", $value) == 1 or preg_match("/.?\.html$/", $value) == 1 or preg_match("/.?\.js$/", $value) == 1 or preg_match("/.?\.css$/", $value) == 1) {
						if ($report_error) {
							throw new Exception("ERROR: Invalid directory, it is not possible to delete files from the reserved directories.", 500);
						}
						else{
							return false;
						}
					}
				}

				unlink($_SERVER["DOCUMENT_ROOT"].show_link($dir_file));
				return true;
			}
			else{
				if ($report_error) {
					throw new Exception("ERROR: This file does not exist.", 500);
				}
				else{
					return false;
				}
			}
		}
	}

?>