-Cambiado el alineamiento del fuente en varios archivos

-Cambiado el menú para poder elegir si se abre en la misma hoja en una diferente
-Mantenimiento ahora el contenido se centra en la página.
-El fichero pdf ahora se puede grabar en disco y se puede visualizar en una ventana nueva.
This commit is contained in:
2014-02-14 00:18:47 +01:00
parent fb276bd753
commit c54f604b47
14 changed files with 1098 additions and 794 deletions

View File

@@ -1,64 +1,73 @@
<?php
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
define ('PIE','<center><a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0-standalone.html"><img src="img/gplv3.png" alt="GPL v3"/></a>'.
'<a target="_blank" href="http://www.apache.org"><img src="img/apache.gif" alt="Sitio web creado con Apache" /></a>'.
'<a target="_blank" href="http://www.mysql.org"><img src="img/mysql.png" width=125 height=47 alt="Gestor de bases de datos mySQL" /></a>'.
'<a target="_blank" href="http://www.php.net"><img src="img/php.gif" alt="PHP Language" /></a> </center>');
define ('FORMULARIO_ACCESO','<form name="formulario_acceso" action="index.php?registrarse" method="POST">'.
'Usuario<br><input type="text" name="usuario" value="" size="8" /><br><br>Clave<br><input type="password" name="clave" value="" size="8" />'.
'<br><br><input type="submit" value="Iniciar" name="iniciar" /></form>');
define ('MENSAJE_DEMO','Puede Iniciar sesi&oacute;n con<br>usuario <i><b>demo</b></i><br>contrase&ntilde;a <i>demo</i><br>');
define ('USUARIO_INCORRECTO','<label class="error">Usuario y clave incorrectos!</label><br><br>');
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
define('PIE', '<center><a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0-standalone.html"><img src="img/gplv3.png" alt="GPL v3"/></a>' .
'<a target="_blank" href="http://www.apache.org"><img src="img/apache.gif" alt="Sitio web creado con Apache" /></a>' .
'<a target="_blank" href="http://www.mysql.org"><img src="img/mysql.png" width=125 height=47 alt="Gestor de bases de datos mySQL" /></a>' .
'<a target="_blank" href="http://www.php.net"><img src="img/php.gif" alt="PHP Language" /></a> </center>');
define('FORMULARIO_ACCESO', '<form name="formulario_acceso" action="index.php?registrarse" method="POST">' .
'Usuario<br><input type="text" name="usuario" value="" size="8" /><br><br>Clave<br><input type="password" name="clave" value="" size="8" />' .
'<br><br><input type="submit" value="Iniciar" name="iniciar" /></form>');
define('MENSAJE_DEMO', 'Puede Iniciar sesi&oacute;n con<br>usuario <i><b>demo</b></i><br>contrase&ntilde;a <i>demo</i><br>');
define('USUARIO_INCORRECTO', '<label class="error">Usuario y clave incorrectos!</label><br><br>');
// Esta clase aportará el contenido a la plantilla
class AportaContenido {
/**
*
* @var boolean Aporta información sobre si el usuario está registrado o no.
*/
private $registrado;
/**
* @var string Nombre del usuario
*/
private $usuario=NULL;
/**
private $usuario = NULL;
/**
* @var Menu Menú de la página.
*/
private $miMenu;
/**
* @var database Controlador de la base de datos
*/
private $bdd;
/**
* @var string Opción elegida por el usuario
*/
private $opcionActual;
/**
/**
* @var boolean Usuario y clave incorrectos?
*/
private $usuario_inc=false;
private $usuario_inc = false;
/**
* @var array Permisos del usuario
*/
private $perfil;
// El constructor necesita saber cuál es la opción actual
/**
* Constructor de la clase.
@@ -68,40 +77,36 @@ class AportaContenido {
* @param array $perfil Permisos de acceso del usuario
* @param String $opcion Opción elegida por el usuario
*/
public function __construct($baseDatos,$registrado,$usuario,$perfil,$opcion)
{
$this->bdd=$baseDatos;
$this->miMenu=new Menu('inc/inventario.menu');
$this->registrado=$registrado;
$this->usuario=$usuario;
$this->perfil=$perfil;
$this->opcionActual=$opcion;
public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion) {
$this->bdd = $baseDatos;
$this->miMenu = new Menu('inc/inventario.menu');
$this->registrado = $registrado;
$this->usuario = $usuario;
$this->perfil = $perfil;
$this->opcionActual = $opcion;
}
/**
* Devuelve la fecha actual
* @param string $formato formato de devolución de la fecha
* @param string $idioma idioma para formatear la fecha, p.ej. es_ES
* @return string
*/
public function fechaActual($formato='',$idioma='es_ES')
{
if ($formato=='')
$formato="%d-%b-%Y %H:%M";
setlocale(LC_TIME,$idioma);
public function fechaActual($formato = '', $idioma = 'es_ES') {
if ($formato == '')
$formato = "%d-%b-%Y %H:%M";
setlocale(LC_TIME, $idioma);
return strftime($formato);
}
/**
*
* @return string Mensaje el usuario debe registrarse.
*/
private function mensajeRegistro()
{
/**
* @todo: tarea de prueba
*/
private function mensajeRegistro() {
return 'Debe registrarse para acceder a este apartado';
}
// Procesaremos todas las invocaciones a métodos en
// la función __call()
/**
@@ -110,9 +115,8 @@ class AportaContenido {
* @param string $parametros Parámetros del método
* @return string Contenido devuelto por el método
*/
public function __call($metodo,$parametros)
{
switch($metodo) { // Dependiendo del método invocado
public function __call($metodo, $parametros) {
switch ($metodo) { // Dependiendo del método invocado
case 'titulo': // devolvemos el título
return APLICACION;
case 'usuario':
@@ -126,7 +130,7 @@ class AportaContenido {
if ($this->registrado) {
return $this->miMenu->insertaMenu();
} else {
$salida=FORMULARIO_ACCESO;
$salida = FORMULARIO_ACCESO;
if ($this->usuario_inc) {
$salida.=USUARIO_INCORRECTO;
}
@@ -134,8 +138,8 @@ class AportaContenido {
return $salida;
}
case 'opcion':
list($opcion,$parametro)=explode("&",$this->opcionActual);
switch($opcion) {
list($opcion, $parametro) = explode("&", $this->opcionActual);
switch ($opcion) {
case 'bienvenido':
return "Men&uacute; Principal";
case 'principal':
@@ -145,7 +149,7 @@ class AportaContenido {
case 'ubicaciones':
case 'usuarios':
case 'test':
return "Mantenimiento de ".ucfirst($opcion).".";
return "Mantenimiento de " . ucfirst($opcion) . ".";
case 'configuracion':
return 'Configuraci&oacute;n y Preferencias.';
case 'informeInventario':return "Informe de Inventario";
@@ -160,70 +164,70 @@ class AportaContenido {
// Para incluir el contenido central de la página
case 'contenido':
// tendremos en cuenta cuál es la opción actual
/*echo "opcActual=$this->opcActual<br>";
echo "Metodo=$Metodo<br>";
print_r($Parametros);*/
/* echo "opcActual=$this->opcActual<br>";
echo "Metodo=$Metodo<br>";
print_r($Parametros); */
// if (!$this->registrado) {
// return $this->mensajeRegistro();
// }
list($opcion,$parametro)=explode("&",$this->opcionActual);
switch($opcion) {
list($opcion, $parametro) = explode("&", $this->opcionActual);
switch ($opcion) {
case 'principal': // contenido inicial
return '<br><br><center><img src="img/logo.png" alt="'.PROGRAMA.'">'.
'<br><label>'.PROGRAMA.'</label></center><br><br>'.PIE;
return '<br><br><center><img src="img/logo.png" alt="' . PROGRAMA . '">' .
'<br><label>' . PROGRAMA . '</label></center><br><br>' . PIE;
case 'articulos':
case 'ubicaciones':
case 'test':
case 'elementos':
if ($this->perfil['Consulta']) {
$ele=new Mantenimiento($this->bdd,$this->perfil,$opcion);
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta();
} else {
return $this->mensajePermisos(ucfirst($opcion));
}
case 'usuarios':
if ($this->perfil['Usuarios']) {
$ele=new Mantenimiento($this->bdd,$this->perfil,$opcion);
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta();
} else {
return $this->mensajePermisos('Usuarios');
}
case 'bienvenido': // El usuario quiere iniciar sesión
return 'Bienvenido '.$this->usuario.'<br><br><center><img src="img/codigoBarras.png" alt="'.PROGRAMA.'">'.
'<br><label>'.PROGRAMA.'</label></center><br><br>'.PIE;
return 'Bienvenido ' . $this->usuario . '<br><br><center><img src="img/codigoBarras.png" alt="' . PROGRAMA . '">' .
'<br><label>' . PROGRAMA . '</label></center><br><br>' . PIE;
case 'configuracion':
if ($this->perfil['Config']) {
$conf=new Configuracion();
$conf = new Configuracion();
return $conf->ejecuta();
} else {
return $this->mensajePermisos('Configuracion');
}
case 'informeInventario':
if ($this->perfil['Informe']) {
$info=new InformeInventario($this->bdd);
$info = new InformeInventario($this->bdd);
return $info->ejecuta();
} else {
return $this->mensajePermisos('Informes');
}
case 'descuadres':
if ($this->perfil['Informe']) {
$enlace='xml/informe'.ucfirst($opcion).'.xml';
$informe=new InformePDF($this->bdd,$enlace,$this->registrado);
$informe->imprimeInforme();
return;
$enlace = 'xml/informe' . ucfirst($opcion) . '.xml';
$informe = new InformePDF($this->bdd, $enlace, $this->registrado);
$informe->imprimeInforme();
return;
} else {
return $this->mensajePermisos('Informes');
}
} // Fin del contenido
case 'usuario_incorrecto':
$this->usuario_inc=true;
return;
$this->usuario_inc = true;
return;
case 'registro': // Si está registrado mostrar bienvenida
// si no, un enlace
if($this->bEstaRegistrado) {
return "Bienvenido <b>$this->sUsuario</b><hr />".
'<a href="index.php?cerrarSesion">Cerrar sesi&oacute;n</a>';
if ($this->bEstaRegistrado) {
return "Bienvenido <b>$this->sUsuario</b><hr />" .
'<a href="index.php?cerrarSesion">Cerrar sesi&oacute;n</a>';
} else {
return '';
}
@@ -231,14 +235,16 @@ class AportaContenido {
return "Marca {$metodo} queda sin procesar";
}
}
/**
*
* @param string $tipo
* @return string
*/
public function mensajePermisos($tipo)
{
return "<center><h1>No tiene permiso para acceder a ".$tipo."</h1></center>";
public function mensajePermisos($tipo) {
return "<center><h1>No tiene permiso para acceder a " . $tipo . "</h1></center>";
}
}
?>

BIN
Informe.pdf Normal file

Binary file not shown.

View File

@@ -1,154 +1,153 @@
<?php
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
class InformeInventario {
private $bdd;
public function __construct($baseDatos)
{
$this->bdd=$baseDatos;
}
public function ejecuta()
{
$opc=$_GET['opc'];
switch ($opc) {
case 'Ubicacion':return $this->formularioUbicacion();
case 'listarUbicacion':return $this->listarUbicacion();
case 'listarArticulo':return $this->listarArticulo();
case 'Articulo':return $this->formularioArticulo();
case 'Total':return $this->inventarioTotal();
}
}
private function listarUbicacion()
{
$fichero="xml/inventarioUbicacion.xml";
$salida="tmp/inventarioUbicacion.xml";
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$comando="select * from Ubicaciones where id='".$_POST['id']."';";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila=$this->bdd->procesaResultado();
$plantilla=str_replace("{id}",$_POST['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['Descripcion']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$informe=new InformePDF($this->bdd,$salida,true);
$informe->imprimeInforme();
}
private function listarArticulo()
{
$fichero="xml/inventarioArticulo.xml";
$salida="tmp/inventarioArticulo.xml";
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$comando="select * from Articulos where id='".$_POST['id']."';";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila=$this->bdd->procesaResultado();
$plantilla=str_replace("{id}",$_POST['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['descripcion']),$plantilla);
$plantilla=str_replace("{Marca}",utf8_encode($fila['marca']),$plantilla);
$plantilla=str_replace("{Modelo}",utf8_encode($fila['modelo']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$informe=new InformePDF($this->bdd,$salida,true);
$informe->imprimeInforme();
}
private function listaUbicaciones()
{
$salida="<select name=\"id\">\n";
$comando="select * from Ubicaciones order by Descripcion";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while($fila=$this->bdd->procesaResultado()) {
$salida.="<option value=".$fila['id'].">".$fila['Descripcion']."</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function listaArticulos()
{
$salida="<select name=\"id\">\n";
$comando="select * from Articulos order by descripcion, marca, modelo";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while($fila=$this->bdd->procesaResultado()) {
$salida.="<option value=".$fila['id'].">".$fila['descripcion']."-".$fila['marca']."-".$fila['modelo']."</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function formulario($accion,$etiqueta,$lista)
{
$salida='<form name="mantenimiento.form" method="post" action="'.$accion.'">'."\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige $etiqueta</b></legend>\n";
$salida.="<br><br><label>$etiqueta</label>";
$salida.=$lista;
$salida.="<br><br></fieldset><p>";
$salida.='<p align="center"><button type=submit>Aceptar</button></p><br>'."\n";
return $salida;
}
private function formularioUbicacion()
{
//Genera un formulario con las ubicaciones disponibles.
$accion="index.php?informeInventario&opc=listarUbicacion";
return $this->formulario($accion,'Ubicaci&oacute;n',$this->listaUbicaciones());
}
private function formularioArticulo()
{
$accion="index.php?informeInventario&opc=listarArticulo";
return $this->formulario($accion,'Art&iacute;culo',$this->listaArticulos());
}
private function inventarioTotal()
{
$fichero="xml/inventarioUbicacion.xml";
$salida="tmp/inventarioUbicacion.xml";
$comando="select * from Ubicaciones ;";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$salidaTotal='';
while ($fila=$this->bdd->procesaResultado()) {
//$fila=$this->bdd->procesaResultado();
$plantilla=file_get_contents($fichero)
or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla=str_replace("{id}",$fila['id'],$plantilla);
$plantilla=str_replace("{Descripcion}",utf8_encode($fila['Descripcion']),$plantilla);
file_put_contents($salida,$plantilla)
or die('Fallo en la escritura de la plantilla '.$salida);
$informe=new InformePDF($this->bdd,$salida,true);
$salidaTotal.=$informe->getContenido();
}
file_put_contents("tmp/prueba.pdf",$salidaTotal);
$informe->enviaCabecera();
echo $salidaTotal;
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
class InformeInventario {
private $bdd;
public function __construct($baseDatos) {
$this->bdd = $baseDatos;
}
public function ejecuta() {
$opc = $_GET['opc'];
switch ($opc) {
case 'Ubicacion':return $this->formularioUbicacion();
case 'listarUbicacion':return $this->listarUbicacion();
case 'listarArticulo':return $this->listarArticulo();
case 'Articulo':return $this->formularioArticulo();
case 'Total':return $this->inventarioTotal();
}
}
private function listarUbicacion() {
$fichero = "xml/inventarioUbicacion.xml";
$salida = "tmp/inventarioUbicacion.xml";
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$comando = "select * from Ubicaciones where id='" . $_POST['id'] . "';";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $_POST['id'], $plantilla);
$plantilla = str_replace("{Descripcion}", utf8_encode($fila['Descripcion']), $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$informe = new InformePDF($this->bdd, $salida, true);
$informe->guardaArchivo("Informe.pdf");
echo '<script type="text/javascript"> window.open( "Informe.pdf" ) </script>';
}
private function listarArticulo() {
$fichero = "xml/inventarioArticulo.xml";
$salida = "tmp/inventarioArticulo.xml";
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$comando = "select * from Articulos where id='" . $_POST['id'] . "';";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $_POST['id'], $plantilla);
$plantilla = str_replace("{Descripcion}", utf8_encode($fila['descripcion']), $plantilla);
$plantilla = str_replace("{Marca}", utf8_encode($fila['marca']), $plantilla);
$plantilla = str_replace("{Modelo}", utf8_encode($fila['modelo']), $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$informe = new InformePDF($this->bdd, $salida, true);
$informe->guardaArchivo("Informe.pdf");
echo '<script type="text/javascript"> window.open( "Informe.pdf" ) </script>';
}
private function listaUbicaciones() {
$salida = "<select name=\"id\">\n";
$comando = "select * from Ubicaciones order by Descripcion";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while ($fila = $this->bdd->procesaResultado()) {
$salida.="<option value=" . $fila['id'] . ">" . $fila['Descripcion'] . "</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function listaArticulos() {
$salida = "<select name=\"id\">\n";
$comando = "select * from Articulos order by descripcion, marca, modelo";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
while ($fila = $this->bdd->procesaResultado()) {
$salida.="<option value=" . $fila['id'] . ">" . $fila['descripcion'] . "-" . $fila['marca'] . "-" . $fila['modelo'] . "</option><br>\n";
}
$salida.="</select>\n";
return $salida;
}
private function formulario($accion, $etiqueta, $lista) {
$salida = '<form name="mantenimiento.form" method="post" action="' . $accion . '">' . "\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige $etiqueta</b></legend>\n";
$salida.="<br><br><label>$etiqueta</label>";
$salida.=$lista;
$salida.="<br><br></fieldset><p>";
$salida.='<p align="center"><button type=submit>Aceptar</button></p><br>' . "\n";
return $salida;
}
private function formularioUbicacion() {
//Genera un formulario con las ubicaciones disponibles.
$accion = "index.php?informeInventario&opc=listarUbicacion";
return $this->formulario($accion, 'Ubicaci&oacute;n', $this->listaUbicaciones());
}
private function formularioArticulo() {
$accion = "index.php?informeInventario&opc=listarArticulo";
return $this->formulario($accion, 'Art&iacute;culo', $this->listaArticulos());
}
private function inventarioTotal() {
$fichero = "xml/inventarioUbicacion.xml";
$salida = "tmp/inventarioUbicacion.xml";
$comando = "select * from Ubicaciones ;";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$salidaTotal = '';
while ($fila = $this->bdd->procesaResultado()) {
//$fila=$this->bdd->procesaResultado();
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$plantilla = str_replace("{id}", $fila['id'], $plantilla);
$plantilla = str_replace("{Descripcion}", utf8_encode($fila['Descripcion']), $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$informe = new InformePDF($this->bdd, $salida, true);
$salidaTotal.=$informe->getContenido();
}
file_put_contents("tmp/prueba.pdf", $salidaTotal);
$informe->enviaCabecera();
echo $salidaTotal;
}
}
?>

View File

@@ -82,6 +82,20 @@
{
return $this->docu;
}
public function getCabecera()
{
$cabecera = "Content-type: application/pdf";
$cabecera = $cabecera . "Content-length: " . strlen($this->docu);
$cabecera = $cabecera . "Content-Disposition: inline; filename=Informe.pdf";
return $cabecera;
}
public function guardaArchivo($nombre = "Informe.pdf")
{
$fichero = fopen($nombre, "w");
fwrite($fichero,$this->getCabecera());
fwrite($fichero,$this->getContenido(), strlen($this->getContenido()));
fclose($fichero);
}
public function enviaCabecera()
{
header("Content-type: application/pdf");

View File

@@ -1,4 +1,5 @@
<?php
/**
* Clase Inventario que controla la ejecución principal del programa.
* @author Ricardo Montañana Gómez <rmontanana@gmail.com>
@@ -21,62 +22,63 @@
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Clase del objeto principal de la aplicación
// Clase del objeto principal de la aplicación
class Inventario {
// Declaración de miembros
private $bdd; // Enlace con el SGBD
private $registrado; // Usuario registrado s/n
private $usuario=NULL; // Nombre del usuario
private $usuario = NULL; // Nombre del usuario
private $clave; //contraseña del usuario
private $opcActual; // Opción elegida por el usuario
private $perfil; //Permisos del usuario.
private $estado; //BD conectada o no
private $plant='plant/principal.html';
private $plant = 'plant/principal.html';
// Constructor
public function __construct()
{
public function __construct() {
// Analizamos la cadena de solicitud para saber
// qué opción es la actual
$this->opcActual=$_SERVER['QUERY_STRING']=='' ? 'principal' : $_SERVER['QUERY_STRING'];
$this->opcActual = $_SERVER['QUERY_STRING'] == '' ? 'principal' : $_SERVER['QUERY_STRING'];
// Iniciamos una sesión
session_start();
//Conexión con la base de datos.
$this->bdd=new Sql(SERVIDOR,USUARIO,CLAVE,BASEDATOS);
$this->bdd = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($this->bdd->error()) {
echo '<h1>Fallo al conectar con el servidor MySQL.</h1>';
echo SERVIDOR;echo "Servidor [ ". SERVIDOR ." ] usuario [".USUARIO."] clave [".CLAVE."] base [".BASEDATOS."]";
$this->estado=false;
echo SERVIDOR;
echo "Servidor [ " . SERVIDOR . " ] usuario [" . USUARIO . "] clave [" . CLAVE . "] base [" . BASEDATOS . "]";
$this->estado = false;
return;
} else {
$this->estado=true;
$this->estado = true;
}
// Comprobamos si el usuario ya está registrado en esta sesión
$this->registrado=isset($_SESSION['Registrado']);
if($this->registrado) {// si está...
$this->registrado = isset($_SESSION['Registrado']);
if ($this->registrado) {// si está...
// recuperamos el nombre del usuario
$this->usuario=$_SESSION['Usuario'];
$this->perfil=$_SESSION['Perfil'];
// en caso contrario comprobamos si tiene la cookie que le identifica como usuario
} elseif(isset($_COOKIE['InventarioId'])) {
$this->usuario = $_SESSION['Usuario'];
$this->perfil = $_SESSION['Perfil'];
// en caso contrario comprobamos si tiene la cookie que le identifica como usuario
} elseif (isset($_COOKIE['InventarioId'])) {
// y usamos el Id para recuperar el nombre de la base de ddtos
$this->recuperaNombreConId($_COOKIE['InventarioId']);
} else { // en caso contrario el usuario no está registrado
$this->usuario='';
$this->usuario = '';
}
}
public function estado()
{
public function estado() {
return $this->estado;
}
// Esta función pondrá en marcha la aplicación ocupándose
// de las acciones que no generan contenido, esto es
// iniciar sesión, cerrarla, etc.
public function Ejecuta()
{
public function Ejecuta() {
// Dependiendo de la opción a procesar
switch($this->opcActual) {
// El usuario quiere cerrar la sesión actual
switch ($this->opcActual) {
// El usuario quiere cerrar la sesión actual
case 'cerrarSesion':
// Eliminamos los datos de sesión
session_unset();
@@ -86,77 +88,77 @@ class Inventario {
setcookie('InventarioId', '');
// y le redirigmos a la página inicial
header('Location: index.php');
exit;
exit;
// El usuario quiere iniciar sessión
case 'registrarse':
// Se identifica como usuario de la aplicación
$resultado=$this->usuarioRegistrado();
$resultado = $this->usuarioRegistrado();
// Si lo obtuvimos es que el usuario está registrado
if($resultado) {
if ($resultado) {
// establecemos las variables de sesión
$_SESSION['Registrado'] = true;
$_SESSION['Usuario'] = $this->usuario;
$_SESSION['Perfil'] = $this->perfil;
// y enviamos la cookie para reconocerlo la próxima vez
setcookie('InventarioId', $resultado, time()+3600*24*365);
setcookie('InventarioId', $resultado, time() + 3600 * 24 * 365);
// Lo enviamos a la página de bienvenida
header('Location: index.php?bienvenido');
exit;
}
}
//Usuario incorrecto
header('location:index.php?usuario_incorrecto');
exit;
case 'usuario_incorrecto':
$this->opcActual="principal";
$contenido=$this->creaContenido();
$contenido->usuario_incorrecto();
$salida=new Distribucion($this->plant,$contenido);
echo $salida->procesaPlantilla();
break;
case 'usuario_incorrecto':
$this->opcActual = "principal";
$contenido = $this->creaContenido();
$contenido->usuario_incorrecto();
$salida = new Distribucion($this->plant, $contenido);
echo $salida->procesaPlantilla();
break;
default:
// Creamos un objeto Distribución facilitándole el
// nombre del archivo plantilla y el objeto que aportará
// el contenido
$opc=$_GET['opc'];
list($opcion,$parametro)=explode("&",$this->opcActual);
$opc = $_GET['opc'];
list($opcion, $parametro) = explode("&", $this->opcActual);
switch ($opc) {
case 'informe':
$enlace='xml/informe'.ucfirst($opcion).'.xml';
$enlace = 'xml/informe' . ucfirst($opcion) . '.xml';
//$enlace="tmp/inventarioUbicacion.xml";
$informe=new InformePDF($this->bdd,$enlace,$this->registrado);
$informe->imprimeInforme();
$informe = new InformePDF($this->bdd, $enlace, $this->registrado);
$informe->imprimeInforme();
return;
default:
$salida=new Distribucion($this->plant,$this->creaContenido());
$salida = new Distribucion($this->plant, $this->creaContenido());
echo $salida->procesaPlantilla();
break;
}
}
}
}
private function creaContenido()
{
return new AportaContenido($this->bdd,$this->registrado,$this->usuario,$this->perfil,$this->opcActual);
private function creaContenido() {
return new AportaContenido($this->bdd, $this->registrado, $this->usuario, $this->perfil, $this->opcActual);
}
// Esta función comprueba si el usuario está o no registrado,
// devolviendo su IdSesion en caso afirmativo o false
// en caso contrario
private function usuarioRegistrado()
{
$this->usuario=$_POST['usuario'];
$this->clave=$_POST['clave'];
private function usuarioRegistrado() {
$this->usuario = $_POST['usuario'];
$this->clave = $_POST['clave'];
// ejecuta la consulta para buscar el usuario
$res=$this->bdd->ejecuta("SELECT * FROM Usuarios WHERE nombre='$this->usuario'");
$res = $this->bdd->ejecuta("SELECT * FROM Usuarios WHERE nombre='$this->usuario'");
// Si no hemos encontrado el usuario
if(!$res) {
if (!$res) {
return false; // devolvemos FALSE
}
// En caso contrario obtenemos en una matriz
// los datos de las columnas
$fila=$this->bdd->procesaResultado();
$fila = $this->bdd->procesaResultado();
// Para comprobar si la clave coincide
if($fila['clave']==$this->clave) {
$this->perfil=$this->creaPerfil($fila);
if ($fila['clave'] == $this->clave) {
$this->perfil = $this->creaPerfil($fila);
// caso en el que devolveremos un Id de sesión
// único para este usuario
return $fila['idSesion'];
@@ -165,43 +167,44 @@ class Inventario {
// la clave no es correcta
return false;
}
private function creaPerfil($fila)
{
return array("Consulta"=>$fila['consulta'],"Modificacion"=>$fila['modificacion'],
"Alta"=>$fila['alta'],"Borrado"=>$fila['borrado'],"Informe"=>$fila['informe'],
"Usuarios"=>$fila['usuarios'],"Config"=>$fila['config']);
private function creaPerfil($fila) {
return array("Consulta" => $fila['consulta'], "Modificacion" => $fila['modificacion'],
"Alta" => $fila['alta'], "Borrado" => $fila['borrado'], "Informe" => $fila['informe'],
"Usuarios" => $fila['usuarios'], "Config" => $fila['config']);
}
// Esta función intenta recuperar el nombre del usuario
// a partir del Id de sesión almacenado en una cookie,
// dejando las variables Registrado y Usuario con
// los valores apropiados
// @param String Identificador de sesión del usuario actual
private function recuperaNombreConId($idSesion)
{
private function recuperaNombreConId($idSesion) {
// para ejecutar la consulta para buscar el Id de sesión
$res=$this->bdd->ejecuta("SELECT * FROM Usuarios WHERE idSesion='$idSesion'");
$res = $this->bdd->ejecuta("SELECT * FROM Usuarios WHERE idSesion='$idSesion'");
// Si no hemos encontrado el ID
if(!$res) {
// el usuario no está registrado
$this->usuario='';
$this->registrado=false;
if (!$res) {
// el usuario no está registrado
$this->usuario = '';
$this->registrado = false;
} else {
// En caso contrario obtenemos en una matriz
// los datos de las columnas
$fila=$this->bdd->procesaResultado();
$fila = $this->bdd->procesaResultado();
// Asignamos el nombre
$this->usuario=$fila['nombre'];
$this->usuario = $fila['nombre'];
// damos el valor TRUE a bRegistrado
$this->registrado=true;
$this->registrado = true;
// y establecemos las variables de sessión para no tener
// que efectuar todo este proceso de nuevo con cada
// solicitud de página
$_SESSION['Registrado']=true;
$_SESSION['Usuario']=$this->usuario;
$this->perfil=$this->creaPerfil($fila);
$_SESSION['Perfil']=$this->perfil;
$_SESSION['Registrado'] = true;
$_SESSION['Usuario'] = $this->usuario;
$this->perfil = $this->creaPerfil($fila);
$_SESSION['Perfil'] = $this->perfil;
}
}
}
?>

View File

@@ -1,447 +1,457 @@
<?php
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
//Clase que se encargará de manejar los elementos del modelo de datos.
define ('EDICION','Edici&oacute;n');
define ('BORRADO','<i>Borrado</i>');
define ('ANADIR','Inserci&oacute;n');
class Mantenimiento {
private $descripcion;
protected $bdd;
protected $url;
protected $cabecera;
protected $tabla;
protected $cadenaBusqueda;
protected $campos=array();
protected $foraneas=array();
protected $campoBusca="Descripcion";
protected $comandoConsulta="";
protected $perfil;
public function __construct($baseDatos,$perfil,$nombre)
{
$this->bdd=$baseDatos;
$this->url="index.php?$nombre&opc=inicial";
$this->cabecera='Location: '.$this->url;
$this->tabla=ucfirst($nombre);
$this->perfil=$perfil;
}
public function ejecuta()
{
$opc=$_GET['opc'];
$id=$_GET['id'];
$orden=isset($_GET['orden'])?$_GET['orden']:'';
$sentido=isset($_GET['sentido'])?$_GET['sentido']:'asc';
//Sólo tiene sentido para las modificaciones.
//Es la página donde estaba el registro
$pag=isset($_GET['pag'])?$_GET['pag']:'0';
$this->cadenaBusqueda=$_GET['buscar'];
$this->obtenerCampos();
$this->obtieneClavesForaneas();
switch ($opc) {
case 'inicial':return $this->consulta($id,$orden,$sentido);
case 'editar':return $this->muestra($id,EDICION,$pag,$orden,$sentido);
case 'eliminar':return $this->muestra($id,BORRADO);
case 'nuevo':return $this->muestra(null,ANADIR);
case 'insertar':return $this->insertar();
case 'modificar':return $this->modificar($id,$pag,$orden,$sentido);
case 'borrar':return $this->borrar($id);
default:return 'La clase Mantenimiento No entiende lo solicitado.';
}
}
protected function obtieneClavesForaneas()
{
$salida=null;
foreach($this->campos as $clave => $valor) {
$trozos=explode(",",$valor["Comment"]);
foreach($trozos as $trozo) {
if (strstr($trozo,"foreign")) {
$temp=substr($trozo,8,-1);
list($tabla,$atributos)=explode("->",$temp);
list($clave,$resto)=explode(";",$atributos);
//Quita el paréntesis final
$atributos=substr($atributos,0,-1);
$salida[$valor['Campo']]=$tabla.",".$resto;
}
}
}
$this->foraneas=$salida;
}
private function consulta($pagina,$orden,$sentido)
{
//Calcula los números de página anterior y siguiente.
$pagina=$pagina+0;
$pagSigte=$pagina<=0?1:$pagina+1;
$pagAnt=$pagSigte-2;
$pagFwd=$pagSigte+3;
$pagRew=$pagAnt-3<0?$pagAnt:$pagAnt-3;
//Trata con la cadena de búsqueda
$this->cadenaBusqueda=isset($_POST['buscar'])?$_POST['buscar']:$this->cadenaBusqueda;
if (isset($this->cadenaBusqueda) && strlen($this->cadenaBusqueda)) {
$sufijo=" where $this->campoBusca like '%".$this->bdd->filtra($this->cadenaBusqueda)."%'";
$sufijoEnlace="&buscar=".$this->cadenaBusqueda;
$comando=str_replace('{buscar}',$sufijo,$this->comandoConsulta);
} else {
$comando=str_replace('{buscar}','',$this->comandoConsulta);
}
//Trata con el orden de mostrar los datos
if (strlen($orden)>0) {
$comando=str_replace('{orden}',"order by ".$orden." ".$sentido,$comando);
$sufijoOrden="&orden=".$orden."&sentido=".$sentido;
} else {
$comando=str_replace('{orden}',' ',$comando);
}
//Introduce un botón para hacer búsquedas
$salida=$this->enlaceBusqueda();
$salida.=$this->cabeceraTabla();
//Consulta paginada de todas las tuplas
$comando=str_replace('{inferior}',($pagAnt+1)*NUMFILAS,$comando);
$comando=str_replace('{superior}',NUMFILAS,$comando);
//$salida.=$comando;
$salida.='<h4>P&aacute;gina '.$pagSigte.'</h4>';
$tabla=strtolower($this->tabla);
$this->bdd->ejecuta($comando);
if ($this->bdd->numeroTuplas()==0) {
if ($pagSigte>1) {
// Si no hay datos en la consulta y no es la primera página,
// carga la página inicial
header('Location: '.$this->url);
} else {
$salida="<p align=\"center\"><center><h2>No hay registros</h2></center></p><br>";
}
}
//$salida.=print_r($this->perfil);
while($fila=$this->bdd->procesaResultado()) {
$salida.="<tr>";
foreach ($fila as $clave => $valor) {
if ($clave=="id") {
$id=$valor;
}
$salida.="<td>$valor</td>\n";
}
//Añade el icono de editar
if ($this->perfil['Modificacion']) {
$salida.='<td><a href="index.php?'.$tabla.'&opc=editar&id='.$id."&pag=".$pagina.$sufijoOrden.
'"><img title="Editar" src="img/'.ESTILO.'/editar.png" alt="editar"></a>';
}
//Añade el icono de eliminar
if ($this->perfil['Borrado']) {
$salida.='&nbsp;&nbsp;<a href="index.php?'.$tabla.'&opc=eliminar&id='.$id.
'"><img title="Eliminar" src="img/'.ESTILO.'/eliminar.png" alt="eliminar"></a></td></tr>'."\n";
}
}
$salida.="</tbody></table></p>";
//Añade botones de comandos
$enlace='<a href="'.$this->url.$sufijoOrden.'&id=';
if ($this->bdd->numeroTuplas()) {
$anterior=$enlace.$pagAnt.$sufijoEnlace."\"><img title=\"Pag. Anterior\" alt=\"anterior\" src=\"img/".ESTILO."/anterior.png\"></a>\n";
$siguiente=$enlace.$pagSigte.$sufijoEnlace."\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/".ESTILO."/siguiente.png\"></a>\n";
$fwd=$enlace.$pagFwd.$sufijoEnlace."\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/".ESTILO."/fwd.png\"></a>\n";
$rew=$enlace.$pagRew.$sufijoEnlace."\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/".ESTILO."/rew.png\"></a>\n";
if (strlen($orden)>0) {
$az='<a href="'.$this->url.'&orden='.$orden.'&sentido=asc"><img alt="asc" title="Orden ascendente" src="img/'.ESTILO.'/ascendente.png"></a>';
$za='<a href="'.$this->url.'&orden='.$orden.'&sentido=desc"><img alt="desc" title="Orden descendente" src="img/'.ESTILO.'/descendente.png"></a>';
} else {
$az=$za='';
}
if ($this->perfil['Informe']) {
$informe='<a href="index.php?'.$tabla.'&opc=informe" target="_blank"><img src="img/'.ESTILO.'/informe.png" alt="informe" title="Informe pdf"></a>';
} else {
$informe="";
}
}
if ($this->perfil['Alta']) {
$anadir='<a href="index.php?'.$tabla.'&opc=nuevo">'.
'<img title="A&ntilde;adir registro" alt="nuevo" src="img/'.ESTILO.'/nuevo.png"></a>';
} else {
$anadir="";
}
$salida.='<p align="center">'.
"$rew&nbsp&nbsp$anterior&nbsp&nbsp$az&nbsp&nbsp$anadir&nbsp&nbsp$informe&nbsp&nbsp$za&nbsp&nbsp$siguiente&nbsp&nbsp$fwd</p>";
return $salida;
}
private function enlaceBusqueda()
{
$salida='<p align="center">';
$salida.='<center><form name="busqueda" method="POST"><input type="text" name="buscar"';
$salida.='value="'.$this->cadenaBusqueda.'" size="40" /><input type="submit" value="Buscar" name=';
$salida.='"Buscar" /></form></center>';
$salida.='</p>';
return $salida;
}
protected function borrar($id)
{
$comando="delete from ".$this->tabla." where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
header('Location: '.$this->url);
return;
}
protected function insertar()
{
$comando="insert into ".$this->tabla." (";
$lista=explode("&",$_POST['listacampos']);
$primero=true;
//Añade la lista de campos
foreach ($lista as $campo) {
if ($campo=="") {
continue;
}
if ($primero) {
$primero=false;
$coma=" ";
} else {
$coma=",";
}
$comando.="$coma $campo";
}
$comando.=") values (";
//Añade la lista de valores
$primero=true;
foreach ($lista as $campo) {
if ($campo=="")
continue;
if ($primero) {
$primero=false;
$coma=" ";
} else {
$coma=",";
}
$comando.="$coma \"$_POST[$campo]\"";
}
$comando.=")";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace,$resto)=explode("&",$this->url);
$enlace.="&opc=inicial";
return "<h1><a href=\"$enlace\">Se ha insertado el registro con la clave ".$this->bdd->ultimoId()."</a></h1>";
}
protected function modificar($id,$pag,$orden,$sentido)
{
//Los datos a utilizar para actualizar la tupla vienen en $_POST.
//La lista de atributos de la tupla viene en el campo oculto listacampos
//print_r($_GET);
//echo "id=$id pag=$pag orden=$orden sentido=$sentido";die();
$comando="update ".$this->tabla." set ";
$lista=explode("&",$_POST['listacampos']);
$primero=true;
foreach ($lista as $campo) {
if ($campo=="id" || $campo=="")
continue;
if ($primero) {
$primero=false;
$coma=" ";
} else
$coma=",";
if (strlen(trim($_POST[$campo]))==0)
$comando.="$coma $campo=null";
else
$comando.=$coma.' '.$campo.'="'.$_POST[$campo].'"';
}
$comando.=" where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace,$resto)=explode("&",$this->url);
$enlace.="&opc=inicial&orden=".$orden."&sentido=".$sentido."&id=".$pag;
header('Location: '.$enlace);
return;
}
protected function muestra($id,$tipoAccion,$pag="",$orden="",$sentido="")
{
if (isset($id)) {
$comando="select * from ".$this->tabla." where id='$id'";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->errorBD("","No se han podido encontrar datos del identificador $id");
}
$fila=$this->bdd->procesaResultado();
} else {
$fila=null;
}
//list($tipo,$valor)=explode($columna["Type"]);
$accion="index.php?".strtolower($this->tabla)."&id=$id&opc=";
switch ($tipoAccion) {
case EDICION:
$accion.="modificar";
$accion.=isset($pag)?"&pag=$pag":'';
$accion.=isset($orden)?"&orden=$orden":'';
$accion.=isset($sentido)?"&sentido=$sentido":'';
break;
case BORRADO:
$accion.="borrar";
break;
case ANADIR:
$accion.="insertar";
break;
}
//Genera un formulario con los datos de la tupla seleccionada.
return $this->formularioCampos($accion,$tipoAccion,$fila);
}
//Función que genera un campo de lista con los valores de descripción de la
//tabla a la cual pertenece la clave foránea.
protected function generaLista($datos,$campo,$valorInicial,$modo)
{
$salida="<select name=\"$campo\">\n";
list($tabla,$atributos)=explode(",",$datos);
$atributos=str_replace("/",",",$atributos);
// Elimina las llaves
$atributos=substr($atributos,1,-1);
$comando="select id,$atributos from $tabla order by $atributos";
$resultado=$this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->errorBD($comando);
}
$modoEfectivo=$modo=="readonly" ? "disabled" : "";
$primero=true;
while($fila=$this->bdd->procesaResultado()) {
foreach ($fila as $clave => $valor) {
if ($clave=="id") {
if ($primero) {
$primero=false;
} else {
$salida=substr($salida,0,-1);
$salida.="</option>\n";
}
$seleccionado=$valor==$valorInicial ? " selected " : "";
$salida.='<option value="'.$valor.'" '.$seleccionado.$modoEfectivo.' >';
} else {
$salida.=$valor."-";
}
}
}
$salida.="</select>\n<br><br>";
return $salida;
}
/**
* @todo Hay que hacer lo de las búsquedas automatizadas. Buscar el comment de buscar.
* @todo Hay que hacer lo de las ordenaciones automatizadas. Buscar el comment de ordenable.
*/
private function obtenerCampos()
{
//Si hay un fichero de descripción xml lo utiliza.
$nombre="xml/mantenimiento".$this->tabla.".xml";
if (file_exists($nombre)) {
$def=simplexml_load_file($nombre);
foreach($def->Campos->Col as $columna) {
$this->campos[(string)$columna['Nombre']]=array("Field" => (string)$columna['Titulo'],"Comment" =>(string)$columna['Varios'],
"Type"=> (string) $columna['Tipo'],"Editable" => (string) $columna['Editable'],"Campo"=>(string) $columna['Campo']);
}
$this->comandoConsulta=$def->Consulta;
} else {
//Toma los datos de la tabla.
$datos=$this->bdd->estructura($this->tabla);
for ($i=0;$i<count($datos);$i++) {
$this->campos[$datos[$i]["Field"]][]=$datos[$i];
$this->campos[$datos[$i]["Field"]]=$this->campos[$datos[$i]["Field"]][0];
$this->campos[$datos[$i]["Field"]]["Campo"]=$datos[$i]["Field"];
$this->campos[$datos[$i]["Field"]]["Editable"]="si";
}
$this->comandoConsulta="select * from ".$this->tabla." {buscar} {orden} limit {inferior},{superior}";
}
}
private function cabeceraTabla()
{
$salida='<p align="center"><table border=1 class="tablaDatos"><tbody>';
foreach ($this->campos as $clave => $datos) {
$comen=explode(",",$datos["Comment"]);
$ordenable=false;
foreach ($comen as $co) {
if (strstr($co,"ordenable")) {
$ordenable=true;
break;
}
}
if ($ordenable) {
$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"$this->url&orden=".strtolower($clave)."\"> $clave </a></b></th>\n";
} else {
$salida.='<th><b>'.$clave.'</b></th>'."\n";
}
}
/**
* @package Inventario
* @copyright Copyright (c) 2008, 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/>.
*
*/
//Clase que se encargará de manejar los elementos del modelo de datos.
define('EDICION', 'Edici&oacute;n');
define('BORRADO', '<i>Borrado</i>');
define('ANADIR', 'Inserci&oacute;n');
$salida.="<th><b>Acci&oacute;n</b></th>\n";
return $salida;
}
/**
*
* @param string $accion URL de la acción del POST
* @param string $tipo ANADIR,EDITAR,BORRAR
* @param array $datos Vector con los datos del registro
* @return array lista de campos y formulario de entrada
*/
private function formularioCampos($accion,$tipo,$datos)
{
$modo=$tipo==BORRAR?"readonly":"";
$salida.='<form name="mantenimiento.form" method="post" action="'.$accion.'">'."\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>$tipo</b></legend>\n";
foreach ($this->campos as $clave => $valor) {
if ($valor["Editable"]=="no") {
//Se salta los campos que no deben aparecer
continue;
}
$campo=$valor['Campo'];
$salida.="<label>".ucfirst($clave)."</label> ";
//Se asegura que el id no se pueda modificar.
$modoEfectivo=$clave=='id' ? "readonly" : $modo;
$valorDato=$datos==null?"":$datos[$campo];
if (!isset($this->foraneas[$valor['Campo']])) {
$tipoCampo=$valor['Type'];
//Si es un campo fecha u hora y está insertando pone la fecha actual o la hora actual
if ($tipo==ANADIR) {
if (stripos($tipoCampo,"echa") || stripos($tipoCampo,"ate")) {
$valorDato=strftime("%Y/%m/%d");
}
}
// Calcula el tamaño
if (stripos($tipoCampo,"echa") || stripos($tipoCampo,"ate")) {
$tamano="19";
} else {
list($resto,$tamano)=explode("(",$tipoCampo);
$tamano=substr($tamano,0,-1);
}
//Si no es una clave foránea añade un campo de texto normal
$salida.='<input type="text" name="'.$campo.'" value="'.$valorDato.
'" maxlength="'.$tamano.'" size="'.$tamano.'" '.$modoEfectivo." ><br><br>\n";
} else {
$salida.=$this->generaLista($this->foraneas[$campo],$campo,$valorDato,$modoEfectivo);
}
//Genera una lista con los campos que intervienen en el formulario.
$campos.="$campo&";
}
//genera un campo oculto con la lista de campos a modificar.
$salida.='<input name="listacampos" type="hidden" value="'.$campos."\">\n";
$salida.="</fieldset><p>";
$salida.="<button type=reset>Cancelar</button>&nbsp;&nbsp;<button type=submit>Aceptar</button><br>\n";
return $salida;
}
protected function errorBD($comando,$mensaje="")
{
if (!$mensaje) {
return "<h1>No pudo ejecutar correctamente el comando $comando error=".$this->bdd->mensajeError()." </h1>";
} else {
return "<h1>$mensaje error=".$this->bdd->mensajeError()."</h1>";
}
class Mantenimiento {
private $descripcion;
protected $bdd;
protected $url;
protected $cabecera;
protected $tabla;
protected $cadenaBusqueda;
protected $campos = array();
protected $foraneas = array();
protected $campoBusca = "Descripcion";
protected $comandoConsulta = "";
protected $perfil;
public function __construct($baseDatos, $perfil, $nombre) {
$this->bdd = $baseDatos;
$this->url = "index.php?$nombre&opc=inicial";
$this->cabecera = 'Location: ' . $this->url;
$this->tabla = ucfirst($nombre);
$this->perfil = $perfil;
}
public function ejecuta() {
$opc = $_GET['opc'];
$id = $_GET['id'];
$orden = isset($_GET['orden']) ? $_GET['orden'] : '';
$sentido = isset($_GET['sentido']) ? $_GET['sentido'] : 'asc';
//Sólo tiene sentido para las modificaciones.
//Es la página donde estaba el registro
$pag = isset($_GET['pag']) ? $_GET['pag'] : '0';
$this->cadenaBusqueda = $_GET['buscar'];
$this->obtenerCampos();
$this->obtieneClavesForaneas();
switch ($opc) {
case 'inicial':return $this->consulta($id, $orden, $sentido);
case 'editar':return $this->muestra($id, EDICION, $pag, $orden, $sentido);
case 'eliminar':return $this->muestra($id, BORRADO);
case 'nuevo':return $this->muestra(null, ANADIR);
case 'insertar':return $this->insertar();
case 'modificar':return $this->modificar($id, $pag, $orden, $sentido);
case 'borrar':return $this->borrar($id);
default:return 'La clase Mantenimiento No entiende lo solicitado.';
}
}
protected function obtieneClavesForaneas() {
$salida = null;
foreach ($this->campos as $clave => $valor) {
$trozos = explode(",", $valor["Comment"]);
foreach ($trozos as $trozo) {
if (strstr($trozo, "foreign")) {
$temp = substr($trozo, 8, -1);
list($tabla, $atributos) = explode("->", $temp);
list($clave, $resto) = explode(";", $atributos);
//Quita el paréntesis final
$atributos = substr($atributos, 0, -1);
$salida[$valor['Campo']] = $tabla . "," . $resto;
}
}
}
$this->foraneas = $salida;
}
private function consulta($pagina, $orden, $sentido) {
//Calcula los números de página anterior y siguiente.
$pagina = $pagina + 0;
$pagSigte = $pagina <= 0 ? 1 : $pagina + 1;
$pagAnt = $pagSigte - 2;
$pagFwd = $pagSigte + 3;
$pagRew = $pagAnt - 3 < 0 ? $pagAnt : $pagAnt - 3;
//Trata con la cadena de búsqueda
$this->cadenaBusqueda = isset($_POST['buscar']) ? $_POST['buscar'] : $this->cadenaBusqueda;
if (isset($this->cadenaBusqueda) && strlen($this->cadenaBusqueda)) {
$sufijo = " where $this->campoBusca like '%" . $this->bdd->filtra($this->cadenaBusqueda) . "%'";
$sufijoEnlace = "&buscar=" . $this->cadenaBusqueda;
$comando = str_replace('{buscar}', $sufijo, $this->comandoConsulta);
} else {
$comando = str_replace('{buscar}', '', $this->comandoConsulta);
}
//Trata con el orden de mostrar los datos
if (strlen($orden) > 0) {
$comando = str_replace('{orden}', "order by " . $orden . " " . $sentido, $comando);
$sufijoOrden = "&orden=" . $orden . "&sentido=" . $sentido;
} else {
$comando = str_replace('{orden}', ' ', $comando);
}
//Introduce un botón para hacer búsquedas
$salida = $this->enlaceBusqueda();
//Esta orden de centrado se cierra en el pie de la tabla
$salida.='<center><h4>P&aacute;gina ' . $pagSigte . '</h4>';
$salida.=$this->cabeceraTabla();
//Consulta paginada de todas las tuplas
$comando = str_replace('{inferior}', ($pagAnt + 1) * NUMFILAS, $comando);
$comando = str_replace('{superior}', NUMFILAS, $comando);
//$salida.=$comando;
$tabla = strtolower($this->tabla);
$this->bdd->ejecuta($comando);
if ($this->bdd->numeroTuplas() == 0) {
if ($pagSigte > 1) {
// Si no hay datos en la consulta y no es la primera página,
// carga la página inicial
header('Location: ' . $this->url);
} else {
$salida = "<p align=\"center\"><center><h2>No hay registros</h2></center></p><br>";
}
}
//$salida.=print_r($this->perfil);
while ($fila = $this->bdd->procesaResultado()) {
$salida.='<tr align="center" bottom="middle">';
foreach ($fila as $clave => $valor) {
if ($clave == "id") {
$id = $valor;
}
$salida.="<td>$valor</td>\n";
}
//Añade el icono de editar
if ($this->perfil['Modificacion']) {
$salida.='<td><a href="index.php?' . $tabla . '&opc=editar&id=' . $id . "&pag=" . $pagina . $sufijoOrden .
'"><img title="Editar" src="img/' . ESTILO . '/editar.png" alt="editar"></a>';
}
//Añade el icono de eliminar
if ($this->perfil['Borrado']) {
$salida.='&nbsp;&nbsp;<a href="index.php?' . $tabla . '&opc=eliminar&id=' . $id .
'"><img title="Eliminar" src="img/' . ESTILO . '/eliminar.png" alt="eliminar"></a></td></tr>' . "\n";
}
}
$salida.="</tbody></table></center></p>";
//Añade botones de comandos
$enlace = '<a href="' . $this->url . $sufijoOrden . '&id=';
if ($this->bdd->numeroTuplas()) {
$anterior = $enlace . $pagAnt . $sufijoEnlace . "\"><img title=\"Pag. Anterior\" alt=\"anterior\" src=\"img/" . ESTILO . "/anterior.png\"></a>\n";
$siguiente = $enlace . $pagSigte . $sufijoEnlace . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/siguiente.png\"></a>\n";
$fwd = $enlace . $pagFwd . $sufijoEnlace . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/fwd.png\"></a>\n";
$rew = $enlace . $pagRew . $sufijoEnlace . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/rew.png\"></a>\n";
if (strlen($orden) > 0) {
$az = '<a href="' . $this->url . '&orden=' . $orden . '&sentido=asc"><img alt="asc" title="Orden ascendente" src="img/' . ESTILO . '/ascendente.png"></a>';
$za = '<a href="' . $this->url . '&orden=' . $orden . '&sentido=desc"><img alt="desc" title="Orden descendente" src="img/' . ESTILO . '/descendente.png"></a>';
} else {
$az = $za = '';
}
if ($this->perfil['Informe']) {
$informe = '<a href="index.php?' . $tabla . '&opc=informe" target="_blank"><img src="img/' . ESTILO . '/informe.png" alt="informe" title="Informe pdf"></a>';
} else {
$informe = "";
}
}
if ($this->perfil['Alta']) {
$anadir = '<a href="index.php?' . $tabla . '&opc=nuevo">' .
'<img title="A&ntilde;adir registro" alt="nuevo" src="img/' . ESTILO . '/nuevo.png"></a>';
} else {
$anadir = "";
}
$salida.='<p align="center">' .
"$rew&nbsp&nbsp$anterior&nbsp&nbsp$az&nbsp&nbsp$anadir&nbsp&nbsp$informe&nbsp&nbsp$za&nbsp&nbsp$siguiente&nbsp&nbsp$fwd</p>";
return $salida;
}
private function enlaceBusqueda() {
$salida = '<p align="center">';
$salida.='<center><form name="busqueda" method="POST"><input type="text" name="buscar"';
$salida.='value="' . $this->cadenaBusqueda . '" size="40" /><input type="submit" value="Buscar" name=';
$salida.='"Buscar" /></form></center>';
$salida.='</p>';
return $salida;
}
protected function borrar($id) {
$comando = "delete from " . $this->tabla . " where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
header('Location: ' . $this->url);
return;
}
protected function insertar() {
$comando = "insert into " . $this->tabla . " (";
$lista = explode("&", $_POST['listacampos']);
$primero = true;
//Añade la lista de campos
foreach ($lista as $campo) {
if ($campo == "") {
continue;
}
if ($primero) {
$primero = false;
$coma = " ";
} else {
$coma = ",";
}
$comando.="$coma $campo";
}
$comando.=") values (";
//Añade la lista de valores
$primero = true;
foreach ($lista as $campo) {
if ($campo == "")
continue;
if ($primero) {
$primero = false;
$coma = " ";
} else {
$coma = ",";
}
$comando.="$coma \"$_POST[$campo]\"";
}
$comando.=")";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace, $resto) = explode("&", $this->url);
$enlace.="&opc=inicial";
return "<h1><a href=\"$enlace\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "</a></h1>";
}
protected function modificar($id, $pag, $orden, $sentido) {
//Los datos a utilizar para actualizar la tupla vienen en $_POST.
//La lista de atributos de la tupla viene en el campo oculto listacampos
//print_r($_GET);
//echo "id=$id pag=$pag orden=$orden sentido=$sentido";die();
$comando = "update " . $this->tabla . " set ";
$lista = explode("&", $_POST['listacampos']);
$primero = true;
foreach ($lista as $campo) {
if ($campo == "id" || $campo == "")
continue;
if ($primero) {
$primero = false;
$coma = " ";
}
else
$coma = ",";
if (strlen(trim($_POST[$campo])) == 0)
$comando.="$coma $campo=null";
else
$comando.=$coma . ' ' . $campo . '="' . $_POST[$campo] . '"';
}
$comando.=" where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
list($enlace, $resto) = explode("&", $this->url);
$enlace.="&opc=inicial&orden=" . $orden . "&sentido=" . $sentido . "&id=" . $pag;
header('Location: ' . $enlace);
return;
}
protected function muestra($id, $tipoAccion, $pag = "", $orden = "", $sentido = "") {
if (isset($id)) {
$comando = "select * from " . $this->tabla . " where id='$id'";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->errorBD("", "No se han podido encontrar datos del identificador $id");
}
$fila = $this->bdd->procesaResultado();
} else {
$fila = null;
}
//list($tipo,$valor)=explode($columna["Type"]);
$accion = "index.php?" . strtolower($this->tabla) . "&id=$id&opc=";
switch ($tipoAccion) {
case EDICION:
$accion.="modificar";
$accion.=isset($pag) ? "&pag=$pag" : '';
$accion.=isset($orden) ? "&orden=$orden" : '';
$accion.=isset($sentido) ? "&sentido=$sentido" : '';
break;
case BORRADO:
$accion.="borrar";
break;
case ANADIR:
$accion.="insertar";
break;
}
//Genera un formulario con los datos de la tupla seleccionada.
return $this->formularioCampos($accion, $tipoAccion, $fila);
}
//Función que genera un campo de lista con los valores de descripción de la
//tabla a la cual pertenece la clave foránea.
protected function generaLista($datos, $campo, $valorInicial, $modo) {
$salida = "<select name=\"$campo\">\n";
list($tabla, $atributos) = explode(",", $datos);
$atributos = str_replace("/", ",", $atributos);
// Elimina las llaves
$atributos = substr($atributos, 1, -1);
$comando = "select id,$atributos from $tabla order by $atributos";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->errorBD($comando);
}
$modoEfectivo = $modo == "readonly" ? "disabled" : "";
$primero = true;
while ($fila = $this->bdd->procesaResultado()) {
foreach ($fila as $clave => $valor) {
if ($clave == "id") {
if ($primero) {
$primero = false;
} else {
$salida = substr($salida, 0, -1);
$salida.="</option>\n";
}
$seleccionado = $valor == $valorInicial ? " selected " : "";
$salida.='<option value="' . $valor . '" ' . $seleccionado . $modoEfectivo . ' >';
} else {
$salida.=$valor . "-";
}
}
}
$salida.="</select>\n<br><br>";
return $salida;
}
/**
* @todo Hay que hacer lo de las búsquedas automatizadas. Buscar el comment de buscar.
* @todo Hay que hacer lo de las ordenaciones automatizadas. Buscar el comment de ordenable.
*/
private function obtenerCampos() {
//Si hay un fichero de descripción xml lo utiliza.
$nombre = "xml/mantenimiento" . $this->tabla . ".xml";
if (file_exists($nombre)) {
$def = simplexml_load_file($nombre);
foreach ($def->Campos->Col as $columna) {
$this->campos[(string) $columna['Nombre']] = array("Field" => (string) $columna['Titulo'], "Comment" => (string) $columna['Varios'],
"Type" => (string) $columna['Tipo'], "Editable" => (string) $columna['Editable'], "Campo" => (string) $columna['Campo']);
}
$this->comandoConsulta = $def->Consulta;
} else {
//Toma los datos de la tabla.
$datos = $this->bdd->estructura($this->tabla);
for ($i = 0; $i < count($datos); $i++) {
$this->campos[$datos[$i]["Field"]][] = $datos[$i];
$this->campos[$datos[$i]["Field"]] = $this->campos[$datos[$i]["Field"]][0];
$this->campos[$datos[$i]["Field"]]["Campo"] = $datos[$i]["Field"];
$this->campos[$datos[$i]["Field"]]["Editable"] = "si";
}
$this->comandoConsulta = "select * from " . $this->tabla . " {buscar} {orden} limit {inferior},{superior}";
}
}
private function cabeceraTabla() {
$salida = '<p align="center"><table border=1 class="tablaDatos"><tbody>';
foreach ($this->campos as $clave => $datos) {
$comen = explode(",", $datos["Comment"]);
$ordenable = false;
foreach ($comen as $co) {
if (strstr($co, "ordenable")) {
$ordenable = true;
break;
}
}
if ($ordenable) {
$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"$this->url&orden=" . strtolower($clave) . "\"> $clave </a></b></th>\n";
} else {
$salida.='<th><b>' . $clave . '</b></th>' . "\n";
}
}
$salida.="<th><b>Acci&oacute;n</b></th>\n";
return $salida;
}
/**
*
* @param string $accion URL de la acción del POST
* @param string $tipo ANADIR,EDITAR,BORRAR
* @param array $datos Vector con los datos del registro
* @return array lista de campos y formulario de entrada
*/
private function formularioCampos($accion, $tipo, $datos) {
$modo = $tipo == BORRAR ? "readonly" : "";
$salida.='<form name="mantenimiento.form" method="post" action="' . $accion . '">' . "\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>$tipo</b></legend>\n";
foreach ($this->campos as $clave => $valor) {
if ($valor["Editable"] == "no") {
//Se salta los campos que no deben aparecer
continue;
}
$campo = $valor['Campo'];
$salida.="<label>" . ucfirst($clave) . "</label> ";
//Se asegura que el id no se pueda modificar.
$modoEfectivo = $clave == 'id' ? "readonly" : $modo;
$valorDato = $datos == null ? "" : $datos[$campo];
if (!isset($this->foraneas[$valor['Campo']])) {
$tipoCampo = $valor['Type'];
//Si es un campo fecha u hora y está insertando pone la fecha actual o la hora actual
if ($tipo == ANADIR) {
if (stripos($tipoCampo, "echa") || stripos($tipoCampo, "ate")) {
$valorDato = strftime("%Y/%m/%d");
}
}
// Calcula el tamaño
if (stripos($tipoCampo, "echa") || stripos($tipoCampo, "ate")) {
$tamano = "19";
} else {
list($resto, $tamano) = explode("(", $tipoCampo);
$tamano = substr($tamano, 0, -1);
}
if ($tipoCampo == "Password")
$tipo_campo = "password";
else
$tipo_campo = "text";
//Si no es una clave foránea añade un campo de texto normal
$salida.='<input type="' . $tipo_campo . '" name="' . $campo . '" value="' . $valorDato .
'" maxlength="' . $tamano . '" size="' . $tamano . '" ' . $modoEfectivo . " ><br><br>\n";
} else {
$salida.=$this->generaLista($this->foraneas[$campo], $campo, $valorDato, $modoEfectivo);
}
//Genera una lista con los campos que intervienen en el formulario.
$campos.="$campo&";
}
//genera un campo oculto con la lista de campos a modificar.
$salida.='<input name="listacampos" type="hidden" value="' . $campos . "\">\n";
$salida.="</fieldset><p>";
$salida.="<button type=reset>Cancelar</button>&nbsp;&nbsp;<button type=submit>Aceptar</button><br>\n";
return $salida;
}
protected function errorBD($comando, $mensaje = "") {
if (!$mensaje) {
return "<h1>No pudo ejecutar correctamente el comando $comando error=" . $this->bdd->mensajeError() . " </h1>";
} else {
return "<h1>$mensaje error=" . $this->bdd->mensajeError() . "</h1>";
}
}
}
?>

View File

@@ -29,10 +29,10 @@ class Menu {
// Obtenemos la lista de pares Opción|Enlace
$elementos=explode("\n", $contenido);
foreach($elementos as $elemento) {
list($tipo, $opcion, $enlace)=explode('|', $elemento);
list($tipo, $opcion, $enlace, $destino)=explode('|', $elemento);
// Los guardamos en la matriz de opciones
if ($tipo)
$this->opciones[]=$tipo.",".$opcion.",".$enlace;
$this->opciones[]=$tipo.",".$opcion.",".$enlace.",".$destino;
}
}
public function insertaMenu()
@@ -40,9 +40,9 @@ class Menu {
$salida="";
reset($this->opciones);
foreach($this->opciones as $opcion) {
list($tipo,$opcion,$enlace)=explode(",",$opcion);
list($tipo,$opcion,$enlace,$destino)=explode(",",$opcion);
if ($tipo==2)
$salida.='<a href="'.$enlace.'">'.$opcion.'</a><br />';
$salida.='<a href="'.$enlace.'" target="'.$destino.'">'.$opcion.'</a><br />';
else
$salida.='<label class="key">'.$opcion.'</label><br/>';
}

View File

@@ -1,12 +1,12 @@
1|Maestros|
2|Ubicaciones|index.php?ubicaciones&opc=inicial
2|Art&iacute;culos|index.php?articulos&opc=inicial
2|Elementos|index.php?elementos&opc=inicial&orden=ubicacion&sentido=asc
2|Usuarios|index.php?usuarios&opc=inicial
2|Ubicaciones|index.php?ubicaciones&opc=inicial|_self
2|Art&iacute;culos|index.php?articulos&opc=inicial|_self
2|Elementos|index.php?elementos&opc=inicial&orden=ubicacion&sentido=asc|_self
2|Usuarios|index.php?usuarios&opc=inicial|_self
1|Inventario|
2|Ubicaci&oacute;n|index.php?informeInventario&opc=Ubicacion
2|Art&iacute;culo|index.php?informeInventario&opc=Articulo
2|Total|index.php?informeInventario&opc=Total
2|Descuadres|index.php?descuadres
2|Ubicaci&oacute;n|index.php?informeInventario&opc=Ubicacion|_self
2|Art&iacute;culo|index.php?informeInventario&opc=Articulo|_self
2|Total|index.php?informeInventario&opc=Total|_blank
2|Descuadres|index.php?descuadres|_blank
1|Varios|
2|Configuraci&oacute;n|index.php?configuracion
2|Configuraci&oacute;n|index.php?configuracion|_self

View File

@@ -1,11 +1,8 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" >
<title>Gesti&oacute;n de Inventario</title>
<link rel="stylesheet" href="css/estilo.css" type="text/css">
<link rel="shortcut icon" href="img/tux.ico">
</head>
@@ -51,17 +48,6 @@
{contenido}<br>
</div>
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://alpera.arpicm.org/piwik/" : "http://alpera.arpicm.org/piwik/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://alpera.arpicm.org/piwik/piwik.php?idsite=1" style="border:0" alt="" /></p></noscript>
<!-- End Piwik Tracking Code -->
</body>
</html>

168
sql/inv2.sql Normal file

File diff suppressed because one or more lines are too long

117
sql/setup.sql Normal file
View File

@@ -0,0 +1,117 @@
-- Creación de tablas
--
-- Host: localhost Database: Inventario2
-- ------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `Articulos`
--
DROP TABLE IF EXISTS `Articulos`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `Articulos` (
`id` smallint(6) NOT NULL auto_increment,
`descripcion` varchar(60) NOT NULL COMMENT 'ordenable',
`marca` varchar(20) default NULL COMMENT 'ordenable',
`modelo` varchar(20) default NULL COMMENT 'ordenable',
`cantidad` int(11) default NULL COMMENT 'ordenable',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=785 DEFAULT CHARSET=latin1;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Elementos`
--
DROP TABLE IF EXISTS `Elementos`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `Elementos` (
`id` int(10) unsigned NOT NULL auto_increment,
`id_Articulo` smallint(6) NOT NULL COMMENT 'foreign(Articulos;id),ordenable',
`id_Ubicacion` smallint(5) unsigned NOT NULL COMMENT 'foreign(Ubicaciones;id),ordenable',
`numserie` varchar(30) default NULL COMMENT 'ordenable',
`cantidad` int(10) unsigned default NULL COMMENT 'ordenable',
`fechaCompra` datetime NOT NULL COMMENT 'ordenable',
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `id_Articulo` (`id_Articulo`),
KEY `id_Ubicacion` (`id_Ubicacion`),
CONSTRAINT `Elementos_ibfk_1` FOREIGN KEY (`id_Articulo`) REFERENCES `Articulos` (`id`) ON DELETE CASCADE,
CONSTRAINT `Elementos_ibfk_2` FOREIGN KEY (`id_Ubicacion`) REFERENCES `Ubicaciones` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1884 DEFAULT CHARSET=latin1;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Ubicaciones`
--
DROP TABLE IF EXISTS `Ubicaciones`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `Ubicaciones` (
`id` smallint(5) unsigned NOT NULL auto_increment,
`Descripcion` varchar(30) NOT NULL COMMENT 'ordenable',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=184 DEFAULT CHARSET=latin1;
SET character_set_client = @saved_cs_client;
--
-- Table structure for table `Usuarios`
--
DROP TABLE IF EXISTS `Usuarios`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `Usuarios` (
`id` int(10) unsigned NOT NULL auto_increment,
`nombre` varchar(16) NOT NULL default '',
`clave` varchar(32) NOT NULL default '',
`idSesion` varchar(20) NOT NULL default '',
`alta` tinyint(1) NOT NULL default '0',
`modificacion` tinyint(1) NOT NULL default '0',
`borrado` tinyint(1) NOT NULL default '0',
`consulta` tinyint(1) NOT NULL default '1',
`informe` tinyint(1) NOT NULL default '1',
`usuarios` tinyint(1) NOT NULL default '0',
`config` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
SET character_set_client = @saved_cs_client;
--
-- Usuarios iniciales
--
LOCK TABLES `Usuarios` WRITE;
/*!40000 ALTER TABLE `Usuarios` DISABLE KEYS */;
INSERT INTO `Usuarios` VALUES (1,'admin','galeote','s3LUSqxg{s',1,1,1,1,1,1,1),(2,'demo','demo','NogP_U0Byi',0,0,0,1,1,0,0);
/*!40000 ALTER TABLE `Usuarios` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

View File

@@ -1,12 +1,12 @@
<?xml version="1.0"?>
<Informe>
<Titulo Texto="Estantería de madera con trasera" />
<Titulo Texto="Agitador magnético" />
<Datos>
<Consulta>
select A.id as id,U.Descripcion as ubicacion,E.fechaCompra as fechaCompra,
E.numSerie as numserie,E.Cantidad as cantidad
from Elementos E, Articulos A, Ubicaciones U where A.id=E.id_Articulo and U.id=E.id_Ubicacion
and A.id='593' order by U.Descripcion,numserie;
and A.id='700' order by U.Descripcion,numserie;
</Consulta>
</Datos>
<Pagina Orientacion="P" Formato="A4">

Binary file not shown.

View File

@@ -1,20 +1,21 @@
<?xml version="1.0"?>
<Mantenimiento>
<Titulo>Mantenimiento de Elementos</Titulo>
<Titulo>Mantenimiento de Usuarios</Titulo>
<Consulta>
SELECT E.id as id,U.Descripcion as ubicacion,A.Descripcion as articulo,A.Marca as marca,A.Modelo as modelo,E.numserie as numserie,
DATE_FORMAT(E.fechacompra, '%d/%m/%Y') as fechaCompra,E.cantidad as cantidad
FROM Elementos E inner join Articulos A on E.id_articulo=A.id inner join
Ubicaciones U on E.id_ubicacion=U.id {buscar} {orden} limit {inferior},{superior};
SELECT id, nombre, clave, idSesion, alta, modificacion, borrado, consulta, informe, usuarios, config
FROM Usuarios {buscar} {orden} limit {inferior}, {superior};
</Consulta>
<Campos>
<Col Campo="id" Nombre="id" Ancho="5" Ajuste="D" Titulo="id" Tipo="smallint(6)"/>
<Col Campo="id_Ubicacion" Nombre="ubicacion" Ancho="40" Ajuste="L" Titulo="Ubicación" Varios="ordenable,foreign(Ubicaciones->id;{Descripcion})" Editable="si"/>
<Col Campo="id_Articulo" Nombre="articulo" Ancho="40" Ajuste="L" Titulo="Artículo" Varios="ordenable,foreign(Articulos->id;{Descripcion/Marca/Modelo})" Editable="si"/>
<Col Nombre="marca" Ancho="40" Ajuste="L" Titulo="Marca" Varios="ordenable" Editable="no"/>
<Col Nombre="modelo" Ancho="40" Ajuste="L" Titulo="Modelo" Varios="ordenable" Editable="no"/>
<Col Campo="numserie" Nombre="numserie" Ancho="30" Ajuste="L" Titulo="Nº Serie" Varios="ordenable" Editable="si"/>
<Col Campo="fechaCompra" Nombre="fechaCompra" Ancho="25" Ajuste="L" Titulo="Compra" Varios="ordenable" Tipo="fecha" Editable="si"/>
<Col Campo="cantidad" Nombre="cantidad" Ancho="15" Ajuste="D" Titulo="Cant." Tipo="Int(11)" Editable="si"/>
<Col Campo="id" Nombre="id" Ancho="5" Ajuste="D" Titulo="id" Tipo="int(6)"/>
<Col Campo="nombre" Nombre="nombre" Ancho="16" Ajuste="L" Titulo="Nombre" Varios="ordenable" Editable="si"/>
<Col Campo="clave" Nombre="clave" Ancho="40" Ajuste="L" Titulo="Clave" Tipo="Password" Editable="si"/>
<Col Nombre="idSesion" Ancho="40" Ajuste="L" Titulo="id Sesión" Editable="si"/>
<Col Campo="alta" Nombre="Alta" Ancho="1" Ajuste="R" Titulo="Altas" Editable="si"/>
<Col Campo="modificacion" Nombre="modificacion" Ancho="1" Ajuste="R" Titulo="Modificaciones" Editable="si"/>
<Col Campo="borrado" Nombre="borrado" Ancho="1" Ajuste="R" Titulo="Borrados" Editable="si"/>
<Col Campo="consulta" Nombre="consulta" Ancho="1" Ajuste="R" Titulo="Consultas" Editable="si"/>
<Col Campo="informe" Nombre="informe" Ancho="1" Ajuste="R" Titulo="Informes" Editable="si"/>
<Col Campo="usuarios" Nombre="usuarios" Ancho="1" Ajuste="R" Titulo="Usuarios" Editable="si"/>
<Col Campo="config" Nombre="config" Ancho="1" Ajuste="R" Titulo="Configuración" Editable="si"/>
</Campos>
</Mantenimiento>