<?php
/**
 * Account manager MAIL RegistMail form module
 * author JOJO
 * version: RegistMail.php 00 2008-05-09 23:36:00
 * package AccountManager
 * filesource
 */

/**
 * メール送信方法をいくつか用意しました。
 * あなたのサーバの環境にあわせて、下記の中から、
 * どれか１つだけ有効にしてください。
 * ソースコード中にアカウント・パスワードなどの設定があります。
 */
//require_once 'classes/modules/mail/mb_send_mail.php';
//require_once 'classes/modules/mail/pear_mail.php';
//require_once 'classes/modules/mail/pear_net_smtp.php';
//require_once 'classes/modules/mail/proc_open.php';
//require_once 'classes/modules/mail/popen.php';
require_once 'classes/modules/mail/pop_before_smtp.php';

class Registration extends Module
{
	var $timelimit = '00:30:00';	//有効期限 時:分:秒
	var $transitions;
	var $step;

	/**
	 * Constructor, specification template file and starts to create contents.
	 */
	function Registration()
	{
		$this->Module();
		if (isset($_GET['reissue']))
		{
			$this->transitions = array(NULL
				, '1.変更受付'
				, '2.メール確認'
				, '3.パス入力'
				, '4.完了'
			);

			if (isset($_GET['key']))
			{
				$this->step = 3;
				$htm = 'reissuepass.htm';
				$run = 'check_newpassword_form';
			}
			else
			{
				$this->step = 1;
				$htm = 'reissuemail.htm';
				$run = 'check_reissue_form';
			}
		}
		else
		{
			$this->transitions = array(NULL
				, '1.新規受付'
				, '2.メール確認'
				, '3.アクティベーション'
				, '4.完了'
			);

			if (isset($_GET['key']))
			{
				$this->step = 3;
				$htm = 'registactivate.htm';
				$run = 'check_activate_form';
			}
			else
			{
				$this->step = 1;
				$htm = 'registmail.htm';
				$run = 'check_mail_form';
			}
		}

		if ($this->template = temp_load($this->config->manager['template_path'].$htm))
		{
			call_user_func(array($this,$run));
			$this->output = $this->template;
		} else {
			$this->output = "Class:登録テンプレートがありません。";
		}
	}

	function transitionToString($step)
	{
		$items = $this->transitions;

		$temp = '<div style="font-size=80%;">';
		for ($i = 1; $i < Count($items); $i++) {
			if ($i < $step) {
				$temp .= '<span style="color:#888888; background-color:#CCCCCC; padding:2px; border:1px solid #000000;">'.$items[$i].'</span>';
			} elseif ($i == $step) {
				$temp .= '<b style="color:#000000; background-color:#EEFFEE; padding:2px; border:2px solid #00FF00;">'.$items[$i].'</b>';
			} else {
				$temp .= '<span style="color:#000000; background-color:#F8F8F8; padding:2px; border:1px solid #000000;">'.$items[$i].'</span>';
			}
		}
		$temp .='</div>';
		return $temp;
	}

	/**
	* Check form input and that 
	*/	
	function check_mail_form()
	{
		include('classes/configuration.php');
		if (isset($_POST['login'])) $fill['login'] = htmlspecialchars($_POST['login']); else $fill['login'] = '';
		if (isset($_POST['email'])) $fill['email'] = htmlspecialchars($_POST['email']); else $fill['email'] = '';
		$step = 1;
		
		if (isset($_POST['login'])
		 && isset($_POST['password'])
		 && isset($_POST['password2'])
		 && isset($_POST['email']))
		{
			if ( empty($_POST['login'])
			  || empty($_POST['password'])
			  || empty($_POST['password2'])
			  || empty($_POST['email']) )
			{
				$this->template = '<br><font color=red>項目を入力してください！</font>'.$this->template;
			}
			elseif (! preg_match('/^[0-9A-Za-z_.\-]{4,14}$/', $_POST['login']))
								// [許可する文字]{最低文字数,最大文字数}
			{
				$this->template = '<br><font color=red>アカウントに使用できない文字が含まれてるか、文字数が不正です。</font>'.$this->template;
			}
			elseif ($_POST['password'] != $_POST['password2'])
			{
				$this->template = '<br><font color=red>パスワードが一致しません！再度入力してください。</font>'.$this->template;
			}
			elseif (! preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_POST['email']))
			{
				$this->template = '<br><font color=red>メールアドレスに使用できない文字が含まれてるか、形式が不正です。</font>'.$this->template;
			}
			elseif ($this->get_count() >= $this->config->manager['account_limit'])
			{
				$this->template = '<br><font color=red>アカウント登録上限です : '.$manager['account_limit'].'</font>'.$this->template;
			}
			elseif (! $this->put_accounts_acm())
			{
				$this->template = '<br><font color=red>このアカウントまたはメールアドレスは<br>'
							. 'すでに登録されています。</font>'.$this->template;
			}
			else
			{
				$this->write_log("RegistMail: Account temporary accepted: '{$_POST['login']}'");
				$this->template = '<br><br><font color=red style="size:150%;">"<b>'.htmlspecialchars($_POST['email']).'</b>" へメールを送信しました。<br><br>'
						.'メールボックスを確認して、アクティベーションへ進んでください。</font>';

				$link = '';
				if (strstr($_POST['email'], '@yahoo.co.jp'))    $link .= '[<a href="http://mail.yahoo.co.jp/">Yahoo!メール</a>]';
				if (strstr($_POST['email'], '@nifmail.jp'))     $link .= '[<a href="http://enter.nifmail.jp/">@niftyメール</a>]';
				if (strstr($_POST['email'], '@hotmail.co.jp'))  $link .= '[<a href="http://mail.live.com/">Windows Live</a>]';
				if (strstr($_POST['email'], '@gmail.com'))      $link .= '[<a href="http://mail.google.com/">Gmail</a>]';
				if (strstr($_POST['email'], '@infoseek.jp'))    $link .= '[<a href="http://email.www.infoseek.co.jp/">Infoseek楽天メール</a>]';
				if (strstr($_POST['email'], '@mail.goo.ne.jp')) $link .= '[<a href="http://mail.goo.ne.jp/">gooメール</a>]';
				if (strstr($_POST['email'], '@excite.co.jp'))   $link .= '[<a href="http://www.excite.co.jp/mail/">exciteメール</a>]';
				if (strstr($_POST['email'], '.ocn.ne.jp'))      $link .= '[<a href="https://mail-on.ocn.ad.jp/">OCN MailOn</a>]';
				if (strstr($_POST['email'], '.biglobe.ne.jp'))  $link .= '[<a href="http://email.biglobe.ne.jp/">BIGLOBEメール</a>]';

				if (! empty($link)) $this->template .= '<br><br><center>リンク<br>'.$link.'</center>';

				$step = 2;
			}
		}
		$this->template = temp_subs($this->template, "register", $fill);
		
		$ac_inf['registred'] = account_count();
		$ac_inf['limit'] = $this->config->manager['account_limit'];
		
		$this->template = temp_subs($this->template, "reg", $ac_inf);

		$this->template = $this->transitionToString($step).$this->template;
	}

	/**
	 * Put temporary account in database
	 * @return new=TRUE/exists=FALSE
	 */
	function put_accounts_acm()
	{
		$SQL = sprintf("SELECT login FROM accounts WHERE (login='%s' OR email='%s')"
					, mysql_real_escape_string($_POST['login'])
					, mysql_real_escape_string($_POST['email'])
					);
		if (! ($q = mysql_query($SQL)))
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		if ($r = mysql_fetch_row($q))
			return FALSE; // Duplicate entry

		mysql_query("DELETE FROM accounts_acm WHERE timelimit<NOW()");
		mysql_query("START TRANSACTION");

	//	$registkey = mt_rand(1000000000,2000000000);
		$registkey = strtoupper(substr(md5(uniqid('',1)), -10));
//-		$accountObj = new account($_POST['login'], $_POST['password']);
//-		$SQL = sprintf("INSERT INTO accounts_acm (login,password,email,registkey,timelimit) VALUES ('%s','%s','%s','%s',ADDTIME(NOW(),'%s'))"
//-					, mysql_real_escape_string($accountObj->login/*$_POST['login']*/)
//-					, mysql_real_escape_string($accountObj->encrypted/*$_POST['password']*/)
//-					, mysql_real_escape_string($_POST['email'])
//-					, $registkey
//-					, $this->timelimit
//-					);
		$SQL = sprintf("INSERT INTO accounts_acm (login,password,email,registkey,timelimit) VALUES ('%s','%s','%s','%s',ADDTIME(NOW(),'%s'))"
					, mysql_real_escape_string($_POST['login'])
					, mysql_real_escape_string($this->l2j_encrypt($_POST['password']))
					, mysql_real_escape_string($_POST['email'])
					, $registkey
					, $this->timelimit
					);
		if (! mysql_query($SQL))
		{
//			echo '<br><b>DEBUG</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>';
			return FALSE; // Duplicate entry
		}

		$text = file_get_contents($this->config->manager['template_path'].'registmail-send.txt');
	//	$text = file_get_contents($this->config->manager['template_path'].'registmail-send.htm');
		$text = str_replace(pack('C*',0xEF,0xBB,0xBF),'', $text);	//BOM
		$text = str_replace('%registkey%', $registkey, $text);

		if (! /*$this->*/sendmail($_POST['email'], 'L2J アカウント登録', $text))
			die('<br><b>Error</b>: Can\'t send a mail in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');

		mysql_query("COMMIT");
		return TRUE;
	}

	/**
	 * Encrypt password
	 * @param string
	 * @return string
	 */
	function l2j_encrypt($password) 
	{
		return base64_encode(pack("H*", sha1(utf8_encode($password))));
	}

	/**
	* Check form input and that 
	*/	
	function check_activate_form()
	{
		include('classes/configuration.php');
		if (isset($_POST['login'])) $fill['login'] = htmlspecialchars($_POST['login']); else $fill['login'] = '';
		$step = 3;
		
		if (isset($_POST['login'])
		 && isset($_POST['password'])
		 && isset($_GET['key']))
		{
			if ( empty($_POST['login'])
			  || empty($_POST['password']) )
			{
				$this->template = '<br><font color=red>項目を入力してください！</font>'.$this->template;
			}
			elseif ($this->get_count() >= $this->config->manager['account_limit'])
			{
				$this->template = '<br><font color=red>アカウント登録上限です : '.$manager['account_limit']>'</font>'.$this->template;
			}
			elseif (! $this->put_accounts())
			{
				$this->template = '<br><font color=red>間違っています！</font>'.$this->template;
			}
			else
			{
				$loginPanel = new Loginpanel();
				if ($this->is_logged())
				{
					$this->write_log("RegistActivate: Account created: '{$_POST['login']}'");
					$this->template = '<br><font color=red style="size:150%;">"<b>'.$_POST['login'].'</b>" のアカウントが登録されました。</font>';
					$step = 4;
				}
				else
				{
					$this->template = '<br><font color=red>アカウント "<b>'.$_POST['login'].'</b>" はすでに登録されています。</font>'.$this->template;
				}
			}
		}
		$this->template = temp_subs($this->template, "register", $fill);
		
		$ac_inf['registred'] = account_count();
		$ac_inf['limit'] = $this->config->manager['account_limit'];
		
		$this->template = temp_subs($this->template, "reg", $ac_inf);

		$this->template = $this->transitionToString($step).$this->template;
	}

	/**
	 *
	 */
	function put_accounts()
	{
//-		if (! ($q = mysql_query(sprintf("SELECT login,password,email,registkey FROM accounts_acm WHERE login='%s' AND timelimit>NOW()"
//-					, mysql_real_escape_string($_POST['login']) ))))
//-			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
//-		if (! ($r = mysql_fetch_assoc($q) ))
//-			//die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
//-			return FALSE;
//-
//-		$accountObj = new account($_POST['login'], $_POST['password']);
//-		if ($r['password'] != $accountObj->encrypted/*$_POST['password']*/)
//-			return FALSE;
//-		if ($r['registkey'] != $_GET['key'])
//-			return FALSE;

		$SQL = sprintf("SELECT * FROM accounts_acm WHERE login='%s' AND password='%s' AND registkey='%s' AND timelimit>NOW()"
					, mysql_real_escape_string($_POST['login'])
					, mysql_real_escape_string($this->l2j_encrypt($_POST['password']))
					, mysql_real_escape_string($_GET['key'])
					);
		if (! ($q = mysql_query($SQL)))
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		if (! ($r = mysql_fetch_assoc($q) ))
		//	die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
			return FALSE;

		mysql_query("START TRANSACTION");
		$SQL = sprintf("INSERT INTO accounts (login,password,email,accessLevel) VALUES ('%s','%s','%s',%d)"
					, mysql_real_escape_string($r['login'])
					, mysql_real_escape_string($r['password'])
					, mysql_real_escape_string($r['email'])
					, $this->config->manager['default_level']
					);
		if (! mysql_query($SQL))
		{
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		}
		if (! mysql_query(sprintf("DELETE FROM accounts_acm WHERE login='%s' OR timelimit<NOW()"
					, mysql_real_escape_string($_POST['login'])
					)))
		{
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		}

		mysql_query("COMMIT");
		return TRUE;
	}

	/**
	 * Get account count in database
	 * @return int
	 */
	function get_count()
	{
		if($q = mysql_query("SELECT COUNT(login) as acs FROM accounts"))
		{
			$r = mysql_fetch_array($q);
			return $r['acs'];
		} else {
			return false;
		}
	}

	/**
	 *
	 */
	function check_reissue_form()
	{
		include('classes/configuration.php');
		if (isset($_POST['login'])) $fill['login'] = htmlspecialchars($_POST['login']); else $fill['login'] = '';
		$step = 1;
		
		if (isset($_POST['login']))
		{
			if ( empty($_POST['login']) )
			{
				$this->template = '<br><font color=red>項目を入力してください！</font>'.$this->template;
			}
			elseif (! $this->put_reissue() )
			{
				$this->template = '<br><font color=red>このアカウントは登録されていません。</font>'.$this->template;
			}
			else
			{
				$this->write_log("ReissueMail: Account temporary accepted: '{$_POST['login']}'");
				$this->template = '<br><br><font color=red style="size:150%;">メールを送信しました。<br><br>'
						.'メールボックスを確認して、パスワード入力へ進んでください。</font>';
				$step = 2;
			}
		}
		$this->template = temp_subs($this->template, "register", $fill);
		
		$this->template = $this->transitionToString($step).$this->template;
	}

	/**
	 *
	 */
	function put_reissue()
	{
		$sql = sprintf("SELECT email FROM accounts WHERE login='%s'"
					, mysql_real_escape_string($_POST['login'])
					); /*die('<pre>SQL=['.htmlspecialchars($sql).']</pre>');*/
		if (! ($q = mysql_query($sql)))
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		if (! ($r = mysql_fetch_row($q)) )
			return FALSE; // Notfound
		if (empty($r[0]))
			return FALSE; // Notfound
		$email = $r[0]; /*die('<pre>email=['.htmlspecialchars($email).']</pre>');*/
	//	$registkey = mt_rand(1000000000,2000000000);
		$registkey = strtoupper(substr(md5(uniqid('',1)), -10));

		$sql = sprintf("DELETE FROM accounts_acm WHERE timelimit<NOW() OR login='%s'"
					, mysql_real_escape_string($_POST['login'])
					); /*die('<pre>SQL=['.htmlspecialchars($sql).']</pre>');*/
		mysql_query($sql);

//|		$sql = sprintf("INSERT INTO accounts_acm (login,password,email,registkey,timelimit) VALUES ('%s','%s','%s','%s',ADDTIME(NOW(),'%s'))"
//|					, mysql_real_escape_string($_POST['login'])
//|					, ''
//|					, ''
//|					, $registkey
//|					, $this->timelimit
//|					); /*die('<pre>SQL=['.htmlspecialchars($sql).']</pre>');*/
		$sql = sprintf("INSERT INTO accounts_acm (login,registkey,timelimit) VALUES ('%s','%s',ADDTIME(NOW(),'%s'))"
					, mysql_real_escape_string($_POST['login'])
					, $registkey
					, $this->timelimit
					); /*die('<pre>SQL=['.htmlspecialchars($sql).']</pre>');*/
		if (! mysql_query($sql))
		{
			echo '<br><b>DEBUG</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>';
			return FALSE; // Duplicate entry
		}

		$text = file_get_contents($this->config->manager['template_path'].'reissuemail-send.txt');
	//	$text = file_get_contents($this->config->manager['template_path'].'reissuemail-send.htm');
		$text = str_replace(pack('C*',0xEF,0xBB,0xBF),'', $text);	//BOM
		$text = str_replace('%registkey%', $registkey, $text);
		$text = str_replace('%remoteaddr%', $_SERVER['REMOTE_ADDR'], $text);

		if (! /*$this->*/sendmail($email, 'L2J アカウント変更', $text))
			die('<br><b>Error</b>: Can\'t send a mail in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');

		return TRUE;
	}

	/**
	 *
	 */
	function check_newpassword_form()
	{
		include('classes/configuration.php');
		if (isset($_POST['login'])) $fill['login'] = htmlspecialchars($_POST['login']); else $fill['login'] = '';
		$step = 3;
		
		if (isset($_POST['login'])
		 && isset($_POST['password'])
		 && isset($_GET['key']))
		{
			if ( empty($_POST['login'])
			  || empty($_POST['password']) )
			{
				$this->template = '<br><font color=red>項目を入力してください！</font>'.$this->template;
			}
			elseif ($_POST['password'] != $_POST['password2'])
			{
				$this->template = '<br><font color=red>パスワードが一致しません！再度入力してください。</font>'.$this->template;
			}
			elseif (! $this->update_password())
			{
				$this->template = '<br><font color=red>間違っています！</font>'.$this->template;
			}
			else
			{
				$loginPanel = new Loginpanel();
				if ($this->is_logged())
				{
					$this->write_log("RegistActivate: Account created: '{$_POST['login']}'");
					$this->template = '<br><font color=red style="size:150%;">"<b>'.$_POST['login'].'</b>" のパスワードを登録しました。</font>';
					$step = 4;
				}
				else
				{
					$this->template = '<br><font color=red>間違っています。</font>'.$this->template;
				}
			}
		}
		$this->template = temp_subs($this->template, "register", $fill);

		$this->template = $this->transitionToString($step).$this->template;
	}

	/**
	 *
	 */
	function update_password()
	{
		$SQL = sprintf("SELECT login FROM accounts_acm WHERE login='%s' AND registkey='%s' AND timelimit>NOW()"
					, mysql_real_escape_string($_POST['login'])
					, mysql_real_escape_string($_GET['key'])
					);
		if (! ($q = mysql_query($SQL)))
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		if (! ($r = mysql_fetch_assoc($q) ))
			//die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
			return FALSE;

		mysql_query("START TRANSACTION");

//-		$accountObj = new account($_POST['login'], $_POST['password']);
//-		$SQL = sprintf("UPDATE accounts SET password='%s' WHERE login='%s'"
//-					, mysql_real_escape_string($accountObj->encrypted/*$_POST['password']*/)
//-					, mysql_real_escape_string($accountObj->login/*$_POST['login']*/)
//-					);
		$SQL = sprintf("UPDATE accounts SET password='%s' WHERE login='%s'"
					, mysql_real_escape_string($this->l2j_encrypt($_POST['password']))
					, mysql_real_escape_string($_POST['login'])
					);
		if (! mysql_query($SQL))
		{
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		}
		$SQL = sprintf("DELETE FROM accounts_acm WHERE login='%s' OR timelimit<NOW()"
					, mysql_real_escape_string($_POST['login'])
					);
		if (! mysql_query($SQL))
		{
			die('<br><b>Error</b>: '.mysql_error().' in <b>'.basename(__FILE__).'</b> on line <b>'.__LINE__.'</b><br>');
		}

		mysql_query("COMMIT");
		return TRUE;
	}
}
?>
