<?php
/* 
	Appointment: Завершение регистрации
	File: register.php 
 
*/
if(!defined('MOZG'))
	die('Hacking attempt!');

//Проверяем была ли нажата кнопка, если нет, то делаем редирект на главную
if(!$logged){
	NoAjaxQuery();
	
	//Код безопасности
	$session_sec_code = $_SESSION['sec_code'];
	$sec_code = $_POST['sec_code'];

	//Если код введные юзером совпадает, то пропускаем, иначе выводим ошибку
	if($sec_code == $session_sec_code){
		//Входные POST Данные
		$name = ajax_utf8(textFilter($_POST['name'], false, true));
		$lastname = ajax_utf8(textFilter($_POST['lastname'], false, true));
		$email = ajax_utf8(textFilter($_POST['email'], false, true));
		
		$name = ucfirst($name);
		$lastname = ucfirst($lastname);
		
		$gender = intval($_POST['gender']);
		if($gender < 0 OR $gender > 2) $gender = 0;
		
		$day = intval($_POST['day']);
		if($day < 0 OR $day > 31) $day = 0;
		
		$month = intval($_POST['month']);
		if($month < 0 OR $month > 12) $month = 0;
		
		$year = intval($_POST['year']);
		if($year < 1930 OR $year > 2007) $year = 0;
		
		$country = intval($_POST['country']);
		if($country < 0 OR $country > 10) $country = 0;
		
		$city = intval($_POST['city']);
		if($city < 0 OR $city > 1587) $city = 0;
		
		$_POST['password1'] = ajax_utf8($_POST['password1']);
		$_POST['password2'] = ajax_utf8($_POST['password2']);
		
		$password1 = GetVar($_POST['password1']);
		$password2 = GetVar($_POST['password2']);
		$birthday = $year.'-'.$month.'-'.$day;

		$errors = array();
		
		//Проверка имени
		if(preg_match("/^[a-zA-Zа-яА-Я]+$/", $name) AND strlen($name) >= 2) $errors[] = 0;
		
		//Проверка фамилии
		if(preg_match("/^[a-zA-Zа-яА-Я]+$/", $lastname) AND strlen($lastname) >= 2) $errors[] = 0;

		//Проверка E-mail
		if(preg_match('/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i', $email)) $errors[] = 0;

		//Проверка Паролей
		if(strlen($password1) >= 6 AND $password1 = $password2) $errors[] = 0;

		$allEr = count($errors);

		//Если нет ошибок то пропускаем и добавляем в базу
		if($allEr == 4){
			$check_email = $db->super_query("SELECT COUNT(*) AS cnt FROM `".PREFIX."_users` WHERE email = '{$email}'");
			if(!$check_email['cnt']){
				$md5_pass = md5(md5($password1));
				$profile_group = '5';
				
				if($country > 0 or $city > 0){
					$country_info = $db->super_query("SELECT name FROM `".PREFIX."_country` WHERE id = '".$country."'");
					$city_info = $db->super_query("SELECT name FROM `".PREFIX."_city` WHERE id = '".$city."'");
					
					$country_city = $country_info['name'].'|'.$city_info['name'];
				}
				
				$name_lastname = $name.' '.$lastname;
				
				//Hash ID
				$hid = $md5_pass.md5(md5($_IP));

				$db->query("INSERT INTO `".PREFIX."_users` (email, password, name, lastname, gender, day, month, year, country, city, signup_date, profile_group, hid, country_city, name_lastname, birthday, privacy) VALUES ('{$email}', '{$md5_pass}', '{$name}', '{$lastname}', '{$gender}', '{$day}', '{$month}', '{$year}', '{$country}', '{$city}', '{$server_time}', '{$profile_group}', '{$hid}', '{$country_city}', '{$name_lastname}', '{$birthday}', 'val_msg|1||val_wall1|1||val_wall2|1||val_wall3|1||val_info|1||')");
				$id = $db->insert_id();

				//Устанавливаем в сессию ИД юзера
				$_SESSION['user_id'] = intval($id);

				//Записываем COOKIE
				set_cookie("user_id", intval($id), 365);
				set_cookie("password", md5(md5($password_first)), 365);
				set_cookie("hid", $hid, 365);
				
				//Создаём папку юзера в кеше
				mozg_create_folder_cache("user_{$id}");
				
				//Директория юзеров
				$uploaddir = ROOT_DIR.'/uploads/users/';
	
				@mkdir($uploaddir.$id, 0777);
				@chmod($uploaddir.$id, 0777);
				@mkdir($uploaddir.$id.'/albums', 0777);
				@chmod($uploaddir.$id.'/albums', 0777);

				//Вставляем лог в бд
				$db->query("INSERT INTO `".PREFIX."_log` SET uid = '{$id}', browser = '{$_BROWSER}', ip = '{$_IP}'");

				echo 'ok|'.$id;
			} else
				echo 'err_mail|';
		} else
			echo 'no_val';
	}
	die();
}
?>