<?php
// +---------------------------------------------+
// |     Copyright  2008 - 2018 weenCompany      |
// |     http://www.weentech.com                 |
// |     This file may not be redistributed.     |
// +---------------------------------------------+

if(!defined('IN_WEENCOMPANY'))
{
        die("File not found!");
}

// ######################### FORGOT PASSWORD FORM ########################
function m12_ForgotPasswordForm($errors)
{
        global $categoryid, $inputsize, $m12_language;

        if($errors)
        {
                foreach($errors as $key => $value)
                {
                        echo $value . '<br /><br />';
                }
        }

        echo '<form name="resetpwform" method="post" action="' . RewriteLink('index.php?categoryid='.$categoryid.'&m12_forgotpwd=1') . '">
        <table width="100%" border="0" cellpadding="0" cellspacing="0">
		<tr>
          <td colspan="2"><input name="thisisweencompany" width="0" hight="0" size="0" style="visibility: hidden"></td>
        </tr>
        <tr>
          <td>' . $m12_language['email'] . '&nbsp;</td>
          <td><input name="m12_email" type="text" size="' . $inputsize . '" /> <input type="submit" name="m12_pwdreset" value="' . strip_tags($m12_language['pwd_reset']) . '" /></td>
        </tr>
        </table>
        </form>';
}



// ########################## REGISTER USER ##########################

function m12_ResetPassword()
{
	global $DB, $mainsettings, $categoryid, $m12_language, $rootpath, $sitedefaultlang, $weenurl;

	// check to see if email address exists
	$email = trim($_POST['m12_email']);

	if (!isEmail($email)){
		$errors[] = $m12_language['unvalid_email'];
		m12_ForgotPasswordForm($errors);
	}else{
		if($user = $DB->query_first("SELECT userid, username, password, email FROM " . TABLE_PREFIX . "users WHERE email = '$email'"))
        {

			require_once($rootpath . 'includes/mail/class.phpmailer.php');

			$mail = new PHPMailer();

			if($mainsettings['email_use_smtp'] == '1')
				$mail->IsSMTP();
			else
				$mail->IsMail();

			$verification_code = md5($user['username'] .WEB_COOKIE_KEY.$user['password']);
			$verification_code_url = $weenurl . 'index.php?lang=' . $sitedefaultlang . '&categoryid=' . $categoryid . '&key='.base64_encode($email).'&sid=' . $verification_code;

			$message   = $user['username'] . ":"  . EMAIL_CRLF  . EMAIL_CRLF . $m12_language['email_message_resetpassword']  . EMAIL_CRLF . EMAIL_CRLF . '<a href="' . $verification_code_url . '" target="_blank">' .$verification_code_url . '</a>';
			
			$mail->Host = $mainsettings['email_smtp_host'];
			$mail->Port = $mainsettings['email_smtp_port'];

			if( $mainsettings['email_smtp_require_auth'] == "1" ) {
				$mail->SMTPAuth = true;
				$mail->Username = $mainsettings['email_smtp_user'];
				$mail->Password = $mainsettings['email_smtp_pass'];
			}

			$mail->From      =  $mainsettings['technicalemail'];
			$mail->FromName      =  $mainsettings['copyrighttext'];
			$mail->AddReplyTo($mainsettings['technicalemail'], $mainsettings['copyrighttext']);   
			$mail->Sender      =  $mainsettings['email_smtp_from'];
				
			$mail->AddAddress($user['email']);
			
			$mail->Subject   = $m12_language['email_subject'];
			$mail->Body      = nl2br($message);

			if($mail->Send()){
				echo $m12_language['password_reset_confirm'];
			}else{
				$errors[] = '<font color="#FF0000"><b>A system error occurred. Email was not sent!</b></font>';
				m12_ForgotPasswordForm($errors);
			}

        }
        else
        {
			$errors[] = $m12_language['email_not_found'] . ' ' . $email;
			m12_ForgotPasswordForm($errors);
        }

	}

} 

function m12_ResetPasswordFinished($key, $sid)
{
	global $DB, $mainsettings, $m12_language, $rootpath;
	$email = base64_decode($key);

	if(isEmail($email) AND isName($sid)){
        if($user = $DB->query_first("SELECT userid, username, password FROM " . TABLE_PREFIX . "users WHERE email = '$email'"))
        {
			if($sid == md5($user['username'] .WEB_COOKIE_KEY.$user['password']))
			{
				$pwd = passwdGen(8);

				$result = $DB->query("UPDATE " . TABLE_PREFIX . "users SET password    = '".md5($pwd)."'							 
														   WHERE userid = '$user[userid]' ");

				if (!isset($result)){
					echo 'An error occurred, please try again!';
				}else{
					require_once($rootpath . 'includes/mail/class.phpmailer.php');

					$mail = new PHPMailer();

					if($mainsettings['email_use_smtp'] == '1')
						$mail->IsSMTP();
					else
						$mail->IsMail();

					$mail->Host =  $mainsettings['email_smtp_host'];
					$mail->Port = $mainsettings['email_smtp_port'];

					if( $mainsettings['email_smtp_require_auth'] == '1' ) {
						$mail->SMTPAuth = true;
						$mail->Username = $mainsettings['email_smtp_user'];
						$mail->Password = $mainsettings['email_smtp_pass'];
					}

					$mail->From      =  $mainsettings['technicalemail'];
					$mail->FromName      =  $mainsettings['copyrighttext'];
					$mail->AddReplyTo($mainsettings['technicalemail'], $mainsettings['copyrighttext']);   
					$mail->Sender      =  $mainsettings['email_smtp_from'];
					
					$mail->Subject  = $m12_language['email_subject'];
					$message        = EMAIL_CRLF. $m12_language['user_name'] .' '.$user['username']. EMAIL_CRLF . EMAIL_CRLF . $m12_language['email_message'] .$pwd. EMAIL_CRLF;
					$mail->Body     = nl2br($message);
					$mail->AddAddress($email);

					if($mail->Send()){
						echo $m12_language['password_reset_success'];
					}else{
						echo  '<font color="#339900"><b>'.$m12_language['user_name'] .' '.$user['username']. '<br>'. $m12_language['email_message'] .$pwd . '</b></font>';
					}

				}

			}else{
				$errors[] = $m12_language['invalid_link'];
				m12_ForgotPasswordForm($errors);
			}
		}else{
			$errors[] = $m12_language['invalid_link'];
			m12_ForgotPasswordForm($errors);
		}

	}else{
		$errors[] = $m12_language['invalid_link'];
		m12_ForgotPasswordForm($errors);
	}

} 




// ########################## REGISTER USER ##########################

function m12_Validation($validationKey)
{
        global $DB, $mainsettings, $m12_language;

        // Regular expression to validate guid
        $regex = "{########-####-####-####-############}";
        $regex = str_replace('#', '[0-9,A-F]', $regex);

        // check to see if validation key exists
        if(preg_match($regex, $validationKey) && $user = $DB->query_first("SELECT * FROM " . TABLE_PREFIX . "users WHERE validationkey = '$validationKey'"))
        {
                if($user['activated'] == 0)
                {
                        $DB->query("UPDATE " . TABLE_PREFIX . "users SET activated = 1 WHERE userid = " . $user['userid']);
                        echo $m12_language['validation_success'];
                }
                else
                {
                        echo $m12_language['already_validated'];
                }
        }
        else
        {
                echo $m12_language['validation_key_not_found'];
        }
} // end validation process


// ########################## EMAIL VALIDATION ##########################

function m12_PrintForm($errors)
{
        global $DB, $categoryid, $rootpath, $inputsize, $m12_language, $m12_settings, $sdlanguage;

        $enablejavascript = $m12_settings['校验方式'];
        $maxusername      = $m12_settings['用户名长度'];
        $maxpassword      = $m12_settings['密码长度'];

		if($m12_settings['关闭注册'] == 1){
			echo '<br />' . $m12_language['registration_turnoff'] . '<br /><br />';	
			
		}else{

        if($enablejavascript == 1)
        {
                include($rootpath . 'modules/m12_registration/javascript.php');
                $javascript = 'onsubmit="return CheckData()"';
        }
        else
        {
                $javascript = '';
        }

        if($errors)
        {
                foreach($errors as $key => $value)
                {
                        echo $value . '<br /><br />';
                }
        }

        echo '<form name="form" method="post" action="' . RewriteLink('index.php?categoryid=' . $categoryid) . '" '.$javascript.'>

        <table width="100%" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td width="120">' . $m12_language['user_name'] . '<font color=red> * </font></td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_username" type="text" maxlength="'.$maxusername.'" size="'.$inputsize.'" /></td>
        </tr>
        <tr>
          <td width="120">' . $m12_language['password'] . '<font color=red> * </font></td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_password" type="password" maxlength="'.$maxpassword.'" size="'.$inputsize.'" /></td>
        </tr>
        <tr>
          <td nowrap="nowrap">' . $m12_language['password_again'] . '<font color=red> * </font></td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_passwordconfirm" type="password" maxlength="'.$maxpassword.'" size="'.$inputsize.'" /></td>
        </tr>
        <tr>
          <td width="120">' . $m12_language['email'] . '<font color=red> * </font></td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_email" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>
        <tr>
          <td nowrap="nowrap">' . $m12_language['email_again'] . '<font color=red> * </font></td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_emailconfirm" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';

	if($m12_settings['显示姓名']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_fullname'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_userfullname" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}
		
	if($m12_settings['显示单位']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_company'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_usercompany" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}

	if($m12_settings['显示地址']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_add'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_useradd" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}

	if($m12_settings['显示邮编']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_postcode'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_userpostcode" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}
	if($m12_settings['显示电话']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_tel'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_usertel" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}
	if($m12_settings['显示传真']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_fax'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_userfax" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}
	if($m12_settings['显示在线联系']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_online'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_useronline" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}
	if($m12_settings['显示网址']){
	echo '
        <tr>
          <td width="120">' . $m12_language['user_website'] . '</td>
          <td style="padding-left: 10px; padding-bottom: 10px;"><input name="m12_userwebsite" type="text" maxlength="58" size="'.$inputsize.'" /></td>
        </tr>';
	}

        if($m12_settings['验证码'] == 1)
        {
                $vvcid = CreateVisualVerifyCode();

                echo '<tr>
               <td width="120"></td>
              <td style="padding-left: 10px; padding-bottom: 10px;"><input type="hidden" name="m12_vvcid" value="' . $vvcid . '"/>
                          <img src="includes/vvc.php?vvcid=' . $vvcid . '"/></td>
          </tr>
			<tr>
			<td colspan="2">' . $sdlanguage['enter_verify_code'] . '</td>
			</tr>
			<tr>
			<td width="120"></td>
			<td style="padding-left: 10px; padding-bottom: 10px;"><input type="text" size="'.$inputsize.'" name="m12_verifycode"/></td>
			</tr>';
        }

    echo '<tr>
          <td colspan="2"><hr size=1 noshade="noshade" /></td>
        </tr>
        <tr>
          <td width="120"></td>
          <td style="padding-left: 10px; padding-bottom: 10px;">
            <input type="submit" name="m12_register" value="' . strip_tags($m12_language['register']) . '" />
            <input type="reset" value="' . strip_tags($m12_language['reset_form']) . '" />
          </td>
        </tr>
        </table>

        </form>';
		
	}
}



// ########################## REGISTER USER ##########################

function m12_RegisterUser()
{
        global $DB, $mainsettings, $categoryid, $m12_language, $m12_settings, $sdlanguage, $rootpath, $sitedefaultlang, $weenurl;

        if($m12_settings['验证码'] == 1)
        {
                $vvcid         = $_POST['m12_vvcid'];
                $code        = $_POST['m12_verifycode'];

                if(!ValidVisualVerifyCode($vvcid, $code))
                {
                        $errors[] = $sdlanguage['incorrect_vvc_code'];
                }
        }

        // check the username
		$username = trim($_POST['m12_username']);

        if(!isName($username))
        {
                $errors[] = $m12_language['enter_alnum_username'];
        }elseif($DB->query_first("SELECT username FROM " . TABLE_PREFIX . "users WHERE username = '$username'"))
        {
                $errors[] = $username . ' ' . $m12_language['username_exists'];
        }

        // check to make sure the password is long enough and of the right format
        if(!isPass($_POST['m12_password']))
        {
                $errors[] = $m12_language['enter_alnum_password'];
        }

        // check to make sure that the password matches the confirmed password.
        if($_POST['m12_password'] != $_POST['m12_passwordconfirm'])
        {
                $errors[] = $m12_language['password_unmatched'];
        }

        // check to make sure they entered a valid email address
        if(!isEmail($_POST['m12_email'])) 
        {
                $errors[] = $m12_language['unvalid_email'];
        }elseif($DB->query_first("SELECT email FROM " . TABLE_PREFIX . "users WHERE email = '$_POST[m12_email]'"))
        {
                $errors[] = $m12_language['email_exists'];
        }

        // check to make sure that the email matches the confirmed email.
        if($_POST['m12_email'] != $_POST['m12_emailconfirm'])
        {
                $errors[] = $m12_language['email_unmatched'];
        }

        // check to see if the email address is banned
        if(m12_EmailBanned($_POST['m12_email']))
        {
                $errors[] = $_POST['m12_email'] . ' ' . $m12_language['email_banned'];
        }

        // register if there are no errors
        if(!$errors)
        {
                if($m12_settings['人工审核'] > 0){
                        $DB->query("INSERT INTO " . TABLE_PREFIX . "users (usergroupid, username, password, email, activated, joindate, userfullname, usercompany, useradd, userpostcode, usertel, userfax, useronline, userwebsite)
                        VALUES (3, '".$username."','".md5($_POST['m12_password'])."','".$_POST['m12_email']."',0,'".time()."', '".$_POST['m12_userfullname']."', '".$_POST['m12_usercompany']."', '".$_POST['m12_useradd']."', '".$_POST['m12_userpostcode']."', '".$_POST['m12_usertel']."', '".$_POST['m12_userfax']."', '".$_POST['m12_useronline']."', '".$_POST['m12_userwebsite']."')");

                        
                        echo $m12_language['activation_required_manual'];
				
                }else if($m12_settings['邮件验证'] > 0)
                {
                        $key = CreateGuid();
						$validateurl = $weenurl . 'index.php?lang=' . $sitedefaultlang . '&categoryid=' . $categoryid . '&m12_val=' . $key;

                        $DB->query("INSERT INTO " . TABLE_PREFIX . "users (usergroupid, username, password, email, activated, validationkey, joindate, userfullname, usercompany, useradd, userpostcode, usertel, userfax, useronline, userwebsite)
                        VALUES (3, '".$username."','".md5($_POST['m12_password'])."','".$_POST['m12_email']."', 0, '$key','".time()."', '".$_POST['m12_userfullname']."', '".$_POST['m12_usercompany']."', '".$_POST['m12_useradd']."', '".$_POST['m12_userpostcode']."', '".$_POST['m12_usertel']."', '".$_POST['m12_userfax']."', '".$_POST['m12_useronline']."', '".$_POST['m12_userwebsite']."')");

						require_once($rootpath . 'includes/mail/class.phpmailer.php');

						$mail = new PHPMailer();

						if($mainsettings['email_use_smtp'] == '1')
							$mail->IsSMTP();
						else
							$mail->IsMail();

						$mail->Host =  $mainsettings['email_smtp_host'];
						$mail->Port = $mainsettings['email_smtp_port'];

						if( $mainsettings['email_smtp_require_auth'] == '1' ) {
							$mail->SMTPAuth = true;
							$mail->Username = $mainsettings['email_smtp_user'];
							$mail->Password = $mainsettings['email_smtp_pass'];
						}

						$mail->From      =  $mainsettings['technicalemail'];
						$mail->FromName      =  $mainsettings['copyrighttext'];
						$mail->AddReplyTo($mainsettings['technicalemail'], $mainsettings['copyrighttext']);   
						$mail->Sender      =  $mainsettings['email_smtp_from'];
						
						$mail->Subject  = $m12_language['email_subject_activation'];
						$message        = EMAIL_CRLF. $m12_language['user_name'] .' '.$username. EMAIL_CRLF . EMAIL_CRLF . $m12_language['email_message_activation']  . EMAIL_CRLF . EMAIL_CRLF . '<a href="' . $validateurl . '" target="_blank">' .$validateurl . '</a>';
						$mail->Body     = nl2br($message);
						$mail->AddAddress(trim($_POST['m12_email']));

						if($mail->Send()){
							echo $m12_language['activation_required'];
						}else{
							$errors[] =  '<font color="#FF0000"><b>A system error occurred. Email was not sent!</b></font>';
							m12_PrintForm($errors);
						}
						
                }
                else
                {
                        $DB->query("INSERT INTO " . TABLE_PREFIX . "users (usergroupid, username, password, email, activated, joindate, userfullname, usercompany, useradd, userpostcode, usertel, userfax, useronline, userwebsite)
                        VALUES (3, '".$username."','".md5($_POST['m12_password'])."','".$_POST['m12_email']."',1,'".time()."', '".$_POST['m12_userfullname']."', '".$_POST['m12_usercompany']."', '".$_POST['m12_useradd']."', '".$_POST['m12_userpostcode']."', '".$_POST['m12_usertel']."', '".$_POST['m12_userfax']."', '".$_POST['m12_useronline']."', '".$_POST['m12_userwebsite']."')");

                        // registration successfull
                        echo $m12_language['register_success'];
                }
        }
        else
        {
                m12_PrintForm($errors);
        }

} // end registration proccess


function m12_EmailBanned($newEmail)
{
        global $DB, $m12_settings;

        $newEmail = trim(strtolower($newEmail));

		$bannedemails = trim($m12_settings['禁止Email地址']);

		if(!$bannedemails) return false;

        $addresses = explode(' ', preg_replace("/[[:space:]]+/", " ", $bannedemails));

        if(count($addresses) > 0)
        {
                foreach ( $addresses as $email )
                {

					if(strtolower($email) == $newEmail){
						return true;
					}else{
                        $email = trim(strtolower(preg_replace('/\./', '\\.', $email)));
						if(preg_match("/".$email."$/i", $newEmail))
						return true;
					}
                }
        }

        return false;
}

// ########################## CALL FUNCTIONS ##########################

$m12_language = GetLanguage(12);

// get settings
$getsettings = $DB->query("SELECT title, value FROM " . TABLE_PREFIX . "modulesettings WHERE moduleid = 12 ORDER BY displayorder");

while($settings = $DB->fetch_array($getsettings))
{
        $m12_settings[$settings['title']] = $settings['value'];
}

$m12_usersystem = $DB->query_first("SELECT name FROM " . TABLE_PREFIX . "usersystems WHERE activated = '1'");

if($userinfo['loggedin'] != 1)
{
        if($m12_usersystem['name'] == 'weenCompany')
        {
                if(isset($_GET['m12_val']))
                {
                        m12_Validation($_GET['m12_val']);
                }
				else if(isset($_GET['key']) && isset($_GET['sid']))
				{
						m12_ResetPasswordFinished(trim($_GET['key']), trim($_GET['sid']));
				}
                else if(isset($_POST['m12_register']))
                {
                        m12_RegisterUser();
                }
                else if(isset($_POST['m12_pwdreset']))
                {
                        m12_ResetPassword();
                }
                else if(isset($_GET['m12_forgotpwd']))
                {
                        m12_ForgotPasswordForm(NULL);
                }
                else
                {
                        m12_PrintForm(NULL);
                }
        }
        else
        {
                // $regpath already has been through RewriteLink in the integration file (or $weenurl added)
                echo '<a href="' . ForumLink(1) . '">' . $m12_language['register_now'] . '</a>';
        }
}
else
{
        echo $m12_language['already_logged_in'] . ' ' . $userinfo['username'] . '<br />
        <a href="' . RewriteLink('index.php?categoryid=' . $categoryid . '&logout=1') . '">' . $m12_language['logout'] . '</a>';
}


unset($m12_language, $m12_usersystem, $m12_settings);

?>