<?php
//====================================================================================================
//============================================LIBRERIAS Y VARIABLES===================================
//====================================================================================================
session_start();
//LIBRERIA DEL IDIOMA
include("../../idiomas/idioma_".$_SESSION['lenguaje'].".php");
// lib ------------------------------------------------------------------------------------
require_once '../../lib/config.php';
//libreria mobile detect-------------------------------------------------------------------
require_once '../../recursos/MobileDetect/Mobile_Detect.php';
//-----------------CONECION---------------------------------------------------------------
require_once '../../conexion/conexion.php';
$bd = new connexion();
$bd->query("SET NAMES 'utf8'");
//=========================================================================================
//Creo una nueva variable de mobile detect-------------------------------------------------
$detect = new Mobile_Detect;
//-VARIABLE--------------------------------------------------------------------------------
$user = $_SESSION["user"];
$grupo = $_SESSION['grupo'];
//=========================================================================================
//VALOR MAXIMO DE RESULTADOS A MOSTRAR-----------------------------------------------------
$limit_doc = limiteMaxDocs($bd, $user);
if ($limit_doc == '') {
	//No posee valor asignado por el usuraio
	$limit_doc = "200";
}
//=========================================================================================
//VALIDO LA EXISTENCIA DEL LIBREOFFICE PARA MOSTRAR LA VISTA PREVIA =======================
$libreoffice = "../../recursos/libreoffice/";
$libreoff_exists = file_exists( $libreoffice );
//=======================================================================================================
//============================================ACCIONES===================================================
//=======================================================================================================
//VALIDO EL TIPO DE USUARIO SI ES REGULAR O EXTERNO======================================================
if ($_SESSION['tipo_user']==0) {
	//Es un usuario regular y hago la busqueda normal----------------------------------------------
	$var_acceso = "E.ACCESO='' OR E.ACCESO IS NULL OR E.ACCESO LIKE '%%#*INT$%%' OR ";
}elseif ($_SESSION['tipo_user']==1) {
	//ES UN USUARIO EXTERNO Y HAGO LA QRY ESPECIAL-------------------------------------------------
	$var_acceso = "E.ACCESO LIKE '%%#*EXT$%%' OR ";
}
//HAGO LA QRY DE LA TABLA============================================================================================
$base = tablaDocumentos($bd, $grupo, $user, $var_acceso, $limit_doc);
//===================================================================================================================
//===================================================================================================================
//============================================HTML===================================================================
//===================================================================================================================
while ($row = $base->fetch_object()){
	//CREO MASCARA PARA LA FECHA
	$fecha_str = str_replace("/", "-", $row->DIA);
	//===============================================================================
	//EVALUDO EL IDIOMA DEL DIA A UTILIZAR-------------------------------------------
			$dia = date("l",strtotime($fecha_str));
			if ($dia == "Monday") 		{$nombre_dia = F_DIA_LUN;}
			if ($dia == "Tuesday") 		{$nombre_dia = F_DIA_MAR;}
			if ($dia == "Wednesday") 	{$nombre_dia = F_DIA_MIER;}
			if ($dia == "Thursday") 	{$nombre_dia = F_DIA_JUE;}
			if ($dia == "Friday") 		{$nombre_dia = F_DIA_VIE;}
			if ($dia == "Saturday") 	{$nombre_dia = F_DIA_SAB;}
			if ($dia == "Sunday") 		{$nombre_dia = F_DIA_DOM;}
			//===============================================================================
			//VALOR NUMERICO DEL DIA---------------------------------------------------------
			$dia_num = date("d",strtotime($fecha_str));
			//===============================================================================
			//EVALUO NOMBRE DEL MES Y ASIGNO EL NOMBRE---------------------------------------
			$mes = date("n",strtotime($fecha_str));
			if ($mes == 1) {$nombre_mes = F_MES_ENE;}
			if ($mes == 2) {$nombre_mes = F_MES_FEB;}
			if ($mes == 3) {$nombre_mes = F_MES_MAR;}
			if ($mes == 4) {$nombre_mes = F_MES_ABR;}
			if ($mes == 5) {$nombre_mes = F_MES_MAY;}
			if ($mes == 6) {$nombre_mes = F_MES_JUN;}
			if ($mes == 7) {$nombre_mes = F_MES_JUL;}
			if ($mes == 8) {$nombre_mes = F_MES_AGO;}
			if ($mes == 9) {$nombre_mes = F_MES_SEP;}
			if ($mes == 10) {$nombre_mes = F_MES_OCT;}
			if ($mes == 11) {$nombre_mes = F_MES_NOV;}
			if ($mes == 12) {$nombre_mes = F_MES_DIC;}
			//==============================================================================
			$ano = date("o",strtotime($fecha_str));
			//creo mascara para el tamaño del archivo
			$tamaño_ini = $row->TAMANO;
			
			if ($tamaño_ini < 1048576) {

				$tamaño_masc = $tamaño_ini/1024;
				//Se da Formato al Tamano de los archivos
				$tamaño = number_format($tamaño_masc, 2, ",", ".");
				//unidad de medida
				$unid = 'KB';
			}else{

				$tamaño_masc = $tamaño_ini/1048576;
				//Se da Formato al Tamano de los archivos
				$tamaño = number_format($tamaño_masc, 2, ",", ".");
				//unidad de medida
				$unid = 'MB';

			};

			//Valido la Extencion del Doc para asignarle su respectivo icono
			$ext = strtoupper($row->EXTENSION);
			//CARGO EL NOMBRE DEL DOCUMENTO=============================================================
			$nombre = $row->NOMBRE;
			//CARGO EL ACCESO DEL DOCUMETO==============================================================
			$acceso = $row->ACCESO.$row->ACCESO_AUTO;
			//CARGO EL ACCESO DEL DOCUMETO==============================================================
			$clave_doc = $row->CLAVE;
			//CARGO EL VALOR DEL CAMPO DE GRAPADO DEL DOCUMENTO===============================================================
			$grapado = $row->GRAPADO;
			//CARGO EL VALOR DEL CAMPO DE GRAPADO DEL DOCUMENTO===============================================================
			$edicion = $row->BLOQUEO;
			//================================================================================================================
			//===========================CARACRERISTICAS ESPECIALES SI ES UN MOVIL============================================
			//================================================================================================================
			if ( $detect->isMobile() ) {
				//LIMPIO EL NOMBRE DE "_" PARA UNIR FRASES--------------------------------------------------------------------
				$nombre = limpiar($nombre);
				//HAGO EL EXPLODE EN LOS ESPACIOS EN BLANCO
				$palabras = explode(" ", $nombre);
				//CUENTO LA LONGITUD DEL ARRAY
				$cant_palabras = count($palabras);
				//VARIABLES DE INCREMENTO
				$i = 1;
				$p = 0;
				//VARIABLE DEL NUEVO NOMBRE
				$nuevo_nomb = "";
				//RECORRO EL ARRAY
				while ($i <= $cant_palabras) {
    				//CARGO LA PALABRA LA VARIABLE
    				$palabra = $palabras[$p];
    				//CONTAR CANTIDAD DE CARACTERES DEL CAMPO
    				$long_palabra = strlen($palabras[$p]);
    				//VALIDAR QUE NO SUPERE LOS 19 CARACTRERES
   					if ($long_palabra >= 17) {
        				$max_nombre = substr($palabras[$p], 0, 17);
       					$nuevo_nomb .= $max_nombre . ".. ";
    				}else{
    					$nuevo_nomb .= $palabra." ";
    				}
    				//INCREMENTOS
    				$i++;
    				$p++;
				}
			//CARGO EL NUEVO VALOR DEL NOMBRE
			$nombre = $nuevo_nomb;
			}
			//VALIDO SI EL DOCUMENTO ESTA BLOQUEADO PARA COLOCAR EL ROW EN DARGER---------------------------------------------
			if ($row->BLOQUEO != "") {
					//COLOCO LA ROW EN DANGER
					$row_col_bloq = "class='danger'";
			}else{
					//NO COLOCO NADA
					$row_col_bloq = "";
			}
			//CReo la mascara de 16 digitos del documento---------------------------------------------------------------------
			$id_doc = substr($row->CLAVE, -16);
			//VALIDO SI EL DOCUMENTO POSEE PORTADA----------------------------------------------------------------------------
			$portada = $row->PORTADA;
			//vALIDO LA EXTENSION DE LA PORTADA-------------------------------------------------------------------------------
			$ext_portada = $row->EXT_PORTADA;
			//================================================================================================================
			//======================BLOQUE DE PERMISOS SOBRE DOCUMENTOS=======================================================
			//================================================================================================================
			//OBTENGO EL ACCESO DEL DOCUMENTO---------------------------------------------------------------------------------
			$result = datosDocumento($bd, $row->CLAVE);
			//CARGO LOS PERMISOS DE ACCESO DE LOS DOS CAMPOS ACCESO Y ACCESO AUTO========================================
			$acceso = $result['ACCESO'].$result['ACCESO_AUTO'];
			//CARGO EL CREADOR DEL DOCUMENTO-----------------------------------------------------------------------------
			$creador = $result['CREADOR'];
			$tipo_user = $_SESSION['tipo_user'];
			//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";
			}
			//Varaible de vacio
			$pendiente = $result['ACCION'];
			//VALIDACIONES PARA EL BOTON DE DOWNLOAD-----------------------------------------------------------------------------
			//NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
			$btn_dwn_enabled = permisosDownload($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo);
			//VALIDACIONES PARA EL BOTON DE VINCULOS-----------------------------------------------------------------------------
			//NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
			$btn_vinc_enabled = permisosVinculo($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo);
			//VALIDACIONES PARA EL BOTON DE NOTAS--------------------------------------------------------------------------------
			//NIEGO PERMISOS A LECTURA - VISUALIZAR - ETIQUETADO
			$btn_notas_enabled = permisosNotas($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo);
	//===========================================================================================================================
	//================================================ARMO LA TABLA DE DOCUMENTOS================================================
	//===========================================================================================================================
	echo"	<tr ".$row_col_bloq.">
				<td>
					<div class='row'>";
			echo 	"<div class='col-xs-12'>
						<!-- ============================== ROW DEL DOCUMENTO ============================== -->
			            <div class='media'>
			                <div class='media-left'>";
			                //===================================================================================================================
	                        //	evaluo el icono a tulizar segun la extension=====================================================================
							//EVALUO SI ES UN DOCUMENTO PENDIENTE PARA ASIGNAR EL ICONO CORRESPONDIENTE==========================================
							if ($row->ACCION == 'PAUSED') {
								//CAMBIO EL ICONO POR PENDIENTE----------------------------------------------------------------------------------
			echo    			"<img class='media-object img-rounded' src='recursos/img/ico/pendiente.gif' width='36px' height='36px'>";
								$vista_prev = "<a type='button' class='btn btn_link botones' disabled";
							}else{
								//Evaluo el icono según la extensión del documento---------------------------------------------------------------
								include("../../lib/ico_dir_48.php"); 
							}
		    echo"			</div>
		                    <div class='media-body'>
		                        <h4 class='media-heading'>
		                        	<small>".strtoupper($nombre)."&nbsp;&nbsp;&nbsp;</small>";
		                        	//ICONO DEL DOCUMENTO CUANDO SE ENCUENTRA PUBLICADO-----------------------------------------------------------
									if ($row->PUBLICO == 1 OR $row->PUBLICO == 2) {
										//SE ENCUENTRA PUBLIADO Y ESCRIBO EL  ICONO
										echo "&nbsp;&nbsp;<i class='fa fa-globe text-success' aria-hidden='true'></i>";
									}
									//ICONO DE NOTAS DEL DOCUMENTO--------------------------------------------------------------------------------
									//VALIDO QUE POSEA PARA MSOTRAT EL ICONO
									if ($row->NUMNOT > 0) {
										echo "&nbsp;&nbsp;<a class='btn btn-xs fa fa-sticky-note-o text-warning' ".$btn_notas_enabled."></a>";
									}
									//ICONO DE GRAPADO DEL DOCUMENTO-----------------------------------------------------------------------------
									if ($row->GRAPADO != "") {
										//ESCRIBO EL ICONO DE GRAPADO
										echo "&nbsp;&nbsp;<a class='btn btn-xs fa fa-paperclip text-default' href='javascript:ModalGrapado($id_doc);'></a>";
									}
									//ICONO DE DOCUMENTO BLOQUEADO POR EDICION--------------------------------------------------------------------
									if ($row->BLOQUEO != "") {
										//ELIMINO EL PREFIJO DEL NOMBRE DE USUARIO A MOSTRAR
										$editandose = str_replace("##LOCKED##","",$row->BLOQUEO);
										//ESCRIBO EL BAGET DE EDICION
										echo "&nbsp;&nbsp;<a class='btn btn-xs' href='javascript:ModalEdicion($id_doc);'><span class='badge'><i class='fa fa-lock' aria-hidden='true'></i> ".F_EDIT_EDITANDOSE.": ".$editandose."</span></a>";
									}
		    echo"               </h4>";
		                        //Buscar si posee descripción=================================================
		                        $nota_docs = descripcionDocumentos($bd, $clave_doc);
		    echo"               <small>".$nota_docs."</small>
		                    </div>
		                    <div class='btn-group' role='group'>";
		                        	//BOTON DE VISTA PREVIA===================================================
		    echo"					".$vista_prev.">
		    							<i class='fa fa-eye' aria-hidden='true'></i>
		    						</a>";
		    						//BOTON DE descarga=======================================================
	        						if ($pendiente != 'PAUSED') {
	        echo"						<a id='botones_dwn' class='btn btn_link botones' ".$btn_dwn_enabled.">
                    						<i class='fa fa-download'></i>
                						</a>";
                					}elseif ($pendiente == 'PAUSED') {
                						//No es un documento pendiente
            echo"						<a id='botones_dwn' class='btn btn_link botones' disabled>
                        					<i class='fa fa-download'></i>
                						</a>";
                					}
		        					//BOTON DE NOTAS==========================================================
		    echo"					<a id='botones_dwn' class='btn btn_link botones' ".$btn_notas_enabled.">
		            					<i class='fa fa-sticky-note-o'></i>
		        					</a>";
		        					//BOTON DE COMPARTIR======================================================
		        					if ($pendiente != 'PAUSED') {
		        						//Es un documento pendiente
		    echo"						<a id='botones_vinc' class='btn btn_link botones' ".$btn_vinc_enabled.">
		                					<i class='fa fa-share-alt'></i>
		        						</a>";
		        					}elseif ($pendiente == 'PAUSED') {
		        						//No es un documento pendiente
		      echo"						<a id='botones_soltud' class='btn btn_link botones' href='javascript:modalSolicitarDocs($id_doc);' data-toggle='tooltip' data-placement='top' title='Solicitar'>
	                        				<i class='fa fa-retweet'></i>
	                					</a>";
		        					}
		    						//BOTON DE TIQUETAS=======================================================
		                        	//eVALUO SI TIENE ETIQUETAS
		                        	if ($row->NUMETI == 0) {
		                          		//No posee etiquetas
		    echo"                 		<a id='btn_etq_$id_doc' class='btn btn_link botones' disabled>
		    								<i class='fa fa-tag' aria-hidden='true'></i>
										</a>";
		                        	}elseif ($row->NUMETI > 0) {
		                          		//Posee Etiquetas-----------------------------------------------------
	                              		//Evaluo si tiene permisos de etiquetado------------------------------
	                              		$btn_etq_enabled = permisosEtiquetas($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo);

	        echo"                 		<a id='btn_etq_$id_doc' class='btn btn_link botones' ".$btn_etq_enabled." data-toggle='tooltip' data-placement='top' title='Etiquetas'>
	        								<i class='fa fa-tag' aria-hidden='true'></i>
										</a>";
		                        	}
		                        	//BOTON DE REGISTRO DEL ENTRADA=============================================
	                            	if ($_SESSION["reg_ent_doc"] == 1) {
	                              		//Evaluo si tiene permisos de etiquetado------------------------------
	                              		$btn_reg_enabled = permisosRegistroEntrada($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo);
	                              		//Hacer el count para saber si tiene----------------------------------
	        echo"                 		<a id='btn_reg_$id_doc' class='btn btn_link botones' ".$btn_reg_enabled." data-toggle='tooltip' data-placement='top' title='Registro Entrada'>
	        								<i class='fa fa-book' aria-hidden='true'></i>
										</a>";
	                            	}
		                        	//BOTON DE OPCIONES AVANZADA=========================================================
		                        	//VALIDO QUE EL DOCUMENTO NO ESTE BLOQUEADO PARA MOSTRAR LAS OPCIONES AVANZADAS-
							 		if ($row->BLOQUEO == "") {
										//ESCRIBO EL ICONO DE BOTONES DE OPCIONES AVANZADAS
			echo "						<a class='btn btn_link botones' href='javascript:botonesTabla($id_doc);'  data-toggle='tooltip' data-placement='top' title='".F_BTN_TB_MAS."'>
											<i class='fa fa-ellipsis-v' aria-hidden='true'></i>
		    							</a>";
									}else{
										//ESCRIBO EL BOTON PARA QUE TODO CALSE PERO SIN ACCIONES
			echo "						<a class='btn btn_link botones' disabled>
											<i class='fa fa-ellipsis-v' aria-hidden='true'></i>
		    							</a>";
									}
		    echo"           </div>
		                    <div id='etq_$id_doc' style='display:none' class='oculto'></div>
		                </div>
		            </div>";  	
			echo"	</div>
					<!-- ============================== DATOS DEL CONTACTO ============================== -->
					<div class='row'>
						<div class='col-xs-12' align='left'>
							<i class='fa fa-user text-info' aria-hidden='true'></i>
		                	<small><em> ".$row->CREADOR."</em></small>
		                	<i class='fa fa-calendar text-info' aria-hidden='true'></i>
		                	<small><em> ".$row->DIA."</em></small>
		                	<i class='fa fa-truck text-info' aria-hidden='true'></i>
		                	<small><em> ".$tamaño." ".$unid."</em></small>";
		                	//ICONO DE TIQUETAS==========================================================
							if ($row->NUMETI > 0) {
								//ICONOS DE LOS ESQUEMAS DEL DOCUMENTO--------------------------------------
								$labels = etiquetaEsquemaDoc($row->CLAVE);
								while ($row2 = $labels->fetch_object()){
									echo" &nbsp;&nbsp;&nbsp;&nbsp;<span class='label label-primary label-etq'><i class='fa fa-tag'></i> <small>".$row2->DESCRIPCION."</small></span>";
								}
							}
			echo"			</div>
					</div>
				</td>
           	</tr>";
		}
$base->close();
mysqli_close($bd);
unset($sql, $row, $ext, $ico, $tamaño_masc, $tamaño_ini, $unid);
//===================================================================================================================
//============================================FUNCIONES==============================================================
//===================================================================================================================
//FUNCION PARA CARGAR LA TABLA DE DOCUMENTOS-------------------------------------------------------------------------
function tablaDocumentos($bd, $grupo, $user, $var_acceso, $limit_doc)
{
  $sql =  "	SELECT E.CLAVE, E.NOMBRE, E.EXTENSION, E.ACCESO, E.CREADOR, E.TAMANO, E.GRAPADO, E.NUMNOT, E.NUMETI, E.ACCION, E.PUBLICO, E.BLOQUEO, E.ACCESO_AUTO, date_format(E.FECHA, '%d/%m/%Y') AS DIA, P.CLAVE AS PORTADA, P.EXTENSION AS EXT_PORTADA
			FROM BIBLIOTECA_ELEMENTOS E
			LEFT JOIN BIBLIOTECA_PORTADAS P
			ON P.CLAVE = E.CLAVE
			INNER JOIN BIBLIOTECA_FAVORITOS F
			ON E.CLAVE = F.CLAVE 
			WHERE E.PAPELERA = 0 AND E.TIPO = 'D' AND F.USUARIO = '$user' ORDER BY E.NOMBRE DESC LIMIT $limit_doc";
    $base = $bd->query($sql);
    return $base;
    $base->close();
}
// FUNCION PARA MOSTRAR ETIQ CON LOS ESQUEMAS DEL DOCUMENTO----------------------------------------------------------
function etiquetaEsquemaDoc($id_doc) {
	global $bd;
  $sql =  " SELECT DISTINCT E.DESCRIPCION
            FROM BIBLIOTECA_ETIQUETAS BE 
            INNER JOIN ESQUEMAS E
            ON BE.ESQUEMA = E.CODIGO
            WHERE BE.CLAVE = '$id_doc' AND BE.PADRE <> ''";
  $labels = $bd->query($sql);
  return $labels;
  $base->close();
	
}
//LIMPIO EL NOMBRE DEL DOCUMENTO DE CARACTERES ESPECIALES--------------------------------------------------
function limpiar($String){
    $String = str_replace("_"," ",$String);
    return $String;
}
//Funcion para obtener el limite de documentos a mosstrar 
function limiteMaxDocs($bd, $user){
	$sql =  "   SELECT P.VALOR
				FROM PARAMETROS P
				WHERE P.CODIGO = 'MAX_REGBUS' AND P.USUARIO = '$user'";
    $base = $bd->query($sql);
    $row = mysqli_fetch_array($base);
    $max_doc = $row['VALOR'];
    return $max_doc;
    $base->close();
}
//FUNCION PARA ESTABLECER ACCESOS PARA EL DOWNLOAD-----------------------------------------------------------------
function permisosDownload($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo)
{
      //Por defecto niego el permiso=====================================================
       $btn_dwn_enabled = "disabled";
      //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) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_dwn_enabled = "disabled";
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $btn_dwn_enabled = "href='javascript:DescDoc($id_doc);'";
        }
      }
  return $btn_dwn_enabled;
}
//FUNCION PARA ESTABLECER ACCESOS PARA EL VINCULO-----------------------------------------------------------------
function permisosVinculo($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo)
{
    //Por defecto niego el permiso=====================================================
    $btn_vinc_enabled = "disabled";
    //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) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //================VALIDO PERMISOS=====================
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_vinc_enabled = "disabled";
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $btn_vinc_enabled = "href='javascript:VinculoDoc($id_doc);'";
          }
      }
  return $btn_vinc_enabled;
}
//OBTENGO LOS DATOS DEL DOCUMENTO------------------------------------------------------------------------------------
function datosDocumento($bd, $doc)
{
  $sql =  " SELECT BE.ACCESO, BE.ACCESO_AUTO, BE.CREADOR, BE.ACCION
            FROM BIBLIOTECA_ELEMENTOS BE
            WHERE BE.CLAVE = '$doc'";
  $base = $bd->query($sql);
  $result = mysqli_fetch_array($base);
  $base->close();
  return $result;
}
//FUNCION PARA EL PERMISOS DEL BOTON DE NOTAS-----------------------------------------------------------------
function permisosNotas($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo)
{
    //Por defecto niego el permiso=====================================================
    $btn_notas_enabled = "disabled";
    //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) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //================VALIDO PERMISOS=====================
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_notas_enabled = "disabled";
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $btn_notas_enabled = "href='javascript:ModalNotas($id_doc);'";
          }
      }
  return $btn_notas_enabled;
}
//FUNCION PARA VALIDAR LA EXISTENCIA DE DOCUMENTOS PUBLICOS------------------------------------------------
function descripcionDocumentos($bd, $id_doc) {
	
	$sql =  "   SELECT N.NOTA
				FROM BIBLIOTECA_NOTAS N
				WHERE N.CLAVE = '$id_doc' AND N.DESCRIPCION = 1
				LIMIT 1";
	$base = $bd->query($sql);
	$row = mysqli_fetch_array($base);
	$nota_docs = $row['NOTA'];
	return $nota_docs;
}
//FUNCION PARA EL PERMISOS DEL BOTON DE ETIQUETAS-----------------------------------------------------------------
function permisosEtiquetas($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo)
{
    //Por defecto niego el permiso=====================================================
    $btn_etq_enabled = "disabled";
    //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) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //================VALIDO PERMISOS=====================
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $btn_etq_enabled = "href='javascript:etiquetasDcos($id_doc);'";
          }
      }
  return $btn_etq_enabled;
}
//FUNCION PARA EL PERMISOS DEL BOTON DE registro de entrada-----------------------------------------------------------------
function permisosRegistroEntrada($acceso, $grupo, $user, $id_doc, $tipo_user, $cadena_tipo)
{
    //Por defecto niego el permiso=====================================================
    $btn_reg_enabled = "disabled";
    //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) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$cadena_tipo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$cadena_tipo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$cadena_tipo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$cadena_tipo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //================VALIDO PERMISOS=====================
      //BUSCO POR GRUPO=====================================
      //$1 TOTAL
      $findme_grupo   = '#'.$grupo.'$1';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_grupo   = '#'.$grupo.'$2';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_grupo   = '#'.$grupo.'$3';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_grupo   = '#'.$grupo.'$4';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_grupo   = '#'.$grupo.'$5';
      $pos = strpos($acceso, $findme_grupo);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //BUSCO POR USUARIO===================================
      //$1 TOTAL
      $findme_user   = '#'.$user.'$1';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$2 LECTURA
      $findme_user   = '#'.$user.'$2';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$3 ESCRITURA
      $findme_user   = '#'.$user.'$3';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //$4 VISUALIZAR
      $findme_user   = '#'.$user.'$4';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_reg_enabled = "disabled";
      }
      //$5 ETIQUETADO
      $findme_user   = '#'.$user.'$5';
      $pos = strpos($acceso, $findme_user);
      if ($pos !== false) {
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
      }
      //Si es un usuario interno y el acceso esta en blanco lo permito
      if ($tipo_user == 0) {
          if ($acceso == "") {
          //LO PERMITO
          $btn_reg_enabled = "href='javascript:registroEntDcos($id_doc);'";
          }
      }
  return $btn_reg_enabled;
}
?>