<?php

//DB SQLite Class @0-256FC4BE

/*
 * Database Management for PHP
 *
 * Copyright (c) 1998-2000 NetUSE AG
 *                    Boris Erdmann, Kristian Koehntopp
 * Derived from db_mysql.php
 * 
 * MODIFIED FOR PDO_SQLITE
 * by pierpa@nippon.it
 * FREE FOR USE AND MODIFICATION
 * JUST LEAVE MY EMAIL ADDRESS
 *
 * db_sqlite.php
 *
 */ 

class DB_SQLite {
  
  /* public: connection parameters */
  var $DBHost     = "";
  var $DBPort     = 0;
  var $DBSocket   = "";
  var $DBDatabase = "";
  var $DBUser     = "";
  var $DBPassword = "";
  var $Persistent = false;

  /* public: configuration parameters */
  var $Auto_Free     = 1;     ## Set to 1 for automatic mysqli_free_result()
  var $Debug         = 0;     ## Set to 1 for debugging messages.
  var $Seq_Table     = "db_sequence";

  /* public: result array and current row number */
  var $Record   = array();
  var $Row;

  /* public: current error number and error text */
  var $Errno    = 0;
  var $Error    = "";

  /* public: this is an api revision, not a CVS revision. */
  var $type     = "mysql";
  var $revision = "1.2";

  /* private: link and query handles */
  var $Link_ID  = 0;
  var $Query_ID = 0;
  var $Connected = false;

  var $Encoding = "";

  /* public: constructor */
  function DB_Sql($query = "") {
      $this->query($query);
  }

  /* public: some trivial reporting */
  function link_id() {
    return $this->Link_ID;
  }

  function query_id() {
    return $this->Query_ID;
  }

  function try_connect($DBDatabase = "") {
    $this->Query_ID  = 0;
    /* Handle defaults */
    if ("" == $DBDatabase)   $DBDatabase = $this->DBDatabase;
//    $this->Link_ID = @sqlite _open($DBDatabase, 0666, $this->Error);
    try
     {
      $this->Link_ID = new PDO('sqlite:' . $DBDatabase);
     }
    catch(PDOException $e)
     {
      $this->Error = $e->getMessage();
     }
    $this->Connected = $this->Link_ID ? true : false;
    return $this->Connected;
  }

  /* public: connection management */
  function connect($DBDatabase = "") {
    /* Handle defaults */
    if ("" == $DBDatabase)   $DBDatabase = $this->DBDatabase;
    /* establish connection, select database */
    if (!$this->Connected) {
      $this->Query_ID  = 0;    
      //      $this->Link_ID = $this->Persistent ? @sqlite _popen($DBDatabase, 0666, $this->Error) : @sqlite _open($DBDatabase, 0666, $this->Error);
      $this->Error = "";
      try
	   {
        if($this->Persistent)
	     {
	      $this->Link_ID = new PDO('sqlite:' . $DBDatabase,"","",array(PDO::ATTR_PERSISTENT => true));
	     }
        else
	     {
	      $this->Link_ID = new PDO('sqlite:' . $DBDatabase);
	     }
       }
      catch(PDOException $e)
	   {
	    $this->Error = $e->getMessage();
	   }

      if (!$this->Link_ID) {
        $this->halt("sqlite _open('$DBDatabase') failed " . $this->Error);
        return 0;
      }
      $this->Connected = true;
    }
    return $this->Link_ID;
  }


  /* public: discard the query result */
  function free_result() {
    $this->Query_ID = 0;
  }

  /* public: perform a query */
  function query($Query_String) {
    /* No empty queries, please, since PHP4 chokes on them. */
    if ($Query_String == "")
      /* The empty query string is passed on from the constructor,
       * when calling the class without a query, e.g. in situations
       * like these: '$db = new DB_Sql_Subclass;'
       */
      return 0;

    if (!$this->connect()) {
      return 0; /* we already complained in connect() about that. */
    };

    # New query, discard previous result.
    if ($this->Query_ID) {
      $this->free_result();
    }

    if ($this->Debug)
      printf("Debug: query = %s<br>\n", $Query_String);

    //$this->Query_ID = @sqlite _query($this->Link_ID, $Query_String);
    $this->Error = "";
    try
	 {
	  $this->Query_ID = $this->Link_ID->query($Query_String);
     }
    catch(PDOException $e)
     {
      $this->Errno = $this->Link_ID->errorCode();
      $this->Error = $e->getMessage();
      $this->Errors->addError("Database Error: " . $this->Error);
//	  echo $this->Error;
//      echo "<br>\n";
//	  exit;
     }
    $this->Row = 0;

//echo $this->Query_ID->rowCount();
//echo "<br>\n";
//echo $this->Query_ID->columnCount();
//print_r($this->Query_ID);
//echo "<br>\n";
//echo $Query_String;
//echo "<br>\n";

    # Will return nada if it fails. That's fine.
    return $this->Query_ID;
  }

  /* public: walk result set */
  function next_record() {
    if (!$this->Query_ID) 
      return 0;

//    $this->Record = @sqlite _fetch_array($this->Query_ID	, SQLITE _BOTH);
    $this->Record = $this->Query_ID->fetch(PDO::FETCH_BOTH);
    $this->Row   += 1;
//    $this->Errno = sqlite _last_error($this->Link_ID);
    $this->Errno = $this->Link_ID->errorCode();
//    $this->Error = $this->Errno ? sqlite _error_string($this->Errno) : "";
    $this->Error = $this->Link_ID->errorInfo();
    $stat = is_array($this->Record);
    if (!$stat && $this->Auto_Free) {
      $this->free_result();
    }
    return $stat;
  }

  /* public: position in result set */
  function seek($pos = 0) {
//    $status = @sqlite _seek($this->Query_ID, $pos);
//    if ($status) {
      $this->Row = $pos;
//    } else {
//      $this->Errors->addError("Database error: seek($pos) failed -  result has ".$this->num_rows()." rows");
//
//      /* half assed attempt to save the day, 
//       * but do not consider this documented or even
//       * desireable behaviour.
//       */
//      @sqlite _data_seek($this->Query_ID, $this->num_rows());
      $this->Row = $this->num_rows();
//    }
    return true;
  }

  /* public: table locking */
  function lock($table, $mode="write") {
    return false;
  }
  
  function unlock() {
    return false;
  }


  /* public: evaluate the result (size, width) */
  function affected_rows() {
    return false;
  }

  function num_rows() {
//    return @sqlite _num_rows($this->Query_ID);
	return $this->Query_ID->rowCount();
  }

  function num_fields() {
//    return @sqlite _num_fields($this->Query_ID);
    return $this->Query_ID->columnCount();
  }

  /* public: shorthand notation */
  function nf() {
    return $this->num_rows();
  }

  function np() {
    print $this->num_rows();
  }

  function f($Name) {
    if ($this->Record) 
      if (array_key_exists($Name, $this->Record))
        return $this->Record[$Name];
      else
        foreach ($this->Record as $key => $value) 
          if ("." . $Name == substr($key, strlen($key) - strlen($Name) - 1))
            return $value;
    return "";
  }

  function p($Name) {
    print $this->Record[$Name];
  }

  /* public: sequence numbers */
  function nextid($seq_name) {
    $this->connect();
    
    if ($this->lock($this->Seq_Table)) {
      /* get sequence number (locked) and increment */
      $q  = sprintf("select nextid from %s where seq_name = '%s' LIMIT 1",
                $this->Seq_Table,
                $seq_name);

//      $id  = @sqlite_query($this->Link_ID, $q);
//      $res = @sqlite_fetch_array($id);
      try
       {
	    $id = $this->Link_ID->query($q);
       }
      catch(PDOException $e)
       {
        $this->Errno = $this->Link_ID->errorCode();
        $this->Error = $e->getMessage();
        $this->Errors->addError("Database Error: " . $this->Error);
		return 0;
       }
      $res = $id->fetch(PDO::FETCH_BOTH);
      
      /* No current value, make one */
      if (!is_array($res)) {
        $currentid = 0;
        $q = sprintf("insert into %s values('%s', %s)",
                 $this->Seq_Table,
                 $seq_name,
                 $currentid);

//        $id = @sqlite _query($q, $this->Link_ID);
        try
         {
          $id = $this->Link_ID->query($q);
         }
        catch(PDOException $e)
         {
          $this->Errno = $this->Link_ID->errorCode();
          $this->Error = $e->getMessage();
          $this->Errors->addError("Database Error: " . $this->Error);
		  return 0;
         }

      } else {
        $currentid = $res["nextid"];
      }
      $nextid = $currentid + 1;
      $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
               $this->Seq_Table,
               $nextid,
               $seq_name);
//      $id = @sqlite _query($this->Link_ID, $q);
      try
       {
        $id = $this->Link_ID->query($q);
       }
      catch(PDOException $e)
       {
        $this->Errno = $this->Link_ID->errorCode();
        $this->Error = $e->getMessage();
        $this->Errors->addError("Database Error: " . $this->Error);
		return 0;
       }
      $this->unlock();
    } 
    return $nextid;
  }

  function close()
  {
    if ($this->Query_ID) {
      $this->free_result();
    }
    if ($this->Connected && !$this->Persistent) {
//      sqlite _close($this->Link_ID);
      $this->Link_ID = null;
      $this->Connected = false;
    }
  }  

  /* private: error handling */
  function halt($msg) {
    printf("</td></tr></table><b>Database error:</b> %s<br>\n", $msg);
    printf("<b>SQLite Error</b><br>\n");
    die("Session halted.");
  }

  function table_names() {
   return false;
  }
}

//End DB SQLite Class


?>
