<?php

function vbulletin_init($values){

	set_time_limit(0);

	$GLOBALS["gateway"] = 1;

	$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
	mysql_select_db($values["dbname"],$conn);

	$sql_query = "SELECT username,password,salt,email FROM ".$values["dbprefix"]."user";
	$res = mysql_query($sql_query,$conn);
	while($get = mysql_fetch_assoc($res)){
		$vals = array();
		$vals["email"] = $get["email"];
		$vals["username"] = $get["username"];
		$vals["fname"] = $get["username"];
		$vals["lname"] = "";
		$vals["password"] = $get["password"]."|".$get["salt"]."|vb";
		$GLOBALS["Member"]->values = $vals;
		$mem_id = $GLOBALS["Member"]->create(1);
		if($mem_id && $GLOBALS["settings"]["default_friend"]){
			$GLOBALS["Network"]->add_friend($mem_id,$GLOBALS["settings"]["default_friend"]);
		}//if
		if($mem_id){
			$sql_query = "UPDATE members SET verified='1' WHERE mem_id=".$mem_id;
			$GLOBALS["DB"]->execute($sql_query);
		}//if
	}//while

	mysql_close($conn);
	return true;

}//vbulletin_init

function vbulletin_register($values){

	$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
	mysql_select_db($values["dbname"],$conn);

	$sql_query = "SELECT VERSION()";
	$result    = mysql_query($sql_query,$conn);
    $version   = @mysql_result($result,0);
    $version   = ereg_replace("[^0-9|\.]","",$version);

    if($version >= 4.1){
    	$encoding = extract_encoding("mysql");
        if($encoding){
        	$sql_query = "SET NAMES '".$encoding."'";
        	$result    = mysql_query($sql_query,$conn);
        }//if
    }//if

	$sql_query = "SELECT title FROM ".$values["dbprefix"]."usertitle
				  ORDER BY minposts ASC LIMIT 0,1";
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));
	$title = mysql_result($res,0);

	$values["password"] = stripslashes(html_entity_decode($values["password"]));

	if(!$values["md5"])
		$values["password"] = md5($values["password"]);

	$data["usergroupid"] = "2";
	$data["username"] = stripslashes(html_entity_decode($values["username"]));
	$data["passworddate"] = date("Y-m-d");
	$data["email"] = stripslashes(html_entity_decode($values["email"]));
	$data["usertitle"] = $title;
	$data["joindate"] = "".time();
	$data["lastvisit"] = "".time();
	$data["lastactivity"] = "".time();
	$data["reputation"] = "10";
	$data["reputationlevelid"] = "5";
	$data["options"] = "3159";
	$data["ipaddress"] = $_SERVER['REMOTE_ADDR'];
	$data["languageid"] = "1";
	$data["salt"] = vbulletin_generate_salt(3);
	$data["password"] = md5($values["password"].$data["salt"]);

	$sql_query = "SELECT COUNT(*) FROM ".$values["dbprefix"]."user
				  WHERE username=':username:' OR email=':email:'";
	while(list($k,$v) = each($data)){
		$sql_query = ereg_replace(":".$k.":",$v,$sql_query);
	}//while
	reset($data);
	$res = mysql_query($sql_query,$conn);
	$exists = @mysql_result($res,0);
	if($exists)
		return;

	$sql_query = "INSERT INTO ".$values["dbprefix"]."user
				  (usergroupid,username,password,passworddate,email,usertitle,
				  joindate,lastvisit,lastactivity,reputation,reputationlevelid,
				  options,ipaddress,languageid,salt)
				  VALUES (':usergroupid:',':username:',':password:',':passworddate:',':email:',':usertitle:',
				  ':joindate:',':lastvisit:',':lastactivity:',':reputation:',':reputationlevelid:',
				  ':options:',':ipaddress:',':languageid:',':salt:')";

	while(list($k,$v) = each($data)){
		$sql_query = ereg_replace(":".$k.":",mysql_escape_string($v),$sql_query);
	}//while

	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die($sql_query.":".mysql_error($conn));
	$id = mysql_insert_id($conn);

	$sql_query = "INSERT INTO ".$values["dbprefix"]."userfield (userid)
				  VALUES ('".$id."')";
	mysql_query($sql_query,$conn);

	$sql_query = "INSERT INTO ".$values["dbprefix"]."usertextfield (userid)
				  VALUES ('".$id."')";
	mysql_query($sql_query,$conn);

	$sql_query = "INSERT INTO ".$values["dbprefix"]."passwordhistory (userid,password,passworddate)
				  VALUES ('".$id."','".$data["password"]."','".$data["passworddate"]."')";
	mysql_query($sql_query,$conn);

	$sql_query = "SELECT data FROM ".$values["dbprefix"]."datastore
				  WHERE title='options'";
	$res = mysql_query($sql_query,$conn);
	$data = mysql_result($res,0);

	$options = unserialize($data);

	if ($options['activememberdays'] > 0)
	{
		$sumsql = "SUM(IF(lastvisit >= " . (time() - $options['activememberdays'] * 86400) . ", 1, 0)) AS active,";
	}
	else
	{
		$sumsql = '';
	}

	// get total members
	$sql_query = "SELECT
		$sumsql
		COUNT(*) AS users,
		MAX(userid) AS maxid
		FROM ".$values["dbprefix"]."user";
	$res = mysql_query($sql_query,$conn);
	$members = mysql_fetch_assoc($res);

	// get newest member
	$sql_query = "SELECT userid, username FROM " . $values["dbprefix"] . "user WHERE userid = $members[maxid]";
	$res = mysql_query($sql_query,$conn);
	$newuser = mysql_fetch_assoc($res);

	// make a little array with the data
	$vals = array(
		'numbermembers' => $members['users'],
		'activemembers' => $members['active'],
		'newusername'   => $newuser['username'],
		'newuserid'     => $newuser['userid']
	);

	$sql_query = "REPLACE INTO ". $values["dbprefix"] ."datastore (title, data, unserialize)
				  VALUES ('userstats','".serialize($vals)."','1')";
	$r = mysql_query($sql_query,$conn);

	mysql_close($conn);

	return true;

}//vbulletin_register

function vbulletin_account($values){

	$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
	mysql_select_db($values["dbname"],$conn);

	if($values["password"]){
		$sql_query = "SELECT userid,salt FROM " .$values["dbprefix"]. "user
					  WHERE username='".$values["username"]."'";
		$res = mysql_query($sql_query,$conn);
		$data = @mysql_fetch_assoc($res);
		$salt = $data["salt"];
		$userid = $data["userid"];

		$passhash = md5(md5($values["password"]).$salt);

		$sql_query = "UPDATE " .$values["dbprefix"]. "user SET `password`='".$passhash."'
					  WHERE username='".$values["username"]."'";
		mysql_query($sql_query);

		$sql_query = "UPDATE ".$values["dbprefix"]."passwordhistory
					  SET password='".$passhash."' WHERE userid='".$userid."'";
		mysql_query($sql_query,$conn);

		if(!$values["donotlogin"]){
			vbulletin_logout($values);
			vbulletin_login($values);
		}

	}//if

	if($values["email"]){
		$sql_query = "UPDATE " .$values["dbprefix"]. "user SET `email`='".$values["email"]."'
					  WHERE username='".$values["username"]."'";
		mysql_query($sql_query);
	}//if

	mysql_close($conn);

	return true;

}//vbulletin_account

function vbulletin_login($values){

	$host_details = parse_url($values["url"]);
	$host = $host_details["host"];
	$vbulletin_path = $host_details["path"];
	if(!ereg("/$",$vbulletin_path))
		$vbulletin_path.= "/";

	$vbulletin_values = array(
		"s" => "",
		"do" => "login",
		"forceredirect" => "1",
		"vb_login_md5password" => "",
		"vb_login_md5password_utf" => "",
		"vb_login_username" => $values["username"],
		"vb_login_password" => $values["password"],
		"hs_gateway" => "1"
	);

	$vbulletin_values["cookieuser"] = "1";

	while(list($key,$val) = each($vbulletin_values)){
		$post_string.= $key."=".urlencode($val)."&";
	}//while
	$post_string = rtrim($post_string,"&");

	$fp = fsockopen ($host, 80, $errno, $errstr, 5);
	if($fp){
    fputs($fp, "POST ".$vbulletin_path."login.php HTTP/1.1\r\n");
    fputs($fp, "Host: ".$host."\r\n");
	fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
	fputs($fp, "Content-length: ".strlen($post_string)."\r\n");
	fputs($fp, "User-Agent: ".$_SERVER["HTTP_USER_AGENT"]."\r\n");
	fputs($fp, "Connection: close\r\n\r\n");
	fputs($fp, $post_string."\r\n\r\n");
	$line = "";
	while (!feof($fp)) {
		$line.= fgets ($fp,1024);
	}//while
	fclose ($fp);
	}//if

	$line = ereg_replace("\r","",$line);
	$lines = explode("\n",$line);
	foreach($lines as $header){
		if(eregi("^Set-Cookie",$header)){
			preg_match_all("/^Set-Cookie: ([^=]+)=([^;]+);/",$header,$matches);
			$name   = $matches[1][0];
			$value  = urldecode($matches[2][0]);
			preg_match_all("/expires=([^;]+);/",$header,$matches);
			$expire_string = $matches[1][0];
			if($expire_string)
				$expire = strtotime($expire_string);
			else
				$expire = 0;
			load_cookie($name,$value,$expire);
		}//if
	}//foreach

	return true;

}//vbulletin_login

function vbulletin_generate_salt($length){

	$salt = '';

	for ($i = 0; $i < $length; $i++)
	{
		$salt .= chr(rand(32, 126));
	}

	return $salt;

}//vbulletin_generate_salt

function vbulletin_logout($values){

	$session = $_COOKIE["bbsessionhash"];

	if($session){

		$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
		mysql_select_db($values["dbname"],$conn);
		$sql_query = "DELETE FROM ".$values["dbprefix"]."session WHERE sessionhash='".mysql_escape_string($session)."'";
		mysql_query($sql_query,$conn);
		mysql_close($conn);

	}//if

	while(list($key,$val) = each($_COOKIE)){
		load_cookie("$key","",-1);
	}//while

	return true;

}//vbulletin_logout

function vbulletin_link($values){

	return rtrim($values["url"],"/")."/index.php";

}//vbulletin_link

function vbulletin_delete($values){

	$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
	mysql_select_db($values["dbname"],$conn);

	$sql_query = "SELECT userid FROM " .$values["dbprefix"]. "user
				  WHERE username='".$values["username"]."'";
	$res = mysql_query($sql_query,$conn);
	$userid = @mysql_result($res,0);

	$sql_query = "DELETE FROM " .$values["dbprefix"]. "user
				  WHERE userid='".$userid."'";
	mysql_query($sql_query);

	$sql_query = "DELETE FROM " .$values["dbprefix"]. "userfield
				  WHERE userid='".$userid."'";
	mysql_query($sql_query);

	$sql_query = "DELETE FROM " .$values["dbprefix"]. "usertextfield
				  WHERE userid='".$userid."'";
	mysql_query($sql_query);

	$sql_query = "SELECT data FROM ".$values["dbprefix"]."datastore
				  WHERE title='options'";
	$res = mysql_query($sql_query,$conn);
	$data = mysql_result($res,0);

	$options = unserialize($data);

	if ($options['activememberdays'] > 0)
	{
		$sumsql = "SUM(IF(lastvisit >= " . (time() - $options['activememberdays'] * 86400) . ", 1, 0)) AS active,";
	}
	else
	{
		$sumsql = '';
	}

	// get total members
	$sql_query = "SELECT
		$sumsql
		COUNT(*) AS users,
		MAX(userid) AS maxid
		FROM ".$values["dbprefix"]."user";
	$res = mysql_query($sql_query,$conn);
	$members = mysql_fetch_assoc($res);

	// get newest member
	$sql_query = "SELECT userid, username FROM " . $values["dbprefix"] . "user WHERE userid = $members[maxid]";
	$res = mysql_query($sql_query,$conn);
	$newuser = mysql_fetch_assoc($res);

	// make a little array with the data
	$vals = array(
		'numbermembers' => $members['users'],
		'activemembers' => $members['active'],
		'newusername'   => $newuser['username'],
		'newuserid'     => $newuser['userid']
	);

	$sql_query = "REPLACE INTO ". $values["dbprefix"] ."datastore (title, data, unserialize)
				  VALUES ('userstats','".serialize($vals)."','1')";
	$r = mysql_query($sql_query,$conn);

	mysql_close($conn);
	return true;

}//vbulletin_delete

function vbulletin_custom($values){

	switch($values["type"]){
		case 'photo':
			vbulletin_photo($values);
			break;
	}//switch

}//vbulletin_custom

function vbulletin_photo($values){

	$conn = mysql_connect($values["dbhost"],$values["dbuser"],$values["dbpass"],1);
	mysql_select_db($values["dbname"],$conn);

	$sql_query = "SELECT userid FROM " .$values["dbprefix"]. "user
				  WHERE username='".$values["username"]."'";
	$res = mysql_query($sql_query,$conn);
	$userid = @mysql_result($res,0);

	$sql_query = "DELETE FROM ". $values["dbprefix"] ."customavatar
				  WHERE userid='".$userid."'";
	mysql_query($sql_query);

	if(!$values["file"]){
		return true;
	}//if

	$content = mysql_escape_string(file_get_contents($values["file"]));

	$filesize = filesize($values["file"]);

	$filename = substr($values["file"],strrpos($values["file"],"/")+1);
	list($width,$height) = getimagesize($values["file"]);

	$sql_query = "INSERT INTO ". $values["dbprefix"] ."customavatar (userid,filedata,dateline,filename,visible,filesize,width,height)
				  VALUES ('".$userid."','".$content."','".time()."','".$filename."','1','".$filesize."','".$width."','".$height."')";
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	mysql_close($conn);
	return true;

}//vbulletin_photo

?>