<?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;
  var $DEBUG;
  protected $dispatcher = null;
  
  public function __construct()
  {
  	$this->dispatcher = $GLOBALS['dispatcher'];
  }


  /**
   * 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 = '')
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.init', array('user' => $user, 'password' => $pass, 'host' => $serveur, 'db' => $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()
  {

  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.connect'));
  	 
    $this->DB_LINK = @mysql_connect($this->DB_HOST, $this->DB_USER, $this->DB_PASS) or die($this->DBError(_t('divers','sql_connect_failed')));
    $this->DBSelectDB();

    if(defined('MOD_DEBUG') && MOD_DEBUG == true && isset($GLOBALS['Dbg'])) {
      global $Dbg;

      // $Dbg->queryRel('Connecting to <i>'.SQL.'</i> DATABASE [<b>'.$this->DB_NAME.'</b>] dns: '.$this->DB_USER.':'.$this->DB_PASS.'@'.DB_HOST);
      $Dbg->stopTimer();
    }

    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()
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.selectDB'));
    mysql_select_db($this->DB_NAME, $this->DB_LINK) or die($this->DBError(_t('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 $query : requête provoquant l'erreur
   * @return boolean
   */
  function DBError($message_err, $query = -1)
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.error'));
  	
    $erreur = $message_err . "<br />[<em> error n° " . @mysql_errno() . " : " . @mysql_error() . "</em> ]<br />\n\n";
    if ($query != -1) {
      $this->_logDbError($query);
      $erreur .= "SQL query : $query<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 $query : requête SQL
   * @param string $returnid : Si $returnid==1 ==> renvoie last_id()
   * @return integer || boolean : $result last_id()
   */

  function DBInsert ($query, $returnid = -1)
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.insert', array('query' => $query, 'lastid' => $returnid)));
  	
    if (!($this->RESULT = $this->DBQuery($query))) 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())) {
        $query = "SELECT LAST_INSERT_ID() as last_id";
        $res = $this->DBQuery($query);
      } 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 $query : requête SQL
   * @return boolean : $result
   */
  function DBQuery ($query)
  {

  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.query', array('query' => $query)));
  	
    if(defined('MOD_DEBUG') && MOD_DEBUG == true && isset($GLOBALS['Dbg'])) {
      global $Dbg;

      $this->_logDbQuery($query);
      $Dbg->stopTimer();
      $Dbg->query($query);
      $Dbg->stopTimer();
    }
    $this->RESULT = mysql_query($query, $this->DB_LINK) or die($this->DbError(_t('divers','sql_query_failed'), $query));

    return $this->RESULT;
  }

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

  function DBSelect ($query, $fetch = 'ASSOC')
  {

  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.select', array('query' => $query, 'type' => $fetch)));
  	
    if (!($this->RESULT = $this->DBQuery($query))) {
      @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 $input
   * @return string/array : $output
   */

  function DBescape ($input)
  {

  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'dbconnector.escape', array('data' => $input)), $input);
  	$input = $r->getReturnValue();
  	
    if(is_array($input)) {

      $output = array();
      
      foreach ($input as $key => $value) {
        if(is_string($value)) {
          if (get_magic_quotes_gpc()) $value=stripslashes($value);
          $output[$key] = mysql_real_escape_string($value);
        } else {
          $output[$key] =  $value;
        }
      }
    } else {
      
      // it is a simple string
      if(is_string($input)) {
        if (get_magic_quotes_gpc()) $input=stripslashes($input);
        $output = mysql_real_escape_string($input);
      } else {
        $output =  $input;
      }
    }
    return $output;
     
  }

  /**
   * mysql::DBaffectedRow()
   * Retourne le nombre d'enregistrements affecté par la dernière requête
   *
   * @access public
   * @return integer : $res
   */
  function DBaffectedRow()
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.affected_rows'));
  	
    $res = mysql_affected_rows();
    return $res;
  }

  /**
   * _logDbQuery()
   * @access private
   * @param string $q
   * @return void
   */
  function _logDbQuery($q)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'dbconnector.log_query', array('query' => $q)), $q);
  	$q = $r->getReturnValue();
  	
    if(defined('SQL_LOG_DEBUG') && SQL_LOG_DEBUG == 1) {

      $q = str_replace(array("\r", "\n", "\t"),"",$q);
      logfile(LOG_SQL_QUERIES, array($q, get_class()));

    }
  }

  /**
   * _logDbError()
   * @access private
   * @param string $q
   * @return void
   */
  function _logDbError($q)
  {
  	// Filter data event + return value
  	$r = $this->dispatcher->filter(new sfEvent($this, 'dbconnector.log_error', array('query' => $q)), $q);
  	$q = $r->getReturnValue();
  	
    $q = str_replace(array("\r", "\n", "\t"),"",$q);
    logfile(LOG_SQL_ERRORS, array($q, $_SERVER["SCRIPT_NAME"], get_class()));
  }
  /**
   * mysql::DBclose()
   * Retourne le nombre d'enregistrements affecté par la dernière requête
   *
   * @access public
   * @param string $query : requête SQL
   * @return boolean : $result
   */
  function DBClose()
  {
  	// Notify the end of the current method
  	$this->dispatcher->notify(new sfEvent($this, 'dbconnector.close'));
  	
    @mysql_close();
  }
}

?>