<?php
//=========================================================================================================
//============================================LIBRERIAS Y VARIABLES========================================
//=========================================================================================================
session_start();
//LIBRERIA DEL IDIOMA--------------------------------------------------------------------------------------
include("../../idiomas/idioma_".$_SESSION['lenguaje'].".php");
//CONEXION-------------------------------------------------------------------------------------------------
require_once '../../conexion/conexion.php';
$bd = new connexion();
$bd->query("SET NAMES 'utf8'");
//VARIABLES------------------------------------------------------------------------------------------------
$user = "";
$user = $_SESSION["user"];
$grupo = "";
$grupo = $_SESSION["grupo"];
//OBTENGO EL LINK ACTUAL DONDE SE ENCUENTRA EL USUARIO-----------------------------------------------------
$url_actual =  $_SESSION["url"];
//Valor del directorio destino para validar permisos-------------------------------------------------------
$dir_destino = $_POST['ubic'];
//Tipo de usuario------------------------------------------------------------------------------------------
$tipo_user = $_SESSION['tipo_user'];
//La URL almacenada----------------------------------------------------------------------------------------
$url = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
//==========================================================================================================
//============================================ACCIONES======================================================
//==========================================================================================================

//==========================================================================================================
//=====================================VALIDACIONES DE BOTONES==============================================
//VALIDO SI EL DIRECTORIO VA A SER CREADO EN UNA UBICACIÓN ESPECIAL=========================================
//cuento la string si tiene 9 digitos es un hijo de contacto------------------------------------------------
$string_cont = strlen($dir_destino);
//ES UN MODULO DISTINTO AL EXPLORADOR Y SE CREARA EN EL INBOS DEL USUARIO ASI QUE DOY PERMISO===============
if ($string_cont == 1) {
    $crear_new = 1;
}
//ES UN DIRECTORIO REGULAR==================================================================================
if ($string_cont == 16) {
    $dir = "20".$dir_destino;
    //OBTENGO EL ACCESO DEL DIRECTORIO----------------------------------------------------------------------
    $result = datosDirecotrio($bd, $dir);
    //CARGO LOS PERMISOS DE ACCESO DE LOS DOS CAMPOS ACCESO Y ACCESO AUTO-----------------------------------
    $acceso = $result['ACCESO'].$result['ACCESO_AUTO'];
    //VALIDO EL TIPO DE USUARIO-----------------------------------------------------------------------------
    if ($tipo_user == 0) {
      //Es un usuario interno
      $cadena_tipo = "*INT";
    }elseif ($tipo_user == 1) {
      //Es un usuario externo
      $cadena_tipo = "*EXT";
    }
    //VALIDACIONES PARA LA CREACION DE DIRECTORIO-----------------------------------------------------------
    //NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
    $crear_new = permisosCrearNuevo($acceso, $grupo, $user, $dir, $tipo_user, $cadena_tipo);
}
//ES LA RAIZ DEL PRIVADO O COMPARTIDOS======================================================================
if ($dir_destino == 100000001 OR $dir_destino == 100000002) {
  //Otorgo permisos-----------------------------------------------------------------------------------------
  $crear_new = 1;
}
//ES LA RAIZ DE LA BANDEJA DE USUARIO=======================================================================
if ($dir_destino == 100000003) {
  //Niego permisos------------------------------------------------------------------------------------------
  $crear_new = 0;
}
//ES LA RAIZ DEL DIRECTORIO DEL USUARIO=====================================================================
if ($string_cont == 7) {
    $dir = "US".$dir_destino;
    //OBTENGO EL ACCESO DEL DIRECTORIO----------------------------------------------------------------------
    $result = datosDirecotrio($bd, $dir);
    //CARGO LOS PERMISOS DE ACCESO DE LOS DOS CAMPOS ACCESO Y ACCESO AUTO-----------------------------------
    $acceso = $result['ACCESO'].$result['ACCESO_AUTO'];
    //VALIDO EL TIPO DE USUARIO-----------------------------------------------------------------------------
    if ($tipo_user == 0) {
      //Es un usuario interno
      $cadena_tipo = "*INT";
    }elseif ($tipo_user == 1) {
      //Es un usuario externo
      $cadena_tipo = "*EXT";
    }
    //VALIDACIONES PARA LA CREACION DE DIRECTORIO-----------------------------------------------------------
    //NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
    $crear_new = permisosCrearNuevo($acceso, $grupo, $user, $dir, $tipo_user, $cadena_tipo);
}
//ES EL INBOX DEL USUARIO===================================================================================
if ($string_cont == 10) {
    $dir = "US".$dir_destino.".INBOX";
    //OBTENGO EL ACCESO DEL DIRECTORIO----------------------------------------------------------------------
    $result = datosDirecotrio($bd, $dir);
    //CARGO LOS PERMISOS DE ACCESO DE LOS DOS CAMPOS ACCESO Y ACCESO AUTO-----------------------------------
    $acceso = $result['ACCESO'].$result['ACCESO_AUTO'];
    //VALIDO EL TIPO DE USUARIO-----------------------------------------------------------------------------
    if ($tipo_user == 0) {
      //Es un usuario interno
      $cadena_tipo = "*INT";
    }elseif ($tipo_user == 1) {
      //Es un usuario externo
      $cadena_tipo = "*EXT";
    }
    //VALIDACIONES PARA LA CREACION DE DIRECTORIO-----------------------------------------------------------
    //NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
    $crear_new = permisosCrearNuevo($acceso, $grupo, $user, $dir, $tipo_user, $cadena_tipo);
}
//==========================================================================================================
//============================================HTML==========================================================
//==========================================================================================================
//validacion de permisos sobre los botones------------------------------------------------------------------
if ($crear_new == 1) {
    //Otorgo permiso
    $disabled = "";
}elseif ($crear_new == 0) {
    //Niego permiso
    $disabled = "disabled";
}
//VALIDACION PAA VER SI EXISTEN PLANTILLAS PARA GENERAR DOCUMENTO Y HABILITAR O NO EL BOTON-----------------
//CONSULTO LAS PLANTILLAS DISPONIBLES
$resultado = btnEsquema($bd, $user, $grupo);
//DECLARO EL TOTAL EN CERO
$total = 0;
//CUENTO LA CANTIDAD DE PLANTILLAS DISPONIBLES
while ($fila = mysqli_fetch_row($resultado)) {
    $total++;
}
//VALIDO SI HABILITO EL BOTON A NO
if ($total > 0) {
  //Habilito
  $exist_plantilla = 1;
}else{
  //Inhablito
  $exist_plantilla = 0;
}
//html de los botones---------------------------------------------------------------------------------------
echo   "<div class='row' align='center'>
                    <!-------------------- BOTON DE NUEVO DOCUMENTO ------------------------------->";
                    if ($exist_plantilla == 0 OR $crear_new == 0) {
echo                    "<div class='col-xs-3 col-md-3'>
                            <a class='btn' role='button' data-toggle='tooltip' data-placement='bottom' title='".F_TOOLT_BTN_ACCION."' disabled>
                              <img src='recursos/img/ico/new_doc.ico'>
                            </a><br><p></p>
                         </div>";
                    }elseif ($exist_plantilla == 1 AND $crear_new == 1) {
echo                   "<div class='col-xs-3 col-md-3'>
                            <a class='btn' role='button' href='javascript:plantillasDocumentos();' data-toggle='tooltip' data-placement='bottom' title='".F_TOOLT_BTN_ACCION."'>
                              <img src='recursos/img/ico/new_doc.ico'>
                            </a><br><p></p>
                         </div>";                  
                    }
                    //Verifico si el servidor es seguro para habilitar la opción-----------------------
                    if (isset($_SERVER['HTTPS'])) {
                        // Codigo a ejecutar si se navega bajo entorno seguro.
                        $no_safe = 1;
                    } else {
                        // Codigo a ejecutar si NO se navega bajo entorno seguro.
                        $no_safe = 0;
                    }
echo"               <!-------------------- BOTON DE GRABAR DOCUMENTO ------------------------------->";
                    if ($crear_new == 0 OR $no_safe == 0) {
echo                    "<div class='col-xs-3 col-md-3'>
                            <a class='btn' role='button' data-toggle='tooltip' data-placement='bottom' title='".F_TOOLT_BTN_ACCION."' disabled>
                              <img src='recursos/img/ico/grabar.ico'>
                            </a><br><p></p>
                         </div>";
                    }elseif ($crear_new == 1 AND $no_safe == 0 ) {
echo                   "<div class='col-xs-3 col-md-3'>
                            <a class='btn' role='button' href='record.php' data-toggle='tooltip' data-placement='bottom' title='".F_TOOLT_BTN_ACCION."'>
                              <img src='recursos/img/ico/grabar.ico'>
                            </a><br><p></p>
                         </div>";                  
                    }
                    
                    //=========================================================================================
                    //VALIDO QUE ESTAMOS UBICADOS EN EL EXPLORADOR---------------------------------------------
                    //CARGO LA VARIABLE A BUSCAR
                    $buscar_explorador = 'explorador';
                    //HAGO LA BUSUQEDA
                    $pos_explorador = strpos($url_actual, $buscar_explorador);
                    //EVALUO 
                    if ($pos_explorador !== false) {
echo               "<!-------------------- BOTON DE NUEVA CARPETA ---------------------------------->";
                        if ($crear_new == 0) {
echo                        "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' data-toggle='tooltip' data-placement='bottom' title='".F_TIT_NEW_DIR."' disabled>
                                  <img src='recursos/img/ico/new_carp.ico'>
                                </a><br><p></p>
                            </div>";                         
                        }elseif ($crear_new == 1) {
echo                        "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' href='javascript:modalNuevoDirectorio();' data-toggle='tooltip' data-placement='bottom' title='".F_TIT_NEW_DIR."'>
                                  <img src='recursos/img/ico/new_carp.ico'>
                                </a><br><p></p>
                            </div>";
                        }
                    } 
                    //========================================================================================
                    //EVALUO SI ESTOY EN EL EXPLROADOR CREAR EL DOC EN EL DIRECTORIO ACTUAL-------------------
                    if ($pos_explorador !== false) {
                    //ME ENCUENTRO EN EL EXPLORADOR
echo"              <!-------------------- BOTON DE DOCUMENTO PENDIENTE --------------------------->";
                        if ($crear_new == 0) {
echo                        "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' data-toggle='tooltip' data-placement='bottom' title='".F_BTN_DOCUMENTO_PEND."' disabled>
                                  <img src='recursos/img/ico/pendiente.gif' width='48' height='48'>
                                </a><br><p></p>
                            </div>";
                        }elseif ($crear_new == 1) {
echo                       "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' href='javascript:modalNewDocEmpty(1);' data-toggle='tooltip' data-placement='bottom' title='".F_BTN_DOCUMENTO_PEND."'>
                                  <img src='recursos/img/ico/pendiente.gif' width='48' height='48'>
                                </a><br><p></p>
                            </div>"; 
                        }
                    }elseif ($pos_explorador === false) {
                    //ME ENCUENTRO EN LSO PENDIENTES
echo"              <!-------------------- BOTON DE DOCUMENTO PENDIENTE --------------------------->";
                        if ($crear_new == 0) {
echo                       "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' data-toggle='tooltip' data-placement='bottom' title='".F_BTN_DOCUMENTO_PEND."' disabled>
                                  <img src='recursos/img/ico/pendiente.gif' width='48' height='48'>
                                </a><br><p></p>
                            </div>";
                        }elseif ($crear_new == 1) {
echo                       "<div class='col-xs-3 col-md-3'>
                                <a class='btn' role='button' href='javascript:modalNewDocEmpty(1);' data-toggle='tooltip' data-placement='bottom' title='".F_BTN_DOCUMENTO_PEND."'>
                                  <img src='recursos/img/ico/pendiente.gif' width='48' height='48'>
                                </a><br><p></p>
                            </div>";
                        }
                    }
echo"        </div>  
		        </div>
        </div>";
//===========================================================================================================
//============================================FUNCIONES======================================================
//===========================================================================================================
//OBTENGO LOS DATOS DEL DIRECTORIO---------------------------------------------------------------------------
function datosDirecotrio($bd, $dir)
{
  $sql =  " SELECT BE.ACCESO, BE.ACCESO_AUTO, BE.CREADOR
            FROM BIBLIOTECA_ELEMENTOS BE
            WHERE BE.CLAVE = '$dir'";
  $base = $bd->query($sql);
  $result = mysqli_fetch_array($base);
  $base->close();
  return $result;
}
//Funcion PARA OBTENER LA CANTIDAD DE PLANTILLAS HTML CON ESQUEMAS-------------------------------------------
function btnEsquema($bd, $user, $grupo) {
  $sql =  " SELECT DISTINCT E.DESCRIPCION
            FROM ESQUEMAS E
            INNER JOIN BIBLIOTECA_ETIQUETAS BE
            ON E.CODIGO = BE.ESQUEMA
            INNER JOIN BIBLIOTECA_ELEMENTOS EL
            ON BE.CLAVE = EL.CLAVE
            WHERE E.CODIGO > 0 AND E.ACTIVO = 1 AND ( EL.EXTENSION = 'HTML' OR EL.EXTENSION = 'HTM' ) 
            AND EL.UBICACION LIKE '##PUBLICO##/##PLAN_PUB##/%' AND EL.PAPELERA = 0
            ORDER BY E.DESCRIPCION ASC";
  $base = $bd->query($sql);
  return $base;
  $base->close();
}
//FUNCION PARA ESTABLECER ACCESOS PARA EL DOWNLOAD-----------------------------------------------------------
function permisosCrearNuevo($acceso, $grupo, $user, $id_dir, $tipo_user, $cadena_tipo)
{
      //Por defecto niego el permiso=====================================================
       $crear_new = 1;
      //VALIDO LOS PERMISOS POR GERARQUIA USUARIO->GRUPO->TIPO===========================
      //LO HAGO A LA INVERSA INICIO POR EL TIPO------------------------------------------
      //================VALIDO PERMISOS=====================
      //BUSCO POR TIPO======================================
      //$1 TOTAL
      $findme_grupo   = '#'.$cadena_tipo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $crear_new = 1;
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $crear_new = 0;
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $crear_new = 1;
        }
      }
  return $crear_new;
}
?>