<?php
include_once "header.php";
include_once "language/{$xoopsConfig['language']}/import.php";

$op=(empty($_REQUEST['op']))?"":$_REQUEST['op'];
$csn=(isset($_REQUEST['csn']))?intval($_REQUEST['csn']) : 0;

switch($op){
	case "import_tad_gallery":
	$csn=import_tad_gallery();
	mk_rss_xml();
  mk_rss_xml($csn);
	header("location: index.php?csn=$csn");
	break;
	
	default:
  echo import_form();
	break;
}


//tad_gallery編輯表單
function import_form(){
	global $xoopsDB;

	$myts =& MyTextSanitizer::getInstance();
	$option=get_tad_gallery_cate_option(0,0,"","",1);
  $option=to_utf8($option);
	//找出要匯入的圖
	if (is_dir(_TADGAL_UP_IMPORT_DIR)) {
	  $pics=read_dir_pic(_TADGAL_UP_IMPORT_DIR);
	}

	//預設值設定

	//$op="replace_tad_gallery";
	$main="
	<p>"._MA_TADGAL_IMPORT_UPLOAD_TO."<span style='color:red;'>"._TADGAL_UP_IMPORT_DIR."</span></p>
  <form action='import.php' method='post' id='myForm' enctype='multipart/form-data'>
  <table id='form_tbl'>
	<tr><td colspan='5'>"._MA_TADGAL_IMPORT_CSN."<select name='csn' size=1>$option</select></td></tr>
	<tr><td colspan='5'>"._MA_TADGAL_IMPORT_NEW_CSN."<input type='text' name='new_csn' size='30'></td></tr>

  <tr>
	<th>"._MA_TADGAL_IMPORT_FILE."</th>
	<th>"._MA_TADGAL_IMPORT_DIR."</th>
	<th>"._MA_TADGAL_IMPORT_DIMENSION."</th>
	<th>"._MA_TADGAL_IMPORT_SIZE."</th>
	<th>"._MA_TADGAL_IMPORT_STATUS."</th>
	</tr>
	$pics
  <tr><td class='bar' colspan='5'>
  <input type='hidden' name='op' value='import_tad_gallery'>
  <input type='submit' value='"._MA_TADGAL_UP_IMPORT."'></td></tr>
  </table>
  </form>";

	//$main=div_3d(_TADGAL_PATCH_IMPORT_FORM,$main,"raised","",$info);

	return $main;
}

//讀取目錄下圖片
function read_dir_pic($main_dir=""){
  global $xoopsDB;
	$pics="";
	
	if(substr($main_dir,-1)!='/')$main_dir=$main_dir."/";
	
  if ($dh = opendir($main_dir)) {
	    $i=0;
      while (($file = readdir($dh)) !== false) {
        if(substr($file,0,1)==".")continue;

        if(is_dir($main_dir.$file)){
          $pics.=read_dir_pic($main_dir.$file);
        }else{
          //讀取exif資訊
          $result = exif_read_data($main_dir.$file,0,true);
          $creat_date=$result['IFD0']['DateTime'];
      		$dir=(empty($creat_date) or substr($creat_date,0,1)!="2")?date("Y_m_d"):str_replace(":","_",substr($result['IFD0']['DateTime'],0,10));

          $exif=mk_exif($result);


          $size=filesize($main_dir.$file);
          $size_txt=sizef($size);
          $pic=getimagesize($main_dir.$file);
  				$width=$pic[0];
  				$height=$pic[1];

  				$subname=strtolower(substr($file,-3));
  			  if($subname=="jpg" or $subname=="peg"){
  					$type="image/jpeg";
  				}elseif($subname=="png"){
  					$type="image/png";
  				}elseif($subname=="gif"){
  					$type="image/gif";
  				}else{
  					$type=$subname;
  		      continue;
  				}

  				$sql = "select width,height from ".$xoopsDB->prefix("tad_gallery")." where filename='{$file}' and size='{$size}'";
  				$result = $xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],3, mysql_error());
  				list($db_width,$db_height)=$xoopsDB->fetchRow($result);
  				if($db_width==$width and $db_height==$height){
            $checked="disabled='disabled'";
            $upload="0";
            $status=_MA_TADGAL_IMPORT_EXIST;
  				}else{
            $checked="checked='checked'";
            $upload="1";
            $status=$type;
  				}

          if(_CHARSET=="UTF-8")$file=to_utf8($file);
          $pics.="
  				<td class='col'>
  				<input type='hidden' name='all[$i]' value='".$main_dir.$file."'>
  				<input type='checkbox' name='import[$i][upload]' value='1' $checked>{$file}
  				<input type='hidden' name='import[$i][filename]' value='{$file}'></td>
  				<td class='col' style='text-align:center'>$dir<input type='hidden' name='import[$i][dir]' value='{$dir}'></td>
  				<td class='col' style='text-align:center'>$width x $height
  				<input type='hidden' name='import[$i][post_date]' value='{$creat_date}'>
  				<input type='hidden' name='import[$i][width]' value='{$width}'>
  				<input type='hidden' name='import[$i][height]' value='{$height}'></td>
  				<td class='col' style='text-align:right'>$size_txt<input type='hidden' name='import[$i][size]' value='{$size}'></td>
  				<td class='col' style='text-align:right'>{$status}
  				<input type='hidden' name='import[$i][exif]' value='{$exif}'>
  				<input type='hidden' name='import[$i][type]' value='{$type}'></td>
  				</tr>";
  				$i++;
				}
      }
      closedir($dh);
	  }
	  return $pics;
}



//新增資料到tad_gallery中
function import_tad_gallery(){
	global $xoopsDB,$xoopsUser,$xoopsModuleConfig,$type_to_mime;

	if(!empty($_POST['new_csn'])){
    $csn=add_tad_gallery_cate($_POST['csn'],$_POST['new_csn']);
	}else{
		$csn=$_POST['csn'];
	}

	$uid=$xoopsUser->getVar('uid');

	if(!empty($_POST['csn']))$_SESSION['tad_gallery_csn']=$_POST['csn'];


		//處理上傳的檔案
	foreach($_POST['all'] as $i => $source_file){
		if($_POST['import'][$i]['upload']!='1'){
			unlink($source_file);
			continue;
		}
		$orginal_file_name= strtolower(basename($_POST['import'][$i]['filename'])); //get lowercase filename
    $file_ending= substr(strtolower($orginal_file_name), -3); //file extension


   	$sql = "insert into ".$xoopsDB->prefix("tad_gallery")." (`csn`,`filename`,`size`,`type`,`width`,`height`,`dir`,`uid`,`post_date`,`counter`,`exif`) values('{$csn}','{$_POST['import'][$i]['filename']}','{$_POST['import'][$i]['size']}','{$_POST['import'][$i]['type']}','{$_POST['import'][$i]['width']}','{$_POST['import'][$i]['height']}','{$_POST['import'][$i]['dir']}','{$uid}','{$_POST['import'][$i]['post_date']}','0','{$_POST['import'][$i]['exif']}')";
		$xoopsDB->query($sql) or redirect_header($_SERVER['PHP_SELF'],10, mysql_error().$sql);
		//取得最後新增資料的流水編號
		$sn=$xoopsDB->getInsertId();

		set_time_limit(0);

		mk_dir(_TADGAL_UP_FILE_DIR.$_POST['import'][$i]['dir']);
		mk_dir(_TADGAL_UP_FILE_DIR."small/".$_POST['import'][$i]['dir']);
		mk_dir(_TADGAL_UP_FILE_DIR."medium/".$_POST['import'][$i]['dir']);

		$filename=photo_name($sn,"source",1);
		if(rename($source_file,$filename)){

			$m_thumb_name=photo_name($sn,"m",1);
			$s_thumb_name=photo_name($sn,"s",1);
			$fb_thumb_name=photo_name($sn,"fb",1);

			if(!empty($xoopsModuleConfig['thumbnail_b_width']) and ($_POST['import'][$i]['width'] > $xoopsModuleConfig['thumbnail_b_width'] or $_POST['import'][$i]['height'] > $xoopsModuleConfig['thumbnail_b_width'])){
				thumbnail($filename,$filename,$type_to_mime[$file_ending],$xoopsModuleConfig['thumbnail_b_width']);
			}

			if($_POST['import'][$i]['width'] > $xoopsModuleConfig['thumbnail_m_width'] or $_POST['import'][$i]['height'] > $xoopsModuleConfig['thumbnail_m_width']){
				thumbnail($filename,$m_thumb_name,$type_to_mime[$file_ending],$xoopsModuleConfig['thumbnail_m_width']);
			}
			
			if($_POST['import'][$i]['width'] > $xoopsModuleConfig['thumbnail_s_width'] or $_POST['import'][$i]['height'] > $xoopsModuleConfig['thumbnail_s_width']){
				thumbnail($filename,$s_thumb_name,$type_to_mime[$file_ending],$xoopsModuleConfig['thumbnail_s_width']);
			}
      //給fb
      thumbnail($filename,$fb_thumb_name,$type_to_mime[$file_ending],100);
		}else{
		  $sql = "delete from ".$xoopsDB->prefix("tad_gallery")." where sn='$sn'";
			$xoopsDB->query($sql);
			redirect_header($_SERVER['PHP_SELF'], 5, sprintf(_MA_TADGAL_IMPORT_IMPORT_ERROR,$filename));
		}
	}
  rrmdir(_TADGAL_UP_IMPORT_DIR);
	return $csn;
}

?>
