<?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
 * pgSQL data manipulation
 */

class pgsql {
  /*
   * @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;

  /**
   * pgsql::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;
  }

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

  function DBConnexion()
  {
    $this->DB_LINK = @pg_connect('host=' .$this->DB_HOST. ' port=5432 dbname=' . $this->DB_NAME . ' user=' . $this->DB_USER. ' password='  . $this->DB_PASS)
    or die($this->DBError($GLOBALS['lang']['divers']['db_connect_failed']));

    return true;
  }

  /**
   * pgsql::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)
  {
    //pg_set_error_verbosity($this->DB_LINK, PGSQL_ERRORS_VERBOSE);
    $res1 = pg_get_result($this->DB_LINK);

    $erreur = $message_err . "<br />[<em> PostgreSQL error (pg_result_error): " . @pg_result_error($res1). "<br />";
    $erreur.= "(pg_last_error): " . @pg_last_error() . "</em> ]<br />\n";
    if ($requete != -1) {
      $this->_logDbError($requete);
      $erreur .= "$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);
  }

  /**
   * pgsql::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) return $this->_DBgetInsertId($requete);

    return true;
     
  }

  /**
   * pgsql::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;
     
  }

  /**
   * pgsql::_DBgetInsertId()
   * Insertion de données dans la BDD
   *
   * @access private
   * @param string $requete : requête SQL
   * @return integer
   */

  function _DBgetInsertId ($requete)
  {
    $array = explode(" ", $requete);
    $tablename = $array[2];

    if (!($res = $this->DBQuery("SELECT * FROM " . $tablename . " LIMIT 1;"))) return false;

    $id_name = pg_field_name ( $res, 0);
    $seq = $tablename. '_' . $id_name . '_seq';

    $res = $this->DBSelect("SELECT currval('" . $seq . "');");

    return $res[0]['currval'];
     
  }


  /**
   * pgsql::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 = pg_query($this->DB_LINK, $requete) or die($this->DbError($GLOBALS['lang']['divers']['sql_query_failed'], $requete));

    return $this->RESULT;
  }

  /**
   * pgsql::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))) {
      @pg_free_result($this->RESULT);
      return false;
    }
    if ($fetch == 'ARRAY') {
      $i = 0;
      while ($data = @pg_fetch_array($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }
    if ($fetch == 'OBJECT') {
      $i = 0;
      while ($data = @pg_fetch_object($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }
    if ($fetch == 'ASSOC') {
      $i = 0;
      while ($data = @pg_fetch_assoc($this->RESULT)) {
        $table[$i] = $data;
        $i++;
      }
    }

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

  /**
   * pgsql::DBaffectedRow()
   * Retourne le nombre d'enregistrements affecté par la dernière requête
   *
   * @access public
   * @return integer : $res
   */
  function DBaffectedRow()
  {
    $res = pg_affected_rows($this->RESULT);
    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, END_LINE);
    @fclose($fp);
  }

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

?>