<?php

class File{
	
	//Gère l'upload d'un fichier des vérifications au stockage dans le dossier file
	public static function upload($index,$path,$maxSize = 1048576,$extensions = array('jpg','png','jpeg','gif','bmp') ){
		if(!isset($_FILES[$index])) throw new Exception("L'index fichier '".$index."' n'existe pas");
		if($_FILES[$index]['error'] != 0) throw new Exception("Erreur lors de l'envois du fichier : N° ".$_FILES[$index]['error']);
		$extension = getExt($_FILES[$index]['name']);
		if($_FILES[$index]['size'] > $maxSize) throw new Exception("Taille du fichier trop grande, taille maximum :".readable_size($maxSize).' ('.$maxSize.' octets)');
		if(!in_array($extension , $extensions)) throw new Exception("Extension '".$extension."' du fichier non permise, autorisé :".implode(', ',$extensions));
		$filePath = str_replace(array('/','\\','{{ext}}'),array(SLASH,SLASH,$extension),$path);
		$fileName = basename($filePath);
		$folderPath = dirname($filePath);
		$folderAbsolutePath = self::dir().$folderPath;
		$fileAbsolutePath = $folderAbsolutePath.SLASH.$fileName;


		if(!file_exists($folderAbsolutePath)) mkdir($folderAbsolutePath,0755,true);

		if(!move_uploaded_file($_FILES[$index]['tmp_name'], $fileAbsolutePath)) throw new Exception("Impossible de déplacer le fichier envoyé");
		
		return array(
			'absolute' => $fileAbsolutePath,
			'relative' => $filePath,
			'name' => $fileName
		);
	}

	public static function move($file,$path){
		
		$extension = getExt($path);
		$filePath = str_replace(array('/','\\','{{ext}}'),array(SLASH,SLASH,$extension),$path);
		$fileName = basename($filePath);
		$folderPath = dirname($filePath);
		$folderAbsolutePath = self::dir().$folderPath;
		$fileAbsolutePath = $folderAbsolutePath.SLASH.$fileName;


		if(!file_exists($folderAbsolutePath)) mkdir($folderAbsolutePath,0755,true);

		if(!rename($file, $fileAbsolutePath)) throw new Exception("Impossible de déplacer le fichier envoyé");
		
		//New version
		//Testée, pour le moment pas de pb survenus
		return array(
			'absolute' => (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($fileAbsolutePath)) : $fileAbsolutePath),
			'relative' => (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($filePath)) : $filePath),
			'name' => (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($fileName)) : $fileName)
		);

		//Old version
		// return array(
		// 	'absolute' => $fileAbsolutePath,
		// 	'relative' => $filePath,
		// 	'name' => $fileName
		// );
	}


	public static function delete($namespace,$file){

		$file =  $namespace.SLASH.substr($file, strlen($namespace)+1);
		$file =  File::dir().$file;
		$file =  str_replace(array('\\','/'),array(SLASH,SLASH),$file);
		if(!file_exists($file)) throw new Exception("Le fichier '".$file."' n'existe pas");
		
		unlink($file);
	}

	public static function downloadFile($path,$name=null,$mime = null,$forceDownload = null){

		if(!file_exists($path)) throw new Exception("Fichier inexistant :".$path);
		$stream = file_get_contents($path);
		if(!isset($mime)){
			$mime = mime_content_type($path);
		}
		if(!isset($name)){
			$name = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') ? utf8_encode(basename($path)) : basename($path);
		}
	
		ob_end_clean();
		header("Content-Type: ".$mime);
		header("Content-Length: " . strlen($stream));
		header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header('Cache-Control: post-check=0, pre-check=0', FALSE);
		header('Pragma: no-cache');
		header("Content-Disposition: ".($forceDownload?"attachment":"inline")."; filename=\"".utf8_decode($name)."\"");
		echo $stream; 
	}

	public static function downloadStream($stream, $name='Sans titre', $mime='application/octet-stream'){

		ob_end_clean();
		header("Content-Type: ".$mime);
		header("Content-Length: " . strlen($stream));
		header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
		header('Cache-Control: no-store, no-cache, must-revalidate');
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header('Cache-Control: post-check=0, pre-check=0', FALSE);
		header('Pragma: no-cache');
		header("Content-Disposition: attachment; filename=\"".$name."\"");
		echo $stream; 
		
	}


	public static function dir(){
		return __ROOT__.FILE_PATH;
	}
	public static function temp(){
		$path = self::dir().SLASH.'tmp'.SLASH;
		if(!file_exists($path)) mkdir($path,0755,true);
		return $path;
	}
	
	public static function clear_temp(){
		$time = time();
		foreach(glob(self::temp().'*.*') as $file){

			if($time - filemtime($file)  > 3600) unlink($file);
		}
	}

	public static function copy($source,$destination){
		if(is_file($source)) return copy($source,$destination);
		$dir = opendir($source); 
	    mkdir($destination,0755,true); 
	    while(false !== ($file = readdir($dir))) { 
	        if (($file != '.') && ($file != '..')) { 
	            if (is_dir($source . SLASH . $file)) { 
	                self::copy($source.SLASH.$file,$destination.SLASH.$file); 
	            } else { 
	                copy($source.SLASH.$file,$destination.SLASH.$file); 
	            } 
	        } 
	    } 
	    closedir($dir); 
	}

}

?>