mirror of
https://github.com/rmontanana/inventario2.git
synced 2025-08-15 07:25:57 +00:00
ref #9 Creada la visualización de imágenes en consulta y en edición.
Realizada la inserción de registros con imágenes.
This commit is contained in:
@@ -70,7 +70,7 @@ class Distribucion {
|
||||
// if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) {
|
||||
// // introducimos la cabecera que indica que el contenido está comprimido
|
||||
// header('Content-Encoding: gzip');
|
||||
// // y comprime al m<EFBFBD>ximo la información antes de enviarla
|
||||
// // y comprime al máximo la información antes de enviarla
|
||||
// return gzencode($pagina, 9);
|
||||
// }
|
||||
return $pagina; // enviamos sin comprimir
|
||||
|
179
Imagen.php
Normal file
179
Imagen.php
Normal file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
/**
|
||||
* @package Inventario
|
||||
* @copyright Copyright (c) 2014, Ricardo Montañana Gómez
|
||||
* @license http://www.gnu.org/licenses/gpl-3.0.txt
|
||||
* This file is part of Inventario.
|
||||
* Inventario is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Inventario is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
//Para comprimir las imágenes
|
||||
require_once('Zebra_Image.php');
|
||||
define("HAYQUEGRABAR", 1);
|
||||
define("HAYQUEBORRAR", 2);
|
||||
define("NOHACERNADA", 3);
|
||||
|
||||
class Imagen {
|
||||
private $archivoSubido;
|
||||
public $archivoComprimido;
|
||||
private $extension;
|
||||
private $dirData;
|
||||
|
||||
public function __construct($directorio = "img.data")
|
||||
{
|
||||
$this->dirData = $directorio;
|
||||
}
|
||||
|
||||
public function determinaAccion($campo)
|
||||
{
|
||||
if (isset($_POST[$campo]) && $_POST[$campo] == "") {
|
||||
return HAYQUEBORRAR; //Hay que borrar el archivo de imagen
|
||||
} elseif ($_FILES[$campo]['error'] == 0) {
|
||||
return HAYQUEGUARDAR; //Hay que guardar el archivo de imagen enviado
|
||||
} else {
|
||||
return NOHACERNADA; //No hay que hacer nada
|
||||
}
|
||||
}
|
||||
|
||||
public function procesaEnvio($campo, &$mensaje)
|
||||
{
|
||||
try {
|
||||
// Undefined | Multiple Files | $_FILES Corruption Attack
|
||||
// If this request falls under any of them, treat it invalid.
|
||||
if (
|
||||
!isset($_FILES[$campo]['error']) ||
|
||||
is_array($_FILES[$campo]['error'])
|
||||
) {
|
||||
throw new RuntimeException('Parámetros inválidos.');
|
||||
}
|
||||
|
||||
// Check $_FILES['upfile']['error'] value.
|
||||
switch ($_FILES[$campo]['error']) {
|
||||
case UPLOAD_ERR_OK:
|
||||
break;
|
||||
case UPLOAD_ERR_NO_FILE:
|
||||
throw new RuntimeException('No se ha enviado ningún fichero.');
|
||||
case UPLOAD_ERR_INI_SIZE:
|
||||
case UPLOAD_ERR_FORM_SIZE:
|
||||
throw new RuntimeException('Se ha excedido el tamaño máximo.');
|
||||
default:
|
||||
throw new RuntimeException('Error desconocido.');
|
||||
}
|
||||
|
||||
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
|
||||
// Check MIME Type by yourself.
|
||||
$finfo = new finfo(FILEINFO_MIME_TYPE);
|
||||
if (false === $ext = array_search(
|
||||
$finfo->file($_FILES[$campo]['tmp_name']),
|
||||
array(
|
||||
'jpg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
),
|
||||
true
|
||||
)) {
|
||||
throw new RuntimeException('Formato de imagen inválido, no es {jpg, png, gif}');
|
||||
}
|
||||
$this->extension = $ext;
|
||||
// You should name it uniquely.
|
||||
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
|
||||
// On this example, obtain safe unique name from its binary data.
|
||||
$this->archivoSubido = sprintf('tmp/%s.%s', sha1_file($_FILES[$campo]['tmp_name']), $ext);
|
||||
if (!move_uploaded_file($_FILES[$campo]['tmp_name'], $this->archivoSubido)) {
|
||||
throw new RuntimeException('Fallo moviendo el archivo subido.');
|
||||
}
|
||||
//Todo ha ido correcto
|
||||
return true;
|
||||
} catch (RuntimeException $e) {
|
||||
$mensaje = $e->getMessage();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public function mueveImagenId($id, &$mensaje)
|
||||
{
|
||||
if (!$this->comprimeArchivo($id, $mensaje)) {
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private function generaNombre()
|
||||
{
|
||||
//De momento no se utiliza
|
||||
$i = 0;
|
||||
$salir = false;
|
||||
$nombre = strftime("%Y%m%d%H%M%S");
|
||||
//limita a 1000 intentos el buscar un archivo inexistente
|
||||
while ($i++<1000 and !$salir) {
|
||||
$test = $nombre . $i;
|
||||
$fichero = $this->dirData . "/" . $test . "." . $this->extension;
|
||||
if (!file_exists($fichero)) {
|
||||
$salir = true;
|
||||
}
|
||||
}
|
||||
if (!salir) {
|
||||
throw new Exception("No se ha podido encontrar un nombre de archivo único en ".$this->dirData, 1);
|
||||
}
|
||||
return $fichero;
|
||||
}
|
||||
|
||||
private function comprimeArchivo($id, &$mensaje)
|
||||
{
|
||||
$zebra = new Zebra_Image();
|
||||
$zebra->source_path = $this->archivoSubido;
|
||||
$this->archivoComprimido = $id . "." . $this->extension;
|
||||
$zebra->target_path = $this->archivoComprimido;
|
||||
$zebra->jpeg_quality = 100;
|
||||
|
||||
// some additional properties that can be set
|
||||
// read about them in the documentation
|
||||
$zebra->preserve_aspect_ratio = true;
|
||||
$zebra->enlarge_smaller_images = true;
|
||||
$zebra->preserve_time = true;
|
||||
|
||||
// resize the image to exactly 100x100 pixels by using the "crop from center" method
|
||||
// (read more in the overview section or in the documentation)
|
||||
// and if there is an error, check what the error is about
|
||||
if (!$zebra->resize(640, 480, ZEBRA_IMAGE_CROP_CENTER)) {
|
||||
// if there was an error, let's see what the error is about
|
||||
switch ($zebra->error) {
|
||||
case 1: $mensaje = 'El fichero origen no se ha encontrado!';
|
||||
break;
|
||||
case 2: $mensaje = 'No se puede leer el archivo origen ' . $this->archivoSubido;
|
||||
break;
|
||||
case 3: $mensaje = 'No se pudo escribir el archivo destino ' . $this->archivoComprimido;
|
||||
break;
|
||||
case 4: $mensaje = 'Formato de fichero origen no soportado ' . $this->archivoSubido;
|
||||
break;
|
||||
case 5: $mensaje = 'Formato de fichero destino no soportado ' . $this->archivoComprimido;
|
||||
break;
|
||||
case 6: $mensaje = 'La versión de la biblioteca GD no soporta el formato de destino ' . $this->archivoComprimido;
|
||||
break;
|
||||
case 7: $mensaje = 'La biblioteca GD no está instalada';
|
||||
break;
|
||||
case 8: $mensaje = 'el comando "chmod" está deshabilitado por configuración';
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
} else {
|
||||
//
|
||||
//unlink($this->archivoSubido);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
@@ -207,7 +207,7 @@ class Mantenimiento {
|
||||
$valor = '<a title="Inventario de ' . $valor . '" $target="_blank" href="index.php?informeInventario&opc=listar' . $datoEnlace . '&id=' . $id . '">' . $valor;
|
||||
}
|
||||
if (strstr($this->campos[$clave]['Comment'], "imagen") && isset($valor)) {
|
||||
$msj = '<button type="button" data-toggle="modal" data-target="#mensajeModal' . $id .'">'.$valor.'</button>';
|
||||
$msj = '<button class="btn btn-info btn-xs" type="button" data-toggle="modal" data-target="#mensajeModal' . $id .'">Imagen</button>';
|
||||
$msj .= $this->creaModal($valor, $id);
|
||||
$valor = $msj;
|
||||
}
|
||||
@@ -312,6 +312,7 @@ class Mantenimiento {
|
||||
$comando = "insert into " . $this->tabla . " (";
|
||||
$lista = explode("&", $_POST['listacampos']);
|
||||
$primero = true;
|
||||
$hayImagen = false;
|
||||
//Añade la lista de campos
|
||||
foreach ($lista as $campo) {
|
||||
if ($campo == "") {
|
||||
@@ -344,7 +345,22 @@ class Mantenimiento {
|
||||
}
|
||||
$valor = $_POST[$campo] == "on" ? '1' : $valor;
|
||||
} else {
|
||||
$valor = $_POST[$campo] == "" ? "null" : '"' . $_POST[$campo] . '"';
|
||||
if (stristr("imagen", $this->campos[$campo]['Type'])) {
|
||||
//procesa el envío de la imagen
|
||||
$imagen = new Imagen();
|
||||
$accion = $imagen->determinaAccion($campo);
|
||||
if ($accion != NOHACERNADA) {
|
||||
// El código 3 es no hacer nada.
|
||||
$mensaje = "";
|
||||
if (!$imagen->procesaEnvio("insertar", $campo, $mensaje)) {
|
||||
return $this->panelMensaje($mensaje, "danger", "ERROR PROCESANDO IMAGEN");
|
||||
}
|
||||
$hayImgen = true;
|
||||
}
|
||||
|
||||
} else {
|
||||
$valor = $_POST[$campo] == "" ? "null" : '"' . $_POST[$campo] . '"';
|
||||
}
|
||||
}
|
||||
$comando.="$coma " . $valor;
|
||||
}
|
||||
@@ -352,13 +368,58 @@ class Mantenimiento {
|
||||
if (!$this->bdd->ejecuta($comando)) {
|
||||
return $this->errorBD($comando);
|
||||
}
|
||||
$id = $this->bdd->ultimoId();
|
||||
if ($hayImagen) {
|
||||
//Tiene que recuperar el id del registro insertado y actualizar el archivo de imagen
|
||||
if (!$imagen->mueveImagenId($id, $mensaje)) {
|
||||
return $this->panelMensaje($mensaje, "danger", "ERROR COMPRIMIENDO IMAGEN");
|
||||
}
|
||||
$comando = "update " . $this->tabla . " set " . $campo . "='" . $imagen->archivoComprimido . "' where id='" . $id ."';";
|
||||
if (!$this->bdd->ejecuta($comando)) {
|
||||
return $this->errorBD($comando);
|
||||
}
|
||||
}
|
||||
$this->datosURL['opc'] = 'inicial';
|
||||
$this->datosURL['id'] = null;
|
||||
$cabecera = "refresh:".PAUSA.";url=".$this->montaURL();
|
||||
header($cabecera);
|
||||
return $this->panelMensaje("Se ha insertado el registro con la clave " . $this->bdd->ultimoId(), "info", "Información");
|
||||
return $this->panelMensaje("Se ha insertado el registro con la clave " . $id, "info", "Información");
|
||||
//return "<h1><a href=\"".$this->montaURL()."\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "</a></h1>";
|
||||
}
|
||||
|
||||
private function procesaEnvioImagen($operacion, $campo)
|
||||
{
|
||||
|
||||
switch ($operacion) {
|
||||
/*
|
||||
* Insertar:
|
||||
* Ha incluido archivo? sino fin
|
||||
* Si se ha incluido ¿se ha subido correctamente? sino error
|
||||
* mover archivo a tmp con un nombre
|
||||
* comprimir con un nombre genérico y único en la carpeta de datos
|
||||
* devolver el nombre del archivo creado como valor a guardar en el campo imagen
|
||||
* (se podría activar una vez insertado el registro que se renombrara el archivo con el id del elemento y se cambiara el campo)
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Borrar:
|
||||
* Hay imagen asociada? sino fin
|
||||
* Se borra el archivo de imagen del directorio de datos
|
||||
*/
|
||||
|
||||
/*
|
||||
* Modificar:
|
||||
* Casuística:
|
||||
* 1: No existe imagen ni antes ni ahora.
|
||||
* 2: No existía imagen y ahora sí
|
||||
* 3: Existía imagen y ahora no
|
||||
* 4: Existía imagen antes y ahora y es la misma
|
||||
* 5: Existía imagen antes y ahora y es distinta
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
protected function modificar()
|
||||
{
|
||||
@@ -667,7 +728,8 @@ class Mantenimiento {
|
||||
<div id="mensajeModal'.$id.'" class="modal fade " tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog text-center">
|
||||
<div class="modal-content text-center">
|
||||
<img src="' . $valor . '">
|
||||
<img src="' . $valor . '" class="img-responsive">
|
||||
<label>Archivo: ' . $valor . '</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>';
|
||||
@@ -692,7 +754,8 @@ class Mantenimiento {
|
||||
$mensaje .= '</div>';
|
||||
$mensaje .= '</div>';
|
||||
return $mensaje;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
1707
Zebra_Image.php
Normal file
1707
Zebra_Image.php
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user