<?php
require_once("linkedin/linkedin.php");
require_once("linkedin/OAuth.php");

$callback = $C->SITE_URL.'oauthlinkedinData';
$linkedIn = new LinkedIn($C->IN_APIKEY, $C->IN_SECRETKEY, $callback);

if (isset($_REQUEST['oauth_verifier'])) {
	$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];

	$linkedIn->request_token = unserialize($_SESSION['requestToken']);
	$linkedIn->oauth_verifier = $_SESSION['oauth_verifier'];
	$linkedIn->getAccessToken($_REQUEST['oauth_verifier']);

	$_SESSION['oauth_access_token'] = serialize($linkedIn->access_token);
	
	$this->redirect($callback);

	exit;
} else {
	$linkedIn->request_token = unserialize($_SESSION['requestToken']);
	$linkedIn->oauth_verifier = $_SESSION['oauth_verifier'];
	$linkedIn->access_token = unserialize($_SESSION['oauth_access_token']);
}
$response = (array)simplexml_load_string($linkedIn->getProfile("~:(id,first-name,last-name,headline,picture-url)"));

$uid = $response['id'];
$firstname = $response['first-name'];
$lastname = $response['last-name'];
$username = preg_replace('/[^\00-\255]+/u', '', preg_replace('/\s+/', '', strtolower($response['first-name'] . ' ' . $response['last-name'])));

$r = $this->db1->query("SELECT username FROM users WHERE auth_id='".$uid."' AND auth='linkedin'");

if (!($obj = $db2->fetch_object($r))) {
	$code = uniqueCode(11, 1, 'users', 'code');
	$in_pass = getCode(10,1);
	
	$salt = md5(uniqid(rand(), true));
	$hash = hash('sha512', $salt.$in_pass);
	$ip	= $this->db1->escape( ip2long($_SERVER['REMOTE_ADDR']) );

	$in_email = $code.'@'.$C->DOMAIN_EMAIL_IN;
	$in_id = $uid;
	$in_firstname = $this->db1->e($firstname);
	$in_lastname = $this->db1->e($lastname);
	$in_username = $this->db1->e($username);
	$in_username = str_replace(' ','',$in_username);
	$in_username = str_replace('.','',$in_username);
	
	$lenun = strlen($in_username);
	if (strlen($in_username)<6) $in_username = $in_username . getCode(6-$lenun,1);
	
	$numu1 = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$in_username."'");
	$numu2 = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$in_username."'");
	$numu3 = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$in_username."'");
	$numu = $numu1 + $numu2 + $numu3;
	if ($numu != 0) $in_username = $in_username.''.($numu + 1);
	
	$in_username = $this->db1->e($in_username);	
	
	$r = $this->db1->query("INSERT INTO users SET code='".$code."', password='" . $hash . "', salt='" . $salt . "', auth='linkedin', username='".$in_username."', auth_id='".$in_id."', firstname='".$in_firstname."', lastname='".$in_lastname."', email='".$in_email."', registerdate='" . time() . "', ipregister='" . $ip . "'");
	
} else {
	$in_username = $obj->username;
}
$this->user->loginSocial($in_username,'linkedin');
$this->redirect($C->SITE_URL);
?>