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

include("config.inc.php3");

##############################################################
# Database abstraction functions                             #
##############################################################
/*
+ Ici on utilise des connections persistantes histoire de performances
+ session_db_connect() = main_db_connect() car la table des sessions 
et les tables du jeu sont dans la même base
*/
function session_db_connect()
{
	main_db_connect();
}

function main_db_connect()
{
	global $DATABASE, $VG_dbLink, $VG_current_dbString;

	# s'il n'y avait pas de connexion, on se connection
	if (!$VG_dbLink)
	{
    	$VG_dbLink = mysql_connect($DATABASE["host"], 
			$DATABASE["login"],
			$DATABASE["password"]);
	}
	
	if ($VG_current_dbString != "main_name")
	{
		$VG_current_dbString = "main_name";
		mysql_select_db($DATABASE[$VG_current_dbString], $VG_dbLink);
	}
}


function main_db_query($query)
{
	main_db_connect();
 	$status = mysql_query($query);
 	
	if(!$status)
		echo "<b>ERROR</b> while processing query <br>$query<br>";
		
	return $status;
}  

function session_db_query($query)
{
	session_db_connect();	
 	$status = mysql_query($query);
 	
	if(!$status)
		echo "<b>ERROR</b> while processing query <br>$query<br>";
		
	return $status;
}  

function db_fetch_array($result) {
  $r = @mysql_fetch_array($result);
  return $r;
}

function db_num_rows($result) {
  return @mysql_num_rows($result);
}

function db_data_seek($result,$row) {
  return @mysql_data_seek($result,$row);
}

##############
# 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 $debug;
    if (!empty($args)) $args = "&" . $args;
    if (isset($debug)) {
      return "$url?sessid=" . urlencode($this->sessid) . "$args&debug=$debug";
    } else {
      return "$url?sessid=" . urlencode($this->sessid) . "$args";
    }
  }

  # Creates a popup link for the modification of the password but without constructing the link
  function popup_password2($url, $args, $fragment = "") 
  {
    global $GAME_PAGE;
    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 = "")
  {
    global $GAME_PAGE;

    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 = "") {
    global $GAME_PAGE;
    global $debug;
    if (!empty($fragment)) $fragment = "#" . $fragment;
      return "javascript: var tt=window.open('" . 
	$this->url($url, $args) . $fragment . 
	  "','','scrollbars=yes,width=505,height=500,screenX=0,left=0,screenY=0,top=0,resizable=yes');";
  }

  # Same as link but does not display the tag (only the url)
  function link3($url, $args, $fragment = "") 
  {
    global $GAME_PAGE;
    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 $GAME_PAGE;
    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 $GAME_PAGE, $debug;
    if (!empty($fragment)) $fragment = "#" . $fragment;
    if (isset($debug)) {
      return $url . $fragment;
#*      return "$GAME_PAGE?url=". urlencode($url) ."&debug=$debug$fragment";
    } else {
#*      return "$GAME_PAGE?url=". urlencode($url) . "$fragment";
      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;
    if (!empty($fragment)) $fragment = "#" . $fragment;
#*    $page = "http://$HTTP_USER:$HTTP_PWD@" . substr($page, 7, strlen($page));
    $text = "Location: $page?sessid=" . urlencode($this->sessid);
    if (isset($args)) $text = $text . "&$args";
    if (isset($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);
	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
      return false;
    }
  }
  
  # Save session data
  function save() {
    session_db_query("UPDATE Sessions SET MemberId = '$this->memberid', " . 
		     " GuestId = '$this->guestid' " .
		     "WHERE 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;
    # Remove old sessions
    $time = my_local_time() - $SESSION_EXPIRATION_TIME;
    session_db_query("DELETE FROM Sessions WHERE Time < $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);
  }
}

##############################################################
# 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) {
  srand(my_local_time());
  $sess = new Session;
  if (isset($sessid)) {
    # Looking for session
    if ($sess->load($sessid) == false) {
      if($msg) {
	echo "Already an error <br>$msg<br>";
	exit();
      }
      if ($require == 1) {
	$sess->reinit("Session loading failed");
      } else {
	$sess->create_session();
      }
    }
  } else {
    # No session, creating one
    # and redirecting to login screen
    if($msg) {
      echo "Already an error <br>$msg<br>";
      exit();
    }
    if ($require == 1) {
      $sess->reinit("No session, creating one");
    } else {
      $sess->create_session();
    }
  }
  return $sess;
}

function close_page($sess)
{
	$sess->update();
}

##############################################################
# 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);
#}

# send a mail via viralMail API
include($BIB_VIRAL_MAIL);
function generic_mail($email, $subject, $message, $headers)
{
	global $VIRAL_MAIL_SPOOL;
	
	viral_mail($VIRAL_MAIL_SPOOL,$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 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 = "";
}

# Check email and password and return the corresponding member row
function checkmember($NickName, $Password) {
  $prerow = "SELECT Members.Id AS Id FROM Players, Members WHERE MemberId=Members.Id AND NickName='$NickName' AND Password= '$Password'";
  $row = main_db_query($prerow);
  $result = db_fetch_array($row);
  if (isset($result)) {
    $id = $result[Id];
  }
  return $id;
}


# 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($player) {
  $query = main_db_query("SELECT COUNT(*) AS Number FROM Players WHERE Score > $player[Score] OR (Score = $player[Score] AND Time <= '$player[Time]')");
  $result = db_fetch_array($query);
  return $result[Number];
}


# 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) {
  return ereg("^ *([a-z_\.0-9A-Z]|-)+"."@".
	      "([a-z_\.0-9A-Z]|-)+ *$", $email);
}

# 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];
}

?>
