<?
/*
실험주소
http://www.owllab.com/ios/smartreport_file.php?listimageid=xxxxxxxxxxxxxx
http://www.owllab.com/ios/smartreport_file.php?imageid=xxxxxxxxxxxx
http://www.owllab.com/ios/smartreport_file.php?moviethumbid=xxxxxxxxxxx
http://www.owllab.com/ios/smartreport_file.php?movieid=xxxxxxxxxx
*/

header("Cache-Control: no-cache, must-revalidate");

include_once ("session.php");
include_once ("dbcon_light.php");

function getFilePath($fileField, $rowid, $ext) {
	global $_FILES, $SCRIPT_FILENAME, $moviethumbid;
	$blanks = "";
	for ($c=0;$c<(10-strlen($rowid));$c++) $blanks .= "0";
	$filename = $blanks.$rowid."_".$fileField;
	$filepath = dirname($SCRIPT_FILENAME)."/files/".$filename.".".$ext;
	
	if ($moviethumbid!="") {
		$filename = $blanks.$rowid."_movie";
		$movpath = dirname($SCRIPT_FILENAME)."/files/".$filename.".".$ext;
		$filepath = dirname($SCRIPT_FILENAME)."/files/".$filename.".jpg";
		if (is_file($movpath) && !is_file($filepath)) {
			$cmd = "/usr/bin/mplayer -ss 1 -frames 1 -nosound -vo jpeg:outdir="
			.dirname($SCRIPT_FILENAME)."/files/ $movpath; mv "
			.dirname($SCRIPT_FILENAME)."/files/00000001.jpg $filepath";
			exec($cmd, $output);
//			echo $cmd;
//			print_r($output);
		}//if filepath
	}//if moviethumbid
	
	return $filepath;
}

$table = "report_demo";

if ($listimageid!="") {
	$filefield = "listimage";
	$sql = " select rowid, cryptid, listimage as data from $table 
	where cryptid like '$listimageid' ";
} else if ($imageid!="") {
	$filefield = "image";
	$sql = " select rowid, cryptid, image as data from $table 
	where cryptid like '$imageid' ";
} else if ($movieid!="") {
	$filefield = "movie";
	$sql = " select rowid, cryptid, movie as data from $table 
	where cryptid like '$movieid' ";
	$sql .= " and 1=2 ";
} else if ($moviethumbid!="") {
	$filefield = "moviethumb";
	$sql = " select rowid, cryptid, movie as data from $table 
	where cryptid like '$moviethumbid' ";
} else if ($streamid!="") {
	$sqlup = "update read = read+1 $table where cryptid like '$streamid' ";
	mysql_query($sqlup);
	$filefield = "movie";
	$sql = " select rowid, cryptid, movie as data from $table 
	where cryptid like '$streamid' ";
}

$rs = mysql_select_list($sql);

if (count($rs[rowid])>0) {
	$filepath = getFilePath($filefield,$rs[rowid][0], pathinfo($rs[data][0], PATHINFO_EXTENSION));
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control: no-cache, must-revalidate");
	if (is_file($filepath)) {
		if ($streamid!="") {
			header("Content-Type: video/quicktime;");
		} else {
			header("Content-Type: application/octet-stream;");
		}
		header( "Content-Disposition: attachment; filename=\"".$rs[data][0]."\";");
		header("Content-Transfer-Encoding: binary");
		header("Content-Description: File Transfer"); 
		header("Content-Length: ".filesize($filepath));
		flush();
		@readfile($filepath);
	} else {
		//echo $filepath;
	}
}

?>