<?php

#########################################################
# PDFダウyロード切り替えPHP
# modeでダウンロードの方法を切り替えます。
# 1の場合：ブラウザでの閲覧、2の場合：ダウンロード
# ダウンロードするファイルはリンク情報の埋め込まれたcsvから判定
# 1列目が、ファイルのID。 2列目が、dl.phpからの相対パス
#
# 2008.09.21 制作
#########################################################

// リンク情報が埋め込まれたCSV
// 1列目が、ファイルのID。 2列目が、dl.phpからの相対パス
$csvdata = "./link.csv";

//dl.phpから見たpdfのフォルダ
$pdfdir = "./pdf/";

function download_file($path_file,$mode){

	//グローバル変数 PDFの存在場所
	global $pdfdir;
    /* ファイルの存在確認 */
    if (!file_exists($pdfdir . $path_file)) {
        die("Error: File(".$path_file.") does not exist");
    }

    /* オープンできるか確認 */
    if (!($fp = fopen($pdfdir . $path_file, "r"))) {
        die("Error: Cannot open the file(".$path_file.")");
    }
    fclose($fp);

    /* ファイルサイズの確認 */
    if (($content_length = filesize($pdfdir . $path_file)) == 0) {
        die("Error: File size is 0.(".$path_file.")");
    }

    if($mode == "1"){
	    /* ダウンロード用のHTTPヘッダ送信  ブラウザ表示 */
	    header("Content-Disposition: inline; filename=\"".basename($path_file)."\"");
	    header("Content-Length: ".$content_length);
	    header("Content-Type: application/pdf");
    
    }else if($mode == "2"){
	    /* ダウンロード用のHTTPヘッダ送信 ダウンロード */
	    header("Content-Disposition: inline; filename=\"".basename($path_file)."\"");
	    header("Content-Length: ".$content_length);
	    header("Content-Type: application/octet-stream");
    }
    
    /* ファイルを読んで出力 */
    if (!readfile($pdfdir . $path_file)) {
        die("Cannot read the file(".$path_file.")");
    }
}


//ダウンロードするファイルのID、ファイル名から拡張子をのぞいたもの
// この値は'file'
// リクエストパラメータの dl=pdf/n871l67745.pdfに対応
//サニタジング処理も含む

$file = htmlspecialchars($_GET['file']);

//ダウンロードする際のモード
// この値は'mode'
// 1の場合：ブラウザでの閲覧、2の場合：ダウンロード

$mode = htmlspecialchars($_GET['mode']);

/* ファイルの存在確認 */
if (!file_exists($csvdata)) {
die("Error: File(".$csvdata.") does not exist");
}

/* ファイルサイズの確認 */
if (($content_length = filesize($csvdata)) == 0) {
die("Error: File size is 0.(".$csvdata.")");
}

/* オープンできるか確認 */
if (!($fp = fopen($csvdata, "r"))) {
die("Error: Cannot open the file(".$csvdata.")");
}

/* 読むレコードを1行目にセット */
$row = 1;

/* ダウンロードするファイル名にキャッシュの情報が残らないように初期化 */
$dldata = "";

while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
	if($data[0] == $file){
		$dldata = $data[1];
		break;
	}
	/*レコード数のチェック*/
	$row++;
}
fclose($fp);

if($dldata == ""){
	#ダウンロードファイルがCSVに無い場合はエラーを出して死ぬ
	die("Error: Cannot find the file(".$file.")");
}else{
	#ダウンロードファイルとモードで処理を判断します。
	download_file($dldata,$mode);
}

?>