<?php
session_start();
//Libreria de Mobile Detect------------------------------------
require_once '../../recursos/MobileDetect/Mobile_Detect.php';
$detect = new Mobile_Detect;
//varibles-----------------------------------------------------
$doc = $_POST['doc'];
$doc_c = "20".$_POST['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".$_POST['doc'];
//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-----------
$nombre = limpiar($datos['NOMBRE']);
//EXTRAIGO LA EXTENCION DEL DOCUMENTO
$extension = $datos['EXTENSION'];
//===================================================================================
//EVALUO SI ES JPG PRA PROCEGUIR CON LA DESCARGA DEL ARCHIVO=========================
if ($extension == 'JPG' OR $extension == 'PNG' OR $extension == 'GIF') {
    //AL SER IMAGEN PROSIGO CON LA DESCARGA------------------------------------------
    //Obtengo el Sufijo del Fichero------------------------------------------------------
    $tabla_sufijo = 'FICHEROS_'.$datos['SUFIJO'];
    //FICHERO Y DOCUEMNTO A CREAR--------------------------------------------------------
    $ruta_doc = '../../recursos/file-upload/server/php/files/'.$nombre;
    //Elimino el documento si existe-----------------------------------------------------
    @unlink('../../recursos/file-upload/server/php/files/'.$nombre);
    //CREO EL DOCUMEMTO EN EL DIRECTORIO TEMPORAL-----------------------------------------------
    $create_doc = fopen($ruta_doc, 'a');
    //BUSCO EL CONTENIDO DE LAS PARTES--------------------------------------------
    $fichero = ficheroThumb($doc, $tabla_sufijo);
    //VACIO ESE CONTENIDO EN EL DOCUMENTO-----------------------------------------
    fwrite($create_doc, $fichero);
    //CIERRO EL DOCUMENTO----------------------------------------------------------------
    fclose($create_doc);
    //===================================================================================
    //CREO EL THUMBNAIL==================================================================
    $resize = new ResizeImage('../../recursos/file-upload/server/php/files/'.$nombre);
    $resize->resizeTo(64, 64, 'exact');
    $resize->saveImage('../../recursos/file-upload/server/php/files/thumb_'.$nombre);
    //DEVUELVO EL NOMBRE DEL DOCUMENTO---------------------------------------------------
    echo "thumb_".$nombre;
    //ELIMINO VARIABLES -----------------------------------------------------------------
    mysqli_close($bd);
    unset($bd, $doc, $tabla_sufijo, $ruta_doc, $create_doc, $num_parte, $fichero_partes);
    //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) > 240) and !(is_dir('../../recursos/file-upload/server/php/files/'.$f)))
    unlink('../../recursos/file-upload/server/php/files/'.$f);
    }
    closedir($dir);
}else{
    // ES OTRO FORMATO DEVUELVO 0 para indicar que no se creara thumbnail-----------------------
    echo 0;
}

//============================================================================================
//=======================================FUNCIONES============================================
//============================================================================================	
//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;
 }    
 //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;
}
//============================================================================================================================
//============================================================================================================================
class ResizeImage
{
  private $ext;
  private $image;
  private $newImage;
  private $origWidth;
  private $origHeight;
  private $resizeWidth;
  private $resizeHeight;

  /**
   * Class constructor requires to send through the image filename
   *
   * @param string $filename - Filename of the image you want to resize
   */
  public function __construct( $filename )
  {
    if(file_exists($filename))
    {
      $this->setImage( $filename );
    } else {
      throw new Exception('Image ' . $filename . ' can not be found, try another image.');
    }
  }

  /**
   * Set the image variable by using image create
   *
   * @param string $filename - The image filename
   */
  private function setImage( $filename )
  {
    $size = getimagesize($filename);
    $this->ext = $size['mime'];

    switch($this->ext)
      {
        // Image is a JPG
          case 'image/jpg':
          case 'image/jpeg':
            // create a jpeg extension
              $this->image = imagecreatefromjpeg($filename);
              break;

          // Image is a GIF
          case 'image/gif':
              $this->image = @imagecreatefromgif($filename);
              break;

          // Image is a PNG
          case 'image/png':
              $this->image = @imagecreatefrompng($filename);
              break;

          // Mime type not found
          default:
              throw new Exception("File is not an image, please use another file type.", 1);
      }

      $this->origWidth = imagesx($this->image);
      $this->origHeight = imagesy($this->image);
  }

  /**
   * Save the image as the image type the original image was
   *
   * @param  String[type] $savePath     - The path to store the new image
   * @param  string $imageQuality     - The qulaity level of image to create
   *
   * @return Saves the image
   */
  public function saveImage($savePath, $imageQuality="100", $download = false)
  {
      switch($this->ext)
      {
          case 'image/jpg':
          case 'image/jpeg':
            // Check PHP supports this file type
              if (imagetypes() & IMG_JPG) {
                  imagejpeg($this->newImage, $savePath, $imageQuality);
              }
              break;

          case 'image/gif':
            // Check PHP supports this file type
              if (imagetypes() & IMG_GIF) {
                  imagegif($this->newImage, $savePath);
              }
              break;

          case 'image/png':
              $invertScaleQuality = 9 - round(($imageQuality/100) * 9);

              // Check PHP supports this file type
              if (imagetypes() & IMG_PNG) {
                  imagepng($this->newImage, $savePath, $invertScaleQuality);
              }
              break;
      }

      if($download)
      {
        header('Content-Description: File Transfer');
      header("Content-type: application/octet-stream");
      header("Content-disposition: attachment; filename= ".$savePath."");
      readfile($savePath);
      }

      imagedestroy($this->newImage);
  }

  /**
   * Resize the image to these set dimensions
   *
   * @param  int $width         - Max width of the image
   * @param  int $height        - Max height of the image
   * @param  string $resizeOption - Scale option for the image
   *
   * @return Save new image
   */
  public function resizeTo( $width, $height, $resizeOption = 'default' )
  {
    switch(strtolower($resizeOption))
    {
      case 'exact':
        $this->resizeWidth = $width;
        $this->resizeHeight = $height;
      break;

      case 'maxwidth':
        $this->resizeWidth  = $width;
        $this->resizeHeight = $this->resizeHeightByWidth($width);
      break;

      case 'maxheight':
        $this->resizeWidth  = $this->resizeWidthByHeight($height);
        $this->resizeHeight = $height;
      break;

      default:
        if($this->origWidth > $width || $this->origHeight > $height)
        {
          if ( $this->origWidth > $this->origHeight ) {
               $this->resizeHeight = $this->resizeHeightByWidth($width);
               $this->resizeWidth  = $width;
          } else if( $this->origWidth < $this->origHeight ) {
            $this->resizeWidth  = $this->resizeWidthByHeight($height);
            $this->resizeHeight = $height;
          }  else {
            $this->resizeWidth = $width;
            $this->resizeHeight = $height;  
          }
        } else {
                $this->resizeWidth = $width;
                $this->resizeHeight = $height;
            }
      break;
    }

    $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight);
      imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight);
  }

  /**
   * Get the resized height from the width keeping the aspect ratio
   *
   * @param  int $width - Max image width
   *
   * @return Height keeping aspect ratio
   */
  private function resizeHeightByWidth($width)
  {
    return floor(($this->origHeight/$this->origWidth)*$width);
  }

  /**
   * Get the resized width from the height keeping the aspect ratio
   *
   * @param  int $height - Max image height
   *
   * @return Width keeping aspect ratio
   */
  private function resizeWidthByHeight($height)
  {
    return floor(($this->origWidth/$this->origHeight)*$height);
  }
}
 //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 ficheroThumb($id_doc, $tabla_sufijo){
  global $bd;
  $sql_partes = " SELECT FICHERO
          FROM $tabla_sufijo
          WHERE 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;
 }
 ?>