<?php
require("twitter/twitteroauth.php");

if (!empty($_GET['oauth_verifier']) && !empty($_SESSION['oauth_token']) && !empty($_SESSION['oauth_token_secret'])) {

	$twitter = new TwitterOAuth($C->TW_APPID, $C->TW_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
	$accessToken = $twitter->getAccessToken($_REQUEST['oauth_verifier']);
	
	if($twitter->http_code != 200) {
		session_destroy();
		die('Ups. Looks like there was an error.');
	}
	
	unset($_SESSION['oauth_token']);
	unset($_SESSION['oauth_token_secret']);
	
	$connection = new TwitterOAuth($C->TW_APPID, $C->TW_SECRET, $accessToken['oauth_token'], $accessToken['oauth_token_secret']);
	$user_info = $connection->get('account/verify_credentials');
	
	if($connection->http_code != 200) {
		session_destroy();
		die('Ups. Looks like there was an error.');
	}

    if (isset($user_info->error)) {
        header('Location: '.$C->SITE_URL.'oauthtwitter');
    } else {
		
		$r = $this->db1->query("SELECT username FROM users WHERE auth_id='".$user_info->id."' AND auth='twitter'");
		if (!($obj = $db2->fetch_object($r))) {
			$code = uniqueCode(11, 1, 'users', 'code');
			$tw_pass = getCode(10,1);
			
			$salt = md5(uniqid(rand(), true));
			$hash = hash('sha512', $salt.$tw_pass);
			$ip	= $this->db1->escape( ip2long($_SERVER['REMOTE_ADDR']) );

			$tw_email = $code.'@'.$C->DOMAIN_EMAIL_TW;
			$tw_id = $user_info->id;
			$tw_Name = explode(' ', $user_info->name);

			$tw_first_name = $this->db1->e($tw_Name[0]);
			$tw_last_name = $this->db1->e($tw_Name[1]);
			$tw_twitter = $this->db1->e($user_info->url);
			$tw_username = $user_info->screen_name;
			
			$numu1 = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$tw_username."'");
			$numu2 = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$tw_username."'");
			$numu3 = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$tw_username."'");
			$numu = $numu1 + $numu2 + $numu3;
			if ($numu != 0) $tw_username = $tw_username.''.($numu + 1);
			
			$tw_username = $this->db1->e($tw_username);	
			
			$r = $this->db1->query("INSERT INTO users SET code='".$code."', password='" . $hash . "', salt='" . $salt . "', auth='twitter', username='".$tw_username."', auth_id='".$tw_id."', firstname='".$tw_first_name."', lastname='".$tw_last_name."', email='".$tw_email."', registerdate='" . time() . "', ipregister='" . $ip . "'");
			
		} else {
			$tw_username = $obj->username;
		}
		$this->user->loginSocial($tw_username,'twitter');
		$this->redirect($C->SITE_URL);		
	}

} else {
	$this->redirect($C->SITE_URL.'oauthtwitter');
}
?>