<?php

require_once("yahoo/openid.php");

$yahoo = new LightOpenID($C->YH_DOMAIN_MAIN);

if ($yahoo->validate()) {
	$identity = $yahoo->identity;
	$attributes = $yahoo->getAttributes();
	
	$email = $attributes['contact/email'];
	$name = $attributes['namePerson'];

	$firstSpace = strpos($name,' ');
	if ($firstSpace === false) {
		$lastname = '';
	} else {
		$firstname = substr($name,0,$firstSpace);
		$lastname = substr($name,$firstSpace);
	}

	$username = preg_replace('/[^\00-\255]+/u', '', preg_replace('/\s+/', '', strtolower($firstname . ' ' . $lastname)));
	
	$r = $this->db1->query("SELECT username FROM users WHERE email='".$email."' AND auth='yahoo'");
	
	if (!($obj = $db2->fetch_object($r))) {
		$code = uniqueCode(11, 1, 'users', 'code');
		$yh_pass = getCode(10,1);
		
		$salt = md5(uniqid(rand(), true));
		$hash = hash('sha512', $salt.$yh_pass);
		$ip	= $this->db1->escape( ip2long($_SERVER['REMOTE_ADDR']) );
	
		$yh_email = $email;
		$yh_firstname = $this->db1->e($firstname);
		$yh_lastname = $this->db1->e($lastname);
		$yh_username = $this->db1->e($username);
		$yh_username = str_replace(' ','',$yh_username);
		$yh_username = str_replace('.','',$yh_username);
		
		//if the username does not work, use your email
		if (!validateUsername($yh_username)) {
			$newUser = explode('@',$yh_email);
			$yh_username = str_replace('.','',$newUser[0]);
			$yh_username = str_replace('-','',$yh_username);
			$lenun = strlen($yh_username);
			if (strlen($yh_username)<6) $yh_username = $yh_username . getCode(6-$lenun,1);
		}
		
		$numu1 = $this->db1->fetch_field("SELECT count(iduser) FROM users WHERE username='".$yh_username."'");
		$numu2 = $this->db1->fetch_field("SELECT count(idgroup) FROM groups WHERE url='".$yh_username."'");
		$numu3 = $this->db1->fetch_field("SELECT count(idpage) FROM pages WHERE url='".$yh_username."'");
		$numu = $numu1 + $numu2 + $numu3;
		if ($numu != 0) $yh_username = $yh_username.''.($numu + 1);
		
		$yh_username = $this->db1->e($yh_username);	
		
		$r = $this->db1->query("INSERT INTO users SET code='".$code."', password='" . $hash . "', salt='" . $salt . "', auth='yahoo', username='".$yh_username."', firstname='".$yh_firstname."', lastname='".$yh_lastname."', email='".$yh_email."', registerdate='" . time() . "', ipregister='" . $ip . "'");
		
	} else {
		$yh_username = $obj->username;
	}
	$this->user->loginSocial($yh_username,'yahoo');
	$this->redirect($C->SITE_URL);
}
?>