<?php
  /**
   * MiniClick
   * Gestionnaire de tableau collaboratif
   * Copyright (C) 2006 Guillaume Monet <gm@ibreizh.net>
   *
   * This program is free software; you can redistribute it and/or modify
   * it under the terms of the GNU General Public License as published by
   * the Free Software Foundation; either version 2 of the License, or
   * any later version.
   *
   * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program; if not, write to the Free Software
   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 
   *
   * @package miniclick
   * @version 5.0.0
   * @author Guillaume Monet
   */

  //Test de l'appel par le main ou un descendant 
if($GLOBALS['main'] != 1)
  {
    die("Cannot acces directly to this page");
  }

//define_syslog_variables();

class miniclick{
  
  var $module_id;
  var $table;

  var $smarty;

  var $headers;
  var $labels;
  var $types;
  var $values;
  var $defauts;
  var $sizes;
  var $displays;
  var $totaux;
  var $workflows;
  var $read_perm;
  var $write_perm;
  var $key;

  var $nb_headers;

  var $simple_query;
  var $query;
  var $mini_query;
  var $no_limit_query;
  var $select;
  var $where;
  var $having;

  var $current_page;
  var $vue_condition;
  var $vue_rows;
  var $max_elems;
  var $count;
  var $db;

  /**
   * Constructeur de la classe Miniclick
   * @param $table la table à afficher
   * @see "Uses of MiniClick docs"
   */
  function miniclick($table)
  {
    $this->db = db_interface::getInstance();
    $this->db->db_select($_SESSION['database']);
    
    $debut = $this->debut_calcultemps();
    $module_query = "SELECT `Module_Id`,`Table` FROM MODULE WHERE Nom='"
      .$table."' AND App_Id='".$_SESSION['app_id']."'";
    $modules = $this->db->db_query($module_query);
    $module = $this->db->db_fetch_object($modules);
    $this->module_id = $module->Module_Id;
    $this->table = $module->Table;

    $this->current_page = stripcslashes($_SERVER["REQUEST_URI"]);
    $sql_query = "SELECT DISTINCT "
      ." CONFIG.Colonne,Label,Type,IsKey,Value,"
      ."Defaut,Size,Afficher,Total,Wf,Read_Perm,Write_Perm "
      ." FROM CONFIG,DROIT WHERE CONFIG.Module_Id='"
      .$this->module_id."' AND DROIT.Module_Id='"
      .$this->module_id."' AND DROIT.Role_Id='".$_SESSION['role_id']
      ."' AND CONFIG.Colonne = DROIT.Colonne ORDER BY Position";
    print $sql_query."<<<";
    $configs = $this->db->db_query($sql_query);
    
    $this->key = "";

    $this->headers = array();
    $this->labels = array();
    $this->types = array();
    $this->values = array();
    $this->defauts = array();
    $this->sizes = array();
    $this->displays = array();
    $this->totaux = array();
    $this->workflows = array();
    $this->read_perm = array();
    $this->write_perm = array();

    $this->smarty = new Smarty();
    $this->smarty->template_dir = SMARTY_TEMPLATE_DIR;
    $this->smarty->compile_dir = SMARTY_COMPILE_DIR;
    $this->smarty->config_dir = SMARTY_CONFIG_DIR;
    $this->smarty->cache_dir = SMARTY_CACHE_DIR;
    $this->generate_views();
    $shown = explode(",",$this->vue_rows);

    // BUG: This config detection does not detect anything
    // at all, the default config is always generated although
    // there is already one.
    // https://savannah.nongnu.org/bugs/?21361

    if($this->db->db_num_rows($configs) == 0)
      {
        $this->generate_defaut_config();
      }

    // BUG: Ici pas de else: Si il trouve 0, enchaine
    // de suite avec le while(fetch()) alors qu'il est "vide"
    // Il faut peut-etre refaire un query().
    // Regarder si generate_defaut_config() ne s'en charge pas deja
    // https://savannah.nongnu.org/bugs/?21362

    while($config = $this->db->db_fetch_object($configs))
      {
      
        if(($config->Display != "false" 
            && ($this->vue_rows == "*" || in_array($config->Colonne_Id,$shown))) 
           || $config->IsKey == "1")
          {
            if($config->IsKey == "1")
              {
                $this->key =  $config->Colonne;
              }
            $this->nb_headers++;
            array_push ($this->headers,$config->Colonne);
            array_push ($this->labels,$config->Label);
            array_push ($this->types,$config->Type);
            array_push ($this->values,$config->Value);
            array_push ($this->defauts,$config->Defaut);
            array_push ($this->sizes,$config->Size);
            array_push ($this->displays,$config->Afficher);
            array_push ($this->totaux,$config->Total);
            array_push ($this->workflows,$config->Wf);
            array_push ($this->read_perm,$config->Read_Perm);
            array_push ($this->write_perm,$config->Write_Perm);
          }
      }
    
    $this->smarty->assign('form_action',htmlentities($this->current_page));
    
    $scripts = $this->db->db_query("SELECT * FROM SCRIPT WHERE Module_Id='".$this->module_id."'");
    $ret_scripts = array();
    while($script = $this->db->db_fetch_object($scripts))
      {
        array_push($ret_scripts, array('nom'=>$script->Nom,'lien'=>$script->Lien));
      }
    $this->smarty->assign('scripts',$ret_scripts);

    $this->generate_request();
    if($_POST['action'] != "")
      {
        $this->do_action($_POST['action']);
      }
    $this->generate_headers();
    $this->generate_datas();
    $this->generate_totals();
    $this->generate_tools();
    $this->generate_pages();
    $this->smarty->assign('template_dir_images',SMARTY_IMAGE_DIR_APP);
    
    $this->smarty->display('miniclick/miniclick.tpl');
    
    // echo 'temps',$this->ecrire_temps($debut,10);
    
  }

  function generate_defaut_config()
  {
    $fields = $this->db->db_query("DESCRIBE ".$this->table);
    $pos = 0;
    $key = "";
    while($field = $this->db->db_fetch_object($fields))
      {
        $pos++;
        if($field->Key == "PRI")
          {
            $key = "1";
          }else{  
          $key = "0";
        }
        $insert_config="INSERT INTO CONFIG  VALUES('','"
          .$this->module_id."','"
          .$field->Field."','$pos','$key','INPUT','','10','0','0','','1','"
          .$field->Field."')";
        $this->db->db_query($insert_config);
      }
  }

  function generate_views()
  {
    $views = array();
    $sql_query = "SELECT `Vue_Id`,`Nom`,`Module_Id`,`Rows`,`Condition`,`Defaut` FROM VUE WHERE Module_Id='"
      .$this->module_id."' ORDER BY `Ordre`";
    $vues = $this->db->db_query($sql_query) ;
    if($this->db->db_num_rows($vues) == 0)
      {
        $this->generate_defaut_view();
      }
    while($vue = $this->db->db_fetch_object($vues))
      {
        $actif = 0;
        if($_GET['vue'] == $vue->Vue_Id || ($_GET['vue'] == "" && $vue->Defaut=="1"))
          {
            $actif = 1;
            $this->vue_condition = $vue->Condition;
            $this->vue_rows=$vue->Rows;
          }
        array_push($views,array('nom'=>$vue->Nom,'lien'=>htmlentities($this->current_page)
                                ."&amp;vue=$vue->Vue_Id"."&amp;$vue->Condition",'actif'=>"$actif" ));  
      }
    $this->smarty->assign('views',$views);
  }

  function generate_defaut_view()
  {
    $this->db->db_query("INSERT INTO VUE VALUES('','Tout','".$this->module_id."','*','','1','1')");
  }

  function generate_request()
  {
    $query = "";
    $select = "";
    $where = "";
    $having = "";
    $order = "";

    $mini_query ="";
    $mini_select = "";
    $mini_where = "";
    $mini_having = "";
    $key = $this->key;
    if($this->vue_condition != "")
      {
        if($_GET['where'] != "")
          {
            $_GET['where'] .= " AND ".$this->vue_condition;
          }else{
          $_GET['where'] = " ".$this->vue_condition;
        }
      }
    $_GET['where'] = stripslashes($_GET['where']);
    $cwhere = explode(" AND ",$_GET['where']);
    if(strlen($_GET['where']) > 0)
      {
        foreach($cwhere as $clause)
          {
            $cl = explode("=",$clause);
            $c_id = stripslashes($cl[0]);
            $c_value = stripslashes($cl[1]);
            $c_value =  str_replace("'","",$c_value);
            if(isset($_POST[$c_id]) || in_array($c_id,$this->headers))
              {
                $_POST[$c_id] = $c_value;
              }else{
              $where .= "$c_id = '$c_value' AND ";
              $_POST[$c_id] = $c_value;
            }
          }
      }
    $mini_where = $where;
    
    for($i = 0 ; $i < $this->nb_headers ; $i++)
      {
        $value = $this->headers[$i];
        $label = $this->labels[$i];
        $select .= "`".$value."`";
        $mini_select .= "`".$value."`";
        if ($_POST[$value] != "" && $_POST[$value] != $label) {  
          if(($_POST[$value]{0} == "=" || $_POST[$value]{0} == ">" || $_POST[$value]{0} == "<" ) 
             && is_numeric(substr($_POST[$value],1)))
            {
              $where .= "$value ".$_POST[$value];
              $mini_where .=  "$value ".$_POST[$value];
            }else{
            if($this->types[$i] == "RECHERCHE" 
               || $this->types[$i] == "LINKED" 
               || $this->types[$i] == "COMPLETION")
              {
                if(strstr($_POST[$value],'_'))
                  {
                    $having .= "(LINKED_".$value." like '".$_POST[$value]
                      ."' OR   '$_POST[$value]' LIKE REPLACE(LINKED_".$value.",'%',''))";
                    $mini_having .= "(LINKED_".$value." like '".$_POST[$value]
                      ."' OR   '$_POST[$value]' LIKE REPLACE(LINKED_".$value.",'%',''))";
                  }else{
                  $having .= "(LINKED_".$value." LIKE '%".$_POST[$value]
                    ."%' OR '$_POST[$value]' like REPLACE(LINKED_".$value.",'%',''))";
                  $mini_having .= "(LINKED_".$value." LIKE '%".$_POST[$value]
                    ."%' OR '$_POST[$value]' like REPLACE(LINKED_".$value.",'%',''))";
                }
                if($having != "")
                  {
                    $having .= " AND ";
                    $mini_having .= " AND ";
                  }
              }else{ 
              if(strstr($_POST[$value],'_'))
                {
                  $where .= "($value like '$_POST[$value]' OR '".$_POST[$value]."' like REPLACE($value,'%',''))";
                  $mini_where .= "($value like '$_POST[$value]' OR '".$_POST[$value]."' like REPLACE($value,'%',''))";

                }else{
                $where .= "($value like '%$_POST[$value]%' OR '".$_POST[$value]."' like REPLACE($value,'%',''))";
                $mini_where .= "($value like '%$_POST[$value]%' OR '".$_POST[$value]."' like REPLACE($value,'%',''))";
              }
              if($where != "")
                {
                  $where .= " AND ";
                  $mini_where .= " AND ";
                }
            
            }
          }
        }
        if($this->types[$i] == "RECHERCHE" 
           || $this->types[$i] == "LINKED" 
           || $this->types[$i] == "COMPLETION")
          {
            $vars = explode(",",$this->values[$i]);
            if(count($vars) > 1)
              {
                $select.=",(SELECT `".$vars[0]."` FROM ".$this->defauts[$i]." WHERE "
                  .$this->defauts[$i].".".$vars[1]."=".$this->table.".".$vars[1].") AS LINKED_".$this->headers[$i];
                $mini_select.=",(SELECT `".$vars[0]."` FROM ".$this->defauts[$i]." WHERE "
                  .$this->defauts[$i].".".$vars[1]."=".$this->table.".".$vars[1].") AS LINKED_".$this->headers[$i];
              }else{ 
              $select.=",(SELECT `".$this->values[$i]."` FROM ".$this->defauts[$i]." WHERE "
                .$this->defauts[$i].".".$this->headers[$i]."=".$this->table."."
                .$this->headers[$i].") AS LINKED_".$this->headers[$i];
              $mini_select.=",(SELECT `".$this->values[$i]."` FROM ".$this->defauts[$i]." WHERE "
                .$this->defauts[$i].".".$this->headers[$i]."=".$this->table."."
                .$this->headers[$i].") AS LINKED_".$this->headers[$i];
            }
        
          }

        if($this->types[$i] == "SUM")
          {
            // $select.=",(SELECT ".str_replace(",","+",$this->values[$i])." FROM ".$this->table." WHERE "
            // .$this->table.".".$key."=".$this->table.".".$key.") AS SUM_".$this->headers[$i];
            // $mini_select.=",(SELECT ".str_replace(",","+",$this->values[$i])." FROM ".$this->table
            // ." WHERE ".$this->table.".".$key."=".$this->table.".".$key.") AS SUM_".$this->headers[$i];
          }
  
        if($this->workflows[$i] == "1")
          {
            $select.=",(SELECT Valider FROM WORKFLOW WHERE WORKFLOW.Objet_Id="
              .$this->module_id.".".$key." AND WORKFLOW.Colonne = '$value' AND WORKFLOW.Module_Id='"
              .$this->module_id."' LIMIT 1) AS AWF_$value";
            $select.=",(SELECT Workflow_Perm FROM DROIT WHERE DROIT.Colonne = '$value' AND DROIT.Module_Id='"
              .$this->module_id."' AND DROIT.Role_Id='".$_SESSION['role_id']."' LIMIT 1) AS DWF_$value";
          }

        if($this->nb_headers != $i+1)
          {
            $select .= ",";
            $mini_select .=",";
          }
      }
    if(substr($where,-5) == " AND ")
      {
        $where = substr($where,0,strlen($where)-5);
        $mini_where = substr($mini_where,0,strlen($mini_where)-5);
      }
    if(substr($having,-5) == " AND ")
      {
        $having = substr($having,0,strlen($having)-5);
        $mini_having = substr($mini_having,0,strlen($mini_having)-5);
      }

    if($_POST['sort'] != "")
      {
        $order = " ORDER BY $_POST[sort] $_POST[order]";
      }

    if($having != "")
      {
        $having = "HAVING ".$having;
        $mini_having = "HAVING ".$mini_having;
      }
    // On genere la requete sql
    $count = "";
    if($where == "")
      {
        // BUG: $select is set but empty!
        $query = "SELECT $select FROM ".$this->table." $having $order";
        $mini_query = "SELECT $mini_select FROM ".$this->table." $mini_having $order";
      }
    else
      {
        print "WHERE pas vide";
        $query = "SELECT $select FROM ".$this->table." WHERE $where  $having $order";
        $mini_query = "SELECT $mini_select FROM ".$this->table." WHERE $mini_where  $mini_having $order";
      }
    $this->query =$query;
    $this->select = $select;
    $this->where = $where;
    $this->having = $having;
    $page = $_POST['page'];
    if($page=="")
      {
        $page = 0;
      }
  
    $this->no_limit_query = $this->query;
    $this->mini_query = $mini_query;
    $this->query .= " LIMIT $page,".MINICLICK_MAX_ROW_DISPLAY;
  }

  function generate_pages()
  {    
    $page = $_POST['page'];
    if($page=="")
      {
        $page = 0;
      }
    $this->smarty->assign('sort',$_POST['sort']);
    $this->smarty->assign('order',$_POST['order']);
    $this->smarty->assign('sort',$_POST['sort']);
    $this->smarty->assign('module_id',$this->module_id);
    $this->smarty->assign('page_minus',$page-MINICLICK_MAX_ROW_DISPLAY);
    $this->smarty->assign('page_plus',$page+MINICLICK_MAX_ROW_DISPLAY);
    $this->smarty->assign('page_max_minus',$this->max_elems-MINICLICK_MAX_ROW_DISPLAY);
    $this->smarty->assign('page_current',$page);  
  }

  function generate_headers()
  {
    
    $headers = array();
    for($i = 0 ; $i < $this->nb_headers ; $i++)
      {
        $tphead = $this->headers[$i];
        $tplabel = $this->labels[$i];
        $text = "";
        $class = "0";
        if ($_POST[$tphead] !="" && $_POST[$tphead] != $tplabel) {
          $text = $_POST[$tphead];
          $class="1";
        }else{
          $text = $tplabel;
        }
        $order = "";
        $imgorder = "";
        if($_POST['order']!="desc" && $_POST['sort'] == $tphead)
          {
            $order = "desc";
            $imgorder = "down";
          }else{
          $order = "asc";
          $imgorder = "up";
        }
        array_push($headers,array('id'=>$tphead,'size'=>$this->sizes[$i],'text'=>$text,'style'=>$class,'order'=>$order,'imgorder'=>$imgorder,'display'=>$this->displays[$i]));
      }
    $this->smarty->assign('headers',$headers);
  }

  function generate_datas()
  {
    $key = $this->key;
    $datas = array();
    $sql_datas = $this->db->db_query($this->query);
    while($ligne = $this->db->db_fetch_object($sql_datas))
      {
        $tmp = array();
        for($i = 0 ; $i < $this->nb_headers ; $i++)
          {
            $tphead = $this->headers[$i];
            $id = $tphead.$ligne->$key;
            $value = $ligne->$tphead;
        
            $size = $this->sizes[$i];
            $type = $this->types[$i];
            if($type == "SPECIAL")
              {
                $array_values = $this->values[$i];
                if($array_values != "")
                  {
                    $exp = explode("=",$array_values);
                    if(count($exp) > 1)
                      {
                        $arg1 = $exp[0];
                        $arg2 = $exp[1]; 
                      }else{
                      $arg1 = $exp[0];
                      $arg2 = $exp[0];
                    }
                  }else{
                  $arg1 = $key;
                  $arg2 = $key;
                }
                $value = str_replace("[where]",$arg1."='".$ligne->$arg2."'",$this->defauts[$i]);
              }
            $linked = "";
            if($type == "RECHERCHE" || $type == "LINKED" || $type == "COMPLETION")
              {
                $id_link = "LINKED_".$tphead;
                $vals = explode(";",$value);
                if(count($vals) > 1)
                  {
                    $tp_vals = explode(",",$this->values[$i]);
                    $select = $tp_vals[0];
                    $egal = $tp_vals[1];
                    if($egal == "")
                      {
                        $egal = $tphead;
                      }
                    foreach($vals as $val)
                      {
                        $tp_query_vals = $this->db->db_query("SELECT $select AS Value FROM ".$this->defauts[$i]." WHERE $egal='$val'");
                        while($tp_query_val = $this->db->db_fetch_object($tp_query_vals))
                          {
                            $linked .= $tp_query_val->Value." ";
                          }
                      }
                  }else{
                  $linked = $ligne->$id_link;
                }
              }

            if($type == "SUM")
              {
                $id_link = "SUM_".$tphead;
                $value = $ligne->$id_link;
              }
        
            $next = array();
            if($type == "ROLL")
              {
                if(!strrpos($value,";"))
                  {
                    $value = $this->defauts[$i];
                  }
                $tmp_array = explode(";",$value);
                foreach ($tmp_array as $tmp_item)
                  {
                    $tmp_ar = explode(",",$tmp_item);
                    $tmp_linked = explode(":",$tmp_ar[0]);
                    $tmp_next = explode(":",$tmp_ar[1]);
                    array_push($next,array('nom'=>$tmp_linked[1],'array_next'=>$tmp_next[1]));
                  }
              }
            $value = htmlentities($value);
            if($this->read_perm[$i] == "0")
              {
                $type="NONE";
              }else{
              if($this->write_perm[$i] == "0")
                {
                  $type="RO";
                  if($type != "INPUT" && $type != "RECHERCHE")
                    {
                      $type="RO";
                    }
                }
            }
            $col_wf_actif = "AWF_".$tphead;
            $col_wf_droit = "DWF_".$tphead;
            $wf_actif = "0";
            $wf_droit = "0";
            if($ligne->$col_wf_actif == "1")
              {
                $wf_actif = "1";
              }
            if($ligne->$col_wf_droit == "1")
              {
                $wf_droit = "1";
              }        
            array_push($tmp,array('col'=>$tphead,'value'=>$value,'size'=>($size+3),'id'=>$id,'type'=>$type,'linked'=>$linked,'table'=>($this->defauts[$i]),'workflow_col'=>$this->workflows[$i],'next'=>$next,'wf_droit'=>$wf_droit,'wf_actif'=>$wf_actif,'display'=>$this->displays[$i]));
          }
        array_push($datas,array('ligneid'=>$ligne->$key,'values'=>$tmp));
      }
    $this->smarty->assign('datas',$datas);
    unset($sql_datas);
  }

  function generate_totals()
  {
    $totals = array();
    $select_sql_query = "";
    for($i = 0 ; $i < $this->nb_headers ; $i++)
      {
        if($this->totaux[$i]=="1")
          {
            $head = $this->headers[$i];
            $select_sql_query .= "SUM($head) AS TOTAL_$head,";
          }
      }
    $select_sql_query .= "COUNT(".$this->key.") AS Nombre";
    $qu_tot = "SELECT $select_sql_query FROM (".$this->mini_query.") AS tempo";
    
    $resultats = $this->db->db_query($qu_tot);
    $resultat = $this->db->db_fetch_object($resultats);
    for($i = 0 ; $i < $this->nb_headers ; $i++)
      {
        if($this->totaux[$i]=="1")
          {
            $head = "TOTAL_".$this->headers[$i];
            $res = $resultat->$head;
            array_push($totals,array('value'=>$res));
          }else{
          array_push($totals,array('value'=>""));
        }
      }
    $this->smarty->assign('col_totals',$totals);
    $this->smarty->assign('page_max',$resultat->Nombre);
    $this->max_elems = $resultat->Nombre;
  }

  function generate_tools()
  {
    $this->smarty->assign('role',$_SESSION["role_id"]);
  }

  function do_action($action)
  {
    switch($action)
      {
      case "EXP":
        include("export_include.php");
        export_cvs_table($this->no_limit_query);
        break;

      case "REM":
        //$rem_query = "UPDATE ".$this->table." SET ".$_POST['rr_colonne']."=REPLACE(".$_POST['rr_colonne'].",'".$_POST['rr_recherche']."','".$_POST['rr_par']."')  WHERE ".$_POST['rr_colonne']." like '%".$_POST['rr_recherche']."%' AND ".$this->key." IN (SELECT ".$this->key." FROM ((".$this->no_limit_query.") AS Temp ))";
        $sp_query=$this->no_limit_query;
        $que= $this->db->db_query($sp_query);
        $key = $this->key;
        while($id = $this->db->db_fetch_object($que))
          {
            $col = $_POST['rr_colonne'];
            $val = $id->$col;
            if($_POST['rr_recherche'] == "" && $val == "")
              {
                $res = $_POST['rr_par'];
              }else{
              $res = str_replace($_POST['rr_recherche'],$_POST['rr_par'],$val);
            }
            $rem_query = "UPDATE ".$this->table." SET ".$_POST['rr_colonne']."='$res' ";
            if($val == "" && $_POST['rr_recherche'] == "")
              {
                $rem_query .= " WHERE (".$_POST['rr_colonne']." like '%".$_POST['rr_recherche']."%' OR  ".$_POST['rr_colonne']."  IS NULL ) AND ".$key."='".$id->$key."' ";
              }else{
              $rem_query .= " WHERE ".$_POST['rr_colonne']." like '%".$_POST['rr_recherche']."%' AND ".$key."='".$id->$key."'";
            }
            //echo $rem_query;
            $this->db->db_update($rem_query);
          }
        break;

      case "MAJ":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        break;

      case "ADD":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        break;

      case "ADD10":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->add_row_table($this->table,$this->headers,$this->defauts,$this->key);
        break;

      case "WRK":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->workflow_validate_table($this->table,$_POST["wf_key"],$_POST["wf_col"]);
        break;
  
      case "UWK":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->workflow_unvalidate_table($this->table,$_POST["wf_key"],$_POST["wf_col"]);
        break;

      case "DEL":
        $this->delete_row_table($this->table,$this->headers,$this->key);
        break;

      case "DUP":
        $this->update_table($this->table,$this->headers,$this->defauts,$this->key);
        $this->duplicate_row_table($this->table,$this->headers,$this->key);
        break;

      case "FIL":
        $this->filtre_table($this->table,$this->headers,$this->key,$_POST["filtre_id"]);
        break;
      
      case "LOC":
        include('locate.php');
        break;

      case "WAY":
        include('trajet.php');
        break;
      
      case "SFI":
        $this->create_filtre_table($this->table,$this->headers,$this->key,$_POST["filtre_id"]);
        break;
      
      case "SEQ":
        echo "Sequence";
        $this->sequence_table($_POST['sq_key'],$_POST['sq_col'],$_POST['sq_nex']);
        break;
      }
  }
  function add_row_table($table,$headers,$defauts,$key)
  {
    $insert = "";
    $values = "";
    $headers = array();
    $heads = $this->db->db_query("DESCRIBE $table");
    while($head = $this->db->db_fetch_object($heads))
      {
        array_push($headers,$head->Field);
      }
    $nb_headers = count($headers);
    for($i = 0 ; $i < $nb_headers ; $i++)
      {
        $insert .= "`".$headers[$i]."`,";
        $temp = $headers[$i];
        $types = $this->db->db_query("SELECT Label,Type,Defaut,Value FROM CONFIG WHERE Module_Id = '".$this->module_id."' AND Colonne='$temp'");
        $resultat = $this->db->db_fetch_object($types);
        $type = $resultat->Type;
        $defaut = $resultat->Defaut;
        $value = $resultat->Value;
        $label = $resultat->Label;
        if ($_POST[$temp] !="" && $_POST[$temp] != $label) {
          if($type == "RECHERCHE")
            {
              $tp_query = "SELECT $temp AS Value FROM ".$defaut." WHERE ".$value."='".$_POST[$temp]."' LIMIT 1";
              $res_tp_query = $this->db->db_query($tp_query);
              $re_tp_query=$this->db->db_fetch_object($res_tp_query);
              $values .= "'".$re_tp_query->Value."',";
            }else{
            $values .= "'".$_POST[$temp]."',";
          }
        }else{
          $def = $defaut;
          if($_SESSION[$def] != "")
            {
              $values .= "'".$_SESSION[$def]."',";
            }else{
            $values .= "'".$defaut."',";
          }
        }
      }
    $insert = substr($insert,0,strlen($insert)-1);
    $values = substr($values,0,strlen($values)-1);
    $sql_query = "INSERT INTO $table ($insert) VALUES ($values)";
    if($this->db->db_insert($sql_query))
      {
        //$this->throw_infos("[ADD] Ajout d'une ligne OK");
      }else{
      //$this->throw_errors("[ADD] Erreur lors de l'ajout d'une ligne");
    }
  }

  function update_table($table,$headers,$defauts,$key)
  {
    $values = $this->db->db_query($this->query);
    while($ligne = $this->db->db_fetch_object($values))
      {
        $sem = "SEM".$ligne->$key;
        if($_POST[$sem] == "ON")
          {
            for($i = 0 ; $i < $this->nb_headers ; $i++)
              {
                $value = $headers[$i];
                $t = $value."".$ligne->$key;
                $val = $_POST[$t];
                $prev = $this->db->db_query("SELECT $value FROM $table WHERE $key='".$ligne->$key."'");
                $pre = $this->db->db_fetch_object($prev);
                if($pre->$value != $val)
                  {
                    $arch = "INSERT INTO ARCHIVAGE VALUES('','$table','".$ligne->$key."','$value','".$pre->$value."','".date('ymdHis')."','".$_SESSION['login']."','')";
                    $upd = "UPDATE $table SET $value = '$val' WHERE $key='".$ligne->$key."'";
                    $this->db->db_insert($arch);
                    $this->db->db_update($upd);
                  }
              }
          }
      }
  }

  function duplicate_row_table($table,$headers,$key)
  {
    $values = $this->db->db_query($this->query);
    while($ligne = $this->db->db_fetch_object($values))
      {
        $check = "CK".$ligne->$key;
        if("$_POST[$check]" == "on")
          {
            $insert = "";
            $fields = $this->db->db_query("DESCRIBE $table");
            while($field = $this->db->db_fetch_object($fields))
              {
                $value = $field->Field;
                if($value != $key)
                  {
                    $insert .= "'".addslashes($ligne->$value)."'";
                    $insert .= ",";  
                  }else{
                  $insert .= "''";
                  $insert .= ",";
                }
              }
            $insert = substr($insert,0,strlen($insert)-1);
            $sql_query = "INSERT INTO $table VALUES($insert)";
            $this->db->db_insert($sql_query);
            $this->save_actions($table,$ligne->$key,"DUP",$sql_query);
          }
      }
  }

  function delete_row_table($table,$headers,$key)
  {
    $values = $this->db->db_query($this->query);
    while($ligne = $this->db->db_fetch_object($values))
      {
        $check = "CK".$ligne->$key;
        if("$_POST[$check]" == "on")
          {
            $this->save_actions($table,$ligne->$key,"DEL",implode(",",$this->db->db_fetch_array($this->db->db_query("SELECT * FROM $table WHERE $key= '".$ligne->$key."'"))));
            $this->db->db_delete("DELETE FROM $table WHERE $key= '".$ligne->$key."'");
          }
      }
  }

  function workflow_validate_table($table,$key,$colonne)
  {
    $this->db->db_insert("INSERT INTO WORKFLOW VALUES('','$table','$key','$colonne','true','')");
  }

  function workflow_unvalidate_table($table,$key,$colonne)
  {
    $this->db->db_insert("DELETE FROM WORKFLOW WHERE Objet_Id='$key' AND Colonne_Id='$colonne' AND Valider='true'");
  }

  function sequence_table($key,$colonne,$step_suivant)
  {
    $steps = $this->db->db_query("SELECT Module_Id,Colonne_Id,Action,Step,Nexts FROM CYCLE WHERE Module_Id='".$this->table."' AND Colonne_Id='$colonne' AND Step='$step_suivant'");
    $step = $this->db->db_fetch_object($steps);
    if(file_exists("apps/".$_SESSION['app']."/scripts/functions_".$this->table.".php"))
      {
        include("apps/".$_SESSION['app']."/scripts/functions_".$this->table.".php");
        $funtion = "step_".$step_suivant."($key,$colonne)";
        $$function;
      }
    $nexts = explode(",",$step->Nexts);
    $res = "";
    foreach($nexts as $next)
      {
        $steps = $this->db->db_query("SELECT Nom FROM CYCLE WHERE Module_Id='".$this->table."' AND Colonne_Id='$colonne' AND Step='$next'");
        $step = $this->db->db_fetch_object($steps);
        $res.="LINK:".$step->Nom.",NEXT:$next;";
      }
    $this->db->db_query("UPDATE ".$this->table." SET $colonne ='$res' WHERE ".$this->key."='$key'");
  }

  function save_actions($table_id,$object_id,$action,$description)
  {
    $description = addslashes($description);
    $this->db->db_insert("INSERT  INTO  `ACTION` (  `Action_Id` ,  `Module_Id` ,  `Object_Id` ,  `Acteur_Id` ,  `Description` ,  `Type_action` ,  `Date`  ) VALUES ( '',  '$table_id',  '$object_id',  '".$_SESSION['login']."',  '$description',  '$action',  '".date('ymdHis')."')");
  }

  function throw_errors($string_errors)
  {
    $this->smarty->assign('error',$string_errors);
    $this->smarty->display('miniclick/miniclick_errors.tpl');
  }

  function throw_infos($string_infos)
  {
    $this->smarty->assign('info',$string_infos);
    $this->smarty->display('miniclick/miniclick_infos.tpl');
  }


  function debut_calcultemps() {
    $trouver_temps = explode(' ',microtime() );
    $temps_debut = $trouver_temps[1].substr($trouver_temps[0], 1);
    return $temps_debut;
  }

  function ecrire_temps($temps_debut,$precision) {
    $partie_temps = explode(' ',microtime() );
    $fin_temps = $partie_temps[1].substr($partie_temps[0],1);
    $chrono = number_format($fin_temps - $temps_debut, 4);
    if($precision > strlen($chrono)) {
      $chrono = substr($chrono, 0, strlen($chrono)); //on donne la precision maximale
    } else {
      $chrono = substr($chrono, 0, $precision);
    }
    return $chrono;
  }
}
?>