<?php

if (!ISSET($__DB)):
        $__DB = "DB SET";

class DB_Sql {
  var $Host     = "localhost";
  var $Database = "";
  var $User     = "root";
  var $Password = "";

  var $Auto_Free     = 0;     ## Set to 1 for automatic mysql_free_result()
  var $Debug         = 0;     ## Set to 1 for debugging messages.
  var $Halt_On_Error = "yes"; ## "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore error, but spit a warning)
  var $Seq_Table     = "db_sequence";

  var $Record   = array();
  var $Row;

  var $Errno    = 0;
  var $Error    = "";

  var $type     = "mysql";
  var $revision = "1.2";

  var $Link_ID  = 0;
  var $Query_ID = 0;

  function DB_Sql($query = "") {
      $this->query($query);
  }

  function link_id() {
    return $this->Link_ID;
  }

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

  function connect($Database = "", $Host = "", $User = "", $Password = "") {
    /* Handle defaults */
    if ("" == $Database)
      $Database = $this->Database;
    if ("" == $Host)
      $Host     = $this->Host;
    if ("" == $User)
      $User     = $this->User;
    if ("" == $Password)
      $Password = $this->Password;

    /* establish connection, select database */
    if ( 0 == $this->Link_ID ) {

      $this->Link_ID = mysql_pconnect($Host, $User, $Password);
      if (!$this->Link_ID) {
        $this->halt("pconnect($Host, $User, \$Password) failed.");
        return 0;
      }

      if (!@mysql_select_db($Database,$this->Link_ID)) {
        $this->halt("cannot use database ".$this->Database);
        return 0;
      }
    }

    return $this->Link_ID;
  }

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

  /* public: perform a query */
  function query($Query_String) {
          GLOBAL $logger;
    /* 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();
    }

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

    $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);
    $this->Row   = 0;
          $this->Errno = mysql_errno();
    $this->Error = mysql_error();

    if (!$this->Query_ID) {
            $this->halt("Invalid SQL: ".$Query_String);
            //$logger->log(SQLLOG, "Invalid SQL: ".$Query_String);
    } else {
            //$logger->log(SQLLOG, $Query_String);
    }

    // Will return nada if it fails. Thats fine.
    return $this->Query_ID;
  }

  /* public: walk result set */
  function next_record() {
    if (!$this->Query_ID) {
      $this->halt("next_record called with no query pending.");
      return 0;
    }

    $this->Record = @mysql_fetch_assoc($this->Query_ID);
    $this->Row   += 1;
    $this->Errno  = mysql_errno();
    $this->Error  = mysql_error();

        $stat = is_array($this->Record);
        if (!$stat && $this->Auto_Free) {
      $this->free();
        }
        return $stat;
  }

  /* public: position in result set */
  function seek($pos = 0) {
    $status = @mysql_data_seek($this->Query_ID, $pos);
    if ($status)
      $this->Row = $pos;
    else {
      $this->halt("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.
       */
      @mysql_data_seek($this->Query_ID, $this->num_rows());
      $this->Row = $this->num_rows;
      return 0;
    }

    return 1;
  }

  /* public: table locking */
  function lock($table, $mode="write") {
    $this->connect();

    $query="lock tables ";
    if (is_array($table)) {
      while (list($key,$value)=each($table)) {
        if ($key == "read" && $key!=0) {
          $query.="$value read, ";
        } else {
          $query.="$value $mode, ";
        }
      }
      $query=substr($query,0,-2);
    } else {
      $query.="$table $mode";
    }
    $res = @mysql_query($query, $this->Link_ID);
    if (!$res) {
      $this->halt("lock($table, $mode) failed.");
      return 0;
    }
    return $res;
  }

  function unlock() {
    $this->connect();

    $res = @mysql_query("unlock tables");
    if (!$res) {
      $this->halt("unlock() failed.");
      return 0;
    }
    return $res;
  }


  /* public: evaluate the result (size, width) */
  function affected_rows() {
    return @mysql_affected_rows($this->Link_ID);
  }

  function num_rows() {
    return @mysql_num_rows($this->Query_ID);
  }

  function num_fields() {
    return @mysql_num_fields($this->Query_ID);
  }

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

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

  function f($Name) {
    return $this->Record[$Name];
  }

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

        function mysql_insert_id()
        {
                return mysql_insert_id($this->Link_ID);
        }

  /* 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'",
                $this->Seq_Table,
                $seq_name);
      $id  = @mysql_query($q, $this->Link_ID);
      $res = @mysql_fetch_array($id);

      /* 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 = @mysql_query($q, $this->Link_ID);
      } 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 = @mysql_query($q, $this->Link_ID);
      $this->unlock();
    } else {
      $this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
      return 0;
    }
    return $nextid;

  }

  /* public: return table metadata */
  function metadata($table='', $full=false) {
    $count = 0;
    $id    = 0;
    $res   = array();

    /*
     * Due to compatibility problems with Table we changed the behavior
     * of metadata();
     * depending on $full, metadata returns the following values:
     *
     * - full is false (default):
     * $result[]:
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *
     * - full is true
     * $result[]:
     *   ["num_fields"] number of metadata records
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *   ["meta"][field name]  index of field named "field name"
     *   The last one is used, if you have a field name, but no index.
     *   Test:  if (isset($result['meta']['myfield'])) { ...
     */

    // if no $table specified, assume that we are working with a query
    // result
    if ($table) {
      $this->connect();
      $id = @mysql_list_fields($this->Database, $table);
      if (!$id)
        $this->halt("Metadata query failed.");
    } else {
      $id = $this->Query_ID;
      if (!$id)
        $this->halt("No query specified.");
    }

    $count = @mysql_num_fields($id);

    // made this IF due to performance (one if is faster than $count if's)
    if (!$full) {
      for ($i=0; $i<$count; $i++) {
        $res[$i]["table"] = @mysql_field_table ($id, $i);
        $res[$i]["name"]  = @mysql_field_name  ($id, $i);
        $res[$i]["type"]  = @mysql_field_type  ($id, $i);
        $res[$i]["len"]   = @mysql_field_len   ($id, $i);
        $res[$i]["flags"] = @mysql_field_flags ($id, $i);
      }
    } else { // full
      $res["num_fields"]= $count;

      for ($i=0; $i<$count; $i++) {
        $res[$i]["table"] = @mysql_field_table ($id, $i);
        $res[$i]["name"]  = @mysql_field_name  ($id, $i);
        $res[$i]["type"]  = @mysql_field_type  ($id, $i);
        $res[$i]["len"]   = @mysql_field_len   ($id, $i);
        $res[$i]["flags"] = @mysql_field_flags ($id, $i);
        $res["meta"][$res[$i]["name"]] = $i;
      }
    }

    // free the result only if we were called on a table
    if ($table) @mysql_free_result($id);
    return $res;
  }

  /* private: error handling */
  function halt($msg) {

    $this->Error = @mysql_error($this->Link_ID);
    $this->Errno = @mysql_errno($this->Link_ID);

    if ($this->Halt_On_Error == "no")
      return;

    $this->haltmsg($msg);

    if ($this->Halt_On_Error != "report")
      die("Session halted.");
  }

  function haltmsg($msg) {
    printf("</td></tr></table><b><hr>\nDatabase error:</b> %s<br>\n", $msg);
    printf("<b>MySQL Error</b>: %s (%s)<br>\n",
      $this->Errno,
      $this->Error);
  }

  function table_names() {
    $this->query("SHOW TABLES");
    $i=0;
    while ($info=mysql_fetch_row($this->Query_ID))
     {
      $return[$i]["table_name"]= $info[0];
      $return[$i]["tablespace_name"]=$this->Database;
      $return[$i]["database"]=$this->Database;
      $i++;
     }
   return $return;
  }
};


class MyDB extends DB_Sql {
        var $classname = "MyDB";

        Function MyDB() {
                GLOBAL $db, $dbhost, $dbuser, $dbpassword;
                $this->Database = $db;
                $this->Host = $dbhost;
                $this->User = $dbuser;
                $this->Password = $dbpassword;
                $this->Halt_On_Error = _Halt_On_Error;
        }
}

$DB = new MyDB();

ENDIF;
?>
<?

class uni_db
{
        // // Properties.
        // // ------------------------
        //
        // var $ERR;
        // var $DB;
        var $DEBUG = false;
        //
        // // Constructor
        // // ---------------------------
        function uni_db($DB )
        {
                if (!get_class($DB ) )
                {
                        print $this->ERR = "Error while new class construction!";
                        return false;
                }
                $this->DB = $DB;
        }
        // Private checking function
        // -------------------------------------
        function checkData($postData )
        {
                if (!is_array($postData ) )
                {
                        $this->ERR = "Error while inserting!";
                        return false;
                }
                return true;
        }
        // Get
        // -------------------------------------------------------
        function uniGet($tableName, $idArr, $where = "" )
        {
                $sql = "SELECT * FROM $tableName ";
                if (is_array($idArr ) && count($idArr ) > 0 )
                {
                        list($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE $idkey = '$idval' ";
                        $f = 1;
                }
                if ($where != "" )
                {
                        if ($f != 1 )
                        {
                                $sql .= " WHERE ";
                        }
                        $sql .= " $where ";
                }

                $this->debug($sql);
                //echo $sql."<BR>";
                $this->DB->query($sql );
                if ($this->DB->num_rows() == 1 )
                {
                        $this->DB->next_record();
                        return stripSlashesArr($this->DB->Record );
                        // return $this->DB->Record;
                }

                return Array();
        }
        // Get list...
        // ----------------------------------------------------------------
        /**
         * uni_db::uniGetList()
         *
         * @param  $tableName
         * @param  $idField
         * @param  $order
         * @param  $start
         * @param  $count
         * @return array
         */
        function uniGetList($tableName, $idField, $order = "", $start = 0, $count = 999999 )
        {
                $sql = "SELECT * FROM $tableName ";
                if (!empty($order ) )
                {
                        $sql .= " ORDER BY $order ";
                }
                if (!empty($count ) )
                {
                        $sql .= " LIMIT " . intval($start ) . ", " . intval($count ) . " ";
                }
                // echo $sql;
                $this->debug($sql);
                $this->DB->query($sql );

                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        // by SavaJr
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record;
                        else
                                $arr[] = $this->DB->Record;
                }
                return (Array )$arr;
        }
        // Get List Where....
        // ----------------------------------------------------------------
        function uniGetListWhere($tableName, $idField, $where, $order = "", $start = 0, $count = 999999 )
        {
                $sql = "SELECT * FROM $tableName WHERE $where";
                if (!empty($order ) )
                {
                        $sql .= " ORDER BY $order ";
                }
                if (!empty($count ) )
                {
                        $sql .= " LIMIT " . intval($start ) . ", " . intval($count ) . " ";
                }
                // dump ($sql);
                $this->debug($sql);
                $this->DB->query($sql );

                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record;
                        else
                                $arr[] = $this->DB->Record;
                }

                return (Array )$arr;
        }
        // Get count
        // ---------------------------------------------------------
        function uniGetCount($tableName, $where = "", $mysql = "" )
        {
                $sql = "SELECT count(*) AS num ";
                if (!empty($mysql ) )
                {
                        $sql .= $mysql;
                } elseif (!empty($where ) )
                {
                        $sql .= "FROM $tableName WHERE $where ";
                }
                else
                {
                        $sql .= "FROM $tableName";
                }
                $this->debug($sql );
                $this->DB->query($sql );
                $this->DB->next_record();
                return $this->DB->f("num" );
        }
        // Insert something into defined table!
        // ------------------------------------------------------------------------
        // $postData = assoc array, where the keys are the table fields names too.
        // $tableName = "table name!"
        // OUTPUT -> id of new record!
        function uniAdd($postData, $tableName )
        {
                if (!$this->checkData($postData ) )
                {
                        return 0;
                }

                $sql = "INSERT INTO $tableName (";

                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= $key . ", ";
                }

                $sql = substr($sql, 0, -2 );
                $sql .= ") VALUES (";
                reset($postData );

                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= "'" . addslashes($val ) . "', ";
                }
                $sql = substr($sql, 0, -2 );
                $sql .= ") ";
                // echo $sql;
                $this->debug($sql );

                $this->DB->query($sql );
                return $this->DB->mysql_insert_id();
        }
        // Update defined(or all) field(s).
        // -----------------------------------------------------------------------
        // $postData = assoc array, where the keys are the table fields names too.
        // $tableName = "table name"
        // $ID = array ( "idfieldname"=>"idvalue" )
        // OUTPUT -> 1/0!
        function uniUpdate($postData, $tableName, $idArr = "" )
        {
                if (!$this->checkData($postData ) )
                {
                        return false;
                }

                $sql = "UPDATE $tableName SET ";
                while (list($key, $val ) = each($postData ) )
                {
                        $sql .= "$key = '" . addslashes($val ) . "', ";
                }
                $sql = substr($sql, 0, -2 );
                if (is_array($idArr ) )
                {
                        list ($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE  $idkey = '$idval' ";
                }
                // dump($sql);
                $this->debug($sql );
                $this->DB->query($sql );

                if ($this->DB->affected_rows() == 0 && empty($this->DB->error ) )
                {
                        $result = 1;
                }
                else
                {
                        $result = $this->DB->affected_rows();
                }
                return $result;
        }
        // Delete defined(or all) field(s).
        // -------------------------------------------------
        function uniDelete($idArr = "", $tableName )
        {
                $sql = "DELETE FROM $tableName ";

                if (is_array($idArr ) )
                {
                        list($idkey, $idval ) = each($idArr );
                        $sql .= " WHERE $idkey = '$idval' ";
                }
                else
                {
                        $sql .= "WHERE " . $idArr;
                }
                $this->debug($sql );
                $this->DB->query($sql );

                return $this->DB->affected_rows();
        }
        // Get custom SQL (aka custom list)...
        // ---------------------------------------------------------
        function uniSQL($sql, $idField )
        {
                // echo $sql;
                $this->DB->query($sql );
                while ($this->DB->next_record() )
                {
                        // extract($DB->Record, EXTR_OVERWRITE);
                        while (list($key, $val ) = each($this->DB->Record ) )
                        {
                                $this->DB->Record[$key] = stripslashes($this->DB->Record[$key] );
                        }
                        if (!empty($idField ) )
                                $arr[$this->DB->f($idField )] = $this->DB->Record[$idField];
                        else
                        {
                                $arr[] = $this->DB->Record;
                        }
                }
                return (Array )$arr;
        }

        Function stripSlashesArr($arr )
        {
                if (is_array($arr ) )
                        foreach ($arr as $key => $val )
                {
                        $arr[$key] = norm($val );
                }
                return $arr;
        }

        function debug($str )
        {
                if ($this->DEBUG )
                {
                        echo $str;
                }
        }
}

$uni_db = new uni_db($DB);

?>
<?
class basedb {

                var $uni_db;
                var $table;
                var $metadata;
                var $dateFieldNames = Array();
                var $debug = false;

                function basedb($uni_db, $table) {
                        if (is_object ($uni_db) && !empty($table)) {
                                $this->uni_db = $uni_db;
                                $this->table = $table;
                                $this->metaData = $this->uni_db->DB->metadata($this->table, true);

                                foreach ($this->metaData as $key => $val) {
                                                if ($val['type'] == "date" || $val['type'] == "datetime")
                                                        $this->dateFieldNames[] = $val[name];
                                }
                        } else {
                                user_error("Bad parameter passed to constructor");
                                exit;
                        }
                }

                function add($arr = Array()) {
                        if (is_array($arr)) {
                                $arr = $this->_formatDates($arr, "toSQL", true);
                                $arr = $this->_checkFields($arr);
                                $res = $this->uni_db->uniAdd($arr, $this->table);
                        } else {
                                $res = 0;
                        }
                        return $res;
                }

                /**
                 * @return int
                 * @param idArr array
                 * @desc Delete record
                 */
                function delete($idArr = Array()) {
                                if (is_array($idArr)) {
                                                $res = $this->uni_db->uniDelete($idArr, $this->table);
                                } else {
                                                $res = false;
                                }
                                return $res;
                }

                /**
                 * @return int
                 * @param arr array
                 * @param idArr array
                 * @desc Update record accorring to given attributes
                 */
                function update($arr, $idArr, $isDatetimePreformed = false) {
                                // Error handling
                                list($key, $val) = $idArr;
                                if (!is_array($idArr) || count($idArr) != 1) {
                                                user_error ("<br>Bad arguments passed");
                                }

                                if (is_array($arr) && is_array($idArr)) {
                                                if(!$isDatetimePreformed)$arr = $this->_formatDates($arr, "toSQL", false);
                                                $arr = $this->_checkFields($arr);
                                                $res = $this->uni_db->uniUpdate($arr, $this->table, $idArr);
                                } else {
                                                $res = 0;
                                                user_error ("<br>Not updated");
                                }
                                return $res;
                }

                /**
                 * @return int
                 * @param query = "" string
                 * @desc Returns number of records from supplied query
                 */
                function count($query = "") {
//                        $res = $this->uni_db->uniGetCount($this->table, $where);
//                        echo $query;
                        $this->uni_db->DB->query($query);
                        $res = $this->uni_db->DB->num_rows();
                        return intval($res);
                }

                /**
                 * @return Array
                 * @param idArr Array
                 * @param where String
                 * @desc Returns complete record information from database according to supplied parameters
                 */
                function get($idArr = Array(), $where = "") {

                        if (is_array($idArr)) {
                                        $res = $this->uni_db->uniGet($this->table, $idArr, $where);
                                        $res = $this->_formatDates($res, "fromSQL", false);
                        } else {
                                        $res = Array();
                        }
                        return $res;
                }

                /**
                 * @return boolean
                 * @param recordArr array
                 * @desc Returns if record(s) exists in the database
                 */
                function exists($recordArr) {
                        assert(is_array($recordArr));
                        $query = "select count(*) as number from ".$this->table." where 1 ";
                        foreach ($recordArr as $field => $value) {
                                // check if field exists in database
                                if (in_array($field, array_keys($this->metaData[meta])))
                                        $query .= " and ".$field." = '".addslashes($value)."'";
                        }
//                        echo $query;
                        $res = $this->plainSQL($query, "number");

                        return ($res[0][number] > 0);
                }

                /**
                 * @return array
                 * @param idField array
                 * @param where string
                 * @param order string
                 * @param start int
                 * @param count int
                 * @desc Returns list of items
                 */
                function getList($idField = "", $where = "", $order = "", $start = 0, $count = "") {
                        //make first parameter optional

                        if (empty($idField) && !empty($this->idField))
                                        $idField = $this->idField;

                        if (!empty($idField)) {
                                        if (empty($where)) {
                                                $res = $this->uni_db->uniGetList($this->table, $idField, $order, $start, $count);
                                        } else {
                                                $res = $this->uni_db->uniGetListWhere($this->table, $idField, $where, $order, $start, $count);
                                        }
                        } else {
                                        $res = Array();
                        }

                        return $res;
                }

                /**
                 * @return array
                 * @param idField = "" string
                 * @param where = "" string
                 * @param valueField = "name" string
                 * @desc Returns list of objects in "short form": key => value
                 */
                function getListShort ($idField = "", $where = "", $valueField = "name") {
                                $list = $this->getList($idField = "", $where);
                                $arr = Array();

                                foreach ($list as $key => $val) {
                                                $arr[$key] = $val[$valueField];
                                }
                                return $arr;
                }

                /**
                 * @return array
                 * @param sql string
                 * @param index_name string
                 * @desc Returns query results as associative array with field names - second parameter as keys
                 */
                function customSQL($sql, $index_name) {
                                return $this->uni_db->uniSQL($sql, $index_name);
                }

                /**
                 * @return array
                 * @param sql sql
                 * @desc Deprecated, alias for query
                 */
                function plainSQL($sql) {
                        return $this->query($sql);
                }

                /**
                 * @return array
                 * @param query string
                 * @desc Execute query and return query results
                 */
                function query($query) {
                        $this->uni_db->DB->query($query);
                        while ($this->uni_db->DB->next_record()) {
                                        while (list($key, $val) = each($this->uni_db->DB->Record))
                                        {
                                                        $this->uni_db->DB->Record[$key] = stripslashes($this->uni_db->DB->Record[$key]);
                                        }
                                        $arr[] = $this->uni_db->DB->Record;
                        }
                        return (Array)$arr;
                }

                function _fromSQLDateTime($datetime = "0000-00-00 00:00:00", $delim = "[/.-]") {
                                list($date, $time) = split (" ", $datetime);
                                list ($hour, $minute, $second) = split ($delim, $time);
                                list ($year, $month, $day) = split ('[/.-]', $date);
                                //return date("Y-m-d H:i:s", mktime ($hour, $minute, $second, $month, $day, $year));
                                return mktime ($hour, $minute, $second, $month, $day, $year);
                }

                function _toSQLDateTime ($datetime = "",  $delim = '[/.-]', $doSetDateNow = false) {
                        // format = 0000-00-00 00:00:00
                        if ($doSetDateNow == true && empty($datetime)) {
                                //return date("Y-m-d H:i:s"); //now
                                return null;
                        } elseif ($doSetDateNow == false && empty($datetime)) {
                                return null;
                        }
                        else {
                                list ($date, $time) = split (" ", $datetime);
                                list ($hour, $minute, $second) = split (":", $time);
                                list ($year, $month, $day) = split ('[/.-]', $date);
                                return date("Y-m-d H:i:s", mktime ($hour, $minute, $second, $month, $day, $year));
                        }
                }

                function _formatDates (&$arr, $direction, $doSetDateNow = false) {
                        if (is_array($this->dateFieldNames))
                        foreach ($this->dateFieldNames as $key => $val) {
                                if ($direction == "fromSQL") {
                                        if ($arr[$val] != null)
                                                $arr[$val] = $this->_fromSQLDateTime($arr[$val], "-");
                                } else {
                                        if (!($doSetDateNow == false && empty($arr[$val])))
                                                $arr[$val] = $this->_toSQLDateTime($arr[$val], "/", $doSetDateNow);
                                }
                        }
                        return $arr;
                }

                function _checkFields ($arr) {
                        assert(is_array($this->metaData[meta]));
                        $fieldNames = array_keys($this->metaData[meta]);

                        if (is_array($arr))
                        foreach ($arr as $key => $val) {
                                        if (in_array($key, $fieldNames)) {
                                                        $recordArr[$key] = $val;
                                        }
                        }
                        return $recordArr;
                }

                function debug($trigger = 1) {
                        $this->uni_db->DB->Debug = (int)$trigger;
                        return $this->uni_db->DB->Debug;
                }

                /*
                **************************************************************************

                Visual part

                **************************************************************************
                */

                function showRecordForm ($templateFormName, $recordArr = Array()) {
                        return $this->show($templateFormName, $recordArr);
                }

                function show ($templateFormName, $recordArr = Array()) {
                        $this->template->assign($recordArr);
                        return $this->template->fetch($templateFormName);
                }

                function showList ($templateFormName = "") {
                                assert(strlen($templateFormName) > 0);
                                $orderList = $this->getList($this->idField);
                                $this->template->assign("list", $orderList);
                                return $this->template->fetch($templateFormName);
                }
}
?>
<?
class easydb extends basedb {

        function easydb() {
                global $uni_db;
                parent::basedb($uni_db, $this->table);
        }

        function getByID($id){
        return $this->get(array($this->idField=>$id));
        }

        function getWhere($where = "", $order = "", $start = 0, $count = ""){
                return $this->getList("", $where, $order, $start, $count);
        }

        function showRecord($values, $lists = array()){
                $record = array();
                $check_fields = '';
                if (is_array($this->RecordFields))
                foreach ($this->RecordFields as $field) {
                        $rec = array();
                        if (count($field) > 1) {
                                if ($field["type"]){
                                        $rec["type"] = $field["type"];
                                        unset($field["type"]);
                                }
                                if ($field["check"]){
                                        $rec["check"] = $field["check"];
                                        unset($field["check"]);
                                }
                                /*if ($field["readonly"]){
                                        $rec["readonly"] = $field["readonly"];
                                        unset($field["readonly"]);
                                } */
                        }
                        list($name, $title) = each($field);
                        $rec["name"]=$name;
                        $rec["title"]=$title;
                        if (is_array($values)) $rec["value"]=$values[$name];
                        if ((is_array($values)) && ($rec["type"] == "password")) $rec["check"]=str_replace("#","",$rec["check"]);
                        if ((count($lists) > 0) && ($rec["type"] == "select" || $rec["type"] == "radio")) {
                                $rec["list"] = $lists[$name];
                        }
                        if ($rec["check"]) $check_fields .= "$rec[name],$rec[check],";
                        $record[] = $rec;
                }
                if ($check_fields != '') $record[] = array("name"=>"check__fields","value"=>substr($check_fields,0,strlen($check_fields)-1),"type"=>"hidden");
                if ($values[$this->idField])
                        $record[] = array("name"=>$this->idField,"value"=>$values[$this->idField],"type"=>"key");
                return $record;
        }

        function showList($arr, $key, $val){
                $list = array();
                if (is_array($arr))
                foreach ($arr as $option) {
                        $list[$option[$key]] = $option[$val];
                }
                return $list;
        }

        function edit($dataArr, $id){
                return parent::update($dataArr, array($this->idField=>$id), true);
        }

        function delete($id){
        return parent::delete(array($this->idField=>$id));
        }

}
?>