<?php
/******************************************************************************
	Files(WEBファイル共有PHPスクリプト)
	Files(WEB file share PHP script)

	ファイルのアップロード処理
	Up-loading processing of file

  	upload.php

	Written by:	Takashi Miyagi

	Copyright (c) 2004-2014 GUSUKU All rights reserved.

	Update:

	Ver.2.6.2
		著作権者変更
		The copyright owner has been changed.

	Ver.2.6
		アップロードのエラー発生時にメッセージと戻り先を表示できるようにした。
		When an error occurred by upload, I was able to display a message and return.

	Ver.2.1
		構成ファイル配置設定を追加
		The configuration file arrangement setting is added.

	Ver.2.0
		表示文字列を locale.php から取得するように修正
		The display character string was acquired from locale.php. 

		文字コードの指定も locale.php から取得するように修正
		The specification of the character-code was acquired from locale.php.

		所有者とグループによるアクセス権制御機能を付加
		The access control function by the group is added with the owner. 

		HTML部分に２バイト文字を使用しないように修正した、
		ブラウザの文字コード自動判別に影響しないようにするため
		To make it not misidentified by the character-code automatic operation 
		identification of a browser, it was corrected that Japanese was not 
		used for the HTML part. 

	Ver.1.4 までの更新履歴
	Update history to Ver.1.4
		2005/08/02	ページヘッダー部分を共通化
					A common page header partial function is added. 
		2005/07/26	JavaScriptでアップロードファイルの重複をチェック
					The repetition of the up-loading file is checked with
					JavaScript.
		2005/08/02	サーバー側での重複チェックを追加
					The checking for duplication in the servers end is added.
******************************************************************************/

require('files_com.php');

$conf = init_files(FALSE);

$mode = get_post_get_val("mode");
$force = get_post_get_val("force");

$submit = get_post_get_val("submit");
$cancel = get_post_get_val("cancel");

$fname = get_post_get_val("fname");
$comment = get_post_get_val("comment");
$owner = get_post_get_val("owner");
$date = get_post_get_val("date");
$time = get_post_get_val("time");
$user = get_post_get_val("user");
$group = get_post_get_val("group");
$attr = get_post_get_val("attr");

$scriptname = "upload.php";

$s_name = files_session_name();
$s_id = session_id();

if (! isset($conf["curdir"])) {
	 $conf["curdir"] = "";
}
$curdir = make_path($conf["TOPDIR"], $conf["curdir"], "");

$login_user = get_login_user();
$login_user_groups = get_user_groups($conf, $login_user);
$default_attr = $conf["DEFAULT_ATTR"];

//カレントディレクトリの情報を得る
//Information on the current directory is obtained.
$curdir_inf = get_file_info($conf, $curdir);

//カレントディレクトリのパーミッションを得る
//The permission of the current directory is obtained.
$curdir_permit = get_permission($conf, $curdir_inf,
							$login_user, $login_user_groups);

$login_user_group = "";
if (isset($login_user_groups[0])) {
	$login_user_group = $login_user_groups[0];
}

?>

<HTML>
<HEAD>
<?php echo get_charset_line(); ?>
<TITLE><?php echo $conf["HEADER_TITLE"] ?></TITLE>

<?php
if ($mode == "select") {
?>

<script type="text/javascript">
<!--
function file_exist_check() {
	file_lst = new Array(
<?php
	$file_list = get_dir_file_list($curdir);
	$flg = 0;
	foreach($file_list as $fname) {
		if ($flg == 0) {
			echo "\t\t \"$fname\"\n";
			$flg = 1;
		} else {
			echo "\t\t,\"$fname\"\n";
		}
	}
?>
	);

	//The full path of the file is acquired from the form.
	fname = document.form1.UploadFile.value;

	//The file name is cut out from passing.
	path = fname.split("/");
	for (i = 0; i < path.length; i++) {
		fname = path[i];
	}
	path = fname.split("\\");
	for (i = 0; i < path.length; i++) {
		fname = path[i];
	}

	//File list and comparison in folder
	found = false;
	for (i = 0; i < file_lst.length; i++) {
		if (file_lst[i] == fname) {
			found = true;
			break;
		}
	}
	if (found == true) {
		if (! confirm("<?php echo get_txt("overwrite message"); ?>")) {
			return false;
		}
		document.form1.force.value = 1;
	} else {
		document.form1.force.value = 0;
	}
	return true;
}
// -->
</SCRIPT>

<?php
}
?>

</HEAD>
<BODY <?php echo get_body_bg_str($conf); ?>>

<?php

if ($mode == "select") {
	//送信ファイル指定フォーム表示
	//Transmission file specification and form displays
	$max_upload_size = 10000000;
	if (isset($conf["MAX_UPLOAD_SIZE"]) &&
						$conf["MAX_UPLOAD_SIZE"] != "") {
		$max_upload_size = $conf["MAX_UPLOAD_SIZE"];
	}
	$free_size = get_free_size($conf);
	if ($free_size < $max_upload_size) {
		$max_upload_size = $free_size;
	}
	$max_size_str = get_filesize_str($max_upload_size);

	$date = date("Y/m/d");
	$time = date("H:i:s");
?>

<?php
	//ページヘッダーHTMLを取得
	//Page header HTML is acquired.
	echo get_page_header_HTML($conf, "TITLE_COMMENT_UPLOAD",
									TRUE, $conf["SHOW_HELP_LINK"]);
?>

<CENTER>
<HR>
<TABLE width=95% border=0><TBODY>
	<TR>
		<TD>
			<?php
				//ファイル一覧に戻るのHTML文字列を取得
				//The HTML string to return to the file list is acquired.
				echo get_return_files_HTML($conf);
			?>
		</TD>
	</TR>
	<TR>
		<TD>
			<P align=center><B><?php echo $conf["title"] ?></B>&nbsp;(
					<?php echo get_txt("update datetime") .
						"&nbsp;:&nbsp;" . $conf["uptime"] ?>)
			</P>
		</TD>
	</TR>
</TBODY></TABLE>
<form name="form1" enctype="multipart/form-data" action="<?php echo $conf["UPLOAD_CGI"] ?>" method="post">
	<input type="hidden" name="mode" value="send">
	<input type="hidden" name="force" value=0>
	<input type="hidden" name="user" value="<?php echo $login_user ?>">
	<input type="hidden" name="group" value="<?php echo $login_user_group ?>">
	<input type="hidden" name="attr" value="<?php echo $default_attr ?>">
	<input type="hidden" name="dir" value="<?php echo $conf["curdir"] ?>">
	<input type="hidden" name="config" value="<?php echo $conf["config"] ?>">
	<input type="hidden" name="topdir" value="<?php echo $conf["TOPDIR"] ?>">
	<input type="hidden" name="<?php echo $s_name ?>" value="<?php echo $s_id ?>">
	<TABLE border=1><TBODY>
		<TR BGCOLOR="<?php echo $conf["LIST_TITLE_BG"] ?>">
			<TD colspan=2>
				<CENTER>
					<B><?php echo get_txt("file upload"); ?>
						(<?php echo get_txt("file size limit") .
									"&nbsp;:&nbsp;" . $max_size_str ?>)</B>
				</CENTER>
			</TD>
		</TR>
		<TR>
			<TD><B><?php echo get_txt("file"); ?>&nbsp:&nbsp;</B></TD>
			<TD>
				<input type="hidden" name="MAX_FILE_SIZE"
									value="<?php echo $max_upload_size ?>">
				<input name="UploadFile" type="file" size=80 maxlength=256>
			</TD>
		</TR>
		<TR>
			<TD><B><?php echo get_txt("comment"); ?>&nbsp:&nbsp;</B></TD>
			<TD><input name="comment" type="text" size=80 maxlength=128></TD>
		</TR>
		<TR>
			<TD><B><?php echo get_txt("create user name"); ?>&nbsp:&nbsp;
				</B></TD>
			<TD><input name="owner" type="text" size=20 maxlength=30></TD>
		</TR>
		<TR>
			<TD><B><?php echo get_txt("create date"); ?>&nbsp:&nbsp;</B></TD>
			<TD><input name="date" type="text" size=20 maxlength=15
									value="<?php echo $date ?>"></TD>
		</TR>
		<TR>
			<TD><B><?php echo get_txt("create time"); ?>&nbsp:&nbsp;</B></TD>
			<TD><input name="time" type="text" size=20 maxlength=5
									value="<?php echo $time ?>"></TD>
		</TR>
		<TR>
			<TD colspan=2>
				<CENTER>
				<input type="submit" name="submit" value="<?php echo get_txt("upload"); ?>" onClick="return file_exist_check();">
				<input type="reset" value="<?php echo get_txt("reset"); ?>">
				<input type="submit" name="cancel" value="<?php echo get_txt("cancel"); ?>">
				</CENTER>
			</TD>
		</TR>
	</TBODY></TABLE>
</form>
<center>
<table border=0>
<tr>
<td>
	<b>[<?php echo get_txt("caution"); ?>]&nbsp;:&nbsp;</b><br>&nbsp;:&nbsp;
</td>
<td>
	<b><?php echo get_txt("not use multibyte string for filename"); ?></b>
</td>
</tr>
</table>
</center>
<HR>

<?php
	//戻り先１と戻り先２へのリンクを表示するHTMLを生成
	//Link HTML to return 1 and return 2 destination is generated.
	echo get_return_url_HTML($conf);

} elseif ($mode == "send") {

	//ファイル送信処理
	//File transmission processing
	$msg = "";
	if ($submit == "") {
		$sts = TRUE;
	} else {
		$sts = FALSE;

		$upload_file_name = "";
		$upload_tmpfile_name = "";
		$upload_file_size = "";
		$dst_fname = "";

		$upfile_info = get_upload_file_info();

		if (isset($upfile_info["name"])) {
			$upload_file_name = $upfile_info["name"];
		}
		if (isset($upfile_info["size"])) {
			$upload_file_size = $upfile_info["size"];
		}
		if (isset($upfile_info["tmp_name"])) {
			$upload_tmpfile_name = $upfile_info["tmp_name"];
			if (! is_uploaded_file($upload_tmpfile_name)) {
				$msg .= get_txt("illegal upload file") . "<br>";
				$msg .= get_txt("filename") . "=" . $upload_tmpfile_name . "<BR>\n";
				$msg .= get_txt("target filename") . "=" . $upload_file_name . "<BR>\n";
				$msg .= get_txt("size") . "=" . $upload_file_size . "<BR>\n";
			}
		}
		// 使用可能容量を得る
		//The capacity that can be used is obtained.
		$free_size = get_free_size($conf);

		$fsize = sprintf("%u", filesize($upload_tmpfile_name));

		put_log($conf, "Upload File=" . $upload_file_name .
					" Size=" . $upload_file_size .
					" User=" . $login_user .
					" TmpFile=" . $upload_tmpfile_name);

		if ($fsize > $free_size) {
			$msg .= get_txt("file seize is too large") .
							"&nbsp;:&nbsp;size=" . $fsize . "<BR>\n";
			$msg .= get_txt("max upload size") .
							"&nbsp;:&nbsp;max =" . $free_size . "<BR>\n";
		} elseif ($upload_file_name != "" && $upload_tmpfile_name != "") {
			//ターゲットのフルパスを作成
			//The full path of the target is made.
			$dst_fname = make_path($curdir, "", $upload_file_name);
			if ($upload_tmpfile_name != "" && $upload_tmpfile_name != "none") {
				$sts = TRUE;
				if (file_exists($dst_fname)) {
					if ($force != 1) {
						$msg .= get_txt("the file name overlaps") .
										"&nbsp(" . $dst_fname . ")<BR>\n";
						$sts = FALSE;
					} else {
						$finf = get_file_info($conf, $dst_fname);
						$permit = get_permission($conf, $finf,
									$login_user, $login_user_groups);
						if (!$permit["w"]) {
							$msg .= get_txt("the file name overlaps") .
										"&nbsp(" . $dst_fname . ")<BR>\n";
							$sts = FALSE;
						}
					}
				}
				if ($sts) {
		   			$sts = copy($upload_tmpfile_name, $dst_fname);
					if (! $sts) {
						$msg .= get_txt("cannot copy") .
							"&nbsp;(" . $upload_tmpfile_name .
							"--&gt;" . $dst_fname . ")<BR>\n";
					}
				}
				put_log($conf, "Upload File=" . $dst_fname .
								" Size=" . $fsize .
								" User=" . $login_user .
								" TmpFile=" . $upload_tmpfile_name);
			} else {
				$msg .= get_txt("file name is not specified") .
							"&nbsp;:&nbsp;" .
							get_txt("source file name") .
							"&nbsp;(" . $upload_tmpfile_name . ")" .
							get_txt("destination file name") .
							"&nbsp;(" . $upload_file_name . ")<BR>\n";
			}
		}
		
		if ($sts) {
			//コピーしたファイルのパーミッションを設定
			//The permission of the copied file is set.
			chmod($dst_fname, get_data_file_attr($conf));

			//ロックする
			//It locks.
			$lockfile = make_path($curdir, "", $conf["LOCKFILE"]);
			$lock_fp = lock_files($lockfile);
			if (! $lock_fp) {
				$msg .= get_txt("cannot lock") . "<br>\n";
				$sts = FALSE;
			} else {
				// ファイルリスト記録ファイル名
				//File list record file name
				$listfile = make_path($curdir, "", $conf["LISTFILE"]);

				// ファイルリストを読み込む
				//The file list is read.
				if (file_exists($listfile)) {
					$conf["uptime"] = date("Y/m/d H:i:s", filemtime($listfile));
					$list_files = read_filelist($curdir, $conf["LISTFILE"]);
				}

				//アイコンイメージの種類を得る
				//The kind of the icon image is obtained. 
				$fimg = get_file_image($curdir, $upload_file_name);
				if (! isset($date) || $date == "") {
					$fdate =  date("Y/m/d");
					$ftime =  date("H:i:s");
				} else {
					$fdate = $date;
					if (isset($time)) {
						$ftime = $time;
					} else {
						$ftime = "";
					}
				}
				$fsize = sprintf("%u", filesize($dst_fname));
				$found = 0;
				for ($i = 0; $i < count($list_files); $i++) {
					$finf = $list_files[$i];
					if ($finf["name"] == $upload_file_name) {
						$finf["comment"] = $comment;
						$finf["owner"] = $owner;
						$finf["size"] = $fsize;
						$finf["date"] = $fdate;
						$finf["time"] = $ftime;
						$finf["user"] = $login_user;
						$finf["group"] = $login_user_group;
						$finf["attr"] = $default_attr;
						$finf["image"] = $fimg;
						$list_files[$i] = $finf;
						$found = 1;
						break;
					}
				}
				if (! $found) {
					$list_files[] = array(
						"name" => $upload_file_name,
						"comment" => $comment,
						"owner" => $owner,
						"size" => $fsize,
						"date" => $fdate,
						"time" => $ftime,
						"user" => $login_user,
						"group" => $login_user_group,
						"attr" => $default_attr,
						"image" => $fimg
					);
				}
				//カレントディレクトリ内のファイル一覧を得る
				//The file list in the current directory is obtained.
				list($files, $update) = get_dirfiles($conf,
													$curdir, $list_files);

				// ファイルリスト書き込み
				//File list writing
				$conf["uptime"] = date("Y/m/d H:i:s");

				if (!write_file_list($listfile, $files)) {
					$msg .= get_txt("cannot write file list") .
									"&nbsp;(" . $listfile . ")<br>\n";
					$sts = FALSE;
				}
				//ロックを解除する
				//The lock is released.
				unlock_files($lock_fp, $lockfile);

				if ($sts) {
					//フォルダの日付を更新する
					update_dir_time($conf, $curdir, "", "");
				}
			}
			if ($sts) {
				put_log($conf, "Upload success : " . $dst_fname);

			} else {
				//put_log($conf, "Upload failure : " . $dst_fname);
				put_log($conf, "Upload failure : " . $dst_fname . " : " . $msg);
			}
		} else {
			$msg .= get_txt("cannot upload file") .
						"&nbsp(" . $upload_file_name . ")<br>";
			//put_log($conf, "Upload failure : " . $upload_file_name);
			put_log($conf, "Upload failure : " . $upload_file_name . " : " . $msg);
		}
	}
	if ($sts) {
		//ファイル一覧にリダイレクトする
		//It redirects it to the file list.
		echo get_redirect_files_JavaScriptHTML($conf);
		exit;
	}
	if (!$sts) {
		echo $msg;
		echo "<HR>";
		//ファイル一覧に戻るのHTML文字列を取得
		//The HTML string to return to the file list is acquired.
		echo get_return_files_HTML($conf);
	}
} elseif ($mode == "list") {
	if ($cancel != "") {
		//ファイル一覧にリダイレクトする
		//It redirects it to the file list.
		echo get_redirect_files_JavaScriptHTML($conf);
		exit;
	}
	$sts = TRUE;
	$msg = "";
	$upload_file_name = get_filename($UploadFile);

	//ロックする
	$lockfile = make_path($curdir, "", $conf["LOCKFILE"]);
	$lock_fp = lock_files($lockfile);
	if (! $lock_fp) {
		$msg .= get_txt("cannot lock") . "<br>\n";
		$sts = FALSE;
	} else {
		// ファイルリスト記録ファイル名
		//File list record file name
		$listfile = make_path($curdir, "", $conf["LISTFILE"]);

		// ファイルリストを読み込む
		//The file list is read.
		if (file_exists($listfile)) {
			$conf["uptime"] = date("Y/m/d H:i:s", filemtime($listfile));
			$list_files = read_filelist($curdir, $conf["LISTFILE"]);
		}

		$fimg = get_file_image($curdir, $upload_file_name);
		if (! isset($date) || $date == "") {
			$fdate =  date("Y/m/d");
			$ftime =  date("H:i:s");
		} else {
			$fdate = $date;
			if (isset($time)) {
				$ftime = $time;
			} else {
				$ftime = "";
			}
		}
		$fsize = sprintf("%u", filesize($dst_fname));

		$found = 0;
		for ($i = 0; $i < count($list_files); $i++) {
			$finf = $list_files[$i];
			if ($finf["name"] == $upload_file_name) {
				$finf["comment"] = $comment;
				$finf["owner"] = $owner;
				$finf["size"] = $fsize;
				$finf["date"] = $fdate;
				$finf["time"] = $ftime;
				$finf["image"] = $fimg;
				$list_files[$i] = $finf;
				$found = 1;
				break;
			}
		}
		if (! $found) {
			$list_files[] = array(
				"name" => $upload_file_name,
				"comment" => $comment,
				"owner" => $owner,
				"size" => $fsize,
				"date" => $fdate,
				"time" => $ftime,
				"image" => $fimg
			);
		}
		//カレントディレクトリ内のファイル一覧を得る
		//The file list in the current directory is obtained.
		list($files, $update) = get_dirfiles($conf, $curdir, $list_files);

		$conf["uptime"] = date("Y/m/d H:i:s");

		// ファイルリスト書き込み
		//File list writing
		if (!write_file_list($listfile, $files)) {
			$msg .= get_txt("cannot write file list") .
							"&nbsp(" . $listfile . ")<br>\n";
			$sts = FALSE;
		}
		//ロックを解除する
		//The lock is released.
		unlock_files($lock_fp, $lockfile);
	}
	if ($sts) {
		put_log($conf, "Write filelist success : " . $upload_file_name);

		//ファイル一覧にリダイレクトする
		//It redirects it to the file list.
		echo get_redirect_files_JavaScriptHTML($conf);
		exit;
	}
	if (!$sts) {
		put_log($conf, "Write filelist failure : " . $msg);

		echo $msg;
		echo "<HR>";
		//ファイル一覧に戻るのHTML文字列を取得
		//The HTML string to return to the file list is acquired.
		echo get_return_files_HTML($conf);
	}
} else {
	$msg = get_txt("cannot upload file");
	put_log($conf, "Upload failure : " . $msg);

	echo $msg . "<br>";
	echo "<HR>";

	//ファイル一覧に戻るのHTML文字列を取得
	//The HTML string to return to the file list is acquired.
	echo get_return_files_HTML($conf);
}

//ページフッター（プログラム・バージョンとCopyright表示）
//Page footer(program version and Copyright display)
echo get_page_footer_HTML($conf)

?>

</CENTER>
</BODY>
</HTML>
