<?php 
 include("errorreport.php");
 $uploaddir="upload/";
 if(isset($_POST['months']))
  {
   $months=$_POST['months']; 
   if($months=='') die('月份不可以空白');	  
  }
  else {
    die("請輸入月份");      
  } 
 if(isset($_POST['years']))
  {
   $years=$_POST['years'];
   if($years=='') die('年份不可以空白');
   if(@mkdir("./$uploaddir/$years", 0700))
      echo "成功建立資料夾"."<br>";
   else
	echo "建立資料夾失敗"."<br>";   
   $uploaddir.= $years."/";
  }
 else {
    die("請輸入年份");      
  }
 $_SESSION['keywords']="";
 if(isset($_POST['keywords']))
  {
    $_SESSION['keywords']=$_POST['keywords'];
  }
  $_SESSION['docutitle']="";
  if(isset($_POST['docutitle']))
  {
    $_SESSION['docutitle']=$_POST['docutitle'];
  } 
 $_SESSION['years']=$years;
 $_SESSION['months']=$months;	 
 $dateTime2 = new DateTime("now", new DateTimeZone('Asia/Taipei'));
 $day1=$dateTime2->format("d");
 $hours1=$dateTime2->format("h");
 $min1=$dateTime2->format("i");
 $sec1=$dateTime2->format("s"); 
 $file_Mname = $years.$months.$day1.$hours1.$min1.$sec1;
 $file_Sname = substr($_FILES['userfile']['name'],
         strrpos($_FILES['userfile']['name'] , ".")+1);
 $file_name = $file_Mname . "." . $file_Sname; 
 $_SESSION['upload1']=0; 
 $tmpfile=$_FILES["userfile"]["tmp_name"];
 $file_name=mb_convert_encoding($file_name ,"big5","UTF-8");
 $blacklist = array(".php",".js",".html", ".htm", ".inc");
 $allowed_filetypes = array('.pdf','.xlsx','.docx','.ppt','xls','.doc');
 if (isset($_FILES['userfile'])) 
  {
  if ($_FILES['userfile']['error'] != 0) 
   {
	errorreport($_FILES['userfile']['error']);
   } 
  else 
   {
	foreach ($blacklist as $item) 
	{
	if (preg_match("/$item$/i", $_FILES['userfile']['name'])) 
	 {
	  echo "不合法檔案類型!";
	  unset($_FILES['userfile']['tmp_name']);
	  exit; 
	 }
    }
	$name1=$_FILES['userfile']['name'];
	$ext = substr($name1, strpos($name1,'.'), strlen($name1)-1);
	if(!in_array($ext,$allowed_filetypes))
	 {
	  die('上傳的檔案沒有列在允許上傳清單內');
	 }
	if (is_uploaded_file($_FILES['userfile']['tmp_name'])) 
	 {    		 
	  if(move_uploaded_file($tmpfile,$uploaddir.$file_name )) 
	   {
        echo "上傳成功！";
        $_SESSION['upload1']=1;
	    $_SESSION['uploadfile']=$uploaddir.$file_name;
	   }
	  else
	   {
		echo "上傳失敗.";
		errorreport($_FILES['userfile']['error']);
		unset($_FILES['userfile']['tmp_name']);
	   }
	  }
	 else 
	  { errorreport($_FILES['userfile']['error']); }			
	}
  }
 else 
  { 	echo "請挑選一個檔案上傳";  }
  if( $_SESSION['upload1']==0)
  {      die("檔案上傳失敗就不再往下執行"); }
 ?>

