<?php
/**
 * @package linea21.core
 * @subpackage system
 * @author linea21 <info@linea21.com>
 * @version $id SVN
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * MySQL data manipulation
 */

class mysql {
  /*
   * @parameters
   */
  var $DB_HOST = DB_HOST;
  var $DB_USER = DB_USER;
  var $DB_PASS = DB_PASS;
  var $DB_NAME = DB_NAME;
  var $DB_LINK = "";
  var $DB_ADMINMAIL = DB_ADMINMAIL;
  var $RESULT;

  /**
   * mysql::DBInitialise()
   * Initialisation de la connexion
   *
   * @access public
   * @param string $user : utilisateur base de données
   * @param string $pass : password utilisateur base de données
   * @param string $serveur : serveur de base de données
   * @param string $bdd : nom de la base de données
   * @return boolean
   */

  function DBInitialise($user = '', $pass = '', $serveur = '', $bdd = '')
  {
    if ($user != '') {
      $this->DB_USER = $user;
    }
    if ($pass != '') {
      $this->DB_PASS = $pass;
    }
    if ($serveur != '') {
      $this->DB_HOST = $serveur;
    }
    if ($bdd != '') {
      $this->DB_NAME = $bdd;
    }
    return true;
  }

  /**
   * mysql::DBConnexion()
   * connexion Base de données
   *
   * @access public
   * @param none $
   * @return boolean
   */

  function DBConnexion()
  {
    $this->DB_LINK = @mysql_connect($this->DB_HOST, $this->DB_USER, $this->DB_PASS) or die($this->DBError($GLOBALS['lang']['divers']['sql_connect_failed']));
    $this->DBSelectDB();
    if(strtolower(CHARSET) == 'utf-8') $this->DBQuery("SET NAMES UTF8");
    return true;
  }

  /**
   * mysql::DBSelectDB()
   * Sélection de la Base de données
   *
   * @access public
   * @param none $
   * @return boolean
   */

  function DBSelectDB()
  {
    mysql_select_db($this->DB_NAME, $this->DB_LINK) or die($this->DBError($GLOBALS['lang']['divers']['db_connect_failed']));
    return true;
  }

  /**
   * mysql::DBError()
   * Gestion des erreurs MySQL
   *
   * @access private
   * @param string $message_err : message retourné par la requête
   * @param string $requete : requête provoquant l'erreur
   * @return boolean
   */
  function DBError($message_err, $requete = -1)
  {
    $erreur = $message_err . "<br />[<em> error n° " . @mysql_errno() . " : " . @mysql_error() . "</em> ]<br />\n\n";
    if ($requete != -1) {
      $this->_logDbError($requete);
      $erreur .= "SQL query : $requete<br />\n";
    }
    $date = date("[D d/M/y H:i:s]<br />\n");
    $erreur .= $date;
    $erreur .= "running script :" . $_SERVER["SCRIPT_NAME"] . getHttpParameters(). "<br />";
    if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
      echo $erreur;
    }
    if ($this->DB_ADMINMAIL != -1) @error_log ($erreur, 1, $this->DB_ADMINMAIL);
  }

  /**
   * mysql::DBInsert()
   * Insertion de données dans la BDD
   *
   * @access public
   * @param string $requete : requête SQL
   * @param string $returnid : Si $returnid==1 ==> renvoie last_id()
   * @return integer || boolean : $result last_id()
   */

  function DBInsert ($requete, $returnid = -1)
  {
    if (!($this->RESULT = $this->DBQuery($requete))) return false;
    // Si returnid=1 on renvoie l'id de l'enregistrement
    // A utiliser uniquement si attribut auto_increment
    if ($returnid == 1) {
      if (!(mysql_insert_id())) {
        $requete = "SELECT LAST_INSERT_ID() as last_id";
        $res = $this->DBQuery($requete);
      } else {
        $res = mysql_insert_id();
      }
    } else {
      $res = true;
    }
    return $res;
  }

  /**
   * mysql::DBQuery()
   * effectue une requête en tous genres -UPDATE - DELETE - SELECT
   *
   * @access public
   * @param string $requete : requête SQL
   * @return boolean : $result
   */
  function DBQuery ($requete)
  {
    if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
      $this->_logDbQuery($requete);
    }
    $this->RESULT = mysql_query($requete, $this->DB_LINK) or die($this->DbError($GLOBALS['lang']['divers']['sql_query_failed'], $requete));

    return $this->RESULT;
  }

  /**
   * mysql::DBSelect()
   * Requêtes - SELECT
   *
   * @access public
   * @param string $requete : requête SQL
   * @param string $fetch : renvoie des données, valeur ASSOC (default), ARRAY, OBJECT
   * @return array : $result
   */

  function DBSelect ($requete, $fetch = 'ASSOC')
  {
    if(defined('MOD_DEBUG') && MOD_DEBUG == true) {
      $this->_logDbQuery($requete);
    }
    if (!($this->RESULT = $this->DBQuery($requete))) {
      @mysql_free_result($this->RESULT);
      return false;
    }
    if ($fetch == 'ARRAY') {
      $i = 0;
      while ($data = @mysql_fetch_array($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }
    if ($fetch == 'OBJECT') {
      $i = 0;
      while ($data = @mysql_fetch_object($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }
    if ($fetch == 'ASSOC') {
      $i = 0;
      while ($data = @mysql_fetch_assoc($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }

    if (!isset($table)) $table = 0;
    return $table;
  }

  /**
   * mysql::DBescape()
   * Echappement  des variables
   *
   * @access public
   * @param string $array : données
   * @return array : $array
   */

  function DBescape ($array)
  {

    $final_array = array();

    foreach ($array as $key => $value) {
      if(is_string($value)) {
        if (get_magic_quotes_gpc()) $value=stripslashes($value);
        $final_array[$key] = mysql_real_escape_string($value);
      } else {
        $final_array[$key] =  $value;
      }
    }
    return $final_array;
     
  }

  /**
   * mysql::DBaffectedRow()
   * Retourne le nombre d'enregistrements affecté par la dernière requête
   *
   * @access public
   * @return integer : $res
   */
  function DBaffectedRow()
  {
    $res = mysql_affected_rows();
    return $res;
  }

  /**
   * _logDbQuery()
   * @access private
   * @param string $q
   * @return void
   */
  function _logDbQuery($q)
  {
    $sep = '##';
    $fp = @fopen(LOG_SQL_QUERIES, 'a');
    @fwrite($fp, $q . $sep);
    @fwrite($fp, date('[d-m-y H:i:s]' . $sep)); // date
    @fwrite($fp, get_class() . $sep);
    @fwrite($fp, END_LINE);
    @fclose($fp);
  }

  /**
   * _logDbError()
   * @access private
   * @param string $q
   * @return void
   */
  function _logDbError($q)
  {
    $sep = '##';
    $fp = @fopen(LOG_SQL_ERRORS, 'a');
    @fwrite($fp, $q . $sep);
    @fwrite($fp, date('[d-m-y H:i:s]' . $sep)); // date
    @fwrite($fp, $_SERVER["SCRIPT_NAME"] . getHttpParameters() . $sep);
    @fwrite($fp, get_class() . $sep);
    @fwrite($fp, END_LINE);
    @fclose($fp);
  }
  /**
   * mysql::DBclose()
   * Retourne le nombre d'enregistrements affecté par la dernière requête
   *
   * @access public
   * @param string $requete : requête SQL
   * @return boolean : $result
   */
  function DBClose()
  {
    @mysql_close();
  }
}

?>