<?php

// IBExpertWebForms
// copyright  ©  2006-2008 Holger Klemt hklemt@ibexpert.biz
// www.ibexpert.com


  function mystrtoupper($s)
  {
    return $s;
  }

  class TDataSet extends TComponent
  {
    var $db;
    var $Refresh;

    function __construct($owner=null)
    {
      parent::__construct($owner);

      $this->CalcEOF();
    }

    function Init()
    {
      global $main_db,$action;

      //$action="nix";
      //echo $action;

      //if($action=="init")
      if($action=="init")
        $this->Refresh=true;


      $database=$this->Database;
      if(!$database)
        $database=$this->DatabaseName;

      $database=$this->GetComponentByName($database);

      if($database)
        $this->db=$database->db;
      else
        $this->db=$main_db;
    }

    function Close()
    {
      $this->Active="False";
      $this->Refresh=true;
      $this->query->close();
      unset($this->row);
      $this->UpdateData();
      //$this->query->PrepareRemote(true);
      //$this->First();
      $this->EOF="True";
    }

    function Open($sql="")
    {
      if(!$sql)
        $sql=$this->GetSQL();

      if($sql)
      {
        //$this->ca->alert($this->db->databasename);

        $this->Active="True";
        $this->isUpdatedData=false;

        //$this->ca->Alert($this->Name."Open(".$sql.")");

        $this->Refresh=true;
        $this->query->open($sql);
        $this->query->PrepareRemote(true);
        //$this->ca->Alert($this->Name."Open(".$this->query->GetRow(0).")");
        $this->First();
        $this->UpdateData();
        $this->EOF="False";
        //$this->row=$this->query->Row;
      }
    }

    function First()
    {
      //echo $this->query->remotecursor;
      $this->row=$this->query->First();
      $this->UpdateData();
    }

    function Last()
    {
      //echo $this->query->remotecursor;
      $this->row=$this->query->Last();
      $this->UpdateData();
      $this->EOF="True";
    }

    function Next()
    {
      //echo $this->query->remotecursor;
      $this->row=$this->query->Next();
      $this->UpdateData();
    }

    function Prev()
    {
      $this->row=$this->query->Prev();
      $this->UpdateData();
    }

    function GoTo($pos)
    {
      $this->row=$this->query->Goto($pos);
      $this->UpdateData();
    }

    /*
    function Set($property,$value="")
    {
      parent::Set($property,$value);

      if($property=="ACTIVE")
      {
        if($value=="True")
          $this->Open();
        else if($value=="False")
          $this->Close();
      }
    }
    */

    function Action($object,$action)
    {
      if($action=="init" && $this->Active=="True")
        $this->First();
    }

    function Commit()
    {
      global $HTTP_POST_FILES,$_FILES;

      if($_FILES)
        $uploaded_files=$_FILES;
      else
        $uploaded_files=$HTTP_POST_FILES;

      $table="unknown";

      $table=$this->query->Fields[0]['relation'];

      $isUpdateSQL=false;

      if($this->UpdateSQL->Text)
      {
        $isUpdateSQL=true;
        $sql=$this->UpdateSQL->Text;
      }
      else
        $sql="update ".$table." set ";

      $c=$this->ParseComponents(null,"FindByProperty","DataSet;".$this->Name);
      $anz=0;
      $isblob_query=false;

      for($i=0;$i<count($c);$i++)
      {
        if($c[$i]->Class=="TDataSource" ||
           $c[$i]->Class=="TWFDataSource")
        {
          $c2=$this->ParseComponents(null,"FindByProperty","DataSource;".$c[$i]->Name);

          $firstField=true;

          for($j=0;$j<count($c2);$j++)
          {
            //echo $c2[$j]->Class."<br>";

            $field="";
            for($i=0;$i<count($this->query->Fields);$i++)
              if($this->query->Fields[$i]['alias']==mystrtoupper($c2[$j]->DataField))
                $field=$this->query->Fields[$i];

            //$sql=str_replace(":".$field['alias'],$this->query->Row[$field['alias']],$sql);

            $integer=false;
            $isblob=false;
            if($field['type']=="BIGINT")
              $integer=true;
            else if($field['type']=="INTEGER")
              $integer=true;
            else if($field['type']=="BLOB")
            {
              $isblob=true;
              $isblob_query=true;
            }

            if($c2[$j]->Class=="TWFDBEdit" ||
               $c2[$j]->Class=="TWFDBLabel" ||
               $c2[$j]->Class=="TWFDBMemo" ||
               $c2[$j]->Class=="TWFDBRichEdit" ||
               $c2[$j]->Class=="TWFDBComboBox" ||
               $c2[$j]->Class=="TWFDBLookupComboBox" ||
               ($c2[$j]->Class=="TWFDBButton" && $c2[$j]->Direction=="bdUpload") ||
               $c2[$j]->Class=="TDBEdit" ||
               $c2[$j]->Class=="TDBMemo" ||
               $c2[$j]->Class=="TDBRichEdit" ||
               $c2[$j]->Class=="TDBComboBox" ||
               $c2[$j]->Class=="TDBLookupComboBox")
            {
              $make_sql=true;

              if($anz && !$isUpdateSQL && !$firstField)
                $sql.=", ";

              $v=$_REQUEST[strtoupper($c2[$j]->Name)];

              $v_filename="";
              if($isblob)
              {
                if($c2[$j]->FilenameField!="")
                {
                  $v_filename=$uploaded_files[strtoupper($c2[$j]->Name)]['name'];
                  $v_filename_field=$c2[$j]->FilenameField;
                }

                $filename=$uploaded_files[strtoupper($c2[$j]->Name)]['tmp_name'];

                if($filename)
                {
                  $fh=fopen($filename,"rb");
                  $v=fread($fh,filesize($filename));
                  fclose($fh);
                }
                else
                  $make_sql=false;
              }

              if($make_sql)
              {
                if($isblob)
                {
                  //die(".".$_REQUEST['WFDBBUTTON1']);
                  //die($v);
                  $v=$this->db->PrepareBlob($v);
                  //die("ok");
                }

                if(!isset($v))
                {
                  if($c2[$j]->Class=="TWFDBLabel")
                    $v=$this->query->Row[mystrtoupper($this->GetComponentByName($c2[$j]->Name)->TextField)];
                  else
                    $v=$this->query->Row[mystrtoupper($this->GetComponentByName($c2[$j]->Name)->DataField)];
                }

                $v_sql=$v;

                if(!$integer)
                  $v_sql="'".$v_sql."'";
                else if($integer)
                  if(!$v)
                    $v_sql="null";

                if($v_filename)
                  $v_sql.=", ".$v_filename_field."='".$v_filename."'";

                if(mystrtoupper($c2[$j]->DataField)!="xID")
                {
                  if(($isblob && $v) || (!$isblob))
                  {
                    $firstField=false;
                    if(!$isUpdateSQL)
                      $sql.=mystrtoupper($c2[$j]->DataField)."=".$v_sql;
                  }
                }

                if($isUpdateSQL)
                {
                  if($c2[$j]->Class=="TWFDBLabel")
                    $sql=str_replace(":".$c2[$j]->TextField,$v_sql,$sql);
                  else
                    $sql=str_replace(":".mystrtoupper($c2[$j]->DataField),$v_sql,$sql);
                }

                $anz++;
              }
            }
            else if($c2[$j]->Class=="TDBGrid" ||
                    $c2[$j]->Class=="TWFDBGrid")
            {
              //$this->ca->alert("ok");
              //$ca->JS("DBGrid".$c2[$j]->Name.".setRowPosition(20); DBGrid".$c2[$j]->Name.".test(); //setAttribute('title','moin'); ");
            }
          }
        }
      }

      if($anz>0)
      {
        // get primary keys
        $psql="select idxs.rdb\$field_name field_name ".
              "from rdb\$relation_constraints rc ".
              "join rdb\$index_segments idxs on idxs.rdb\$index_name=rc.rdb\$index_name ".
              "join rdb\$relation_fields rf on rf.rdb\$relation_name=rc.rdb\$relation_name and rf.rdb\$field_position=idxs.rdb\$field_position ".
              "where rc.rdb\$relation_name='".mystrtoupper($table)."' ".
              "and rc.rdb\$constraint_type='PRIMARY KEY'";
        $this->db->query($psql);

        $pk_sql="";

        while($this->db->fetch())
        {
          $field_name=trim($this->db->Row['FIELD_NAME']);
          if($pk_sql)
            $pk_sql.=" and ";

          $pk_sql.=$field_name."=".$this->query->Row[$field_name];
        }

        if($isUpdateSQL)
        {
           for($i=0;$i<count($this->query->Fields);$i++)
           {
              $field=$this->query->Fields[$i];

              $sql=str_replace(":".$field['alias'],$this->query->Row[$field['alias']],$sql);
           }
        }
        else
          $sql.=" where ".$pk_sql;

        if(!$isblob_query)
          $sql_arr=explode("||||",$sql);
        else
          $sql_arr[0]=$sql;

        for($isql=0;$isql<count($sql_arr);$isql++)
        {
          $this->db->blobquery(trim($sql_arr[$isql]),$table);

          //echo $sql_arr[$isql]."<hr>";
        }
        $row=$this->db->queryandfetch("select * from ".$table." where ".$pk_sql);

        $this->query->RefreshRemote($row);
      }
    }

    function CalcEOF()
    {
      $cursor=$this->query->remotedata['cursor'];
      $max_cursor=$this->query->remotedata['max_cursor'];

      if($cursor==$max_cursor-1)
      {
        //$this->ca->alert($cursor."/".$max_cursor);
        $this->EOF="True";
      }
      else
        $this->EOF="False";

      //$this->ca->alert("CalcEOF:".$this->EOF);
      //$this->ca->alert($this->EOF);
    }

    function UpdateData()
    {
      global $object,$action,$action_value;

      $this->CalcEOF();

      //$this->isUpdatedData=true;

      if($this->isUpdatedData)
        return;

      $this->isUpdatedData=true;

      $ok=true;
      /*
      $ok=false;
      if(!$this->datasource && !$this->mastersource)
        $ok=true;

      if(($this->datasource || $this->mastersource) && $this->MasterDetailUpdate)
        $ok=true;
      */

      //if(!$this->Parent->isUpdatedData)
      //  $ok=true;

      //$this->ca->Alert($object."->".$action."(".$action_value.")");

      $this->MasterDetailUpdate="";

      if(!$ok)
        return;

      //$this->ca->Alert("test: ".$this->Name." (".$this->MasterDetailUpdate.")");
      //$this->ca->Alert("UpdateData in ".$this->Name);

      $c=$this->ParseComponents(null,"FindByProperty","DataSet;".$this->Name);

      for($i=0;$i<count($c);$i++)
      {
        if($c[$i]->Class=="TDataSource" ||
           $c[$i]->Class=="TWFDataSource")
        {
          $c2a=$this->ParseComponents(null,"FindByProperty","DataSource;".$c[$i]->Name);
          $c2b=$this->ParseComponents(null,"FindByProperty","MasterSource;".$c[$i]->Name);

          if(is_array($c2b))
            $c2=@array_merge($c2a,$c2b);
          else
            $c2=$c2a;

          for($j=0;$j<count($c2);$j++)
          {
            $this->query->GetCurrentRow();
            if($c2[$j]->Class=="TWFDBLabel")
              $value=mystrtoupper($this->row[$c2[$j]->TextField]);
            else
              $value=mystrtoupper($this->row[$c2[$j]->DataField]);
            $coding="";

            $fields=$this->query->fields();

            for($k=0;$k<count($fields);$k++)
            {
              //$this->ca->alert($c2[$j]->Name."(".$fields[$k]['alias'].")");

              if($fields[$k]['alias']==mystrtoupper($c2[$j]->DataField))
                if($fields[$k]['type']=="BLOB" && ($fields[$k]['subtype']=="0" || !$fields[$k]['subtype']))
                //if($fields[$k]['type']=="BLOB" && ($fields[$k]['subtype']=="0")
                {
                  //$this->ca->alert("subtype:".$fields[$k]['subtype']);
                  //$this->ca->alert($c2[$j]->DataField);
                  //echo strlen($this->row['DATEI']);
                  $file="blob/".$this->Name."_".session_id()."_".$k."_".$this->row['ID']."_".$this->query->remotedata['cursor'].".image";
                  //$file="blob/image".$this->row['ID'].".data";
                  $fh=fopen($file,"wb+");
                  fwrite($fh,$value);
                  fclose($fh);

                  $value=$file;
                  $coding="link";
                }
            }

            if($c2[$j]->Class=="TDBEdit" ||
               $c2[$j]->Class=="TDBComboBox" ||
               $c2[$j]->Class=="TWFDBEdit" ||
               $c2[$j]->Class=="TWFDBLabel" ||
               $c2[$j]->Class=="TWFDBComboBox")
              $c2[$j]->Set("update",$value);
            else if($c2[$j]->Class=="TDBMemo" ||
                    $c2[$j]->Class=="TDBText" ||
                    $c2[$j]->Class=="TDBRichEdit" ||
                    $c2[$j]->Class=="TWFDBMemo" ||
                    $c2[$j]->Class=="TWFDBText" ||
                    $c2[$j]->Class=="TWFDBRichEdit")
              $c2[$j]->Set("update",$value);
              //$c2[$j]->Set("LINES_TEXT",$value);
              //$this->ca->Alert($value);
            else if($c2[$j]->Class=="TDBImage" ||
                    $c2[$j]->Class=="TWFDBImage")
              $c2[$j]->Set("IMAGE",$value);
            else if($c2[$j]->Class=="TDBLookupComboBox" ||
                    $c2[$j]->Class=="TWFDBLookupComboBox")
              $c2[$j]->Set("LOOKUP",$value);
            else if($c2[$j]->Class=="TDBGrid" ||
                    $c2[$j]->Class=="TWFDBGrid")
            {
              //$this->ca->alert("ok");
              //$this->ca->Alert("Set".$c2[$j]->Name."() aus ".$this->Name);
              if($this->Refresh)
                $c2[$j]->Set("ROWS",$this->query->remotedata);

              $c2[$j]->Set("ROW",$this->query->remotedata['cursor']);
            }
            else if($c2[$j]->Class=="TDBNavigator" ||
                    $c2[$j]->Class=="TWFDBNavigator")
              $c2[$j]->Set("BUTTONS",$this->query->remotedata);
            else if($c2[$j]->Class=="TIBTable")
            {
              $c2[$j]->MasterDetailUpdate="1";
              $c2[$j]->Set("update");
            }
            else if($c2[$j]->Class=="TIBQuery")
            {
              //$this->ca->Alert("call UpDateData: ".$this->Name." -> ".$c2[$j]->Name);

              //$this->ca->Alert($this->Name." (".$this->datasource."),".$c2[$j]->Name." (".$c2[$j]->datasource.")");
              //if(!$c2[$j]->datasource)
                $c2[$j]->MasterDetailUpdate="1";
                $c2[$j]->Set("update");
                //$c2[$j]->MasterDetailUpdate="";
            }
            else if($c2[$j]->Class=="TWFDataset")
            {
              //$this->ca->Alert("call UpDateData: ".$this->Name." -> ".$c2[$j]->Name);

              //$this->ca->Alert($this->Name." (".$this->datasource."),".$c2[$j]->Name." (".$c2[$j]->datasource.")");
              //if(!$c2[$j]->datasource)
                $c2[$j]->MasterDetailUpdate="1";
                $c2[$j]->Set("update");
                //$c2[$j]->MasterDetailUpdate="";
            }
              //$c2[$j]->Set("BUTTONS",$this->query->remotedata);
          }
        }
      }
    }

  }

?>