<?php
ini_set('session.cookie_domain', '.wauhaha.com');
session_start();
error_reporting(0);

ini_set("display_errors", 1);
include("includes/site_info.php");
include_once('functions.php');

require 'includes/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => '132880206758943',
  'secret' => '16d42b51af2920ff3c03f9dbf7c0d5e2'
));

$user = $facebook->getUser();
if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
//    error_log($e);
//	 echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $me = null;
  }
}

if ($me) { 
	$email_id = $me['email'];
}

$_SESSION["facebook_login"] = "no";
$client_ip = $_SERVER["REMOTE_ADDR"]." ".$_SERVER["HTTP_X_FORWARDED_FOR"];

$query="SELECT blacklist_ip from blacklist where blacklist_ip='$client_ip'";
$getIP=mysql_query($query);
$countIP = mysql_num_rows($getIP);
if($countIP>0){
                echo "<script> location.href='$CONST_LINK_ROOT/login.php?error_msg=ip_blacklisted'</script>";
}

if ($_REQUEST['WUsername']){

	$WUsername=trim(form_get('WUsername'));

 	$WPassword=md5(trim(form_get('WPassword')));

} elseif ($_REQUEST['RUsername']){

	$WUsername=trim(form_get('RUsername'));

 	$WPassword=md5(trim(form_get('RPassword')));

} elseif ($email_id) {
	$WUsername="";
 	$WPassword="";

		setcookie ("WUsername_c", $WUsername, time()-3600,  "/", ".wauhaha.com");
		setcookie ("WPassword_c", $WPassword, time()-3600,  "/", ".wauhaha.com");

		$_COOKIE['WUsername_c'] = '';
		$_COOKIE['WPassword_c'] = '';
	
$current_query="SELECT * FROM members WHERE mem_email = '".$email_id."' AND mem_confirm =1";

$current_retval=mysql_query($current_query,$link) or die(mysql_error());

$current_result=mysql_num_rows($current_retval);

if ($current_result == 0) {
	$dob = $me['birthday'];
	$_SESSION["reg_post1"] = '';
	$_SESSION["reg_post2"] = '';
	$_SESSION['reg_post1']['WAuthEmail'] = $me['email'];
	list($_SESSION['reg_post2']['WMonth'], $_SESSION['reg_post2']['WDay'], $_SESSION['reg_post2']['WYear']) = explode("/", $dob);
	$_SESSION['reg_post2']['facebook_uid'] = $user;
	$_SESSION['reg_post2']['WFullname'] = $me['name'];
	echo "<script> location.href='$CONST_LINK_ROOT/register1.php'</script>";
	exit;
} else {
	$current_user = mysql_fetch_object($current_retval);

	$WUsername=$current_user->mem_username;

 	$WPassword=$current_user->mem_password;
	$_SESSION["facebook_login"] = "yes";
}
} elseif ($_COOKIE['WUsername_c']) {

	 $WUsername=trim($_COOKIE['WUsername_c']);

	 $WPassword=md5(trim($_COOKIE['WPassword_c']));

} else {
	$WUsername="";

 	$WPassword="";
}

$query="SELECT * FROM members WHERE mem_username = '$WUsername' AND mem_confirm =1";

$retval=mysql_query($query,$link) or die(mysql_error());

 $result=mysql_num_rows($retval);

if ($result < 1) {
	echo "<script> location.href='$CONST_LINK_ROOT/register1.php'</script>";
}

$query="SELECT *, DATE_ADD(mem_joindate, INTERVAL 30 DAY) as getstart FROM members WHERE mem_username = '$WUsername' AND mem_password = '".$WPassword."' AND mem_confirm =1";

$retval=mysql_query($query,$link) or die(mysql_error());

 $result=mysql_num_rows($retval);

# if no user is found then display error else set the cookie

if ($result < 1) {
	setcookie ("WUsername_c", $WUsername, time()+3600*24*30,  "/", ".wauhaha.com");
	echo "<script> location.href='$CONST_LINK_ROOT/login.php?error_msg=login_error'</script>";

} else {

	$arr_row = mysql_fetch_object($retval);



	if ($arr_row->mem_confirm==0) {

		$error_message=sprintf(LOGIN_ERROR2,$CONST_URL);

		error_page($error_message,GENERAL_USER_ERROR);

	}



    if ($arr_row->mem_suspend=="Y") {

        $error_message=sprintf(LOGIN_ERROR4,$CONST_URL);

        error_page($error_message,GENERAL_USER_ERROR);

    }

	if ($_POST['save']){

		setcookie ("WUsername_c", $WUsername, time()+3600*24*30,  "/", ".wauhaha.com");
		setcookie ("WPassword_c", $WPassword, time()+3600*24*30,  "/", ".wauhaha.com");
	}

	else{

		setcookie ("WUsername_c", $WUsername, time()-3600,  "/", ".wauhaha.com");
		setcookie ("WPassword_c", $WPassword, time()-3600,  "/", ".wauhaha.com");

		$_COOKIE['WUsername_c'] = '';
		$_COOKIE['WPassword_c'] = '';

	}

	$time=time();
	
	$q = "UPDATE members SET timestamp = '$time' WHERE mem_username = '$arr_row->mem_username'";
      mysql_query($q);
	$q = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$arr_row->mem_userid','$arr_row->mem_username', '$time')";
      mysql_query($q);

	$memCount=mysql_query("SELECT * from member_stats where statDate=CURDATE()");
	
	if(mysql_num_rows($memCount) > 0){
		mysql_query("UPDATE member_stats set counter=counter+1 where statDate=CURDATE()");	
	}else{
	mysql_query("INSERT into member_stats set counter=counter+1, statDate=CURDATE()");	
	}

 	$_SESSION['Sess_UserType']=$arr_row->mem_type;

	$_SESSION['Sess_UserName']=$arr_row->mem_username;

	$_SESSION['Sess_UserId']=$arr_row->mem_userid;

	$_SESSION['Sess_LastVisit']=$arr_row->mem_lastvisit;
	
	$_SESSION['Sess_UserSex']=$arr_row->mem_sex;
	
    $_SESSION['lang_id'] = $arr_row->lang_id;
	 
	 $_SESSION['Sess_referCode'] = $arr_row->mem_referCode;

	# update the last visit date

	$lastvisit=date("Y-m-d H:i:s");

	$query="UPDATE members SET mem_lastvisit='$lastvisit' WHERE mem_username = '$WUsername' AND mem_password = '".$WPassword."'";

	$retval=mysql_query($query,$link) or die(mysql_error());

	# special code for prgcomeback.php

	if (isset ($comeback)) {

		$expiredate=mktime (0,0,0,date("m") ,date("d")+3,date("Y"));

		$expiredate=date('Y-m-d H:i:s',$expiredate);

		$query="UPDATE members SET mem_expiredate='$expiredate' WHERE mem_username = '$WUsername' AND mem_password = '".$WPassword."'";

		$retval=mysql_query($query,$link) or die(mysql_error());

	}

}

if (isset($_REQUEST['return_path']) && $_REQUEST['return_path']!='') {
echo "<script> location.href='".$_REQUEST['return_path']."'</script>";
} else {
echo "<script> location.href='$CONST_LINK_ROOT/home.php'</script>";
}


?>