<?php 

	require_once("vk/VK.php");
	require_once("vk/VKException.php");
	$vk = new VK($C->VK_APPID, $C->VK_SECRET);
	$callbackurl = $C->SITE_URL.'oauthvkData';

	if ( isset($_REQUEST['code'])) {
		
		if (isset($_SESSION['vk_token'])) {
			$access_token = $_SESSION['vk_token'];
		} else {

			$vk_token = $vk->getAccessToken($_REQUEST['code'], $callbackurl);

			$_SESSION['vk_token'] = $vk_token;
			$access_token = $_SESSION['vk_token'];			
		}

		$result = $vk->api('getProfiles', array(
			'uids' => $access_token['user_id'],
			'fields' => 'uid, first_name, last_name, nickname, screen_name, photo_big, gender',
		));

		$user_info = $result['response'][0];

		extract($user_info);
		
		$r = $this->db1->query("SELECT username FROM users WHERE auth_id='".$uid."' AND auth='vk'");
		
		if (!($obj = $db2->fetch_object($r))) {
			$code = uniqueCode(11, 1, 'users', 'code');
			$vk_pass = getCode(10,1);
			
			$salt = md5(uniqid(rand(), true));
			$hash = hash('sha512', $salt.$vk_pass);
			$ip	= $this->db1->escape( ip2long($_SERVER['REMOTE_ADDR']) );
		
			$vk_email = $code.'@'.$C->DOMAIN_EMAIL_VK;
			$vk_id = $uid;
			$vk_first_name = $this->db1->e($first_name);
			$vk_last_name = $this->db1->e($last_name);
			$vk_username = $this->db1->e($screen_name);
			
			$numu1 = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$vk_username."'");
			$numu2 = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$vk_username."'");
			$numu3 = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$vk_username."'");
			$numu = $numu1 + $numu2 + $numu3;
			if ($numu != 0) $vk_username = $vk_username.''.($numu + 1);
			
			$vk_username = $this->db1->e($vk_username);	
			
			$r = $this->db1->query("INSERT INTO users SET code='".$code."', password='" . $hash . "', salt='" . $salt . "', auth='vk', username='".$vk_username."', auth_id='".$vk_id."', firstname='".$vk_first_name."', lastname='".$vk_last_name."', email='".$vk_email."', registerdate='" . time() . "', ipregister='" . $ip . "'");
			
		} else {
			$vk_username = $obj->username;
		}
		$this->user->loginSocial($vk_username,'vk');
		$this->redirect($C->SITE_URL);

	} else {
		$authorize_url = $vk->getAuthorizeURL('photos,wall', $callbackurl);
		$this->redirect($C->SITE_URL.'oauthvk');
		
	}

?>