<?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 _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)
    {
      //return $this->_tail(9);
      return "ok";
    }


/*
 */
    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 get_ajuda( $txt )
    {
      return "texto da Ajuda";
    }

/*
 *  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_ = $_SERVER['DOCUMENT_ROOT'] . "/studio/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 = $_SERVER['DOCUMENT_ROOT'] . "/studio/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 = $_SERVER['DOCUMENT_ROOT'] . "/studio/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;

      if ( $prj_ == 'novo' )
      {
        $prj_ = nextProjeto();
        //return $prj_;
        $t    = newProjeto( $prj_ );
        $flagNovo = true;
      }// End if()
      //return $prj_;

      $path1 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/projetos/" . $prj_ . "/" ;
      $path2 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/usuarios/" . $log_ . "/" ;

      // 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_ );

      // 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()

      // 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
     
/**
 *  Fechar o projeto em Edição
 */
    function close_projeto( $txt )
    {
      $arr = explode( ":", $txt );
      $log_ = $arr[0];
      $prj_ = $arr[1];

      $path1 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/projetos/" . $prj_ . "/" ;
      $path2 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/usuarios/" . $log_ . "/" ;

      // 1º Passo:
      //  Deleta o arquivo de Status
      $n_file_ = "nProjeto.status";

      if ( file_exists( $path2 . $n_file_ ) )
      {
        unlink( $path2 . $n_file_ );
      }

      // 2º Passo:
      //  deleta os arquivos do diretorio do Usuário
      $flag = deleteAll( $path2 );
      
      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";
      }
      // 3º Passo:
      // Ajusta o arquivo de LOG

      return $ret;
    }


/**
 *  get_projetos
 */
    function get_projetos( $path )
    {
      $arrDir = getDir( $_SERVER['DOCUMENT_ROOT'] . "/studio/" . $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 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/projetos/" . $prj_ . "/" ;
      $path2 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/usuarios/" . $log_ . "/" ;

      // 1º Passo:
      //  Criar o arquivo de Status
      $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_ );
      }
      
      // 2º Passo :
      //  Copia os arquivos para o diretorio de trabalho do Usuário
      $flag = copyFile( $path1, $path2 );

      // 3º Passo:
      // Ajusta o arquivo de LOG
      if( $flag )
      {
        $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

/*
 */
    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 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/usuarios/".$arr[5]."/";

      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 = $_SERVER['DOCUMENT_ROOT'] . '/studio/desenv/usuarios/' . $log_ . '/config/';
      $n_file = $comp . ".config.def.php";
      $atrib  = "";
//return "erro:1";
      if ( file_exists( $n_path . $n_file ) )
      {
        include( $n_path . $n_file );
        $tmp = $comp . "_Conf";
        
        $arrItem = $$tmp;
        
        if ( isset( $arrItem[$item] ) )
        {
          $arrItem[$item] = $val_;
          write_config_def( $log_, $comp, $arrItem );
        }// 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 ) )
          {
//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;
//return "erro: $ii_ " . $item;
                }// End if( $ii_ == $item  )
              }// End foreach( $_arr_ as $ii_ => $_ite_ )
            }// End foreach( $arrINI as $_i_ => $_arr_ )
//return "erro:" . $t_ .'::'.$item;
            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 = $_SERVER['DOCUMENT_ROOT'] . '/studio/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 );
//return $nComp;

      // arquivo de configuração no padrão antigo
      // para manter compatibilidade com versão anterior
      if ( file_exists( $_SERVER['DOCUMENT_ROOT'] . '/studio/core/' . $nComp . '.comp.php' ) )
      {
        include( $_SERVER['DOCUMENT_ROOT'] . '/studio/core/' . $nComp . '.comp.php' );
        $tmp = $nComp . '_Conf';
         //return "erro: ".$tmp;
        $arrKey = $$tmp;
        //return "erro: ".$arrKey['marginTop'];
      }
      //
      //
      
      
      // arquivo de configuração no padrão novo
      if ( file_exists( $_SERVER['DOCUMENT_ROOT'] . '/studio/core/' . $nComp . '.comp.ini' ) )
      {
        $arrINI = readINIfile ( $_SERVER['DOCUMENT_ROOT'] . '/studio/core/' . $nComp . '.comp.ini', ';' );
        $arrKey = $arrINI[ strtolower($nComp) . '_conf' ];
        //return 'erro: ' . $arrKey;
      }
      //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 = $_SERVER['DOCUMENT_ROOT'] . "/studio/core/pattern/";
      $path2 = $_SERVER['DOCUMENT_ROOT'] . "/studio/desenv/usuarios/" . $log_ . "/" ;

      // 1º Passo:
      // criar o arquivo 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 if()
      
      // 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, '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');

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

