<?php

class register_sxExe extends xIExecutor {

	public function main() {
		global $_APP, $_SLEX;
		if(xUser::$cur->isGuest()) {
			if($_APP['register']['open']) {
				$verify = unserialize($_SESSION['verify_py']);
				if($verify['time'] > time() - 900) {
					if(strtolower($verify['code']) == strtolower($_POST['ver'])) {
						try {
							$user = xUser::creat($_POST['username'], $_POST['password'], $_POST['email']);
							// --- 检测是否要验证邮箱 ---
							if($_APP['register']['verify']===false) {
								$user->class = $_APP['register']['group'];
							} else {
								$user->class = $_APP['register']['vgroup'];
								$key = new xKey(true, 11, 32, $user, 1, 0, 3600); 
								// --- 发送邮件 ---
								include_once(__ROOT__.'exts/PHPMailer_5.2.4/class.phpmailer.php');
								$mail = new PHPMailer();
								$mail->CharSet = 'UTF-8';
								$mail->IsSMTP();
								$mail->SMTPAuth = true;
								if($_SLEX['smtp']['ssl']=='1') $mail->SMTPSecure = 'ssl';
								$mail->SetFrom($_SLEX['smtp']['from'], $_SLEX['smtp']['from']);
								$mail->AddReplyTo($_SLEX['smtp']['from'], $_SLEX['smtp']['from']);
								$mail->Port = $_SLEX['smtp']['port'];
								$mail->Host = $_SLEX['smtp']['smtp'];
								$mail->Username = $_SLEX['smtp']['username'];
								$mail->Password = $_SLEX['smtp']['password'];
								$mail->Subject = '【邮箱验证】' . $_SLEX['site']['title'];
								$mail->AltBody = '';
								$mail->MsgHTML('请点击以下链接进行邮箱验证：<a href="http://'.$_SERVER['HTTP_HOST'].'/verify.php?key='.$key->key.'" target="_blank">http://'.$_SERVER['HTTP_HOST'].'/verify.php?key='.$key->key.'</a><br />（如果以上链接无法点击请复制到浏览器进行访问）');
								$mail->AddAddress($user->email, $user->email);
								$mail->Send();
							}
							$user->update();
							// --- AppData ---
							$rootFolder = new xFolder(0, $user);
							xFolder::create('AppData', $user, $rootFolder);
							echo json_encode(array(
								'result' => $user->id,
								'verify' => $_APP['register']['verify']
							));
						} catch(xError $e) {
							if($e->getCode() == xError::ERR_DUP) {
								echo json_encode(array(
									'result' => '0',
									'msg' => '注册失败，用户名或邮箱已存在'
								));
							} else if($e->getCode() == xUser::ERR_BAD_EMAIL) {
								echo json_encode(array(
									'result' => '0',
									'msg' => '无效的邮箱地址'
								));
							} else if($e->getCode() == xUser::ERR_BAD_USERNAME) {
								echo json_encode(array(
									'result' => '0',
									'msg' => '用户名禁止含有特殊字符'
								));
							}
						}
					} else {
						echo json_encode(array(
							'result' => '0',
							'msg' => '验证码不正确'
						));
					}
				} else {
					echo json_encode(array(
						'result' => '0',
						'msg' => '验证码已过期'
					));
				}
			} else {
				echo json_encode(array(
					'result' => '0',
					'msg' => '站点注册被关闭'
				));
			}
		} else {
			echo json_encode(array(
				'result' => xUser::$cur->id
			));
		}
	}

	public function onError($result) {

	}
}

