<?php
  
##############################################################################
# generic.inc                                                                #
# Contains generic functions (e.g. database functions, session management)   #
#                                                                            #
# Copyright ViralGames SARL 2000                                             #
##############################################################################

include_once($BIB."bib_db.php3");

function debug($str, $date = "no_date")
{
	global $ARCHIVES_DIR, $SCRIPT_NAME, $VG_DEBUG_THREAD;
	
	if ($date == "no_date")
		$date = date("Y-m-d H:i:s", my_local_time());

	if (empty($VG_DEBUG_THREAD))
		$VG_DEBUG_THREAD = substr(md5(uniqid("")), 0, 8);
	
	$fd = fopen($ARCHIVES_DIR."debug.txt", "a");
	fwrite($fd, $date." > ".$SCRIPT_NAME." > ".$VG_DEBUG_THREAD." > ".$str."\n");
	fclose($fd);
	
}

##############
# Date utils #
##############

# Il y a un décalage horaire entre virtuaVia et l'heure francaise
#(7 heures)
function my_local_time()
{
	global $JETLAG;
	return time()+$JETLAG;
}

# Returns the difference in seconds between the date
# and now. The date is a string with format yyyy-mm-dd hh:mm:ss
function time_diff_now($date) {
  $now = my_local_time();
  $year = intval(strtok($date, "- :"));
  $month = intval(strtok("- :"));
  $day = intval(strtok("- :"));
  $hour = intval(strtok("- :"));
  $minute = intval(strtok("- :"));
  $second = intval(strtok("- :"));
  $old = mktime($hour, $minute, $second, $month, $day, $year);
  return $now - $old;
}

# Returns the difference in seconds between the two dates
# The dates are strings with format yyyy-mm-dd hh:mm:ss
function time_diff($olds, $news) {
  $year = intval(strtok($olds, "- :"));
  $month = intval(strtok("- :"));
  $day = intval(strtok("- :"));
  $hour = intval(strtok("- :"));
  $minute = intval(strtok("- :"));
  $second = intval(strtok("- :"));
  $old = mktime($hour, $minute, $second, $month, $day, $year);

  $year = intval(strtok($news, "- :"));
  $month = intval(strtok("- :"));
  $day = intval(strtok("- :"));
  $hour = intval(strtok("- :"));
  $minute = intval(strtok("- :"));
  $second = intval(strtok("- :"));
  $new = mktime($hour, $minute, $second, $month, $day, $year);

  return $new - $old;
}

#################
# Session class #
#################
class Session {
  # Session Id
  var $sessid;
  # Member Id (if user is a member)
  var $memberid = -1;
  # Guest Id (if user has come through a guest email)
  var $guestid;

  # Add the session id to the URL
  # and the debug variable (this is internally used)
  function url($url, $args) 
  {
    global $SESSION_WITH_COOKIE,$debug;
    if (!empty($args)) $args = "&" . $args;
   
	if(!$SESSION_WITH_COOKIE)
	{
		if (isset($debug)) 
		{
	      return "$url?sessid=" . urlencode($this->sessid) . "$args&debug=$debug";
	    } 
		else 
		{
	      return "$url?sessid=" . urlencode($this->sessid) . "$args";
	    }
	}
	else
	{
		if (isset($debug)) 
		{
	      return "$url?$args&debug=$debug";
	    } 
		else 
		{
			if(!empty($args))
				return "$url?$args";
			else
				return "$url";
	    }
	}
	
  }



  # Creates a popup link for the modification of the password but without constructing the link
  function popup_password2($url, $args, $fragment = "") 
  {
    global $debug;
    if (!empty($fragment)) $fragment = "#" . $fragment;
      return "javascript: var tt=window.open('" . 
	$this->url($url, $args) . $fragment . 
	  "','','scrollbars=yes,width=380,height=300,screenX=10,left=10,screenY=20,top=20,resizable=yes');";
  }


  # creates a popup for the postit
  function popup_postit($url, $args, $fragment = "")
  {
    if (!empty($fragment)) $fragment = "#" . $fragment;
    
	return 	"javascript: var tt=window.open('" . 
			$this->url($url, $args) . $fragment . 
		 	"','','scrollbars=yes,width=300,height=270,screenX=0,left=0,screenY=0,top=0,resizable=yes');";
  }

  

  # return JS string to open a new window, no text arg 
  function popup2($url, $args, $fragment = "", $width = 505, $height = 500, $scrollbar = "yes", $resizable = "yes") {

    if (!empty($fragment)) $fragment = "#" . $fragment;
      return "javascript: var tt=window.open('" . 
	$this->url($url, $args) . $fragment . 
	  "','','scrollbars=".$scrollbar.",width=".$width.",height=".$height.",screenX=0,left=0,screenY=0,top=0,resizable=".$resizable."');";
  }

  # Same as link but does not display the tag (only the url)
  function link3($url, $args, $fragment = "") 
  {
    global $debug;
    if (!empty($fragment)) $fragment = "#" . $fragment;
    if (isset($debug)) 
	{
      return $this->url($url, $args) . $fragment;
    }
	else
	{
      return $this->url($url, $args) . $fragment;
    }
  }


  # Same as link2 but does not display the tag (only the url)
  # ie : link2 + link3
  function link4($url, $args, $fragment = "") 
  {
    global $debug;
    if (!empty($fragment)) $fragment = "#" . $fragment;
    if (isset($debug)) 
	{
      return $this->url2($url, $args) . $fragment;
    }
	else 
	{
      return $this->url2($url, $args) . $fragment;
    } 
  }
  
  # Same as url but with no session id (for reinitialization)
  function url2($url, $args) {
    global $debug;
    if (!empty($args)) $args = "?" . $args;
    if (isset($debug)) {
      return "$url$args&debug=$debug";
    } else {
      return "$url$args";
    }
  }

  # Print the url the result of the post has to be sent to 
  # Add an external debug variable
	function action($url, $fragment = "")
	{
		global $debug;
		
		if (!empty($fragment)) $fragment = "#" . $fragment;
    	if (isset($debug))
    	{
			return $url . $fragment;
	    }
	    else
	    {
			return $url . $fragment;
		}
	}

  # Create an hidden field containing the session id
  # Add an internal debug variable
  function hfield() {
    global $debug;
    return "<input type=\"hidden\" name=\"sessid\" value=\"" .
      urlencode($this->sessid) . "\">";
    if (isset($debug)) {
      return "<input type=\"hidden\" name=\"debug\" value=\"$debug\">";
    }
  }

  # Locally redirect to appropriate page
  # This function has to be called before any output is made !!
  # NOTE : redirections are used only at the server to server level
  # (only the customer's server is redirected and not the user's browser)
  # Add an external (AND internal debug variable??)
  function redirect($page, $args, $fragment = "") {
    global $debug, $HTTP_USER, $HTTP_PWD,$SESSION_WITH_COOKIE;
    if (!empty($fragment)) $fragment = "#" . $fragment;
#*    $page = "http://$HTTP_USER:$HTTP_PWD@" . substr($page, 7, strlen($page));
	if(!$SESSION_WITH_COOKIE)
	{
		$text = "Location: $page?sessid=" . urlencode($this->sessid);
		if (isset($args)) $text = $text . "&$args";
		if (isset($debug)) $text = $text . "&debug=$debug";
	}
	else
	{
		$text = "Location: $page";
		if (!empty($args)) $text = $text . "?$args";
		if (!empty($debug)) $text = $text . "&debug=$debug";
	}
   
    header($text . $fragment);
    exit();
  }

  # Load session data and check validity
  function load($sessid) 
  {
    global $SESSION_EXPIRATION_TIME;
    $prerow = "SELECT * FROM Sessions WHERE SessId = '$sessid'";
    $row = session_db_query($prerow);
    if ($res = db_fetch_array($row)) 
	{
    	# Session exists
      	# Checking validity
      	if($res["Time"] + $SESSION_EXPIRATION_TIME < my_local_time())
		{
			# Session expired
			# Removing from database
			$prerow = "DELETE FROM Sessions WHERE SessId = '$sessid'";
			session_db_query($prerow);
			
			#debug($sessid.":2");
			
			return false;
      	}
		else
		{
			# Session is valid
			# Loading session data
			$this->sessid = $sessid;
			$this->memberid = $res["MemberId"];
			$this->guestid = $res["GuestId"];
			return true;
      	}
    } 
	else
	{
      # Session does not exist
      # Redirecting to login screen
      #debug($sessid.":3");
      
      return false;
    }
  }

  # Save session data
  function save() {
	global $COOKIE_SESSION_NAME,$SESSION_WITH_COOKIE;
    session_db_query("UPDATE Sessions SET MemberId = '$this->memberid', " . 
		     " GuestId = '$this->guestid' " .
		     "WHERE SessId = '$this->sessid'");
	if ($SESSION_WITH_COOKIE)
	{
		setcookie("sessid", $this->sessid);
	}
  }

  # Update session data
  function update() {
    $time = my_local_time();
    $prerow = "UPDATE Sessions SET Time=$time WHERE SessId='$this->sessid'";
    $row = session_db_query($prerow);
  }

  function reinit($msg) {
    global $LOGIN_PAGE;
    $this->create_session();
	if (!defined("WAP"))
	{
	    $this->redirect($LOGIN_PAGE, "msg=" .urlencode($msg));
	}
  }

function create_session()
{
	global $SESSION_EXPIRATION_TIME, $SERVER_NAME;
    
    # Remove old sessions
    $time = my_local_time();
    
    if (mt_rand(0,100) > 98)
    	session_db_query("DELETE FROM Sessions WHERE Time < ".($time - $SESSION_EXPIRATION_TIME));
    
    # Generate unique is which is not in the database
	/*    
    $i = 0;
    do
    {
		$this->sessid = md5(uniqid(rand()));
		$prerow = "SELECT * FROM Sessions WHERE SessId = '$this->sessid'";
		$row = session_db_query($prerow);
		$i++;
	}
	while (($res = db_fetch_array($row)) && $i < 10);
	
    if ($i == 10)
    {
		echo "<b>INTERNAL ERROR</b>:Could not allocate session id<br>";
	} 
    
    # Expiration set to current time + delay
    $time = my_local_time();
    $prerow = "INSERT INTO Sessions (SessId, Time, MemberId, GuestId) ". 
      "VALUES ('$this->sessid', '$time', '-1', '0')";
    $row = session_db_query($prerow);
    */
	    
	$this->sessid = md5(uniqid($SERVER_NAME.mt_rand()));
    session_db_query("INSERT INTO Sessions (SessId, Time, MemberId, GuestId) VALUES ('$this->sessid', '$time', '-1', '0')");
  }

  	# supprime toutes les sessions ayant le même memberid sauf la session en cours
	function clear_similar_sessions()
	{
		if ($this->memberid > 0)
			main_db_query("DELETE FROM Sessions WHERE MemberId='".$this->memberid."' AND SessId != '".$this->sessid."'");
		#debug("DELETE FROM Sessions WHERE MemberId='".$this->memberid."' AND SessId != '".$this->sessid."'");
	}
	
// 1. Si le joueur n'est pas connecté, on regarde si on peut le connecter automatiquement
function auto_connect()
{
	global $HTTP_COOKIE_VARS, $COOKIE_LOGIN, $COOKIE_PWD;
	
	// 1. le joueur n'est pas identifié, et le cookie existe
	if ($HTTP_COOKIE_VARS[$COOKIE_LOGIN] != '' and $this->memberid == -1 )
	{
		// On vérifié le mot de pass
		$query = "SELECT MemberId FROM Players LEFT JOIN Members ON Members.Id=Players.MemberId WHERE Members.Password='".$HTTP_COOKIE_VARS[$COOKIE_PWD]."' AND Players.NickName='".$HTTP_COOKIE_VARS[$COOKIE_LOGIN]."' LIMIT 0,1";
//		echo $query."<br>";
		$member_row = db_fetch_array(main_db_query($query));

		if ($member_row['MemberId'] > 0)
		{
			// mot de passe ok
			$this->memberid = $member_row['MemberId'];
			$this->save();
		}
	}
}

// j'enregistre les coordonnées du joueur
function save_member_cookies($NickName, $Pwd)
{
	global $COOKIE_LOGIN, $COOKIE_PWD, $COOKIE_NAME;

	$expiration = time()+2592000; // date  d'expiration : 30 jours
	setcookie($COOKIE_LOGIN, $NickName, $expiration);
	setcookie($COOKIE_PWD, $Pwd, $expiration);
//	echo "Set cookie : ".$COOKIE_LOGIN.", ".$NickName."<br>";
}

// j'efface les cookies login & pwd du joueur
function remove_member_cookies()
{
	global $COOKIE_NAME;
	$this->save_member_cookies('', '');
	setcookie($COOKIE_NAME, '');
}

}

##############################################################
# Session management functions                               #
##############################################################

# Validate the session at the begining of a page
# sessid is the session id contained in the URL (or passed via a POST)
# require is 1 when authentication is required, 0 otherwise
function open_page($sessid, $require = 0)
{
	$sess = new Session;
	
	# si sessid n'est pas nul
	if ($sessid != "")
	{
    	# si on arrive à charger la session, on la retourne
    	# avant on vérifie si on la met à jour
    	if ($sess->load($sessid))
    	{
    		//debug("sessid existe".print_r($sess, true));
    		return $sess;
    	}
    }

	# il n'a pas de sessid, on lui en crée
	if ($require == 1)
	{
		//debug("require=1 mais il n'a pas de ssesid : ".print_r($sess, true));
		$sess->memberid = -1;
	}
	else
	{
		$sess->create_session();
	}
	
	return $sess;
}


/*function open_page($sessid, $require = 0)
{
	srand(my_local_time());
	$sess = new Session;
	
	// récupération du member via cookie
	//$sess->auto_connect();
	
	if (isset($sessid)) 
	{
		$load_ok = $sess->load($sessid);
	
		# Looking for session
		if ($load_ok == false)
		{
			if($msg) 
			{
				echo "Already an error <br>$msg<br>";
				exit();
			}
			
			if ($require == 1) 
			{
				$sess->reinit("The Session loading failed");
			}
			else
			{
				$sess->create_session();
			}
		}
	}

	
	
	if (!($sess->memberId > 0))
		//$sess->auto_connect();
	
	return $sess;
}*/

function close_page($sess)
{
	global $BIB, $ORIGIN;
	
	$sess->update();
	
	# spécial page vues
	# include($BIB."bib_pages_vues.php3");
}

##############################################################
# Utility functions                                          #
##############################################################

############
# php_self
# permet d'obtenir l'url de la page où on est
function php_self()
{
	global $PHP_SELF,$SERVER_URL;
	
	# on decoupe php_self pour récuperer juste le nom du script
	$aHere = explode("/",$PHP_SELF);
	
	# on retourne l'equivalent de ce qu'il y a dans $MACHIN_PAGE
	# il ne reste plus qu'à comparer pour voir où on est
	return $SERVER_URL.$aHere[count($aHere)-1];
}

# Send an email
# This generic function is used in order to be able to plug
# any email system
#function generic_mail($email, $subject, $message, $headers) {
# Using the default mail function
#  mail($email, $subject, $message, $headers);
#}

# Return the member row for this member (from member id)
function getmember($id) {
  $prerow = "SELECT * FROM Members WHERE Id = '$id'";
  $row = main_db_query($prerow);
  return db_fetch_array($row);
}

# Return the member row for this member (from player id)
function getmember2($id) {
  $prerow = "SELECT * FROM Players WHERE Id = '$id'";
  $row = main_db_query($prerow);
  $player = db_fetch_array($row);
  return getmember($player[MemberId]);
}

# Return the player row for this member
function getplayer($memberid) {
  $prerow = "SELECT * FROM Players WHERE MemberId = '$memberid'";
  $row = main_db_query($prerow);
  return db_fetch_array($row);
}
# Return the playerScores row for this player id
function getplayerscore($playerid, $aDate)
{
	$prerow = "SELECT * FROM PlayerScores WHERE PlayerId = '$playerid' AND Date='".$aDate."'";
	$row = main_db_query($prerow);
	return db_fetch_array($row);
}


# Return the player row from this player id
function getplayer2($playerid) {
  $prerow = "SELECT * FROM Players WHERE Id = '$playerid'";
  $row = main_db_query($prerow);
  return db_fetch_array($row);
}

# cette fonction change la base active. on passe le tableau (type $DATABASE) en parametre
function switchBase($base)
{
	global $VG_dbLink, $VG_current_dbString;
	
	$db = mysql_connect($base["host"], 
						$base["login"],
						$base["password"]);
	
    mysql_select_db($base["main_name"], $db);
    
    /*
    on réaffecte les variables globales de connexions, ainsi
    dans le prochain main_db_query, on refait la connexion sur la base $DATABASE
    qui est le comportement attendu par défaut de main_db_query
    */
    $VG_dbLink = false;
    $VG_current_dbString = "";
}


# Generate a random password
function generatepwd() {
#  srand(my_local_time());
  $pif = rand() % 10 + 1;
  $rowpwd = main_db_query("SELECT * FROM Password WHERE Id = $pif");
  $pwd = db_fetch_array($rowpwd);
  return $pwd[Name];
}

# Return rank of the player in the high scores
function rank($players, $field = "Score", $date = "")
{
	if ($date == "" and $players[Time]<>"")
	{
		$squery = "SELECT COUNT(*) AS Number FROM Players WHERE ".$field." > ".$players[$field]." OR (".$field." = ".$players[$field]." AND Time <= '$players[Time]')";
		$result = db_fetch_assoc(main_db_query($squery));
		return $result['Number'];
	}
	else
	{
		$squery = "SELECT COUNT(*) AS Number FROM PlayerScores WHERE (Date='".$date."') AND (".$field." > ".$players[$field]." OR (".$field." = ".$players[$field]." AND PlayerId < '".$players['PlayerId']."'))";
		$result = db_fetch_assoc(main_db_query($squery));
		return $result['Number']+1;
	}
}


# Return an array of email adresses extracted from the string
function extractemail($email) {
	return split("[,;\n]",$email);
}

# Check whether the email is in the right format
function checkemail($email, $checkLevel = 0) {
	
	$blackListDomain = array(
	'yopmail.com',
	'jetable.org',
	'mail-temporaire.fr',
	'ephemail.com',
	'trashmail.net',
	'kasmail.com',
	'spamgourmet.com',
	'tempomail.com',
	'guerrillamail.com',
	'mytempemail.com',
	'saynotospams.com',
	'tempemail.co.za',
	'mailinator.com',
	'mytrashmail.com',
	'mailexpire.com',
	'maileater.com',
	'spambox.us',
	'guerrillamail.com',
	'10minutemail.com',
	'dontreg.com',
	'filzmail.com',
	'spamfree24.org',
	'brefmail.com',
	'0-mail.com',
	'link2mail.com',
	'DodgeIt.com',
	'dontreg.com',
	'e4ward.com',
	'gishpuppy',
	'guerrillamail.com',
	'haltospam.com',
	'kasmail.com',
	'mailexpire.com',
	'mailEater.com',
	'mailinator.com',
	'mailNull.com',
	'mytrashMail',
	'nobulk.com',
	'nospamfor.us',
	'PookMail.com',
	'shortmail.net',
	'sneakemail.com',
	'spam.la',
	'spambob.com',
	'spambox.us',
	'spamDay.com',
	'spamh0le.com',
	'spaml.com',
	'tempInbox.com',
	'temporaryinbox.com',
	'willhackforfood.biz',
	'willSelfdestruct.com',
	'wuzupmail.net',
	'10minutemail.com'
	);

	
 	$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
 	//on check le format général
	if(eregi($exp,$email)){
	  $domain = strtolower(array_pop(explode("@",$email)));
	  //on check si ce n'est pas une adresse ùmail jetable
	  if(!in_array($domain, $blackListDomain)){
		  //on check si le domain à bien un enregistrement MX lié
		  if(checkdnsrr($domain,"MX")){
		    return true;
		  }else{
		  	debug("Rejected Email : ".$email." - MX non trouvé");
		    return false;
		  }
		}
		else
		{
			debug("Rejected Email : ".$email." - domaine jettable");
	  		return false;
		}

	}else{
		debug("Rejected Email : ".$email." - format");
	  	return false;
	}  
}

# Extracts the date with the format dd/mm/yyyy from a mysql date field
function date_mysql($datefield) {
//	preg_match("/(\d{4})\-(\d{2})\-(\d{2})/i",$datefield,$splittedfield);
ereg("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})",$datefield,$splittedfield);
	return $splittedfield[3]."/".$splittedfield[2]."/".$splittedfield[1];
}

# Extracts the time with the format hh"h"mm from a mysql date field

function time_mysql($datefield) {
//	preg_match("/(\d{2}):(\d{2}):(\d{2})/i",$datefield,$splittedfield);
ereg("([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})",$datefield,$splittedfield);
	return $splittedfield[1]."h".$splittedfield[2];
}

# returns the number of guests the player (from his Id) has invited

function guests_number($playerId)
{
  $row = main_db_query("SELECT COUNT(Id) AS Number FROM Guests WHERE FatherPId='$playerId'");
  $result = db_fetch_array($row); 
  return $result[Number];
}

# retourne la difference de score entre le score actuel et le dernier log 
# ( ou entre le score actuel et 100 si le joueur n'est pas dans la table ScoresLog) 
function delta_score($player_id,$score){
	$last = db_fetch_array(main_db_query("SELECT MAX(NewsId) AS Max FROM ScoresLog")); 
	$log = db_fetch_array(main_db_query("SELECT * FROM ScoresLog WHERE PlayerId=$player_id AND NewsId=$last[Max]"));
	return $score - ( $log ? $log[Score] : 100 );
}

# retourne le nombre de points restant à parier pour un joueur
# excepté une catégorie donnée. Il suffit de ne pas spécifier la categorie
# pour avoir tous les points restant
function pointsBet($PlayerId,$CategoryId)
{
	# pour calculer les points restant à miser, il faut prendre chaque
	# categorie et voir pour chaque categorie combien de points on ete misé
	# SAUF ceux de la categorie où on est puisqu'on est dessus !
	$total = db_fetch_array(main_db_query("SELECT SUM(Amount) AS total FROM Paris WHERE Done='0' AND Paris.PlayerId='".$PlayerId."'"));
	return $total[total];
}

# inscrit la date de dernière connexion dans le Player
# ATTENTION il faut que le PlayerId = MemberId !!!!!!!
function setLastConnect($playerId)
{
	$current_european_date = date("Y-m-d H:i:s", my_local_time());
	
	main_db_query("UPDATE Players SET LastConnect='".$current_european_date."' WHERE Id='".$playerId."'");
}

if (!function_exists('formatString')){
    function formatString($string){
        return stripslashes(htmlentities($string, ENT_QUOTES, 'ISO-8859-1'));
    }

    function formatStringUTF($string){
        return stripslashes(htmlentities($string, ENT_QUOTES, 'UTF-8'));
    }
}
?>
