<?php
session_start();
//Libreria de Mobile Detect------------------------------------
require_once '../recursos/MobileDetect/Mobile_Detect.php';
$detect = new Mobile_Detect;
//varibles-----------------------------------------------------
$doc = $_GET['doc'];
$doc_c = "20".$_GET['doc'];
//conexion-----------------------------------------------------
require_once '../conexion/conexion.php';
$bd = new connexion();
$bd->query("SET NAMES 'utf8'");
// ==================================================================================
// =====================DESCARGO EL ARCHIVO AL TEMPORAL DE LA DESCARGA===============
// ==================================================================================
//varibles===========================================================================
$doc = "20".$_GET['doc'];
//Nombre sello-----------------------------------------------------------------------
$nombre_sello = "sello_desc.pdf";
//Obtencion Datos del Doc------------------------------------------------------------
$datos = datosDoc($doc);
//REGRESO EL NOMBRE DEL DOCUMENTO----------------------------------------------------
$nombre = $datos['NOMBRE'];
//VALIDO EL DISPOSITIVO DONDE SE REALIZA LA DESCARGA PARA MODIFICAR NOMBRE-----------
//if ( $detect->isMobile() ) {
$nombre = limpiar($datos['NOMBRE']);
//}
//EXTENSION DEL DOCUMENTO------------------------------------------------------------
$ext = strtolower($datos['EXTENSION']);
//Obtengo el Sufijo del Fichero------------------------------------------------------
$tabla_sufijo = 'FICHEROS_'.$datos['SUFIJO'];
//FICHERO Y DOCUEMNTO A CREAR--------------------------------------------------------
$ruta_doc = '../recursos/file-upload/server/php/files/'.$nombre;
//User, grupo y otras variables------------------------------------------------------
$user = $_SESSION['user'];
$ordenador = $_SESSION['host'];
//===================================================================================
//==============Registro del historial de traza======================================
//variables para registrar la traza--------------------------------------------------
$ambito = $datos['AMBITO'];
$acceso = $datos['ACCESO'].$datos['ACCESO_AUTO'];
$tamano = $datos['TAMANO'];
$padre = nombrePadre($bd, $datos['PADRE']);  
$accion = 2; //APERTURA
$tipo = "D"; //Tipo documento
$awa = 1;
//CREO REGISTRO EN EL HISTORIAL------------------------------------------------------
registroHistorial($bd, $doc, $user, $ordenador, $nombre, $padre, $ambito, $acceso, $tamano, $awa, $accion, $tipo);
// ==================================================================================
//==========================ACCIONES=================================================
// ==================================================================================
//Elimino el documento si existe-----------------------------------------------------
@unlink('../recursos/file-upload/server/php/files/'.$nombre);
//Obtencion de la Primera parte del Fichero------------------------------------------
$archivo = parte1Doc($doc, $tabla_sufijo);
//CREO EL DOCUMEMTO EN EL DIRECTORIO TEMPORAL----------------------------------------
$create_doc = fopen($ruta_doc, 'a');
//Obtengo LA CANTIDAD DE PARTES DEL DOCUMENTO----------------------------------------
$num_parte = $datos['PARTES'];
//LLENO EL DOCUMENTO ----------------------------------------------------------------
if ($num_parte > 0) {
			for ($i=1; $i<=$num_parte; $i++) {
				//BUSCO EL CONTENIDO DE LAS PARTES-------------------------------------------
				$fichero_partes = parteAdicionalDoc($doc, $tabla_sufijo, $i);
				//VACIO ESE CONTENIDO EN EL DOCUMENTO----------------------------------------
				fwrite($create_doc, $fichero_partes);
	}
}
//CIERRO EL DOCUMENTO-------------------------------------------------------------------------
fclose($create_doc);
//ELIMINO VARIABLES --------------------------------------------------------------------------
mysqli_close($bd);
unset($bd, $doc, $tabla_sufijo, $ruta_doc, $create_doc, $num_parte, $fichero_partes);
//============================================================================================
//=====================EVALUO SI SE DEBE APLICAR SELLO AL DOCUMENTO===========================
//============================================================================================
//SIN SELLO-----------------------------------------------------------------------------------
if ($_SESSION["sello"] == 0) {
    //NO se aplica sello al documento=========================================================
    set_time_limit(0);
    //Defino el path del temporal del documento a descargar--------------------------
    $file_path='../recursos/file-upload/server/php/files/'.$nombre;
    //Le doy salida al documento-----------------------------------------------------
    output_file($file_path, ''.$nombre.'', $row['type']);
//CON SELLO===================================================================================
}elseif ($_SESSION["sello"] == 1) {
    //============================================================================================
    //EVALUO LA EXTENSION DEL DOCUMENTO PARA SELLARLO SEGUN CORRESPONDA===========================
    switch ($ext) {
        //ESTA EN FORMATO PDF=====================================================================
        case 'pdf':
                  //PDF_WATERMARK===================================================================
                  require_once('../recursos/pdf_watermark/pdfwatermarker/pdfwatermarker.php');
                  require_once('../recursos/pdf_watermark/pdfwatermarker/pdfwatermark.php');
                  require_once('../recursos/pdf_watermark/FPDF-master/fpdf.php');
                  require_once('../recursos/pdf_watermark/FPDI-master/fpdi.php');
                  //Me descargo el sello de la base de datos========================================
                  //Ruta donde creare el sello------------------------------------------------------
                  $ruta_doc = '../recursos/file-upload/server/php/files/sello.png';
                  //Elimino el documento si existe--------------------------------------------------
                  @unlink('../recursos/file-upload/server/php/files/sello.png');
                  //bUSCO EL FICHERO DEL SELLO PARA LAS DESCARGAS-----------------------------------
                  require_once '../conexion/conexion.php';
                  $bd = new connexion();
                  $bd->query("SET NAMES 'utf8'");
                  $fichero = creoSello($bd);
                  //EVALUO SI EXISTE O SINO UTILIZO EL DE POR DEFECTO-------------------------------
                  if ($fichero != '') {
                      //Si exite y continuo con la descarga y acciones------------------------------
                      //CREO EL DOCUMEMTO EN EL DIRECTORIO TEMPORAL---------------------------------
                      $create_doc = fopen($ruta_doc, 'a');
                      //VACIO ESE CONTENIDO EN EL DOCUMENTO-----------------------------------------
                      fwrite($create_doc, $fichero);
                      //CIERRO EL DOCUMENTO---------------------------------------------------------
                      fclose($create_doc);
                      //Apunto el Watermark al documento--------------------------------------------
                      $watermark = new PDFWatermark('../recursos/file-upload/server/php/files/sello.png'); 
                      //Set the position
                      $watermark->setPosition('center');
                      //Place watermark behind original PDF content. Default behavior places it over the content.
                      $watermark->setAsBackground();
                      //Specify the path to the existing pdf, the path to the new pdf file, and the watermark object
                      $watermarker = new PDFWatermarker('../recursos/file-upload/server/php/files/'.$nombre,'../recursos/file-upload/server/php/files/result_'.$nombre,$watermark); 
                      //Set page range. Use 1-based index.
                      $watermarker->setPageRange(1,5);
                      //Save the new PDF to its specified location
                      $watermarker->savePdf(); 
                  }else{
                      //============================================================================
                      //Me subo el sello por defecto a la base de datos=============================
                      //Creo la clave---------------------------------------------------------------
                      $clave = get_id_unico();
                      //Descripcion del sello-------------------------------------------------------
                      $desc_sello = "SELLO_DESC_AWA";
                      //este es el archivo temporal-------------------------------------------------
                      $imagen_temporal  = "../recursos/pdf_watermark/base_sello.png";
                      //Tamaño----------------------------------------------------------------------    
                      $tamano = filesize($imagen_temporal);
                      //============================================================================
                      //============================================ACCIONES========================
                      //============================================================================
                      //============================================================================
                      //leer el archivo temporal en binario-----------------------------------------
                      $fp     = fopen($imagen_temporal, 'r');
                      $data = fread($fp, filesize($imagen_temporal));
                      fclose($fp);
                      //escapar los caracteres------------------------------------------------------
                      $data = mysqli_real_escape_string($bd, $data);
                      //============================================================================
                      //Incluyo el sello y debo crearlo en la base de datos-------------------------
                      $fichero_ok = subirSello($bd, $clave, $data, $tamano, strlen($data), $desc_sello);
                      //Utilizo el sello base para crear el documento-------------------------------
                      $watermark = new PDFWatermark('../recursos/pdf_watermark/base_sello.png');
                      //Set the position
                      $watermark->setPosition('center');
                      //Place watermark behind original PDF content. Default behavior places it over the content.
                      $watermark->setAsBackground();
                      //Specify the path to the existing pdf, the path to the new pdf file, and the watermark object
                      $watermarker = new PDFWatermarker('../recursos/file-upload/server/php/files/'.$nombre,'../recursos/file-upload/server/php/files/result_'.$nombre,$watermark); 
                      //Set page range. Use 1-based index.
                      $watermarker->setPageRange(1,5);
                      //Save the new PDF to its specified location
                      $watermarker->savePdf(); 
                  }
                  //NO se aplica sello al documento-------------------------------------------------
                  set_time_limit(0);
                  //Defino el path del temporal del documento a descargar---------------------------
                  //$file_path='../file-upload/server/php/files/temp_'.$nombre;
                  $file_path='../recursos/file-upload/server/php/files/result_'.$nombre;
                  //Le doy salida al documento------------------------------------------------------
                  output_file($file_path, ''.$nombre.'', $row['type']);
        break;
        //esta en formato de la suite ofimatica=====================================================
        case 'doc':
        case 'docx':
        case 'xlsx':
        case 'xls':
        case 'txt':
        case 'ppt':
        case 'pptx':
        case 'dot':
        case 'dotx':
        case 'xlt':
        case 'xltx':
        case 'jpg':
        case 'gif':
        case 'png':
                  //VALIDAR LA EXISTENCIA DEL FICHERO PREVIO A LANZAR A CONVERTIRLO
                  $nombre_fichero = "../recursos/file-upload/server/php/files/".$nombre."";
                  if (file_exists($nombre_fichero)) {
                    //ME CAMBIO AL DIRECTORIO DEL EJECUTABLE DEL LIBREOFFICE
                    chdir('../recursos/libreoffice/LibreOffice/App/libreoffice/program/');
                    //
                    $parametro = parametroOffice($bd);
                    //
                    if ( $parametro != "") {
                      //MANDO EL COMANDO DE CONVERSION
                      $exec_string = $parametro . " --headless --convert-to pdf ../../../../../../preview/temp/".$nombre." --outdir ../../../../../../preview/temp/";
                    }else{
                      //MANDO EL COMANDO DE CONVERSION
                      $exec_string = "soffice --headless --convert-to pdf ../../../../../../preview/temp/".$nombre." --outdir ../../../../../../preview/temp/";
                    }
                    //EJECUTO EL COMANDO
                    $salida = exec($exec_string);
                    //CAMBIO LA EXTENCION DEL DOC A PDF
                    echo $ext;
                    $nombre = str_replace($ext, "pdf", $nombre);
                    //VUELVO A COLOCAR EL DIRECTORIO EN LA RAIZ DEL AWA
                    chdir('../../../../../../lib/');
                    //PDF_WATERMARK===================================================================
                    require_once('../recursos/pdf_watermark/pdfwatermarker/pdfwatermarker.php');
                    require_once('../recursos/pdf_watermark/pdfwatermarker/pdfwatermark.php');
                    require_once('../recursos/pdf_watermark/FPDF-master/fpdf.php');
                    require_once('../recursos/pdf_watermark/FPDI-master/fpdi.php');
                    //Me descargo el sello de la base de datos========================================
                    //Ruta donde creare el sello------------------------------------------------------
                    $ruta_doc = '../recursos/file-upload/server/php/files/sello.png';
                    //Elimino el documento si existe--------------------------------------------------
                    @unlink('../recursos/file-upload/server/php/files/sello.png');
                    //bUSCO EL FICHERO DEL SELLO PARA LAS DESCARGAS-----------------------------------
                    require_once '../conexion/conexion.php';
                    $bd = new connexion();
                    $bd->query("SET NAMES 'utf8'");
                    $fichero = creoSello($bd);
                    //EVALUO SI EXISTE O SINO UTILIZO EL DE POR DEFECTO-------------------------------
                    if ($fichero != '') {
                        //Si exite y continuo con la descarga y acciones------------------------------
                        //CREO EL DOCUMEMTO EN EL DIRECTORIO TEMPORAL---------------------------------
                        $create_doc = fopen($ruta_doc, 'a');
                        //VACIO ESE CONTENIDO EN EL DOCUMENTO-----------------------------------------
                        fwrite($create_doc, $fichero);
                        //CIERRO EL DOCUMENTO---------------------------------------------------------
                        fclose($create_doc);
                        //Apunto el Watermark al documento--------------------------------------------
                        $watermark = new PDFWatermark('../recursos/file-upload/server/php/files/sello.png'); 
                        //Set the position
                        $watermark->setPosition('center');
                        //Place watermark behind original PDF content. Default behavior places it over the content.
                        $watermark->setAsBackground();
                        //Specify the path to the existing pdf, the path to the new pdf file, and the watermark object
                        $watermarker = new PDFWatermarker('../recursos/file-upload/server/php/files/'.$nombre,'../recursos/file-upload/server/php/files/result_'.$nombre,$watermark); 
                        //Set page range. Use 1-based index.
                        $watermarker->setPageRange(1,5);
                        //Save the new PDF to its specified location
                        $watermarker->savePdf(); 
                    }else{
                        //============================================================================
                        //Me subo el sello por defecto a la base de datos=============================
                        //Creo la clave---------------------------------------------------------------
                        $clave = get_id_unico();
                        //Descripcion del sello-------------------------------------------------------
                        $desc_sello = "SELLO_DESC_AWA";
                        //este es el archivo temporal-------------------------------------------------
                        $imagen_temporal  = "../recursos/pdf_watermark/base_sello.png";
                        //Tamaño----------------------------------------------------------------------    
                        $tamano = filesize($imagen_temporal);
                        //============================================================================
                        //============================================ACCIONES========================
                        //============================================================================
                        //============================================================================
                        //leer el archivo temporal en binario-----------------------------------------
                        $fp     = fopen($imagen_temporal, 'r');
                        $data = fread($fp, filesize($imagen_temporal));
                        fclose($fp);
                        //escapar los caracteres------------------------------------------------------
                        $data = mysqli_real_escape_string($bd, $data);
                        //============================================================================
                        //Incluyo el sello y debo crearlo en la base de datos-------------------------
                        $fichero_ok = subirSello($bd, $clave, $data, $tamano, strlen($data), $desc_sello);
                        //Utilizo el sello base para crear el documento-------------------------------
                        $watermark = new PDFWatermark('../recursos/pdf_watermark/base_sello.png');
                        //Set the position
                        $watermark->setPosition('center');
                        //Place watermark behind original PDF content. Default behavior places it over the content.
                        $watermark->setAsBackground();
                        //Specify the path to the existing pdf, the path to the new pdf file, and the watermark object
                        $watermarker = new PDFWatermarker('../recursos/file-upload/server/php/files/'.$nombre,'../recursos/file-upload/server/php/files/result_'.$nombre,$watermark); 
                        //Set page range. Use 1-based index.
                        $watermarker->setPageRange(1,5);
                        //Save the new PDF to its specified location
                        $watermarker->savePdf(); 
                    }
                    set_time_limit(0);
                    //Defino el path del temporal del documento a descargar---------------------------
                    $file_path='../recursos/file-upload/server/php/files/result_'.$nombre;
                    //Le doy salida al documento------------------------------------------------------
                    output_file($file_path, ''.$nombre.'', $row['type']);
                  }
        //otros tipos de archivo======================================================================
        default:
                  //NO se aplica sello al documento=========================================================
                  set_time_limit(0);
                  //Defino el path del temporal del documento a descargar--------------------------
                  $file_path='../recursos/file-upload/server/php/files/'.$nombre;
                  //Le doy salida al documento-----------------------------------------------------
                  output_file($file_path, ''.$nombre.'', $row['type']);
        break;
    }
}
//============================================================================================
//=====================LIMPIO EL TEMPORAL DE DOCUMENTOS=======================================
//============================================================================================
//LIMPIO LOS DOCUMENTOS CON ANTIGUEDAD MAYOR A 5 min--------------------------------
$dir = opendir('../recursos/file-upload/server/php/files/');
while($f = readdir($dir))
{
if((time()-filemtime('../recursos/file-upload/server/php/files/'.$f) > 300) and !(is_dir('../recursos/file-upload/server/php/files/'.$f)))
unlink('../recursos/file-upload/server/php/files/'.$f);
}
closedir($dir);
//header('Location:home.php');
//============================================================================================
//=======================================FUNCIONES============================================
//============================================================================================	
//Funcion para descargar el archivo-----------------------------------------------------------
function output_file($file, $name, $mime_type='')
{
    if(!is_readable($file)) die('File not found or inaccessible!');
    $size = filesize($file);
    $name = rawurldecode($name);
    $known_mime_types=array(
      '.txt' => 'text/plain',
      '.htm' => 'text/html',
      '.html' => 'text/html',
      '.php' => 'text/html',
      '.css' => 'text/css',
      '.js' => 'application/javascript',
      '.json' => 'application/json',
      '.xml' => 'application/xml',
      '.swf' => 'application/x-shockwave-flash',
      '.pdf' => 'application/pdf',
      '.ps' => 'application/postscript',
      '.zip' => 'application/zip',
      '.flv' => 'video/x-flv',
      // office
      '.odt' => 'application/vnd.oasis.opendocument.text',
      '.ods' => 'application/vnd.oasis.opendocument.spreadsheet',
      '.odp' => 'application/vnd.oasis.opendocument.presentation',
      '.odg' => 'application/vnd.oasis.opendocument.graphics',
      '.doc' => 'application/vnd.ms-word',
      '.xls' => 'application/vnd.ms-excel',
      '.ppt' => 'application/vnd.ms-powerpoint',
      '.docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      '.xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      '.pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      // images
      '.png' => 'image/png',
      '.jpe' => 'image/jpeg',
      '.jpeg' => 'image/jpeg',
      '.jpg' => 'image/jpeg',
      '.gif' => 'image/gif',
      '.bmp' => 'image/bmp',
      '.ico' => 'image/vnd.microsoft.icon',
      '.tiff' => 'image/tiff',
      '.tif' => 'image/tiff',
      '.svg' => 'image/svg+xml',
      '.svgz' => 'image/svg+xml',
      // video
      '.3gp' => 'video/3gpp',
      '.3g2' => 'video/3g2',
      '.avi' => 'video/avi',
      '.mp4' => 'video/mp4',
      '.asf' => 'video/asf',
      '.mov' => 'video/quicktime',
      '.mpg' => 'video/mpeg',
      // audio
      '.mp3' => 'audio/mp3'
    );

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };
    @ob_end_clean();
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');

    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end) {
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }

        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    $chunksize = 1*(1024*1024);
    $bytes_send = 0;
    if ($file = fopen($file, 'r'))
    {
        if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

        while(!feof($file) &&
            (!connection_aborted()) &&
            ($bytes_send<$new_length)
        )
        {
            $buffer = fread($file, $chunksize);
            echo($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }
        fclose($file);
    } else
        die('Error - can not open file.');
    die();
}
//FUNCION PARA OBTENER LOS DATOS DEL DOCUMENTO------------------------------------------------
 function datosDoc($id_doc){
  global $bd;
  $sql =  " SELECT e.CLAVE, e.NOMBRE, e.EXTENSION, e.TAMANO, e.SUFIJO, e.PARTES, e.PADRE, e.AMBITO, e.ACCESO, e.ACCESO_AUTO
			FROM BIBLIOTECA_ELEMENTOS e 
			WHERE e.CLAVE = '$id_doc'";
  $base = $bd->query($sql);
  $datos = mysqli_fetch_assoc($base);
  $base->close();
  return $datos;
 }  
 //FUNCION PARA OBTENER LA PRIMERA PARTE DEL FICHERO------------------------------------------------
 function parte1Doc($id_doc, $tabla_sufijo){
  global $bd;
  $sql =  " SELECT FICHERO
		 	FROM $tabla_sufijo 
		 	WHERE CLAVE = '$id_doc'
		 	AND PARTE = 1 AND VERSION = 0 LIMIT 1";
  $base = $bd->query($sql);
  $archivo = mysqli_fetch_assoc($base);
  $base->close();
  return $archivo;
 }  
 //FUNCION PARA OBTENER LA PRIMERA PARTE DEL FICHERO------------------------------------------------
 function parteAdicionalDoc($id_doc, $tabla_sufijo, $parte){
  global $bd;
  $sql_partes = "	SELECT FICHERO
					FROM $tabla_sufijo
					WHERE PARTE = $parte
					AND CLAVE = '$id_doc'
					AND VERSION = 0 LIMIT 1";
	//$qry = sprintf($sql_partes, $parte , $id_doc);
	$parte = $bd->query($sql_partes);
	$fichero = mysqli_fetch_assoc($parte);
	$fichero_partes = $fichero['FICHERO'];
	$parte->close();
  	return $fichero_partes;
 }   
 //LIMPIO EL NOMBRE DEL DOCUMENTO DE CARACTERES ESPECIALES--------------------------------------------------
function limpiar($String){
    //$String = str_replace(array('á','à','â','ã','ª','ä'),"a",$String);
    //$String = str_replace(array('Á','À','Â','Ã','Ä'),"A",$String);
    //$String = str_replace(array('Í','Ì','Î','Ï'),"I",$String);
    //$String = str_replace(array('í','ì','î','ï'),"i",$String);
    //$String = str_replace(array('é','è','ê','ë'),"e",$String);
    //$String = str_replace(array('É','È','Ê','Ë'),"E",$String);
    //$String = str_replace(array('ó','ò','ô','õ','ö','º'),"o",$String);
    //$String = str_replace(array('Ó','Ò','Ô','Õ','Ö'),"O",$String);
    //$String = str_replace(array('ú','ù','û','ü'),"u",$String);
    //$String = str_replace(array('Ú','Ù','Û','Ü'),"U",$String);
    $String = str_replace(array('[','^','´','`','¨','~',']', "'"),"",$String);
    //$String = str_replace("ç","c",$String);
    //$String = str_replace("Ç","C",$String);
    //$String = str_replace("ñ","n",$String);
    //$String = str_replace("Ñ","N",$String);
    //$String = str_replace("Ý","Y",$String);
    //$String = str_replace("ý","y",$String);
     
    $String = str_replace("&aacute;","a",$String);
    $String = str_replace("&Aacute;","A",$String);
    $String = str_replace("&eacute;","e",$String);
    $String = str_replace("&Eacute;","E",$String);
    $String = str_replace("&iacute;","i",$String);
    $String = str_replace("&Iacute;","I",$String);
    $String = str_replace("&oacute;","o",$String);
    $String = str_replace("&Oacute;","O",$String);
    $String = str_replace("&uacute;","u",$String);
    $String = str_replace("&Uacute;","U",$String);

    $String = str_replace("/","-",$String);
    //$String = str_replace(" ","_",$String);
    $String = strtolower($String);
    return $String;
}
 //===============================================================================================================================
 //=========================================BLOQUE TRAZA HISTORIAL================================================================
 //FUNCION PARA Hacer el Registro en el Historial------------------------------------------------
 function registroHistorial($bd, $doc, $user, $ordenador, $nombre, $padre, $ambito, $acceso, $tamano, $awa, $accion, $tipo)
 {
  $query =" INSERT INTO BIBLIOTECA_HISTORIAL ( CLAVE, USUARIO, FECHA, ACCION, DOCUMENTO, CARPETA, ORDENADOR, AMBITO, ACCESO, TIPO, TAMANO, CREADOR, AWA)
            VALUES ( '$doc', '$user', NOW(), $accion, '$nombre', '$padre', '$ordenador', '$ambito', '$acceso', '$tipo', $tamano, '$user', $awa)";
  mysqli_query($bd, $query);
 }  
 //FUNCION PARA OBTENER EL NOMBRE DEL PADRE DEL DOCUMENTO-------------------------------------
function nombrePadre($bd, $id_padre){
  //EVALUO SI EL PADRE NO PERTECENE A ALGUN DIRECTORIO RAIZ PUBLICO O PRIVADO
  if ($id_padre == "##PUBLICO##" OR $id_padre == "##PRIVADO##" OR $id_padre == "##USUARIOS##") {
      if ($id_padre == "##PUBLICO##") {
          $padre = "##PUBLICO##";
      }
      if ($id_padre == "##PRIVADO##") {
          $padre = "##PRIVADO##";
      } 
      if ($id_padre == "##USUARIOS##") {
          $padre = "##USUARIOS##";
      }  
}else{
      $sql = "  SELECT e.NOMBRE
      FROM BIBLIOTECA_ELEMENTOS e
      WHERE e.CLAVE = '$id_padre'
      AND e.TIPO = 'C' LIMIT 1";
      $base = $bd->query($sql);
      $nomb_padre = mysqli_fetch_assoc($base);
      $padre = $nomb_padre['NOMBRE'];
}
  //REgreso el valor del padre
  return $padre;
} 
//FUNCION PARA OBTENER LA PRIMERA PARTE DEL FICHERO------------------------------------------------
 function creoSello($bd)
 {
  $sql_partes = " SELECT S.FICHERO
                  FROM BIBLIOTECA_SELLOS S
                  WHERE S.ALIAS = 'SELLO_DESC_AWA' LIMIT 1";
  $parte = $bd->query($sql_partes);
  $fichero = mysqli_fetch_assoc($parte);
  $fichero_partes = $fichero['FICHERO'];
  $parte->close();
  return $fichero_partes;
 }
 //Funcion para obtener la clave unica del registro-----------------------------------------------------------
function get_id_unico() {
    return date( "YmdHis" ) . sprintf( "%04d", rand( 0, 9999 ) );
}
//Funcion PARA SUBIR CONTENIDO DEL SELLO---------------------------------------------------------------------
function subirSello($bd, $clave, $data, $tamano, $size, $desc_sello) {

    mysqli_query($bd, " INSERT INTO BIBLIOTECA_SELLOS 
                        (CLAVE, TAMANO, DESCRIPCION, ALIAS, FICHERO) 
                        VALUES 
                        ('$clave', $tamano, '$desc_sello', '$desc_sello', '$data')");
    
}
//FUNCION PARA OBTENER LA PRIMERA PARTE DEL FICHERO------------------------------------------------
 function parametroOffice($bd)
 {
  $sql_partes = " SELECT P.VALOR
                  FROM PARAMETROS P
                  WHERE P.CODIGO = 'AWA_OFFICE_CMD'";
  $parte = $bd->query($sql_partes);
  $row = mysqli_fetch_assoc($parte);
  $result = $row['VALOR'];
  $parte->close();
  return $result;
 }
?>