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

	ログイン処理
	Login processing

  	login.php

	Written by:	Takashi Miyagi

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

	Update history:

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

	Ver.2.6
		セットされていない変数への参照で警告が出ていたので、先にチェックするようにした
		Because warning was given by cf. variable that was not set, I checked it earlier.

	Ver.2.4
		ログイン画面への接続用のURLを表示するようにした
		URL for the connection to the login screen was displayed. 

	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. 

******************************************************************************/

$login_page = TRUE;

require('files_com.php');

$conf = init_files($login_page);
$mode = get_post_get_val("mode");
$return_url = get_post_get_val("return_url");

//セッションIDを得る(パスワード暗号化時のチャレンジ変数として使用)
//Session ID is obtained. 
//(Use it as a challenge variable when the password is encrypted. )
$s_name = files_session_name();
$s_id = session_id();

if ($return_url != "") {
	$conf["returl"] = $return_url;
}

$submit = get_post_get_val("submit");

if ($conf["LOGIN_SCRIPT"] != "") {
	$scriptname = $conf["LOGIN_SCRIPT"];
} else {
	$scriptname = "login.php";
}

if ($conf["LOGIN_TITLE"] != "") {
	$title_str = $conf["LOGIN_TITLE"];
} else {
	$title_str = get_txt("user auth");
}
$userid_str = get_txt("user id");
$passwd_str = get_txt("password");
$submit_str = get_txt("login");
$reset_str = get_txt("reset");
$cancel_str = get_txt("cancel");

$returl = "";
if (isset($conf["returl"])) {
	$returl = $conf["returl"];
}

if (referer_url_check($conf, $returl, FALSE, FALSE)) {
	put_log($conf, "Referer url is permitted : login success");

	//許可された呼び出し元なら設定メニューまたはファイル一覧にリダイレクトする
	//It redirects it to permitted call former Japanese oak setting menu or
	//file list.
	if ($conf["CONFIG_DIR"] == 0) {
		//ファイル一覧にリダイレクトする
		//It redirects it to the file list. 
		echo get_redirect_files_JavaScriptHTML($conf);
	} else {
		//設定メニューにリダイレクトする
		//It redirects it to a set menu.
		echo get_redirect_confmenu_JavaScriptHTML($conf);
	}
	exit;
}
if (isset($conf["PASSWD_FILE"]) && $conf["PASSWD_FILE"] != "") {
	$pwdfile = $conf["PASSWD_FILE"];
} else {
	put_log($conf, "No password file : login success");

	//パスワードファイルが未設定ならファイル一覧にリダイレクトする
	//If the password file is a unsetting, it redirects it to the file list.
	echo get_redirect_files_JavaScriptHTML($conf);
	exit;
}
?>

<HTML>
<HEAD>
<?php echo get_charset_line(); ?>
<TITLE><?php echo $conf["HEADER_TITLE"] ?></TITLE>
<SCRIPT LANGUAGE="JavaScript" SRC="md5hash.js"></SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
//Login execution
function login()
{
	var	pwd;
	var	hash;
	var	join_str;
	var	send_pwd;

	//The input password is obtained.
	pwd = document.inp_form.inpstr.value;
	if (pwd.length > 0) {
<?php
if (is_md5_use($conf)) {
?>
		//The MD5 hush value of the input password is obtained.
		hash = md5hash_hexstr(pwd);

		//The MD5 hush values of session ID and the input password are united.
		join_str = "<?php echo $s_id ?>" + hash;

		//The MD5 hush value of the uniting character string is
		//assumed to be a transmission password character string.
		send_pwd = md5hash_hexstr(join_str);
<?php
} else {
?>
		//When you do not use MD5 with JavaScript when the password is input
		send_pwd = pwd;
<?php
}
?>
	} else {
		send_pwd = "";
	}
	document.inp_form.inpstr.value = "";
	document.inp_form.passwd.value = send_pwd;
	document.inp_form.mode.value = "send";
	document.inp_form.action = "<?php echo $scriptname; ?>";
	document.inp_form.target = "_top";
	document.inp_form.submit();
}
// -->
</SCRIPT>
</HEAD>
<BODY <?php echo get_body_bg_str($conf); ?>>
<?php
/****
	echo "return_url=" . $return_url . "<br>\n"; 
	echo "returl=" . $returl . "<br>\n"; 
	echo "conf[returl]=" . $conf["returl"] . "<br>\n"; 
	echo "session value RET_URL=" . get_session_value("RETURN_URL") . "<br>\n"; 
****/
?>
<CENTER>
<TABLE border=0>
	<TR>
		<TD>
			<CENTER>
				<?php
					//ページタイトルのイメージまたは文字列
					//Image or character string in page title
					echo get_page_title_HTML($conf);
				?>
			</CENTER>
		</TD>
	</TR>
</TABLE>
<?php

//タイトル下のコメント行表示
//Comment line display under title
if ($conf["TITLE_COMMENT_LOGIN"] != "") {
	echo "<CENTER>" . $conf["TITLE_COMMENT_LOGIN"] . "</CENTER>";
}

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

echo get_header_info_HTML($conf, FALSE, FALSE, TRUE);

?>
<HR>

<?php

if ($mode != "send") {
	//ログイン入力フォーム表示
	//Login input form display
?>
<form name="inp_form" method="post">
	<input type="hidden" name="mode" value="">
	<input type="hidden" name="passwd" value="">
	<input type="hidden" name="config" value="<?php echo $conf["config"] ?>">
	<input type="hidden" name="returl" value="<?php echo $returl ?>">
	<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 $title_str ?></B></CENTER>
			</TD>
		</TR>
		<TR>
			<TD><B><?php echo $userid_str ?>:</B></TD>
			<TD><input name="userid" type="text" size=20 maxlength=30></TD>
		</TR>
		<TR>
			<TD><B><?php echo $passwd_str ?>:</B></TD>
			<TD><input name="inpstr" type="password" size=20 maxlength=30></TD>
		</TR>
		<TR>
			<TD colspan=2>
			<CENTER>
			<input type="button" value="<?php echo $submit_str ?>"
												onClick="login()">
			<input type="reset" value="<?php echo $reset_str ?>">
			</CENTER>
			</TD>
		</TR>
	</TBODY></TABLE>
</form>
<HR>

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

?>
<br>
<?php

	if ($conf["ENTRY_PAGE_DIR_URL"] != "") {
		$link_url = $conf["ENTRY_PAGE_DIR_URL"];
		$str = "<b>" . get_txt("link address to this page") . "&nbsp;:&nbsp;";
		$str .= get_return_refer_url_HTML($link_url . "/", $link_url . "/");
		echo $str;
	}
} else {
	//ログイン実行
	//Login execution

	$msg = "";
	$logmsg = "";
	$sts = FALSE;
	$fp = 0;

	$userid = get_post_get_val("userid");
	$passwd = get_post_get_val("passwd");

	if ($userid == "") {
		//ユーザーID未設定
		//User ID unsetting
		$msg .= $userid_str . "&nbsp;" . get_txt("is not specified");
		$logmsg = "no user id";
	} elseif(! file_exists($pwdfile)) {
		if ($userid != $conf["ADMIN_USERID"]) {
			$msg .= get_txt("no password file");
			$logmsg = get_txt("no password file");
		} else {
			if (!($fp = fopen($pwdfile, "w"))) {
				$msg .= get_txt("password file cannot be created");
				$logmsg = get_txt("password file cannot be created");
			} else {
				flock($fp, 2);

				//管理者のデフォルトのパスワードを設定
				//The password of manager's default is set.
				$default_passwd = "";
				if ($conf["ADMIN_DEFAULT_PASSWD"] != "") {
					$default_passwd = md5($conf["ADMIN_DEFAULT_PASSWD"]);
				}
				$buffer = $userid . "\t" . $default_passwd . "\n";
				fputs($fp, $buffer, strlen($buffer));

				flock($fp, 3);
				fclose($fp);

				chmod($pwdfile, get_pwd_file_attr($conf));

				$sts = TRUE;
			}
		}
	} elseif (!($fp = fopen ($pwdfile, "r"))) {
		$msg .= get_txt("cannot open password file");
		$logmsg = get_txt("cannot open password file");
	} else {
		flock($fp, 2);

		$found = FALSE;

		while (!feof($fp)) {
			//１行読み込み
			//One line reading
			$buffer = fgets($fp, 4096);
			$buffer = chop($buffer);
			if (strlen($buffer) < 3) {
				//３文字以下の行は捨てる
				//The line of three characters or less is thrown away.
				continue;
			}
			if (substr($buffer, 0, 1) == "#") {
				//コメント行はスキップ
				//The comment line is skipped.
				continue;
			}
			//行をＴＡＢで分割
			//The line is divided with TAB.
			$flds = split("\t", $buffer);

			//２つのフィールドがあること
			//There must be two fields.
			if ($flds[0] != "") {
				if (strcmp($flds[0], $userid) == 0) {
					//ユーザー名が一致
					//The user name is corresponding.
					$found = TRUE;

					//ファイル中のパスワードのMD5ハッシュ値を得る
					//The MD5 hush value of the password under the
					//file is obtained.
					if (isset($flds[1]) && $flds[1] != "") {
						$pwd = $flds[1];
						if (!is_md5_use($conf)) {
							//パスワード入力時にJavaScriptでMD5を使わない場合
							//パスワードファイルにはMD5でハッシュ化したものが
							//登録されているため、比較するために入力したものを
							//ここでハッシュ化する
							//When you do not use MD5 with JavaScript when the
							//password is input
							//Because what made a hush with MD5 is registered
							//in the password file
							//What input for the sake of comparison is made a 
							//hush here. 
							$passwd = md5($passwd);
						} else {
							// セッションIDとパスワードMD5ハッシュ値を結合
							//Session ID and password MD5 hush value are 
							//united.
							$pwd = $s_id . $pwd;

							//結合した文字列のMD5ハッシュ値を得る
							//The MD5 hush value of the uniting character 
							//string is obtained.
							$pwd = md5($pwd);
						}
						// 受け取ったMD5ハッシュ値と比較
						//Received MD5 hush value and comparison
						if ($passwd == $pwd) {
							$sts = TRUE;
						} else {
							$msg = $passwd_str . "&nbsp;" . get_txt("is different");
							// for DEBUG
							//$msg .= "<BR>\n";
							//$msg .= "input password：" . $passwd . "<br>\n";
							//$msg .= "crypted password：" . $pwd . "<br>\n";
						}
					} else {
						$sts = TRUE;
					}
					break;
				}
			}
		}
		if (!$found) {
			$msg = $userid_str . "&nbsp;" . get_txt("is different");
			$logmsg = "bad user id : " . $userid;
		}
		flock($fp, 3);
		fclose($fp);
	}
	if ($sts) {
		set_session_value("LOGIN_USER", $userid);
		put_log($conf, "Login success");
		if ($conf["CONFIG_DIR"] == 0) {
			//ファイル一覧にリダイレクトする
			//It redirects it to the file list.
			echo get_redirect_files_JavaScriptHTML($conf);
		} else {
			//設定メニューにリダイレクトする
			//It redirects it to a set menu.
			echo get_redirect_confmenu_JavaScriptHTML($conf);
		}
		exit;
	}
	if (!$sts) {
		put_log($conf, "Login failure : " . $logmsg);

		$return_url .= "?config=" . $conf["config"];
		$return_url .= "&" . $s_name . "=" . $s_id;

		echo "<br>" . $msg . "<br>\n";
		echo "<br>\n";

		//元のＵＲＬに戻るのHTML文字列を取得
		//HTML that returns to former URL is acquired.
		echo get_return_refer_url_HTML($return_url, get_txt("back"));

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

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

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