<?php
include('include/autoloader.php');
if (isset($_GET['case'])) {
$case = make_safe(xss_clean($_GET['case']));	
} else {
$case = '';	
}
switch ($case) {
case 'twitter';
$consumer_key = $options['users_twitter_consumer_key'];
$consumer_secret = $options['users_twitter_consumer_secret'];
$callbac_url = $options['general_siteurl'].'/social_login.php?case=twitter_auth';
$oauth_callback = str_replace(':/','://',str_replace('//','/',($callbac_url)));
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
	$request_token = $connection->getRequestToken($oauth_callback); //get Request Token
	if(	$request_token)
	{
		$token = $request_token['oauth_token'];
		$_SESSION['request_token'] = $token ;
		$_SESSION['request_token_secret'] = $request_token['oauth_token_secret'];
		
		switch ($connection->http_code) 
		{
			case 200:
				$url = $connection->getAuthorizeURL($token);
				//redirect to Twitter .
		    	header('Location: ' . $url); 
			    break;
			default:
			    header('Location: '.$options['general_siteurl']);
		    	break;
		}

	} else {
		header('Location: '.$options['general_siteurl']);
	}
break;
case 'twitter_auth';
$consumer_key = $options['users_twitter_consumer_key'];
$consumer_secret = $options['users_twitter_consumer_secret'];
if(isset($_GET['oauth_token']))
{
	$connection = new TwitterOAuth($consumer_key, $consumer_secret, $_SESSION['request_token'], $_SESSION['request_token_secret']);
	$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
	if($access_token)
	{
			$connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']);
			$params =array();
			$params['include_entities']='false';
			$content = $connection->get('account/verify_credentials',$params);
			if($content && isset($content->id) && isset($content->screen_name))
			{
				$social_id = $content->id;
				$provider = 'twitter';
				if ($general->check_social_user($social_id,$provider) == 0) {
					$username = $content->screen_name;
					$datetime = time();
					$password = genRandomString(8);
					$encoded_password = hash('sha256', md5($password));
					$activation_code = genRandomString(24);
					$day = date('j');
					$month = date('n');
					$year = date('Y');
					$ip_address = getRealIpAddr();
					$active = 1;
					if (isset($content->profile_image_url) AND !empty($content->profile_image_url)) {
					$filetype = strtolower(substr(strrchr($content->profile_image_url,'.'),1));
					$avatar = 'twitter_'.$social_id.'.'.$filetype;
					$up = file_put_contents('upload/avatars/'.$avatar,file_get_contents($content->profile_image_url));		
					} else {
					$avatar = '';	
					}
					$add = $mysqli->query("INSERT INTO users (username,password,provider,social_id,avatar,activation_code,ip_address,datetime,last_login,day,month,year,active) VALUES ('$username','$encoded_password','twitter','$social_id','$avatar','$activation_code','$ip_address','$datetime','$datetime','$day','$month','$year','$active')");
					if ($add) {
						$user_id = $mysqli->insert_id;
						$_SESSION['media_cms_user'] = $user_id;
						$_SESSION['super_admin'] = 0;
					}
				} else {
					$user = $mysqli->query("SELECT * FROM users WHERE provider='$provider' AND social_id='$social_id' LIMIT 1");
					$row = $user->fetch_assoc();
					$_SESSION['media_cms_user'] = $row['id'];
					$_SESSION['super_admin'] = $row['super_admin'];
				}
				header('Location: '.$options['general_siteurl']); 

			} else {
				header('Location: '.$options['general_siteurl']);
			}
	} else {
	header('Location: '.$options['general_siteurl']);
	}
} else {
header('Location: '.$options['general_siteurl']); 
}
break;
case 'facebook';
include_once("include/facebook/facebook.php");
$appId = $options['users_facebook_app_id']; //Facebook App ID
$appSecret = $options['users_facebook_app_secret']; // Facebook App Secret
$return_url = $options['general_siteurl'];  //return url (url to script)
$homeurls = $options['general_siteurl'].'/social_login.php?case=facebook';  //return to home
$fbPermissions = 'email';  //Required facebook permissions
$homeurl = str_replace(':/','://',str_replace('//','/',($homeurls)));

//Call Facebook API
$facebook = new Facebook(array(
  'appId'  => $appId,
  'secret' => $appSecret

));
$fbuser = $facebook->getUser();
if(!$fbuser){
	$fbuser = null;
	$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
	header('Location: '.$loginUrl); 	
} else {
	$access_token =  $facebook->getAccessToken();
	$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='.$appId.'&client_secret='.$appSecret.'&grant_type=fb_exchange_token&fb_exchange_token='.$access_token;
	$res = file_get_contents($token_url);
	$str = parse_str($res,$output);
	$extended_access_token = $output['access_token'];
	$extended_access_token_expires = $output['expires'];
	$process_tokens = $general->process_tokens($extended_access_token,$extended_access_token_expires);
	$user_profile = $facebook->api('/me?fields=id,email,picture,name');
	$social_id = $user_profile['id'];
	$provider = 'facebook';
	if ($general->check_social_user($social_id,$provider) == 0) {
		$email = $user_profile['email'];
		$username = str_replace(' ','',$user_profile['name']);
		$avatar_url = $user_profile['picture']['data']['url'];
		$datetime = time();
		$password = genRandomString(8);
		$encoded_password = hash('sha256', md5($password));
		$activation_code = genRandomString(24);
		$day = date('j');
		$month = date('n');
		$year = date('Y');
		$ip_address = getRealIpAddr();
		$active = 1;
		if (isset($avatar_url) AND !empty($avatar_url)) {
		$avatar = 'facebook_'.$social_id.'.jpg';
		$up = file_put_contents('upload/avatars/'.$avatar,file_get_contents($avatar_url));		
		} else {
		$avatar = '';	
		}
		$add = $mysqli->query("INSERT INTO users (username,email,password,provider,social_id,avatar,activation_code,ip_address,datetime,last_login,day,month,year,active) VALUES ('$username','$email','$encoded_password','facebook','$social_id','$avatar','$activation_code','$ip_address','$datetime','$datetime','$day','$month','$year','$active')");
		if ($add) {
			$user_id = $mysqli->insert_id;
			$_SESSION['media_cms_user'] = $user_id;
			$_SESSION['super_admin'] = 0;
		}
		} else {
			$user = $mysqli->query("SELECT * FROM users WHERE provider='$provider' AND social_id='$social_id' LIMIT 1");
			$row = $user->fetch_assoc();
			$_SESSION['media_cms_user'] = $row['id'];
			$_SESSION['super_admin'] = $row['super_admin'];
		}
header('Location: '.$options['general_siteurl']); 
}
break;
default;
	
}



?>