<?php
/*********************************************************************
 *
 *  WEB-Service:  Server.Studio
 *
 *  @author Sam Blum  bs_php@users.sourceforge.net
 *  @doc    http://js-rs.sourceforge.net
 *  @source http://sourceforge.net/projects/js-rs/
 */


  include( "../lib_PHP/PhPage.lib.php" );
  include( "../lib_PHP/Studio.lib.php" );

  // Inclui a Classe JsrsServer
  require("../lib_PHP/JsrsServer.class.php");
  


  /**********************************************************
  * Save chat data so disk and offer to methods to the client:
  *
  *   read()  : Read out the chat text collected so far.
  *
  *   write() : Add text to the chat text.
  */
  class MsgServer
  {
  
    /*
     *  propriedade: chatFile
     */
    var $chatFile = 'chatBuffer.txt';
    var $statusFile = 'statusBuffer.txt';
    var $path_ = '';
    
/**  Methods private
 *
 */
    function get_root()
    {
      $uri = $_SERVER['REQUEST_URI'];
      $p = strpos( $uri, 'core' );
      return( $_SERVER['DOCUMENT_ROOT'] . substr( $uri, 0, $p ) );
      //return( $_SERVER['DOCUMENT_ROOT'] . substr( $uri, 0, $p ) .'core' );
    }

    function _tail($lineCount=10) {
      $ret = '';
      if ( file_exists($this->chatFile) )
      {
        $t = @file($this->chatFile);
        $t = array_slice($t, -$lineCount);
        $ret = join ('', $t);
      }
      return $ret;
    }

/*
 * This is a methods to be propergated (See below)
 */
    function read($txt)
    {
      $arr  = explode( ':', $txt );
      $nUsr = $arr[0];  // login do Usuário
      $nObj = $arr[1];  // nome Objeto dbGrid
      $key  = $arr[2];  // chave (PK) do dbGrid

      $lib = $this->get_root() . "core/dbGrid.lib.php";
      include( $lib );

      $path = $this->get_root() . "desenv/usuarios/".$nUsr."/config/" ;
      $nFile = $path . $nObj . ".config.data.ini";
      $field = array();

      if( file_exists( $nFile ) )
      {
  /**
   *  le o .config.data.ini do dbGrid
   */
        $arrINI = readINIfile( $nFile );

        $ind = $nObj . '_field';
        $arrField = $arrINI[ $ind ];
        $dts = $path . $arrINI[ $nObj . '_data']['datasource'] . '.config.data.ini';

        if( file_exists( $dts ) )
        {
  /**
   *  le o .config.data.ini do DataSource
   */
          $arrDTS = readINIfile( $dts );
          $host  = $arrDTS['db_conect']['host'];
          $user  = $arrDTS['db_conect']['user'];
          $pass  = $arrDTS['db_conect']['pass'];
          $dbase = $arrDTS['db_conect']['dbase'];

  /**
   *  Abre a conexão com o SGDB
   */
          $con = mysql_connect( $host, $user );
          $db = mysql_select_db( $dbase, $con);

          $tabela = $arrINI[ $nObj . '_data']['tabela'];
          $pk_    = $arrINI[ $nObj . '_data']['pk'];
          $pkey   = explode( '*', $pk_ );

          $query    = "SELECT status FROM " . $tabela . " WHERE " . $pkey[0] . " = '" . $key . "';";
          $result   = mysql_query( $query );
          $valField = mysql_result( $result, 0 );
          if( $valField == 'F' )
          {
            $ret = '0#erro#Mensagem já finalizada';
          }else
          {
            $update  = " UPDATE " . $tabela . " SET status = 'F' WHERE " . $pkey[0] . " = '" . $key . "';";
            if( !$re = mysql_query( $update ) )
            {
              $ret = '0#erro#not found ' . $update;
            }else
            {
              $ret = '1#'.$conf.'#Mensagem finalizada com sucesso';
            }// End if( !$re = mysql_query( $update ) )
          }// End if( $valField == 'F' )
          
        }else
        {
          $ret = '0#erro#dataource.config.data.ini not found. ';
        }// End if( file_exists( $dts ) )

      }else
      {
        //$ret = '0#erro#'.$arr[0].'.config.data.ini not found.';
        $ret = '0#erro#'.$nFile.' not found ';
      }// End if( file_exists( $nFile ) )

      return( $ret );

    }// End function read($txt)
    
    
    function teste($txt)
    {
      $arr  = explode( ':', $txt );
      $nUsr = $arr[0];  // login do Usuário
      $nObj = $arr[1];  // nome Objeto dbGrid
      $key  = $arr[2];  // chave (PK) do dbGrid
      $dest = $arr[3];  // nome do campo onde seu valor será o destino
      $mens = $arr[4];  // valor do campo onde existe a mensagem
      $resp = $arr[5];  // valor do campo que será enviado ao destino

      $lib = $this->get_root() . "core/dbGrid.lib.php";
      include( $lib );

      $path = $this->get_root() . "desenv/usuarios/".$nUsr."/config/" ;
      $nFile = $path . $nObj . ".config.data.ini";
      $field = array();

      if( file_exists( $nFile ) )
      {
  /**
   *  le o .config.data.ini do dbGrid
   */
        $arrINI = readINIfile( $nFile );

        $ind = $nObj . '_field';
        $arrField = $arrINI[ $ind ];
        $dts = $path . $arrINI[ $nObj . '_data']['datasource'] . '.config.data.ini';

        if( file_exists( $dts ) )
        {
  /**
   *  le o .config.data.ini do DataSource
   */
          $arrDTS = readINIfile( $dts );
          $host  = $arrDTS['db_conect']['host'];
          $user  = $arrDTS['db_conect']['user'];
          $pass  = $arrDTS['db_conect']['pass'];
          $dbase = $arrDTS['db_conect']['dbase'];

  /**
   *  Abre a conexão com o SGDB
   */
          $con = mysql_connect( $host, $user );
          $db = mysql_select_db( $dbase, $con);
          
          $tabela = $arrINI[ $nObj . '_data']['tabela'];
          $pk_    = $arrINI[ $nObj . '_data']['pk'];
          $pkey   = explode( '*', $pk_ );
          $query  = "SELECT ".$dest. " FROM " . $tabela . " WHERE " . $pkey[0] . " = '" . $key . "';";
          $query2 = "SELECT assunto FROM " . $tabela . " WHERE " . $pkey[0] . " = '" . $key . "';";

          $result   = mysql_query( $query );
          $valField = mysql_result( $result, 0 );
          
          $result2 = mysql_query( $query2 );
          $assunto = mysql_result( $result2, 0 );
          
          if( $result && $result2 )
          {
            $remet = "suporte@phpage.com.br";
            $mail = $valField;
            $msg = "<html>
                          <body>
                            <b>De: </b>".$remet."<br>
                            <b>Para: </b>".$mail."<br>
                            <b>Assunto: </b> Re: <label>".$assunto."</label><br><p>"
                            .$resp."<p><p>
                            <label><b>".$mail." </b>enviou:</label><br>
                            <textarea cols='50' rows='5'>"
                              .$mens.
                            "</textarea>
                          </body>
                    </html>";

/*
            if( $_SERVER['SERVER_NAME'] == "www.phpage.com.br" )
            {
              ini_set( 'SMTP', 'mail.phpage.com.br' );
              ini_set( 'sendmail_from', 'suporte@phpage.com.br' );
            }else
            {
              ini_set( 'SMTP', 'smtp.smart.net.br' );
              ini_set( 'sendmail_from', 'zaes@smart.net.br' );
            }// End if( $_SERVER['SERVER_NAME'] == "192.168.0.10" )
*/
            ini_set( 'SMTP', 'mail.phpage.com.br' );
            ini_set( 'sendmail_from', 'suporte@phpage.com.br' );

            $conf = mail( $mail, "Re: ".$assunto, $msg,
                          "Content-Type: text/html" );

            if ( $conf === true )
            {
              $update  = " UPDATE " . $tabela . " SET status = 'R' WHERE " . $pkey[0] . " = '" . $key . "';";
              if( !$re = mysql_query( $update ) )
              {
                $ret = '0#erro#not found ' . $update;
              }else
              {
                $ret = '1#'.$conf.'#Mensagem enviada com sucesso';
              }// End if( !$re = mysql_query( $update ) )
            }else
            {
              $ret = '0#erro#not found '. $conf;
            }// End if ( $conf )

          }else
          {
            $ret = '0#erro#'.$nFile.'#not found ' . $query;
          }// End if( $result && $res )

        }else
        {
          $ret = '0#erro#dataource.config.data.ini not found. ';
        }// End if( file_exists( $dts ) )

      }else
      {
        //$ret = '0#erro#'.$arr[0].'.config.data.ini not found.';
        $ret = '0#erro#'.$nFile.' not found ';
      }// End if( file_exists( $nFile ) )

      return( $ret );
    
    }// End function teste($txt)
    

    function write($txt)
    {
      $box = $this->read();
      $box .= $txt . "\n";

      $fp = @fopen( $this->chatFile, 'wb' );
      @fwrite( $fp, $box, strLen( $box ) );
      @fclose( $fp );
      return $box;
    }// End function write($txt)

/**
 */
    function set_msg( $txt )
    {
      return "";
    }
    function get_ajuda( $txt )
    {
      return "texto da Ajuda";
    }

/**
 *  set_dbgrid_col()  -------------------------------------------------------  //
 */

    function set_dbgrid_col( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $obj_ = $arr[1];
      $col_ = $arr[2];
      $tit_ = $arr[3];

      $path_ = $this->get_root() . "desenv/usuarios/" . $log_ . "/config/" ;
      $nFile = $obj_ . ".config.data.ini";
      $fileINI = $path_ . $nFile;

      if( file_exists( $fileINI ) )
      {
        $arrINI = readINIfile( $fileINI, ';' );
        $idx = trim($obj_ . '_field' . $col_);
        //return $idx;
        //$ret = $arrINI['dbgrid1_field2']['caption'];
        $arrINI[ $idx ]['caption'] = $tit_;
        $ret = $arrINI[ $idx ]['caption'];
        
        writeINIfile( $fileINI, $arrINI, ';', '' );
      }else
      {
        $ret = "erro:" . $path_ . $nFile;
      }// End
      return $ret;
      
      
      return $tit_;
    }// End function setDBgrid_col( $txt )

/*
 *  Gerar o Script Executável do Projeto que esta sendo Editado.
 */
    function create_script( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];
      $path_ = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;

      return gerar_script_exec( $prj_, $path_, $log_ );
    }

/**
 *  retorna os componentes do projeto
 */
    function get_componente( $txt )
    {
      //return "get";
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];
      $arrComp = '';
      
      $path = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;

      $n_file_ = $prj_ . ".main.prj";

      if ( file_exists( $path . $n_file_ ) )
      {
        $linhas = @file( $path . $n_file_ );

        foreach( $linhas as $ind => $linha )
        {
          if( $linha != "\n" )
          {
           $tmp = explode( ':', trim( $linha ) );
            $arrComp .= $tmp[1] . ':';
          }//
        }// End foreach()
      }else
      {
        $arrComp = 'nil';
      }// End if()
      
      return $arrComp;
    }

/**
 *  Retorna o nome do projeto aberto
 */
    function back_projeto( $log_ )
    {

      $path = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;
      $n_file_ = "nProjeto.status";

      if ( file_exists( $path . $n_file_ ) )
      {
        $arr = @file( $path . $n_file_ );
        $ar_ = explode( ':', trim( $arr[0] ) );
        $nome_prj = trim( $ar_[1] );
        $ar_ = explode( ':', trim( $arr[1] ) );
        $status_prj = trim( $ar_[1] );
        
        $ret = $nome_prj . ":" . $status_prj;
      }else
      {
        $ret = "nil";
      }// End if()
      
      return $ret;
    }// End function
    
/**
 *  save_projeto()
 *
 *  Savar o projeto em edição
 *  atualiza os arquivos da área de Projetos (repositorio) 
 *  com as modificações dos arquivos na área de trabalho do usuário.
 */
    function save_projeto( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];
      $flagNovo = false;
//return('erro: '.$prj_);
      if ( $prj_ == 'novo' )
      {
        $prj_ = nextProjeto();
//return $prj_;
        $t    = newProjeto( $prj_ );
        $flagNovo = true;
//return('t: '.$t.'  ['.$prj_.']');
      }// End if()
//return $prj_;

      $path1 = $this->get_root() . "desenv/projetos/" . $prj_ . "/" ;
      $path2 = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;
//return('erro1: '.$path2);
// 1º Passo:
//  Ajustar o arquivo de Status
      $n_file_ = "nProjeto.status";
      $msg     = "Projeto: " . $prj_ . "\n";
      $msg    .= "status : Modificado \n";
      
      $_fp_  = @fopen( $path2 . $n_file_, 'wb');
      @fwrite( $_fp_, $msg );
      @fclose( $_fp_ );
//return('erro: Passo1');

// 2º Passo:
//  Copia os arquivos do diretorio do Usuário para o diretorio do Projeto
      $flag = copyFile( $path2, $path1 );
      
      if( $flagNovo && $flag )
      {
        $ret = renProjeto( $prj_, 'novo', $prj_ );
        //return $ret;
      }// End if()
//return('erro: Passo2');

// 3º Passo:
// Ajusta o arquivo de LOG
      if( $flag )
      {
        $msg   = "salvo por [ " .$log_ . " ] as [ " . date( 'H:i:s' ) . " ]\n";

        $nFile = "desenv/log/" . "PRJ_" . $prj_ . '_' . date('Y_m_d') . ".log";
        $fp    = @fopen( $nFile, 'ab+' );

        @fwrite($fp, $msg );
        @fclose($fp);

        $ret = 'Ok';
      }else
      {
        $ret = 'erro';
      }// End if()

      return $ret;
    }// End function save_projeto( $txt )
     
/**
 *  Fechar o projeto em Edição  --------------------------------------------  //
 */
    function close_projeto( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];
//return('1[ '.$log_.' ]   2[ '.$prj_.' ]');

      $path1 = $this->get_root() . "desenv/projetos/" . $prj_ . "/" ;
      $path2 = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;
//return('1[ '.$path1.' ]   2[ '.$path2.' ]');
// 1º Passo:
//  Deleta o arquivo de Status
      $n_file_ = "nProjeto.status";

      if ( file_exists( $path2 . $n_file_ ) )
      {
        unlink( $path2 . $n_file_ );
        $ret = 'ok';
      }else
      {
        $ret = 'err';
      }// End
//return('erro: passo 1 ['.$ret.']');

// 2º Passo:
//  deleta os arquivos do diretorio do Usuário
      $flag = deleteAll( $path2 );
      
      if ( $flag )
      {
        $ret = "OK";
      }else
      {
        $ret = "Erro";
      }
//return( 'erro'.$ret );
      if ( $flag )
      {
        $msg   = "fechado por [ " .$log_ . " ] as [ " . date( 'H:i:s' ) . " ]\n";

        $nFile = "desenv/log/" . "PRJ_" . $prj_ . '_' . date('Y_m_d') . ".log";
        $fp    = @fopen($nFile, 'ab+');

        @fwrite($fp, $msg );
        @fclose($fp);

        $ret = "OK";
      }else
      {
        $ret = "Erro";
      }
//return("erro[3] $ret [".$nFile.']');

// 3º Passo:
// Ajusta o arquivo de LOG

      return( $ret );
    }// End function close_projeto( $txt )


/**
 *  get_projetos
 */
    function get_projetos( $path )
    {
      $arrDir = getDir( $this->get_root() . $path );
      $ix = 1;
      $ret = '';
      foreach( $arrDir as $i => $nDir )
      {
        $ret .= $nDir . ':';
        $ix ++;
      }
      return( $ret );
    }// End function()
    
/**
 *  Abrir um projeto para Edição  ------------------------------------------  //
 */
    function open_projeto( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];

      $flag = true;
      
      $path1 = $this->get_root() . "desenv/projetos/" . $prj_ . "/" ;
      $path2 = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;

//  1º Passo :
//  Copia os arquivos para o diretorio de trabalho do Usuário
//  ------------------------------------------------------------------------  //
      $flag = copyFile( $path1, $path2 );

      if( $flag )
      {

//  2º Passo:
//  Atualizar o arquivo de Status do Projeto
//  ------------------------------------------------------------------------  //
        $n_file_ = "nProjeto.status";
      
        if ( file_exists( $path2 . $n_file_ ) )
        {
          $arr = @file( $path2 . $n_file_ );
          $ar_ = explode( ':', $arr[0] );
          $nome_prj = trim( $ar_[1] );
          $ar_ = explode( ':', $arr[1] );
          $status_prj = trim( $ar_[1] );
        }else
        {
          $msg  = "Projeto: " . $prj_ . "\n";
          $msg .= "status : OK \n";
          $_fp_    = @fopen( $path2 . $n_file_, 'wb');
          @fwrite($_fp_, $msg );
          @fclose( $_fp_ );
        }
      
//  3º Passo:
//  Copia os arquivos do framework para o diretorio de trabalho do Usuário
//  ------------------------------------------------------------------------  //
        $arrFile = getNameFile_framework();
        
        foreach( $arrFile as $file )
        {
          //copy( $origem . $file, $destino . $file );
          
        }// End
        
//  4º Passo:
//  Ajusta o arquivo de LOG do Projeto
//  ------------------------------------------------------------------------  //
        $msg   = "aberto por [ " .$log_ . " ] as [ " . date( 'H:i:s' ) . " ]\n";
        
        $nFile = "desenv/log/" . "PRJ_" . $prj_ . '_' . date('Y_m_d') . ".log";
        //$nFile = "desenv/log/" . date('Y_m_d') . "_PRJ_" . $prj_ . ".log";
        $fp    = @fopen($nFile, 'ab+');
      
        @fwrite($fp, $msg );
        @fclose($fp);
        
        $ret = 'ok';
      }else
      {
        $ret = 'erro';
      }// End if()
      
      return $ret;
    }// End function open_projeto( $txt )


/**
 *  log_write()  -----------------------------------------------------------  //
 */
    function log_write($txt)
    {
      $arr = explode( ":", $txt );
      $nFile = "desenv/log/" . date('Y_m_d') . '_USR_' . $arr[1] . ".log";

      $linhaNew  = str_repeat('.', 9) . '+' . str_repeat('.', 9) . '+';
      $linhaNew .= str_repeat('.', 9) . '+' . str_repeat('.', 9) . '+';
      $linhaNew .= str_repeat('.', 9) . '+' . str_repeat('.', 9) . '+';

      if( file_exists( $nFile ) )
      {
        $linhas = @file( $nFile );
        $hora   = date('G');
        $min    = date( 'i' );

        for( $key = 0; $key < 24; $key ++ )
        {
          if ( array_key_exists( $key, $linhas ) )
          {
            $linha = trim( $linhas[ $key ] );
            if( strlen($linha) <= 0 )
            {
              $linhas[ $key ] = $linhaNew . "\n";
            }
          }else
          {
            $linhas[ $key ] = $linhaNew . "\n";
          }
        }
        $linha  = trim( $linhas[$hora] );
        $branco = str_repeat( '.', 60);
        $linha  = substr($linha.$branco , 0, 60 );

        $tmp = "";
        for( $m = 0; $m <= 60; $m ++ )
        {
          $old = substr($linha, $m, 1);
          $mm = ( $m == $min ) ? $arr[0] : $old ;
          $tmp .= $mm;
        }
        $linhas[$hora] = $tmp . "\n";

        $fp = @fopen($nFile, 'wb');
        for( $l=0; $l <24; $l++ )
        {
          @fwrite($fp, $linhas[$l]);
        }
        @fclose($fp);
      }//End if()

      return "Ok";
    }// End function log_write($txt)

/*
 */
    function obj_ativo($txt) {
      $box = $this->read();
      $box .= $txt . "\n";

      $fp = @fopen($this->chatFile, 'wb');
      @fwrite($fp, $box, strLen($box));
      @fclose($fp);
      return "Ok";
    }// End function write($txt)

/**
 *
 */
    function exec_cmd( $txt )
    {
      $arr = explode( ":", $txt );
      $box = "";
      $box .= "cmd: "       . $arr[0] . "\n";
      $box .= "obj: "       . $arr[1] . "\n";
      $box .= "paleta: "    . $arr[2] . "\n";
      $box .= "container: " . $arr[3] . "\n";
      $box .= "projeto: "   . $arr[4] . "\n";
//return "OK [ " . $arr[0]  . " ]";

      $path = $this->get_root() . "desenv/usuarios/".$arr[5]."/";
//return "OK [ " . $path  . " ]";

      switch( $arr[0] )
      {
        case 'addObj':
          $ret = addObj( $arr[1], $arr[2], $arr[3], $arr[4], $path );
          break;
        case 'delObj':
          $ret = delObj( $arr[1], $arr[4], $path );
          break;
        default:
      }// End switch()
      
      return "OK [ " . $ret  . " ]";
    }// End function write($txt)





    /*
     * Method loaded  =======================================================
     */
    function loaded($txt)
    {
      $box = $this->read();

      if ( file_exists($txt) )
      {
        if(unlink($txt) )
          $box .= "arquivo deletado com sucesso: ". $txt . "\n";
        else
          $box .= "falha: ". $txt . "\n";
      }else
      {
        $box .= $txt . "\n";
      }

      $fp = @fopen($this->chatFile, 'wb');
      @fwrite($fp, $box, strLen($box));
      @fclose($fp);
      return $box;
    }// End function loaded($txt)

    /*
     *  Metodo get_winpage()  ------------------------------------------  //
     */
    function get_winpage( $obj )
    {
      $nrPage = "0";
      $nFile  = "PhPage.main.prj";

      $lines = @file( $nFile );
      $texto = "Obj: ".$obj . "\n";
      $texto .= "file: ".$nFile . "\n";
      $texto .= "linhas: ". count($lines);

      foreach( $lines as $i_ => $line )
      {
        if( strlen($line) >= 10 )
        {
          $arr = explode( ':', $line );

          if ( $arr[1] == $obj )
          {
            $nrPage = substr($arr[3], strlen($arr[3])-1, 1 );
            $texto .= $arr[3] . "\n";
          }// End if()
        }
      }// End foreach()

      $fp = @fopen($this->chatFile, 'wb');
      @fwrite($fp, $texto, strLen( $texto ));
      @fclose($fp);

      return $nrPage;
    }//End function
    
/*
 *  Metodo set_atributo()
 *  ------------------------------------------------------------------------  //
 */
    function set_atributo( $obj )
    {
      $arr  = explode( ":", $obj );
      $log_ = $arr[0];
      $prj_ = $arr[1];
      $comp = $arr[2];
      $item = $arr[3];
      $val_ = $arr[4];

      $n_path = $this->get_root() . 'desenv/usuarios/' . $log_ . '/config/';
      $n_file = $comp . ".config.def.php";
      $atrib  = "";
//return "erro: ".$n_path;
      if ( file_exists( $n_path . $n_file ) )
      {
//$ret_1 = "ok_0";
        include( $n_path . $n_file );
        $tmp = $comp . "_Conf";
        
        $arrItem = $$tmp;
        
        if ( isset( $arrItem[$item] ) )
        {
          $arrItem[$item] = $val_;
          write_config_def( $log_, $comp, $arrItem );
//$ret_1 = "ok_1 ".$arrItem[$item];
//$ret_1 = "ok_1 ".$item;
        }else
        {
//$ret_1 = "ok_2";
        }// End

        /*
         *  atualiza o arquivo config.data.ini
         *  ----------------------------------------------------------------  //
         */
//return "erro: ". $arrItem[ 'config' ];
        if( isset($arrItem[ 'config' ]) )
        {
          $fileINI = $n_path . $comp . '.config.' . $arrItem[ 'config' ] . '.ini';
//return "erro: ". $fileINI;
          if( file_exists( $fileINI ) )
          {
//$ret_1 = "ok_2".$fileINI;
//return "erro: ok[". $fileINI;
            $arrINI = readINIfile( $fileINI, ';' );
            $flagINI = false;
            foreach( $arrINI as $_i_ => $_arr_ )
            {
              foreach( $_arr_ as $ii_ => $_ite_ )
              {
                if( $ii_ === $item  )
                {
                  $arrINI[ $_i_  ][ $item ] = $val_;
                  $flagINI = true;
                }// End if( $ii_ == $item  )
              }// End foreach( $_arr_ as $ii_ => $_ite_ )
            }// End foreach( $arrINI as $_i_ => $_arr_ )

            if( $flagINI )
            {
              if( substr($comp,0,5) == 'table' )
              {
                include( 'table.lib.php' );
                switch( $item )
                {
                  case 'datasource':
                    $arrINI = reset_arrINI_table( $comp );
                    $arrINI[ $comp . '_data'  ][ 'datasource' ] = $val_;
                    writeINIfile( $fileINI, $arrINI, ';', '' );
                    break;
                  case 'tabela':
                    if( empty( $val_ ) )
                    {
                      $dts = $arrINI[ $comp . '_data'  ][ 'datasource' ];
                      $arrINI = reset_arrINI_table( $comp );
                      $arrINI[ $comp . '_data'  ][ 'datasource' ] = $dts;
                      writeINIfile( $fileINI, $arrINI, ';', '' );
                    }else
                    {
                      conectarTO( $arrINI[ $comp . '_data'  ][ 'datasource' ], $n_path );
                      createConfigINI_table( $val_, $fileINI, $comp, $arrItem );
                      //return "erro: ".$val_.' : '.$fileINI.' : '.$comp.' : '.$arrItem['datasource'];
                      //createConfigINI_table( $nTabela, $nFile, $table, $table_Conf )
                    }// End if( empty( $val_ ) )
                    break;
                }// End switch( $item )
                //return "erro: ".substr($comp,0,5).' '.$item;
              }else
              {
                writeINIfile( $fileINI, $arrINI, ';', '' );
              }// End
            }// End if( $flagINI )
          }// End if( file_exists( $fileINI ) )
        }// End if( !isset($arrItem[ 'config' ]) )
        $ret = "$comp:$item=" . $val_;

      }else
      {
        $ret = "erro1: ".$n_path . $n_file ;
      }// End if()

      return $ret;
    }// End function()

    
    /*
     *  Metodo get_atributo()  ------------------------------------------  //
     */
    function get_atributo( $obj )
    {
      $arr  = explode( ":", $obj );
      $log_ = $arr[0];
      $prj_ = $arr[1];
      $comp = $arr[2];
      $atrib  = "";
      
      $n_path = $this->get_root() . 'desenv/usuarios/' . $log_ . '/config/';
      $n_file = $comp . ".config.def.php";

      $len = strlen( $comp );
      if( intval(substr( $comp,$len-2, 1)) > 0 )
      {
        $len -= 2;
      }else
      {
        $len -= 1;
      }
      $nComp = substr( $comp, 0, $len );

      // arquivo de configuração no padrão antigo
      // para manter compatibilidade com versão anterior
      if ( file_exists( $this->get_root() . 'core/' . $nComp . '.comp.php' ) )
      {
        include( $this->get_root() . 'core/' . $nComp . '.comp.php' );
        $tmp = $nComp . '_Conf';
         //return "erro: ".$tmp;
        $arrKey = $$tmp;
        //return "erro: ".$arrKey['marginTop'];
      }
      //
      //
//return '>>'.$nComp;

      
      // arquivo de configuração no padrão novo
      $nFile = $this->get_root() . 'core/' . $nComp . '.comp.ini';
      if ( file_exists( $nFile ) )
      {
//return $nFile.' existe';
        $arrINI = readINIfile ( $nFile, ';' );
        $arrKey = $arrINI[ strtolower($nComp) . '_conf' ];
        //return 'erro: ' . $arrKey;
      }
//return $nFile;
      //return 'erro: '.$n_path . $n_file;
      if ( file_exists( $n_path . $n_file ) )
      {
        include( $n_path . $n_file );
        $tmp = $comp . '_Conf';
        //return "erro: ".$tmp;
        $arrConf = $$tmp;
        //return  "erro: ".$arrConf;
        //return "erro: ". $arrConf['top'];

        foreach( $arrKey as $key_ => $val_ )
        {
          if ( isset($arrConf[$key_]) )
          {
            $atrib .= $key_ . ':' . $arrConf[$key_] . ';';
          }else
          {
            if ( isset( $arrConf['config'] ) &&
                 $arrConf['config'] != ''
                )
            {
              $filename = $n_path . $comp . '.config.' . $arrConf['config'] . '.ini';
              //return "erro: ".$filename;
              $arrINI = readINIfile ( $filename, ';' );
              //return "erro: ".$arrINI['db_conect'][$key_];
              $atrib .= $key_ . ':' . $arrINI['db_conect'][$key_] . ';';
            }
            //
            // valor padrão
            //
            //$default_ = $arrINI[ strtolower($nComp) .'_'. $key_ ];
            //$atrib .= $key_ . ':' . $default_['valor'] . ' ;';
          }// End if()
        }
        //return "erro: ".$atrib;
        //return "log: $log_   proj: $prj_   comp: $comp";
      }else
      {
//return "erro[ ".$n_path . $n_file.' ]';
        $texto = "Erro...[".$path . $file."]";
      }
        
      $fp = @fopen($this->chatFile, 'wb');
      @fwrite($fp, $texto, strLen( $texto ));
      @fclose($fp);
      
      return $atrib;
    }// End function

    
/**
 *  Criar um novo projeto
 */
    function new_projeto( $log_ )
    {
      $flag = true;

      $path1 = $this->get_root() . "core/pattern/";
      $path2 = $this->get_root() . "desenv/usuarios/" . $log_ . "/" ;

/**
 *  1º Passo:  -------------------------------------------------------------  //
 *  copiar os arquivos principais
 */
      $arrFile = array( "novo.main.php"          => "",
                        "page1.main.php"         => "/core/",
                        "novo.main.define.php"   => "/config/",
                        "novo.def.php"           => "/lang/pt_br/",
                        "page1.config.def.php"   => "/config/",
                        "page1.header.php"       => "/config/",
                        "page1.body.php"         => "/config/",
                        "page1.foot.php"         => "/config/",
                        "page1.css.php"          => "/css/",
                        "page1.onAfterLoad.php"  => "/include/",
                        "page1.onBeforeLoad.php" => "/include/"
                         );
      foreach( $arrFile as $nFile => $sub )
      {
        copy( $path1 . $nFile, $path2 . $sub . $nFile );
      }// End foreach( $arrFile as $nFile => $sub )
      // copiar biblioteca JS auxiliar
      copy( $this->get_root() . "lib_JS/jsDOM.js",    $path2 . "lib_JS/jsDOM.js" );
      copy( $this->get_root() . "lib_JS/jsDetect.js", $path2 . "lib_JS/jsDetect.js" );

/**
 *  2º Passo:  -------------------------------------------------------------  //
 *  Criar o arquivo de Status
 */
      $n_file_ = "nProjeto.status";
      $msg  = "Projeto: novo \n";
      $msg .= "status : OK \n";
      $_fp_    = @fopen( $path2 . $n_file_, 'wb');
      @fwrite($_fp_, $msg );
      @fclose( $_fp_ );

      return "OK: ";
    }// End function new_projeto( $log_ )


  }// End class MsgServer
  
  // First create the object to be called. (Pseudo static)
  $theMsgServer = new MsgServer();
  
  // Use the static $JsrsServer to 
  // propergate the methodes that are available for the client
  $JsrsServer->propergateMethod( $theMsgServer, 'teste'          );
  $JsrsServer->propergateMethod( $theMsgServer, 'set_msg'        );
  $JsrsServer->propergateMethod( $theMsgServer, 'read'           );
  $JsrsServer->propergateMethod( $theMsgServer, 'write'          );
  $JsrsServer->propergateMethod( $theMsgServer, 'log_write'      );
  $JsrsServer->propergateMethod( $theMsgServer, 'obj_ativo'      );
  $JsrsServer->propergateMethod( $theMsgServer, 'exec_cmd'       );
  $JsrsServer->propergateMethod( $theMsgServer, 'loaded'         );
  $JsrsServer->propergateMethod( $theMsgServer, 'get_winpage'    );
  $JsrsServer->propergateMethod( $theMsgServer, 'get_atributo'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'set_atributo'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'new_projeto'    );
  $JsrsServer->propergateMethod( $theMsgServer, 'open_projeto'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'save_projeto'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'close_projeto'  );
  $JsrsServer->propergateMethod( $theMsgServer, 'get_projetos'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'back_projeto'   );
  $JsrsServer->propergateMethod( $theMsgServer, 'get_componente' );
  $JsrsServer->propergateMethod( $theMsgServer, 'create_script'  );
  $JsrsServer->propergateMethod( $theMsgServer, 'get_ajuda'      );
  $JsrsServer->propergateMethod( $theMsgServer, 'set_dbgrid_col' );

  // Start the JsrsServer to handle the request from the client
  $JsrsServer->start();
?>                                                     	

