<?php
if( isset( $_GET['error'] ) ) {
	$this->redirect($C->SITE_URL);	
}

if( isset( $_GET['code'] ) ) {

	require_once('google/src/apiClient.php'); 
	require_once('google/src/contrib/apiPlusService.php');
	require_once('google/src/contrib/apiOauth2Service.php');
	
	// Google Objects
	$lgoogle = new apiClient();
	$lgoogle->setApplicationName("Friendly Social Network");
	$lgoogle->setClientId($C->GP_CLIENTID);
	$lgoogle->setClientSecret($C->GP_CLIENTSECRET);
	$lgoogle->setRedirectUri($C->SITE_URL.'oauthgplusData');
	$lgoogle->setScopes( array( 'https://www.googleapis.com/auth/plus.me','https://www.googleapis.com/auth/userinfo.email' ) );
	
	$lgoogleplus = new apiPlusService($lgoogle); // For getting user detail from google
	$lgoogleoauth2 = new apiOauth2Service($lgoogle); // For gettting user email from google
	
	if (isset($_SESSION['google_token'])) {
		$lgoogle->setAccessToken($_SESSION['google_token']);
	}

	if (isset($_SESSION['google_token'])) {
		$gplus_access_token = $_SESSION['google_token'];
	} else {
		$google_token = $lgoogle->authenticate();
		$_SESSION['google_token'] = $google_token;
		$gplus_access_token = $_SESSION['google_token'];
	}
	
	//check access token is set or not
	if ( !empty( $gplus_access_token ) ) {
	
		// capture data
		$user_info = $lgoogleplus->people->get('me');
		$user_email = $lgoogleoauth2->userinfo->get(); // to get email
		$user_info['email'] = $user_email['email'];
		
		//if user data get successfully
		if (isset($user_info['id'])){
			
			//var_dump(',', $user_info);
			extract($user_info);
			
			echo($name['givenName'].' - '.$name['familyName'].' - '.$email.' - '.$id.' - '.$displayName.' - '.$gender);
			
			
			
			
			$usersimple = $this->db1->fetch_field("SELECT iduser FROM users WHERE email='".$email."' AND auth<>'gplus'");
			
			if ($usersimple) {
				$D->msg_alert = 'The email, that this Google account is using, is already registered';
				echo('<div style=" font-weight:bold; font-size:15px; margin-top:50px;">'.$D->msg_alert.'</div>');
				echo('<div style="margin-top:50px;"><a href="'.$C->SITE_URL.'">Back to '.$C->SITE_TITLE.'</a></div>');
				session_destroy();
			} else {
				$r = $this->db1->query("SELECT username FROM users WHERE email='".$email."' AND auth='gplus'");
				if (!($obj = $db2->fetch_object($r))) {
					$code = uniqueCode(11, 1, 'users', 'code');
					$gp_pass = getCode(10,1);
					
					$salt = md5(uniqid(rand(), true));
					$hash = hash('sha512', $salt.$gp_pass);
					$ip	= $this->db1->escape( ip2long($_SERVER['REMOTE_ADDR']) );
	
					$gp_id = $id;
					$gp_first_name = $this->db1->e($name['givenName']);
					$gp_last_name = $this->db1->e($name['familyName']);
					$gp_gender = $gender;
					$gp_username = $displayName;
					$gp_username = str_replace(' ','',$gp_username);
					$gp_username = str_replace('.','',$gp_username);
					
					//if the username does not work, use your email
					if (!validateUsername($gp_username)) {
						$newUser = explode('@',$email);
						$gp_username = str_replace('.','',$newUser[0]);
						$gp_username = str_replace('-','',$gp_username);
						$lenun = strlen($gp_username);
						if (strlen($gp_username)<6) $gp_username = $gp_username . getCode(6-$lenun,1);
					}
					
					$numu1 = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$gp_username."'");
					$numu2 = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$gp_username."'");
					$numu3 = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$gp_username."'");
					$numu = $numu1 + $numu2 + $numu3;
					if ($numu != 0) $gp_username = $gp_username.''.($numu + 1);
					
					$gp_username = $this->db1->e($gp_username);				
					
					$gender = 0;
					if ($gp_gender == 'male') $gender = 1;
					if ($gp_gender == 'female') $gender = 2;
					
					$r = $this->db1->query("INSERT INTO users SET code='".$code."', password='" . $hash . "', salt='" . $salt . "', auth='gplus', username='".$gp_username."', auth_id='".$gp_id."', firstname='".$gp_first_name."', lastname='".$gp_last_name."', email='".$email."', registerdate='" . time() . "', ipregister='" . $ip . "', gender=".$gender);
				} else {
					$gp_username = $obj->username;
				}
				$this->user->loginSocial($gp_username, 'gplus');
				$this->redirect($C->SITE_URL);				
			}


		}
		
	}

}


?>