<?php

function ipb_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 a.name,a.email,b.converge_pass_hash AS password,b.converge_pass_salt AS salt
				  FROM ".$values["dbprefix"]."members AS a,".$values["dbprefix"]."members_converge AS b
				  WHERE a.id=b.converge_id";

	$res = mysql_query($sql_query,$conn);

	while($get = mysql_fetch_assoc($res)){
		$vals = array();
		$vals["email"] = $get["email"];
		$vals["username"] = $get["name"];
		$vals["fname"] = $vals["username"];
		$vals["lname"] = "";
		$vals["password"] = $get["password"]."|".$get["salt"]."|ipb";
		$GLOBALS["Member"]->clean();
		$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
	}//while

	mysql_close($conn);
	return true;

}//ipb_init

function ipb_register($values){

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

	$salt     = ipb_generate_salt(5);
	if(!$values["md5"])
	$passhash = ipb_passhash( $salt, md5($values["password"]) );
	else
	$passhash = ipb_passhash( $salt, $values["password"] );

	$vals = array(
		'converge_email'     => $values["email"],
		'converge_joined'    => time(),
		'converge_pass_hash' => $passhash,
		'converge_pass_salt' => str_replace( '\\', "\\\\", $salt )
	);

	$sql_query = ipb_query("INSERT INTO `".$values["dbprefix"]."members_converge` ",$vals);
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));
	$member_id = mysql_insert_id($conn);

	$vals = array (
	'id'					 => $member_id,
	'name'                   => $values["username"],
	'members_l_username'     => strtolower( $values["username"] ),
	'members_display_name'   => $values["username"],
	'members_l_display_name' => strtolower( $values["username"] ),
	'member_login_key'       => ipb_auto_log_in_key(),
	'email'                  => $values["email"],
	'mgroup'                 => 3,
	'posts'                  => 0,
	'joined'                 => time(),
	'ip_address'             => $_SERVER["REMOTE_ADDR"],
	'time_offset'            => 0,
	'view_sigs'              => 1,
	'email_pm'               => 1,
	'view_img'               => 1,
	'view_avs'               => 1,
	'restrict_post'          => 0,
	'view_pop'               => 1,
	'msg_total'              => 0,
	'new_msg'                => 0,
	'coppa_user'             => 0,
	'language'               => "en",
	'members_auto_dst'       => 1,
	'members_editor_choice'  => "std",
	'allow_admin_mails'      => 1,
	'hide_email'             => 1,
	'subs_pkg_chosen'        => 0
	);

	$sql_query = ipb_query("INSERT INTO `".$values["dbprefix"]."members` ",$vals);
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	$vals = array (
		'id' => $member_id,
		'vdirs' => 'in:Inbox|sent:Sent Items'
	);

	$sql_query = ipb_query("INSERT INTO `".$values["dbprefix"]."member_extra` ",$vals);
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	$sql_query = "DELETE FROM `".$values["dbprefix"]."pfields_content` WHERE member_id=".$member_id;
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	$sql_query = "INSERT INTO `".$values["dbprefix"]."pfields_content` (member_id) VALUES ('".$member_id."')";
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	$sql_query = "SELECT cs_value FROM ".$values["dbprefix"]."cache_store
				  WHERE cs_key='stats'";
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));
	$data = mysql_result($res,0);

	$stats = unserialize($data);

	$stats["last_mem_name"] = $values["username"];
	$stats["last_mem_id"] = $member_id;
	$stats["mem_count"] += 1;

	$data = serialize($stats);

	$sql_query = "REPLACE INTO ".$values["dbprefix"]."cache_store (cs_key,cs_value,cs_array)
				  VALUES ('stats','".$data."',1)";
	$res = mysql_query($sql_query,$conn);
	if(!$res)
		die(mysql_error($conn));

	mysql_close($conn);

	return true;

}//ipb_register

function ipb_login($values){

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

	$ipb_values = array(
		"act" => "Login",
		"CODE" => "01",
		"UserName" => $values["username"],
		"PassWord" => $values["password"]
	);

	if($values["remember"])
		$ipb_values["CookieDate"] = "1";

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

	$fp = fsockopen ($host, 80, $errno, $errstr);
	if($fp){
    fputs($fp, "POST ".$ipb_path."index.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

	$client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : getenv('REMOTE_ADDR') );

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

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

	$sql_query = "UPDATE ".$values["dbprefix"]."members SET ip_address = '".$client_ip."'
				  WHERE id='".$member_id."'";
	$d = @mysql_query($sql_query,$conn);
	$sql_query = "UPDATE ".$values["dbprefix"]."sessions SET ip_address = '".$client_ip."'
				  WHERE member_id='".$member_id."'";
	$d = @mysql_query($sql_query,$conn);

	@mysql_close($conn);

	return true;

}//ipb_login

function ipb_logout($values){

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

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

	$info = $GLOBALS["Member"]->info();

	$sql_query = "SELECT id FROM ".$values["dbprefix"]."members
				  WHERE name='".$info["username"]."'";
	$res = mysql_query($sql_query,$conn);
	$member_id = @mysql_result($res,0);

	$sql_query = "DELETE FROM ".$values["dbprefix"]."sessions
				  WHERE member_id='".$member_id."'";
	$d = @mysql_query($sql_query,$conn);

	@mysql_close($conn);

	return true;

}//ipb_logout

function ipb_link($values){

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

}//ipb_link

function ipb_account($values){

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

	if($values["email"]){

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

		$sql_query = "UPDATE ".$values["dbprefix"]."members SET email='".$values["email"]."'
					  WHERE id='".$member_id."'";
		mysql_query($sql_query,$conn);
		$sql_query = "UPDATE ".$values["dbprefix"]."members_converge SET  converge_email='".$values["email"]."'
					  WHERE converge_id='".$member_id."'";
		mysql_query($sql_query,$conn);

	}//if

	if($values["password"]){

		$sql_query = "SELECT id FROM ".$values["dbprefix"]."members
					  WHERE name='".$values["username"]."'";
		$res = mysql_query($sql_query);
		$member_id = @mysql_result($res,0);

		$sql_query = "SELECT converge_pass_salt FROM ".$values["dbprefix"]."members_converge
					  WHERE converge_id='".$member_id."'";

		$res = @mysql_query($sql_query,$conn);
		$salt = @mysql_result($res,0);

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

		$sql_query = "UPDATE ".$values["dbprefix"]."members_converge SET converge_pass_hash = '".$password."'
					  WHERE converge_id='".$member_id."'";
		@mysql_query($sql_query,$conn);

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

	}//if

	@mysql_close($conn);

	return true;

}//ipb_account

function ipb_query($start,$vals){

	$sql_query = $start;
	$sql_query_columns = "(";
	$sql_query_values  = "(";
	while(list($key,$val) = each($vals)){
		$sql_query_columns.= "`".$key."`,";
		$sql_query_values .= "'".mysql_escape_string($val)."',";
	}//while
	$sql_query_columns = rtrim($sql_query_columns,",").")";
	$sql_query_values  = rtrim($sql_query_values,",").")";
	$sql_query.= $sql_query_columns." VALUES ".$sql_query_values;

	return $sql_query;

}//ipb_query

function ipb_auto_log_in_key($len=60){

	$pass = ipb_generate_salt( 60 );
	return md5($pass);

}//ipb_auto_log_in_key

function ipb_generate_salt($len=5){

	$salt = '';

	//srand( (double)microtime() * 1000000 );
	// PHP 4.3 is now required ^ not needed

	for ( $i = 0; $i < $len; $i++ )
	{
		$num   = rand(33, 126);

		if ( $num == '92' )
		{
			$num = 93;
		}

		$salt .= chr( $num );
	}

	return $salt;

}//ipb_generate_salt

function ipb_passhash($salt, $md5_once_password){

	return md5( md5( $salt ) . $md5_once_password );

}//ipb_passhash

?>