<?php
if(isset($_POST['upload'])){
    //Список разрешенных файлов
    $whitelist = array(".mif");         
	$data = array();
	$error = true;
	
	//Проверяем разрешение файла
    foreach  ($whitelist as  $item) {
		if(preg_match("/$item\$/i",$_FILES['userfile']['name'])) $error = false;
    }

    //если нет ошибок, грузим файл
    if(!$error) { 
    	   	  
		$folder =  '../upload/';//директория в которую будет загружен файл
		
		$uploadedFile =  $folder.basename($_FILES['userfile']['name']);
				
		if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
		
			if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadedFile)){
		
		        $data = $_FILES['userfile'];
			}
			else {	
				$data['errors'] = "Во время загрузки файла произошла ошибка";
			}
		}
		else {	
			$data['errors'] = "Файл не  загружен";
		}
    }
    else{
    	
		$data['errors'] = 'Вы загружаете запрещенный тип файла';
    }
    
	$f = fopen('../upload/'.$data['name'], 'r');
	while(!feof($f)){
		$mytext = fgets($f, 999);
		if(strpos($mytext, "Region")!== false){
			$cont = substr($mytext, (strlen($mytext) - 4), 3);
			for($i = 1; $i <= $cont; $i++){
				$mytext = fgets($f, 999);
				$points = $mytext;
				trim($points);
				for($j = 1; $j <= $points; $j++){
					$mytext = fgets($f, 999);
					$p = explode(' ', $mytext);
					$p[1] = substr($p[1], 0, (strlen($p[1]) - 2));
					if(strlen($p[0]) - strripos($p[0], '.') == 2)
						$p[0] .= "0";
					if(strlen($p[0]) - strripos($p[0], '.') == 1)
						$p[0] .= "00";
					if(strripos($p[0], '.') == false)
						$p[0] .= ".00";
					if(strlen($p[1]) - strripos($p[1], '.') == 2)
						$p[1] .= "0";
					if(strlen($p[1]) - strripos($p[1], '.') == 1)
						$p[1] .= "00";
					if(strripos($p[1], '.') == false)
						$p[1] .= ".00";
					$x1 = $p[0];
					$y1 = $p[1];
					$X[$j] = $x1;
					$Y[$j] = $y1;
				}
			}
		}
	}
	$out = "";
	for($i = 1; $i <= $j; $i++){
		$out .= $X[$i].";".$Y[$i]."\n";
	}
	$fout = fopen("../upload/".$data['name'].".csv", "w");
	fwrite($fout, $out);
	fclose($fout);
	
	$file = "../upload/".$data['name'].".csv";
	$size = filesize($file);
	header("Content-type: application/zip");
	header("Content-Length: ".$size);
	header("Content-Disposition: attachment; filename=".$data['name'].".csv");
	readfile($file);
}
?>