<?php
//  ------------------------------------------------------------------------ //
// 本模組由 tad 製作
// 製作日期：2008-03-23
// $Id: uploads.php,v 1.7 2008/05/10 11:46:50 tad Exp $
// ------------------------------------------------------------------------- //

/*-----------引入檔案區--------------*/
include "header.php";
$xoopsOption['template_main'] = "tg_index_tpl.html";

if(sizeof($upload_powers) <= 0 or empty($xoopsUser)){
	redirect_header(XOOPS_URL."/user.php",3, _TADGAL_NO_UPLOAD_POWER);
}
include XOOPS_ROOT_PATH."/header.php";
/*-----------function區--------------*/

function uploads_tabs(){
  global $xoopsTpl;

  $jquery_path=get_jquery(true);
  $now=time();

  $jquery_ui="
  $jquery_path
  <script>
  $(document).ready(function() {
    $('#jquery-tabs{$now}').tabs();
  });
  </script>";
	$xoopsTpl->assign( "xoops_module_header" , $jquery_ui);
  
  $main="
  <div id='jquery-tabs{$now}'>
  
    <ul>
        <li><a href='#fragment-1'><span>"._MA_INPUT_FORM."</span></a></li>
        <li><a href='#fragment-2'><span>"._MA_TADGAL_MUTI_INPUT_FORM."</span></a></li>
        <li><a href='#fragment-3'><span>"._TADGAL_PATCH_IMPORT_FORM."</span></a></li>
        <li><a href='#fragment-4'><span>"._MD_TADGAL_XP_UPLOAD."</span></a></li>
    </ul>
    <div id='fragment-1'>
        ".tad_gallery_form($sn)."
    </div>
    <div id='fragment-2'>
        ".tad_gallery_muti_form($sn)."
    </div>
    <div id='fragment-3'>
        ".import_form()."
    </div>
    <div id='fragment-4'>
    "._MD_TADGAL_XPPW_PAGE."
    </div>

  </div>
  ";
  return $main;
}


//tad_gallery編輯表單
function tad_gallery_form($sn=""){
	global $xoopsDB;

	//抓取預設值
	if(!empty($sn)){
		$DBV=get_tad_gallery($sn);
	}else{
		$DBV=array();
	}

	//預設值設定

	$sn=(!isset($DBV['sn']))?"":$DBV['sn'];
	$csn=(!isset($DBV['csn']))?$_SESSION['tad_gallery_csn']:$DBV['csn'];
	$title=(!isset($DBV['title']))?"":$DBV['title'];
	$description=(!isset($DBV['description']))?"":$DBV['description'];
	$filename=(!isset($DBV['filename']))?"":$DBV['filename'];
	$size=(!isset($DBV['size']))?"":$DBV['size'];
	$type=(!isset($DBV['type']))?"":$DBV['type'];
	$width=(!isset($DBV['width']))?"":$DBV['width'];
	$height=(!isset($DBV['height']))?"":$DBV['height'];
	$dir=(!isset($DBV['dir']))?"":$DBV['dir'];
	$uid=(!isset($DBV['uid']))?"":$DBV['uid'];
	$post_date=(!isset($DBV['post_date']))?"":$DBV['post_date'];
	$counter=(!isset($DBV['counter']))?"":$DBV['counter'];
	$tag=(!isset($DBV['tag']))?"":$DBV['tag'];

	$op=(empty($sn))?"insert_tad_gallery":"update_tad_gallery";
	
	
	$option=get_tad_gallery_cate_option(0,0,$csn,0,1);
	
	$tag_select=tag_select($tag);
	
	//$op="replace_tad_gallery";
	$main="
  <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm' enctype='multipart/form-data'>
  <table class='form_tbl' style='width:auto;'>

	<input type='hidden' name='sn' value='{$sn}'>
	<tr><td class='title' nowrap>"._MA_TADGAL_CSN."</td>
	<td class='col'><select name='csn' size=1>
		$option
	</select></td>
	<td class='title' nowrap>"._MA_TADGAL_NEW_CSN."</td>
	<td class='col'><input type='text' name='new_csn' size='10'></td></tr>
	<tr><td class='title' nowrap>"._MA_TADGAL_PHOTO."</td>
	<td class='col' colspan=3><input type='file' name='image' size='35'></td></tr>
	<tr><td class='title' nowrap>"._MA_TADGAL_TITLE."</td>
	<td class='col' colspan=3><input type='text' name='title' size='40' value='{$title}' style='width: 350px;'></td></tr>
	<tr><td class='title' nowrap>"._MA_TADGAL_DESCRIPTION."</td>
	<td class='col' colspan=3><textarea style='width: 350px; height: 44px; min-height: 44px;font-size:12px;' name='description'></textarea></td></tr>
	<tr><td class='title' nowrap rowspan=2>"._MD_TADGAL_TAG."</td>
		<td class='col' colspan=3><input type='text' name='new_tag' size='20'>"._MD_TADGAL_TAG_TXT."</td></tr>
		<tr>
		<td class='col' colspan=3>$tag_select</td></tr>
  <tr><td class='bar' colspan='4'>
  <input type='hidden' name='op' value='{$op}'>
  <input type='submit' value='"._MA_SAVE."'></td></tr>
  </table>
  </form>";

	//$main=div_3d(_MA_INPUT_FORM,$main);

	return $main;
}


//新增資料到tad_gallery中
function insert_tad_gallery(){
	global $xoopsDB,$xoopsUser,$xoopsModuleConfig;
	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'];
	
	
	//處理上傳的檔案
	if(!empty($_FILES['image']['name'])){

		//$myts =& MyTextSanitizer::getInstance();
		
		$pic=getimagesize($_FILES['image']['tmp_name']);
		$width=$pic[0];
		$height=$pic[1];
		

    //讀取exif資訊
    $result = exif_read_data($_FILES['image']['tmp_name'],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=(empty($result) or empty($result['IFD0']))?"":implodeArray2D("||",$result);
		

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

		mk_dir(_TADGAL_UP_FILE_DIR.$dir);
		mk_dir(_TADGAL_UP_FILE_DIR."small/".$dir);
		mk_dir(_TADGAL_UP_FILE_DIR."medium/".$dir);
		
		$filename=photo_name($sn,"source",1);
		
		if(move_uploaded_file($_FILES['image']['tmp_name'],$filename)){
      
			$m_thumb_name=photo_name($sn,"m",1);
			$s_thumb_name=photo_name($sn,"s",1);

			if($width > $xoopsModuleConfig['thumbnail_m_width'] or $height > $xoopsModuleConfig['thumbnail_m_width'])	thumbnail($filename,$m_thumb_name,$_FILES['image']['type'],$xoopsModuleConfig['thumbnail_m_width']);
			if($width > $xoopsModuleConfig['thumbnail_s_width'] or $height > $xoopsModuleConfig['thumbnail_s_width'])	thumbnail($filename,$s_thumb_name,$_FILES['image']['type'],$xoopsModuleConfig['thumbnail_s_width']);


		}else{
			redirect_header($_SERVER['PHP_SELF'], 5,sprintf(_TADGAL_IMPORT_UPLOADS_ERROR,$filename));
		}
	}

	return $sn;
}



//多檔上傳
function tad_gallery_muti_form($sn){
	global $xoopsDB,$xoopsModule;

	$csn=$_SESSION['tad_gallery_csn'];
	$option=get_tad_gallery_cate_option(0,0,$csn,0,1);

  $main="
  <script src='".XOOPS_URL."/Frameworks/tadtools/multiple-file-upload/jquery.MultiFile.js'></script>
  <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm' enctype='multipart/form-data'>
  <table class='form_tbl' style='width:auto;'>

	<input type='hidden' name='sn' value='{$sn}'>
	<tr><td class='title' nowrap>"._MA_TADGAL_CSN."</td>
	<td class='col'><select name='csn' size=1>
		$option
	</select></td>
	<td class='title' nowrap>"._MA_TADGAL_NEW_CSN."</td>
	<td class='col'><input type='text' name='new_csn' size='10'></td></tr>
	<tr><td class='title' nowrap>"._MA_TADGAL_PHOTO."</td>
	<td class='col' colspan=3>
  <input type='file' name='upfile[]' class='multi'>
  </td></tr>
	
  <tr><td class='bar' colspan='4'>
  <input type='hidden' name='op' value='upload_muti_file'>
  <input type='submit' value='"._MA_SAVE."'></td></tr>
  </table>
  </form>";

	//$main=div_3d(_MA_INPUT_FORM,$main);

	return $main;
}


//上傳圖檔
function upload_muti_file(){
	global $xoopsDB,$xoopsUser,$xoopsModule,$xoopsModuleConfig;

	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'];



	//取消上傳時間限制
  set_time_limit(0);
  
  //設置上傳大小
  ini_set('memory_limit', '80M');

  $files = array();
  foreach ($_FILES['upfile'] as $k => $l) {

    foreach ($l as $i => $v) {
      if(empty($v))continue;
      if (!array_key_exists($i, $files)){
        $files[$i] = array();
			}
      $files[$i][$k] = $v;
    }
  }

  foreach ($files as $i=>$file) {

		$pic=getimagesize($file['tmp_name']);
		$width=$pic[0];
		$height=$pic[1];

    //讀取exif資訊
    $result = exif_read_data($file['tmp_name'],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=(empty($result) or empty($result['IFD0']))?"":implodeArray2D("||",$result);

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

		mk_dir(_TADGAL_UP_FILE_DIR.$dir);
		mk_dir(_TADGAL_UP_FILE_DIR."small/".$dir);
		mk_dir(_TADGAL_UP_FILE_DIR."medium/".$dir);

		$filename=photo_name($sn,"source",1);

		if(move_uploaded_file($file['tmp_name'],$filename)){

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

			if($width > $xoopsModuleConfig['thumbnail_m_width'] or $height > $xoopsModuleConfig['thumbnail_m_width'])	thumbnail($filename,$m_thumb_name,$file['type'],$xoopsModuleConfig['thumbnail_m_width']);
			if($width > $xoopsModuleConfig['thumbnail_s_width'] or $height > $xoopsModuleConfig['thumbnail_s_width'])	thumbnail($filename,$s_thumb_name,$file['type'],$xoopsModuleConfig['thumbnail_s_width']);


    }
  }
  return $csn;
}



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

	$myts =& MyTextSanitizer::getInstance();
	$option=get_tad_gallery_cate_option(0,0,"","",1);

	//找出要匯入的圖
	$pics="";
	if (is_dir(_TADGAL_UP_IMPORT_DIR)) {
	  if ($dh = opendir(_TADGAL_UP_IMPORT_DIR)) {
	    $i=0;
      while (($file = readdir($dh)) !== false) {
        if(substr($file,0,1)==".")continue;


        //讀取exif資訊
        $result = exif_read_data(_TADGAL_UP_IMPORT_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=(empty($result) or empty($result['IFD0']))?"":implodeArray2D("||",$result);

        $size=filesize(_TADGAL_UP_IMPORT_DIR.$file);
        $size_txt=sizef($size);
        $pic=getimagesize(_TADGAL_UP_IMPORT_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=_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='"._TADGAL_UP_IMPORT_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);
	  }
	}

	//預設值設定

	//$op="replace_tad_gallery";
	$main="
  <form action='{$_SERVER['PHP_SELF']}' method='post' id='myForm' enctype='multipart/form-data'>
  <table id='form_tbl'>
	<tr><td colspan='5'>"._MA_TADGAL_CSN."<select name='csn' size=1>$option</select>
	"._MA_TADGAL_NEW_CSN."<input type='text' name='new_csn' size='20'></td></tr>
	<tr>
  <tr>
	<th>"._TADGAL_IMPORT_FILE."</th>
	<th>"._TADGAL_IMPORT_DIR."</th>
	<th>"._TADGAL_IMPORT_DIMENSION."</th>
	<th>"._TADGAL_IMPORT_SIZE."</th>
	<th>"._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='"._TADGAL_UP_IMPORT."'></td></tr>
  </table>
  </form>";

  $info="<p>"._MA_TADGAL_UPLOAD_TO."<span style='color:red;'>".XOOPS_ROOT_PATH."/uploads/tadgallery/upload_pics/</span></p>";
	$main=div_3d(_TADGAL_PATCH_IMPORT_FORM,$main,"raised","",$info);

	return $main;
}


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

	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;
		}

   	$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);

			if($_POST['import'][$i]['width'] > $xoopsModuleConfig['thumbnail_m_width'] or $_POST['import'][$i]['height'] > $xoopsModuleConfig['thumbnail_m_width']){
				thumbnail($filename,$m_thumb_name,$_POST['import'][$i]['type'],$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,$_POST['import'][$i]['type'],$xoopsModuleConfig['thumbnail_s_width']);
			}
		}else{
		  $sql = "delete from ".$xoopsDB->prefix("tad_gallery")." where sn='$sn'";
			$xoopsDB->query($sql);
			redirect_header($_SERVER['PHP_SELF'], 5, sprintf(_TADGAL_IMPORT_IMPORT_ERROR,$filename));
		}
	}

	return $csn;
}


/*-----------執行動作判斷區----------*/

switch($_POST['op']){
	case "insert_tad_gallery":
	$sn=insert_tad_gallery();
	mk_rss_xml();
	redirect_header("view.php?sn=$sn", 1 ,sprintf(_TADGAL_IMPORT_UPLOADS_OK,$filename));
	break;
	
	case "upload_muti_file":
	$csn=upload_muti_file();
	mk_rss_xml();
	redirect_header("index.php?csn=$csn", 1 ,sprintf(_TADGAL_IMPORT_UPLOADS_OK,$filename));
	break;
	
	case "import_tad_gallery":
	$csn=import_tad_gallery();
	mk_rss_xml();
	header("location: index.php?csn=$csn");
	break;
	

	default:
	$main=uploads_tabs();
	break;
}

/*-----------秀出結果區--------------*/
$xoopsTpl->assign( "css" , "<link rel='stylesheet' type='text/css' media='screen' href='".XOOPS_URL."/modules/tadgallery/module.css' />") ;
$xoopsTpl->assign( "toolbar" , toolbar($interface_menu)) ;
$xoopsTpl->assign( "content" , $main) ;
include_once XOOPS_ROOT_PATH.'/footer.php';

?>
