<?php
ini_set('memory_limit', '1024M');
session_start();

if( !isset($_SESSION['admin_id']) || !isset($_SESSION['admin_account']) || !isset($_SESSION['admin_level']) || $_SESSION['admin_id'] == '' || $_SESSION['admin_account'] == '' || $_SESSION['admin_level'] == '' )
{
	session_unset();
	session_destroy();

	exit(json_encode(array('error'=>'請先登入')));
}

require_once('includes/common.php');

if( !isset($_FILES['file']) || !( $static_str_img_file_name = trim($_FILES['file']['tmp_name']) ) || !( $static_str_img_file_type = strtolower($_FILES['file']['type']) ) )
	exit(json_encode(array('error'=>'請輸入圖片網址或選擇上傳圖檔')));
else if( !preg_match('/^image\//', $static_str_img_file_type) || !( $arr_image_info = getimagesize($static_str_img_file_name) ) )
	exit(json_encode(array('error'=>'不正確的圖檔格式')));

if( $arr_image_info[0] <= NEWS_WIDTH )
{
	switch( $arr_image_info[2] )
	{
		case 1:
			$str_img_type = 'gif';
			break;
		case 2:
			$str_img_type = 'jpg';
			break;
		case 3:
			$str_img_type = 'png';
			break;
		case 4:
			$str_img_type = 'swf';
			break;
		case 5:
			$str_img_type = 'psd';
			break;
		case 6:
			$str_img_type = 'bmp';
			break;
		case 7:
		case 8:
			$str_img_type = 'tiff';
			break;
		case 9:
			$str_img_type = 'jpc';
			break;
		case 10:
			$str_img_type = 'jp2';
			break;
		case 11:
			$str_img_type = 'jpx';
			break;
		case 12:
			$str_img_type = 'jb2';
			break;
		case 13:
			$str_img_type = 'swc';
			break;
		case 14:
			$str_img_type = 'iff';
			break;
		case 15:
			$str_img_type = 'wbmp';
			break;
		case 16:
			$str_img_type = 'xbm';
			break;
		default:
			$str_img_type = '';
	}

	$uint_image_width = $arr_image_info[0];
	$uint_image_height = $arr_image_info[1];
	$str_source_file_name = $static_str_img_file_name;
}
else
{
	$uint_image_width = NEWS_WIDTH;
	$uint_image_height = round(NEWS_WIDTH * ( (float)$arr_image_info[1] / (float)$arr_image_info[0] ));
/*
	if( $arr_image_info[2] == IMAGETYPE_GIF && check_gif_animated($static_str_img_file_name) )
	{
		$str_temp_file_name_1 = '../images/uploads/temp_coalesce.gif';
		$str_temp_file_name_2 = '../images/uploads/temp.gif';

		@exec('/usr/bin/convert ' . $static_str_img_file_name . ' -coalesce ' . $str_temp_file_name_1);
		@exec('/usr/bin/convert -size ' . $arr_image_info[0] . 'x' . $arr_image_info[1] . ' ' . $str_temp_file_name_1 . ' -resize ' . $uint_image_width . 'x' . $uint_image_height . ' ' . $str_temp_file_name_2);

		if( file_exists($str_temp_file_name_1) )
			unlink($str_temp_file_name_1);

		if( !file_exists($str_temp_file_name_2) )
			exit(json_encode(array('error'=>'錯誤：無法建立暫存檔案')));
		
		$str_img_type = 'gif';
		$str_source_file_name = $str_temp_file_name_2;
	}
	else
	{*/
		switch( $arr_image_info[2] )
		{
			case IMAGETYPE_GIF:
				$img_file = imagecreatefromgif($static_str_img_file_name);
				break;

			case IMAGETYPE_JPEG:
				$img_file = imagecreatefromjpeg($static_str_img_file_name);
				break;

			case IMAGETYPE_PNG:
				$img_file = imagecreatefrompng($static_str_img_file_name);
				break;

			case IMAGETYPE_WBMP:
				$img_file = imagecreatefromwbmp($static_str_img_file_name);
				break;

			case IMAGETYPE_XPM:
				$img_file = imagecreatefromxpm($static_str_img_file_name);
				break;

			case IMAGETYPE_XBM:
				$img_file = imagecreatefromxbm($static_str_img_file_name);
				break;

			default:
				exit(json_encode(array('error'=>'無法辨識的圖檔格式')));
		}

		if( !$img_file )
			exit(json_encode(array('error'=>'錯誤：無法取得圖檔內容')));

		$img_temp = imagecreatetruecolor($uint_image_width, $uint_image_height);

		if( imagecolorstotal($img_file) )	//not true color
		{
			imagealphablending($img_temp, false);

	        if( ( $int_transparent_color_index = imagecolortransparent($img_file) ) >= 0 )
			{
				$arr_color = imagecolorsforindex($img_file, $int_transparent_color_index);

				$int_color_index = imagecolorallocatealpha($img_temp, $arr_color['red'], $arr_color['green'], $arr_color['blue'], 127);
	            imagefill($img_temp, 0, 0, $int_color_index);
	        }

			imagecopyresampled($img_temp, $img_file, 0, 0, 0, 0, $uint_image_width, $uint_image_height, $arr_image_info[0], $arr_image_info[1]);
		
			if( $int_transparent_color_index >= 0 )
			{
			    imagecolortransparent($img_temp, $int_color_index);

	            for( $i=0; $i<$uint_image_width; $i++ )
				{
					for( $j=0; $j<$uint_image_height; $j++ )
					{
						if( ( ( imagecolorat($img_temp, $i, $j) >> 24 ) & 0x7F ) >= 100 )
							imagesetpixel($img_temp, $i, $j, $int_color_index);
					}
				}
			}

	        imagetruecolortopalette($img_temp, true, 255);	//遞色
		    imagesavealpha($img_temp, false);
		}
		else
		{
			$img_watermark = imagecreatefrompng('../images/watermark.png');
			$uint_watermark_width = imagesx($img_watermark);
			$uint_watermark_height = imagesy($img_watermark);

			imagecopyresampled($img_temp, $img_file, 0, 0, 0, 0, $uint_image_width, $uint_image_height, $arr_image_info[0], $arr_image_info[1]);

			imagecopyresampled($img_temp, $img_watermark, 25, ($uint_image_height - $uint_watermark_height - 25), 0, 0, $uint_watermark_width, $uint_watermark_height, $uint_watermark_width, $uint_watermark_height);
		}

		switch( $arr_image_info[2] )
		{
			case IMAGETYPE_GIF:
				$str_temp_file_name = 'temp.gif';

				if( !imagegif($img_temp, $str_temp_file_name) || !file_exists($str_temp_file_name) )
					exit(json_encode(array('error'=>'錯誤：無法建立暫存檔案')));

				$str_img_type = 'gif';
				$str_source_file_name = $str_temp_file_name;
				break;

			case IMAGETYPE_PNG:
				$str_temp_file_name = 'temp.png';

				if( !imagepng($img_temp, $str_temp_file_name, 9) || !file_exists($str_temp_file_name) )
					exit(json_encode(array('error'=>'錯誤：無法建立暫存檔案')));

				$str_img_type = 'png';
				$str_source_file_name = $str_temp_file_name;
				break;

			default:
				$str_temp_file_name = 'temp.jpg';

				if( !imagejpeg($img_temp, $str_temp_file_name, 100) || !file_exists($str_temp_file_name) )
					exit(json_encode(array('error'=>'錯誤：無法建立暫存檔案')));

				$str_img_type = 'jpg';
				$str_source_file_name = $str_temp_file_name;
		}
//	}
}

$str_hash = md5_file($str_source_file_name);

require_once('includes/admin.php');
$obj_class_admin = new class_admin();

if( $arr_image = $obj_class_admin->get_image_by_size_n_hash($uint_image_width, $uint_image_height, $str_hash) )
{
	if( file_exists($str_source_file_name) )
		unlink($str_source_file_name);

	exit(stripslashes(json_encode(array('filelink'=>'../images/uploads/' . $arr_image[0]['FileName']))));
}
else if( !( $str_image_file_name = $obj_class_admin->add_image($uint_image_width, $uint_image_height, $str_hash, $str_img_type) ) )
{
	if( file_exists($str_source_file_name) )
		unlink($str_source_file_name);

	exit(json_encode(array('error'=>'無法更新資料庫，圖檔上傳失敗')));
}

$str_target_file_name = '../images/uploads/' . $str_image_file_name;

if( !( $bool_result = copy($str_source_file_name, $str_target_file_name) ) )
	$obj_class_admin->delete_image_by_file_name($str_image_file_name);

if( file_exists($str_source_file_name) )
	unlink($str_source_file_name);

if( !$bool_result )
	exit(json_encode(array('error'=>'圖檔上傳失敗')));
else
	exit(stripslashes(json_encode(array('filelink'=>$str_target_file_name))));
?>