27 Commits

Author SHA1 Message Date
727f5787b0 Apply fixes from StyleCI 2018-07-10 17:04:51 +00:00
08122054ce README.md edited online with Bitbucket 2017-03-28 07:22:53 +00:00
c033d788a0 Añadida línea en blanco para probar el editor del iPhone 2016-11-07 19:58:21 +01:00
335674a0bc Merge branch 'release/1.17'
* release/1.17:
  Eliminados los mensajes de aviso de php en todos los archivos php, actualizada la versión y el changelog
  Modificado el README para eliminar los saltos de línea introducidos por el editor online
  Modificado el README para eliminar los saltos de línea introducidos por el editor online
  Modificado el README para eliminar los saltos de línea introducidos por el editor online
  Modificados los programas para eliminar todos los "warnings" de php
2014-07-29 21:41:51 +02:00
2488b7943d Cambiados los saltos de línea en README.md 2014-07-29 21:41:24 +02:00
37f7e1a6cf Eliminados los mensajes de aviso de php en todos los archivos php, actualizada la versión y el changelog 2014-07-29 21:29:32 +02:00
c42fae0514 Merge branch 'feature/warnings' into develop
* feature/warnings:
  Modificado el README para eliminar los saltos de línea introducidos por el editor online
  Modificado el README para eliminar los saltos de línea introducidos por el editor online
  Modificados los programas para eliminar todos los "warnings" de php

Conflicts:
	README.md
2014-07-29 21:23:52 +02:00
0e38e97ff5 Modificado el README para eliminar los saltos de línea introducidos por el editor online 2014-07-29 21:21:27 +02:00
9105f92c26 Modificado el README para eliminar los saltos de línea introducidos por el editor online 2014-07-29 21:19:28 +02:00
1b64dba9b2 Modificado el README para eliminar los saltos de línea introducidos por el editor online 2014-07-29 21:14:54 +02:00
52ddeee4ba Modificados los programas para eliminar todos los "warnings" de php 2014-07-29 21:12:37 +02:00
453045eee2 Merge branch 'release/1.16' 2014-07-29 17:12:26 +02:00
c6bc31a275 Merge branch 'release/1.16' into develop 2014-07-29 17:12:26 +02:00
rmontanana
f5577a4119 Fix #41. Corrige las llamadas que se hacían a instalar.php en lugar de a Instalar.php desde Inventario.php y desde Instalar.php 2014-07-28 15:54:29 +02:00
rmontanana
5676f75b97 Actualizado el README para incluir las estadísticas de ohloh 2014-07-28 15:44:17 +02:00
da1fccf1fd README.md edited online with Bitbucket 2014-07-15 11:38:59 +00:00
dcc0662dfb README.md edited online with Bitbucket 2014-07-15 11:38:05 +00:00
f47e1e5cd1 README.md edited online with Bitbucket 2014-07-15 09:37:12 +00:00
5484495d5a README.md edited online with Bitbucket 2014-07-15 09:36:51 +00:00
c0b0878a74 Merge branch 'release/1.15' into develop
* release/1.15:
  Actualizado el número de versión a 1.15
2014-06-29 21:22:58 +02:00
7272e2b85a Merge branch 'release/1.15'
* release/1.15:
  Actualizado el número de versión a 1.15
  Corregido codificación/decodificación de la cadena de búsqueda en la URL
  Fix #40 Crear la opción de clonar registro en Mantenimiento. -Crear iconos de clonado en todos los estilos. -Corregido determinaAccion en Imagen para aceptar el clonado
  Corregido que aparezca el código de artículo en las etiquetas qr del inventario de Artículos Añadida la creación del directorio de imágenes en las instrucciones de instalación del README
2014-06-29 21:22:57 +02:00
9a8ba799c4 Actualizado el número de versión a 1.15 2014-06-29 21:22:20 +02:00
2452d2a9e6 Merge branch 'develop' of bitbucket.org:rmontanana/inventario2 into develop
# By rmontanana
# Via rmontanana
* 'develop' of bitbucket.org:rmontanana/inventario2:
  Corregido codificación/decodificación de la cadena de búsqueda en la URL
  Fix #40 Crear la opción de clonar registro en Mantenimiento. -Crear iconos de clonado en todos los estilos. -Corregido determinaAccion en Imagen para aceptar el clonado
2014-06-29 21:03:00 +02:00
rmontanana
b48b206950 Corregido codificación/decodificación de la cadena de búsqueda en la URL 2014-06-29 21:01:38 +02:00
rmontanana
a72ef244cd Fix #40 Crear la opción de clonar registro en Mantenimiento.
-Crear iconos de clonado en todos los estilos.
-Corregido determinaAccion en Imagen para aceptar el clonado
2014-06-29 09:40:36 +02:00
cc2129e7d9 Corregido que aparezca el código de artículo en las etiquetas qr del inventario de Artículos
Añadida la creación del directorio de imágenes en las instrucciones de instalación del README
2014-06-08 18:25:13 +02:00
14e5767eb1 Merge branch 'release/1.14.1' into develop
* release/1.14.1:
  Actualizado el CHANGELOG
2014-06-02 19:44:52 +02:00
31 changed files with 4911 additions and 4556 deletions

View File

@@ -1,6 +1,5 @@
<?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.
@@ -16,7 +15,6 @@
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
//Clase encargada de procesar las peticiones ajax
require_once 'inc/configuracion.inc';
@@ -25,64 +23,71 @@ require_once 'Sql.php';
$ajax = new Ajax();
echo $ajax->procesa();
class Ajax {
class Ajax
{
private $sql;
private $tabla;
public function __construct()
{
$this->sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($this->sql->error()) {
return $this->respuesta($this->mensaje(false, 'Error conectando con la Base de Datos'));
};
}
$this->tabla = $_GET['tabla'];
}
private function respuesta($mensaje)
{
header('Content-Type: application/json', true, 200);
return $mensaje;
}
public function procesa()
{
$opc = $_GET['opc'];
switch ($opc) {
case "get": return $this->obtiene();
case "put": return $this->actualiza();
case 'get': return $this->obtiene();
case 'put': return $this->actualiza();
}
}
private function mensaje($exito, $texto)
{
return json_encode(array("success" => $exito, "msj" => $texto));
return json_encode(['success' => $exito, 'msj' => $texto]);
}
private function actualiza()
{
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$comando = "update " . mysql_escape_string($this->tabla) . " set " . mysql_escape_string($_POST['name']) . " = '" . mysql_escape_string($_POST['value']) . "' where id = '" . mysql_escape_string($_POST['pk']). "';";
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$comando = 'update '.mysql_escape_string($this->tabla).' set '.mysql_escape_string($_POST['name'])." = '".mysql_escape_string($_POST['value'])."' where id = '".mysql_escape_string($_POST['pk'])."';";
$this->sql->ejecuta($comando);
$exito = !$this->sql->error();
$mensaje = $this->sql->mensajeError();
$resp = $this->mensaje($exito, $mensaje);
$resp = $this->mensaje($exito, $mensaje);
return $this->respuesta($resp);
}
}
private function obtiene()
{
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$comando = "select id, descripcion from " . $this->tabla . " order by descripcion asc;";
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$comando = 'select id, descripcion from '.$this->tabla.' order by descripcion asc;';
$this->sql->ejecuta($comando);
$exito = !$this->sql->error();
$mensaje = $this->sql->mensajeError();
if (!$exito) {
return $this->respuesta($this->mensaje($exito, $mensaje));
}
$filas = array();
while($r = $this->sql->procesaResultado()) {
$filas[] = array($r['id'] => $r['descripcion']);
$filas = [];
while ($r = $this->sql->procesaResultado()) {
$filas[] = [$r['id'] => $r['descripcion']];
}
$resp = json_encode($filas);
return $this->respuesta($resp);
}
}
}
?>
}

View File

@@ -1,6 +1,5 @@
<?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.
@@ -8,22 +7,21 @@
* 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>' .
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" />' .
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><button type="submit" name="iniciar" class="btn btn-primary">Iniciar <span class="glyphicon glyphicon-log-in"></span></button></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="bg-danger">Usuario y clave incorrectos!</label><br><br>');
@@ -40,7 +38,7 @@ define('CREDITOS_CABECERA', '<div class="modal fade" tabindex="-1" id="creditos"
<h1>Inventario2</h1>
<p> Aplicación para controlar el inventario de un centro educativo.</p>
<p>En la aplicación se hace uso de los siguientes módulos y/o bibliotecas</p>');
define('CREDITOS_PIE', ' <p><h5>Copyright &copy; 2008-2014 Ricardo Montañana Gómez</h5>
<h5><small>Esta aplicación se distribuye con licencia <a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0.html">GPLv3 </a></small></h5></p>
</div>
@@ -50,18 +48,17 @@ define('CREDITOS_PIE', ' <p><h5>Copyright &copy; 2008-2014 Ricard
</div>');
// Esta clase aportará el contenido a la plantilla
class AportaContenido {
class AportaContenido
{
/**
*
* @var boolean Aporta información sobre si el usuario está registrado o no.
* @var bool 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.
@@ -79,7 +76,7 @@ class AportaContenido {
private $opcionActual;
/**
* @var boolean Usuario y clave incorrectos?
* @var bool Usuario y clave incorrectos?
*/
private $usuario_inc = false;
@@ -89,19 +86,20 @@ class AportaContenido {
private $perfil;
/**
*
* @var array Datos pasados en la URL
*/
private $datosURL = array();
private $datosURL = [];
// El constructor necesita saber cuál es la opción actual
/**
* Constructor de la clase.
* @param BaseDatos $baseDatos Manejador de la base de datos
* @param boolean $registrado usuario registrado si/no
* @param String $usuario Nombre del usuario
* @param array $perfil Permisos de acceso del usuario
* @param String $opcion Opción elegida por el usuario
* Constructor de la clase.
*
* @param BaseDatos $baseDatos Manejador de la base de datos
* @param bool $registrado usuario registrado si/no
* @param string $usuario Nombre del usuario
* @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)
{
@@ -112,52 +110,56 @@ class AportaContenido {
$this->perfil = $perfil;
$this->opcionActual = $opcion;
}
/**
* Devuelve una tabla HTML con el contenido de las bibliotecas/módulos utilizadas en la aplicación
* Si el perfil del usuario es de Configuración devuelve también las versiones de las bibliotecas
* @return string
* Si el perfil del usuario es de Configuración devuelve también las versiones de las bibliotecas.
*
* @return string
*/
public function creaTablaAcercaDe()
{
$poner = $this->perfil['Config'];
$tabla = '<table class="table table-condensed">';
$tabla .='<thead><tr><th>Biblioteca/Módulo</th>'.($poner?'<th>Versión</th>':'').'<th>Licencia</th></tr></thead>';
$tabla .='<tbody>';
$tabla .='<tr><td><a href="http://jquery.com/" target="_blank">jquery</a></td>'.($poner?'<td>2.1.0</td>':'').'<td><a target="_blank" href="https://jquery.org/license/">MIT</a></td>';
$tabla .='<tr><td><a href="http://getbootstrap.com/" target="_blank">Twitter Bootstrap</a></td>'.($poner?'<td>3.1.1</td>':'').'<td><a target="_blank" href="https://github.com/twbs/bootstrap/blob/master/LICENSE">MIT</a></td>';
$tabla .='<tr><td><a href="http://www.fpdf.org/" target="_blank">FPDF</a></td>'.($poner?'<td>1.7</td>':'').'<td>Libre</td>';
$tabla .='<tr><td><a href="http://phpqrcode.sourceforge.net/" target="_blank">PHP QR Code Enconder</a></td>'.($poner?'<td>1.1.4</td>':'').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .='<tr><td><a href="http://stefangabos.ro/php-libraries/zebra-image/" target="_blank">Zebra_Image</a></td>'.($poner?'<td>2.2.3</td>':'').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .='<tr><td><a href="http://jasny.github.io/bootstrap/" target="_blank">Jasny Bootstrap</a></td>'.($poner?'<td>3.1.0</td>':'').'<td><a target="_blank" href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a></td>';
$tabla .='<tr><td><a href="http://1000hz.github.io/bootstrap-validator/" target="_blank">Bootstrap Validator</a></td>'.($poner?'<td>0.2.1</td>':'').'<td><a target="_blank" href="https://github.com/1000hz/bootstrap-validator/blob/master/LICENSE">MIT</a></td>';
$tabla .='<tr><td><a href="https://github.com/tkrotoff/jquery-simplecolorpicker" target="_blank">jquery-simplecolorpicker</a></td>'.($poner?'<td>0.3.0</td>':'').'<td><a target="_blank" href="https://github.com/tkrotoff/jquery-simplecolorpicker/blob/master/LICENSE.txt">MIT</a></td>';
$tabla .='<tr><td><a href="http://eonasdan.github.io/bootstrap-datetimepicker/" target="_blank">Bootstrap datetimepicker</a></td>'.($poner?'<td>2.1.32</td>':'').'<td><a target="_blank" href="https://github.com/Eonasdan/bootstrap-datetimepicker/blob/master/src/js/bootstrap-datetimepicker.js">MIT</a></td>';
$tabla .='<tr><td><a href="http://silviomoreto.github.io/bootstrap-select/" target="_blank">Bootstrap-select</a></td>'.($poner?'<td>1.5.4</td>':'').'<td><a target="_blank" href="https://github.com/silviomoreto/bootstrap-select">MIT</a></td>';
$tabla .='<tr><td><a href="https://github.com/vitalets/x-editable" target="_blank">X-editable</a></td>'.($poner?'<td>1.5.1</td>':'').'<td><a target="_blank" href="https://github.com/vitalets/x-editable/blob/master/LICENSE-MIT">MIT</a></td>';
$tabla .='<tr><td><a href="http://momentjs.com/" target="_blank">Moment.js</a></td>'.($poner?'<td>2.5.1</td>':'').'<td><a target="_blank" href="https://github.com/moment/moment/blob/develop/LICENSE">MIT</a></td>';
$tabla .='</tbody>';
$tabla .='</table>';
$tabla .= '<thead><tr><th>Biblioteca/Módulo</th>'.($poner ? '<th>Versión</th>' : '').'<th>Licencia</th></tr></thead>';
$tabla .= '<tbody>';
$tabla .= '<tr><td><a href="http://jquery.com/" target="_blank">jquery</a></td>'.($poner ? '<td>2.1.0</td>' : '').'<td><a target="_blank" href="https://jquery.org/license/">MIT</a></td>';
$tabla .= '<tr><td><a href="http://getbootstrap.com/" target="_blank">Twitter Bootstrap</a></td>'.($poner ? '<td>3.1.1</td>' : '').'<td><a target="_blank" href="https://github.com/twbs/bootstrap/blob/master/LICENSE">MIT</a></td>';
$tabla .= '<tr><td><a href="http://www.fpdf.org/" target="_blank">FPDF</a></td>'.($poner ? '<td>1.7</td>' : '').'<td>Libre</td>';
$tabla .= '<tr><td><a href="http://phpqrcode.sourceforge.net/" target="_blank">PHP QR Code Enconder</a></td>'.($poner ? '<td>1.1.4</td>' : '').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .= '<tr><td><a href="http://stefangabos.ro/php-libraries/zebra-image/" target="_blank">Zebra_Image</a></td>'.($poner ? '<td>2.2.3</td>' : '').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .= '<tr><td><a href="http://jasny.github.io/bootstrap/" target="_blank">Jasny Bootstrap</a></td>'.($poner ? '<td>3.1.0</td>' : '').'<td><a target="_blank" href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a></td>';
$tabla .= '<tr><td><a href="http://1000hz.github.io/bootstrap-validator/" target="_blank">Bootstrap Validator</a></td>'.($poner ? '<td>0.2.1</td>' : '').'<td><a target="_blank" href="https://github.com/1000hz/bootstrap-validator/blob/master/LICENSE">MIT</a></td>';
$tabla .= '<tr><td><a href="https://github.com/tkrotoff/jquery-simplecolorpicker" target="_blank">jquery-simplecolorpicker</a></td>'.($poner ? '<td>0.3.0</td>' : '').'<td><a target="_blank" href="https://github.com/tkrotoff/jquery-simplecolorpicker/blob/master/LICENSE.txt">MIT</a></td>';
$tabla .= '<tr><td><a href="http://eonasdan.github.io/bootstrap-datetimepicker/" target="_blank">Bootstrap datetimepicker</a></td>'.($poner ? '<td>2.1.32</td>' : '').'<td><a target="_blank" href="https://github.com/Eonasdan/bootstrap-datetimepicker/blob/master/src/js/bootstrap-datetimepicker.js">MIT</a></td>';
$tabla .= '<tr><td><a href="http://silviomoreto.github.io/bootstrap-select/" target="_blank">Bootstrap-select</a></td>'.($poner ? '<td>1.5.4</td>' : '').'<td><a target="_blank" href="https://github.com/silviomoreto/bootstrap-select">MIT</a></td>';
$tabla .= '<tr><td><a href="https://github.com/vitalets/x-editable" target="_blank">X-editable</a></td>'.($poner ? '<td>1.5.1</td>' : '').'<td><a target="_blank" href="https://github.com/vitalets/x-editable/blob/master/LICENSE-MIT">MIT</a></td>';
$tabla .= '<tr><td><a href="http://momentjs.com/" target="_blank">Moment.js</a></td>'.($poner ? '<td>2.5.1</td>' : '').'<td><a target="_blank" href="https://github.com/moment/moment/blob/develop/LICENSE">MIT</a></td>';
$tabla .= '</tbody>';
$tabla .= '</table>';
return $tabla;
}
/**
* Devuelve la fecha actual
* 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
* @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";
if ($formato == '') {
$formato = '%d-%b-%y';
}
setlocale(LC_TIME, $idioma);
return strftime($formato);
}
/**
*
* @return string Mensaje el usuario debe registrarse.
*/
private function mensajeRegistro()
@@ -167,74 +169,87 @@ class AportaContenido {
// Procesaremos todas las invocaciones a métodos en
// la función __call()
/**
* Procesa las peticiones de contenido de la plantilla.
* @param string $metodo Método a ejecutar
*
* @param string $metodo Método a ejecutar
* @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
case 'usuario':
if ($this->registrado)
if ($this->registrado) {
return "Usuario=$this->usuario";
else
} else {
return '';
}
case 'fecha':
$script = '<script type="text/javascript">
$(function () {
$(' . "'#fechaCabecera'" . ").datetimepicker({
$('."'#fechaCabecera'".").datetimepicker({
pick12HourFormat: false,
language: 'es',
pickTime: false
});
});
</script>";
$campo = '<input type="hidden" name="fechaCabecera" id="fechaCabecera" value="' . $this->fechaActual("%d/%m/%Y") . '">';
$etiqueta = '<label for="fechaCabecera" onClick="$(' . "'#fechaCabecera'" . ").data('DateTimePicker').show();" . '">' . $this->fechaActual() . '</label>';
return $etiqueta . $campo . $script;
case 'aplicacion':
$nombre = explode(" ", PROGRAMA);
$campo = '<input type="hidden" name="fechaCabecera" id="fechaCabecera" value="'.$this->fechaActual('%d/%m/%Y').'">';
$etiqueta = '<label for="fechaCabecera" onClick="$('."'#fechaCabecera'".").data('DateTimePicker').show();".'">'.$this->fechaActual().'</label>';
return $etiqueta.$campo.$script;
case 'aplicacion':
$nombre = explode(' ', PROGRAMA);
$nombre = $nombre[2];
return $nombre . " v" . VERSION;
return $nombre.' v'.VERSION;
case 'menu': // el menú
if ($this->registrado) {
return $this->miMenu->insertaMenu();
} else {
$salida = FORMULARIO_ACCESO;
if ($this->usuario_inc) {
$salida.=USUARIO_INCORRECTO;
$salida .= USUARIO_INCORRECTO;
}
//$salida.=MENSAJE_DEMO;
return $salida;
}
case 'opcion':
list($opcion, $parametro) = explode("&", $this->opcionActual);
if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode('&', $this->opcionActual);
} else {
$opcion = $this->opcionActual;
$parametro = '';
}
switch ($opcion) {
case 'bienvenido':
return "Men&uacute; Principal";
return 'Men&uacute; Principal';
case 'principal':
return "Pantalla Inicial";
case 'articulos': $opcion = "art&iacute;culos";
return 'Pantalla Inicial';
case 'articulos': $opcion = 'art&iacute;culos';
case 'elementos':
case 'ubicaciones':
case 'usuarios':
case 'test':
return "Mantenimiento " . ucfirst($opcion);
return 'Mantenimiento '.ucfirst($opcion);
case 'configuracion':
return 'Configuraci&oacute;n y Preferencias';
case 'informeInventario':return "Informe de Inventario";
case 'informeInventario':return 'Informe de Inventario';
case 'descuadres':return 'Informe de descuadres';
case 'importacion': return 'Importaci&oacute;n de datos';
case 'copiaseg': return 'Copia de seguridad de datos';
}
return '';
case 'control':
if ($this->registrado)
if ($this->registrado) {
return '<a href="index.php?cerrarSesion">Cerrar Sesi&oacute;n <span class="glyphicon glyphicon-log-out"></span></a>';
else
} else {
return '';
}
// Para incluir el contenido central de la página
case 'contenido':
// tendremos en cuenta cuál es la opción actual
@@ -244,48 +259,56 @@ class AportaContenido {
// if (!$this->registrado) {
// return $this->mensajeRegistro();
// }
list($opcion, $parametro) = explode("&", $this->opcionActual);
if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode('&', $this->opcionActual);
} else {
$opcion = $this->opcionActual;
$parametro = '';
}
switch ($opcion) {
case 'bienvenido':
$mensaje = '<div class="alert alert-success">';
$mensaje .= 'Bienvenid@ ' . $this->usuario . '</div>';
$mensaje .= 'Bienvenid@ '.$this->usuario.'</div>';
case 'principal': // contenido inicial
$mensaje = '';
$creditos = "$('#creditos').modal({keyboard: false});";
$centro = '<div class="well well-sm">' . CENTRO . '</div>';
$centro = '<div class="well well-sm">'.CENTRO.'</div>';
$tabla = $this->creaTablaAcercaDe();
$rama_texto = trim(substr(file_get_contents('.git/HEAD'), 16));
$rama = ($rama_texto != 'master' ? '<br><button class="btn btn-warning btn-xs" type="button"onClick="' . $creditos . '"><span class="glyphicon glyphicon-cog"></span> '.$rama_texto.'</button></center>':'');
return $mensaje . '<br><br><center><img src="img/qrlogo.png" alt="' . PROGRAMA . '" onClick="' . $creditos . '" >' .
'<br><br><label onClick="' . $creditos . '">' . $centro . '</label>' . $rama . '</center>' . CREDITOS_CABECERA . $tabla . CREDITOS_PIE;
$rama = ($rama_texto != 'master' ? '<br><button class="btn btn-warning btn-xs" type="button"onClick="'.$creditos.'"><span class="glyphicon glyphicon-cog"></span> '.$rama_texto.'</button></center>' : '');
return $mensaje.'<br><br><center><img src="img/qrlogo.png" alt="'.PROGRAMA.'" onClick="'.$creditos.'" >'.
'<br><br><label onClick="'.$creditos.'">'.$centro.'</label>'.$rama.'</center>'.CREDITOS_CABECERA.$tabla.CREDITOS_PIE;
case 'articulos':
case 'ubicaciones':
case 'test':
case 'elementos':
$this->cargaDatosURL();
if ($this->datosURL['opc'] == "informe") {
if (!$this->pefil['Informe']) {
if ($this->datosURL['opc'] == 'informe') {
if ($this->perfil['Informe']) {
$this->procesaURL();
$fichero = 'xml/informe' . ucfirst($opcion) . '.xml';
$salida = TMP.'/informe' . ucfirst($opcion) . '.xml';
$fichero = 'xml/informe'.ucfirst($opcion).'.xml';
$salida = TMP.'/informe'.ucfirst($opcion).'.xml';
//Establece los posibles parámetros del listado.
$orden = $this->datosURL['orden'];
$sentido = $this->datosURL['sentido'] == "asc" ? ' ' : ' desc ';
$sentido = $this->datosURL['sentido'] == 'asc' ? ' ' : ' desc ';
$filtro = isset($this->datosURL['buscar']) ? $this->bdd->filtra($this->datosURL['buscar']) : '';
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$plantilla = str_replace("{filtro}", $filtro, $plantilla);
$plantilla = str_replace("{orden}", $orden . $sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla = str_replace('{filtro}', $filtro, $plantilla);
$plantilla = str_replace('{orden}', $orden.$sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
$informe = new InformePDF($this->bdd, $salida, $this->registrado);
$informe->crea($salida);
$informe->cierraPDF();
return $this->devuelveInforme($informe);
} else {
return $this->mensajePermisos("Informes");
return $this->mensajePermisos('Informes');
}
}
if ($this->perfil['Consulta']) {
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta();
} else {
return $this->mensajePermisos(ucfirst($opcion));
@@ -293,28 +316,30 @@ class AportaContenido {
case 'usuarios':
if ($this->perfil['Usuarios']) {
$this->cargaDatosURL();
if ($this->datosURL['opc'] == "informe") {
if ($this->datosURL['opc'] == 'informe') {
if (!$this->pefil['Informe']) {
$this->procesaURL();
$fichero = 'xml/informe' . ucfirst($opcion) . '.xml';
$salida = TMP.'/informe' . ucfirst($opcion) . '.xml';
$fichero = 'xml/informe'.ucfirst($opcion).'.xml';
$salida = TMP.'/informe'.ucfirst($opcion).'.xml';
//Establece los posibles parámetros del listado.
$orden = $this->datosURL['orden'];
$sentido = $this->datosURL['sentido'] == "asc" ? ' ' : ' desc ';
$sentido = $this->datosURL['sentido'] == 'asc' ? ' ' : ' desc ';
$filtro = isset($this->datosURL['buscar']) ? $this->bdd->filtra($this->datosURL['buscar']) : '';
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$plantilla = str_replace("{filtro}", $filtro, $plantilla);
$plantilla = str_replace("{orden}", $orden . $sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla = str_replace('{filtro}', $filtro, $plantilla);
$plantilla = str_replace('{orden}', $orden.$sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
$informe = new InformePDF($this->bdd, $salida, $this->registrado);
$informe->crea($salida);
$informe->cierraPDF();
return $this->devuelveInforme($informe);
} else {
return $this->mensajePermisos("Informes");
return $this->mensajePermisos('Informes');
}
}
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta();
} else {
return $this->mensajePermisos('Usuarios');
@@ -322,6 +347,7 @@ class AportaContenido {
case 'configuracion':
if ($this->perfil['Config']) {
$conf = new Configuracion();
return $conf->ejecuta();
} else {
return $this->mensajePermisos('Configuraci&oacute;n');
@@ -329,6 +355,7 @@ class AportaContenido {
case 'informeInventario':
if ($this->perfil['Informe']) {
$info = new InformeInventario($this->bdd);
return $info->ejecuta();
} else {
return $this->mensajePermisos('Informes');
@@ -336,36 +363,39 @@ class AportaContenido {
case 'importacion':
if ($this->perfil['Modificacion'] && $this->perfil['Borrado']) {
$import = new Importacion($this->bdd, $this->registrado);
return $import->ejecuta();
} else {
return $this->mensajePermisos("Actualizaci&oacute;n, creaci&oacute;n y borrado de elementos");
return $this->mensajePermisos('Actualizaci&oacute;n, creaci&oacute;n y borrado de elementos');
}
case 'copiaseg':
if ($this->perfil['Config']) {
$copia = new CopiaSeguridad();
if ($_GET['confirmado'] == "1") {
if (isset($_GET['confirmado']) && $_GET['confirmado'] == '1') {
if (!$copia->creaCopia()) {
$tipo = "danger";
$cabecera = "ERROR";
$tipo = 'danger';
$cabecera = 'ERROR';
} else {
$tipo = "info";
$cabecera = "INFORMACIÓN";
$tipo = 'info';
$cabecera = 'INFORMACIÓN';
}
return $this->panel($cabecera, $copia->mensaje(), $tipo);
} else {
return $copia->dialogo();
}
} else {
return $this->mensajePermisos("Copias de seguridad");
return $this->mensajePermisos('Copias de seguridad');
}
} // Fin del contenido
case 'usuario_incorrecto':
$this->usuario_inc = true;
return;
case 'registro': // Si está registrado mostrar bienvenida
// si no, un enlace
if ($this->bEstaRegistrado) {
return "Bienvenid@ <b>$this->sUsuario</b><hr />" .
return "Bienvenid@ <b>$this->sUsuario</b><hr />".
'<a href="index.php?cerrarSesion">Cerrar sesi&oacute;n</a>';
} else {
return '';
@@ -386,35 +416,36 @@ class AportaContenido {
}
/**
*
* @param string $tipo
*
* @return string
*/
public function mensajePermisos($tipo)
{
return $this->panel("ERROR", "No tiene permiso para acceder a $tipo", "danger");
return $this->panel('ERROR', "No tiene permiso para acceder a $tipo", 'danger');
}
private function devuelveInforme($informe)
{
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf";
$letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf';
$informe->guardaArchivo($nombre);
return '<div class="container">
<!--<a href="' . $nombre . '" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="' . $nombre . '" type="application/pdf" width="100%" height="700" style="float:left;">
<!--<a href="'.$nombre.'" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="'.$nombre.'" type="application/pdf" width="100%" height="700" style="float:left;">
</object>
</div>';
}
public function panel($cabecera, $mensaje, $tipo)
{
$panel = '<div class="panel panel-' . $tipo . '"><div class="panel-heading">';
$panel .= '<h3 class="panel-title">' . $cabecera . '</h3></div>';
$panel = '<div class="panel panel-'.$tipo.'"><div class="panel-heading">';
$panel .= '<h3 class="panel-title">'.$cabecera.'</h3></div>';
$panel .= '<div class="panel-body">';
$panel .= $mensaje;
$panel .= '</div>';
return $panel;
}
}
?>

View File

@@ -1,3 +1,15 @@
Version 1.17 29-07-2014
-Eliminados los mensajes de aviso de php en todos los archivos php
Versión 1.16 28-07-2014
-Fix #41. Arregla las llamadas a Instalar.php que se hacían desde Inventario.php y desde Instalar.php
Versión 1.15 29-06-2014
-Crear la opción de clonar registro en Mantenimiento.
-Crear iconos de clonado en todos los estilos.
-Corregido determinaAccion en Imagen para aceptar el clonado
-Corregido codificación/decodificación de la cadena de búsqueda en la URL
Versión 1.14.1 02-06-2014
-Añadidos enlaces a manual y a aplicación de ejemplo en readme.md
-Arreglado que los créditos salgan centrados en lugar de alineados a la derecha

View File

@@ -1,6 +1,5 @@
<?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.
@@ -16,59 +15,60 @@
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
class Configuracion {
private $configuracion = "inc/configuracion.inc";
private $confNueva = "inc/configuracion.new";
private $confAnterior = "inc/configuracion.ant";
class Configuracion
{
private $configuracion = 'inc/configuracion.inc';
private $confNueva = 'inc/configuracion.new';
private $confAnterior = 'inc/configuracion.ant';
private $datosConf;
//Campos del fichero de configuración que se van a editar.
private $lista = array('SERVIDOR', 'PUERTO', 'BASEDATOS', 'BASEDATOSTEST', 'USUARIO', 'CLAVE', 'CENTRO', 'NUMFILAS', 'ESTILO', 'PLANTILLA', 'COLORLAT', 'COLORFON', 'MYSQLDUMP', 'GZIP', 'TMP');
private $lista = ['SERVIDOR', 'PUERTO', 'BASEDATOS', 'BASEDATOSTEST', 'USUARIO', 'CLAVE', 'CENTRO', 'NUMFILAS', 'ESTILO', 'PLANTILLA', 'COLORLAT', 'COLORFON', 'MYSQLDUMP', 'GZIP', 'TMP'];
private $campos;
public function __construct()
{
$this->campos = implode(",", $this->lista);
$this->campos = implode(',', $this->lista);
}
//Hecho público para poder efectuar los tests correspondientes.
public function obtieneFichero()
{
return file_get_contents($this->configuracion, FILE_TEXT);
}
public function obtieneLista()
{
return $this->lista;
}
public function obtieneDatos($linea, &$clave, &$valor)
{
$filtro = str_replace("'", "", $linea);
list($clave, $valor) = explode(",", $filtro);
list($resto, $campo) = explode("(", $clave);
list($valor, $resto) = explode(")", $valor);
list($resto, $clave) = explode("(", $clave);
$filtro = str_replace("'", '', $linea);
list($clave, $valor) = explode(',', $filtro);
list($resto, $campo) = explode('(', $clave);
list($valor, $resto) = explode(')', $valor);
list($resto, $clave) = explode('(', $clave);
$valor = trim($valor);
}
private function creaTitulo($titulo, $ayuda)
{
return '<td style="vertical-align:middle"><a class="dato" href="#" data-placement="right" data-content="'.$ayuda.'">'.$titulo.'</a></td>';
}
public function ejecuta() {
public function ejecuta()
{
$fichero = $this->obtieneFichero();
$datos = explode("\n", $fichero);
$grabar = isset($_POST['SERVIDOR']);
if ($grabar) {
$fsalida = @fopen($this->confNueva, "wb");
$fsalida = @fopen($this->confNueva, 'wb');
}
foreach ($datos as $linea) {
if (stripos($linea, "DEFINE") !== false) {
if (stripos($linea, 'DEFINE') !== false) {
//Comprueba que tenga una definición correcta
$this->obtieneDatos($linea, $clave, $valor);
$this->obtieneDatos($linea, $clave, $valor);
$this->datosConf[$clave] = $valor;
if ($grabar && stripos($this->campos, $clave) !== false) {
$linea = str_replace($valor, $_POST[$clave], $linea);
@@ -78,96 +78,98 @@ class Configuracion {
//$salida .= "Post=" . var_export($_POST, true);
}
if ($grabar) {
$registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n";
$registro = substr($linea, 0, 2) == '?>' ? $linea : $linea."\n";
fwrite($fsalida, $registro);
}
}
$salida.=$this->formulario();
$salida = $this->formulario();
if ($grabar) {
$salida.='<div class="alert alert-success">Configuraci&oacute;n guardada correctamente</div>';
$salida .= '<div class="alert alert-success">Configuraci&oacute;n guardada correctamente</div>';
fclose($fsalida);
//unlink($this->confAnterior);
rename($this->configuracion, $this->confAnterior);
rename($this->confNueva, $this->configuracion);
unlink($this->confAnterior);
}
return $salida;
}
private function formulario() {
$coloresLateral = array("Original" => "#C4FAEC", "Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db",
"Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Morado" => "#6633FF",
"Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1");
$coloresFondo = array("Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db",
"Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Rojo" => "#ff887c",
"Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1", "Original" => '#F3FEC8');
$personal = $this->datosConf['ESTILO'] == "personal" ? 'selected' : ' ';
$bluecurve = $this->datosConf['ESTILO'] == "bluecurve" ? 'selected' : ' ';
$cristal = $this->datosConf['ESTILO'] == "cristal" ? 'selected' : ' ';
$bootst = $this->datosConf['ESTILO'] == "bootstrap" ? 'selected' : ' ';
$normal = $this->datosConf['PLANTILLA'] == "normal" ? 'selected' : ' ';
$bootstrap = $this->datosConf['PLANTILLA'] == "bootstrap" ? 'selected' : ' ';
private function formulario()
{
$coloresLateral = ['Original' => '#C4FAEC', 'Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db',
'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Morado' => '#6633FF',
'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1'];
$coloresFondo = ['Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db',
'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Rojo' => '#ff887c',
'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1', 'Original' => '#F3FEC8'];
$personal = $this->datosConf['ESTILO'] == 'personal' ? 'selected' : ' ';
$bluecurve = $this->datosConf['ESTILO'] == 'bluecurve' ? 'selected' : ' ';
$cristal = $this->datosConf['ESTILO'] == 'cristal' ? 'selected' : ' ';
$bootst = $this->datosConf['ESTILO'] == 'bootstrap' ? 'selected' : ' ';
$normal = $this->datosConf['PLANTILLA'] == 'normal' ? 'selected' : ' ';
$bootstrap = $this->datosConf['PLANTILLA'] == 'bootstrap' ? 'selected' : ' ';
$salida = '<center><div class="col-sm-4 col-md-8"><form name="configura" method="post">';
//$salida.='<p align="center"><table border=1 class="tablaDatos"><tbody>';
$salida.='<p align="center"><table border=2 class="table table-hover"><tbody>';
$salida.='<th colspan=2 class="info"><center><b>Preferencias</b></center></th>';
$salida.='<tr>'.$this->creaTitulo("Nombre del Centro","Nombre que aparecerá en los informes y en la página principal de la aplicación").'<td><input type="text" name="CENTRO" value="' . $this->datosConf['CENTRO'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Número de filas","Número de filas que aparecerán en la pantalla de consulta de los maestros. Valor entre 10 y 25.").'<td><input type="number" max="25" min="10" name="NUMFILAS" value="' . $this->datosConf['NUMFILAS'] . '" size="3" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Plantilla","Plantilla html utilizada para mostrar el contenido de la aplicación.").'<td><select name="PLANTILLA" class="form-control">';
$salida.='<option value="normal" ' . $normal . '>normal</option>';
$salida.='<option ' . $bootstrap . '>bootstrap</option></select></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Estilo","Estilo de los botones de control en los mantenimientos de los maestros").'<td><select name="ESTILO" class="form-control">';
$salida.='<option value="personal" ' . $personal . '>personal</option>';
$salida.='<option ' . $bluecurve . '>bluecurve</option>';
$salida.='<option ' . $bootst . '>bootstrap</option>';
$salida.='<option ' . $cristal . '>cristal</option></select></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Color Lateral","Color que se aplicará a la parte izquierda de la aplicación donde aparece el menú").'<td style="vertical-align:middle"><select name="COLORLAT" id="COLORLAT" class="form-control">';
$salida .= '<p align="center"><table border=2 class="table table-hover"><tbody>';
$salida .= '<th colspan=2 class="info"><center><b>Preferencias</b></center></th>';
$salida .= '<tr>'.$this->creaTitulo('Nombre del Centro', 'Nombre que aparecerá en los informes y en la página principal de la aplicación').'<td><input type="text" name="CENTRO" value="'.$this->datosConf['CENTRO'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Número de filas', 'Número de filas que aparecerán en la pantalla de consulta de los maestros. Valor entre 10 y 25.').'<td><input type="number" max="25" min="10" name="NUMFILAS" value="'.$this->datosConf['NUMFILAS'].'" size="3" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Plantilla', 'Plantilla html utilizada para mostrar el contenido de la aplicación.').'<td><select name="PLANTILLA" class="form-control">';
$salida .= '<option value="normal" '.$normal.'>normal</option>';
$salida .= '<option '.$bootstrap.'>bootstrap</option></select></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Estilo', 'Estilo de los botones de control en los mantenimientos de los maestros').'<td><select name="ESTILO" class="form-control">';
$salida .= '<option value="personal" '.$personal.'>personal</option>';
$salida .= '<option '.$bluecurve.'>bluecurve</option>';
$salida .= '<option '.$bootst.'>bootstrap</option>';
$salida .= '<option '.$cristal.'>cristal</option></select></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Color Lateral', 'Color que se aplicará a la parte izquierda de la aplicación donde aparece el menú').'<td style="vertical-align:middle"><select name="COLORLAT" id="COLORLAT" class="form-control">';
foreach ($coloresLateral as $color => $codigo) {
$selec = "";
$selec = '';
if (trim($this->datosConf['COLORLAT']) == $codigo) {
$selec = "selected";
$selec = 'selected';
}
$salida.='<option value="' . $codigo . '" ' . $selec . ' >' . $color . '</option>';
$salida .= '<option value="'.$codigo.'" '.$selec.' >'.$color.'</option>';
}
$salida.='</select></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Color Fondo","Color que aparecerá como fondo en todas las pantallas de la aplicación").'<td style="vertical-align:middle"><select name="COLORFON" id="COLORFON" class="form-control">';
$salida .= '</select></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Color Fondo', 'Color que aparecerá como fondo en todas las pantallas de la aplicación').'<td style="vertical-align:middle"><select name="COLORFON" id="COLORFON" class="form-control">';
foreach ($coloresFondo as $color => $codigo) {
$selec = "";
$selec = '';
if (trim($this->datosConf['COLORFON']) == $codigo) {
$selec = "selected";
$selec = 'selected';
}
$salida.='<option value="' . $codigo . '" ' . $selec . ' >' . $color . '</option>';
$salida .= '<option value="'.$codigo.'" '.$selec.' >'.$color.'</option>';
}
$salida.='</select></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Directorio tmp","Directorio donde se almacenarán los archivos temporales de la aplicación y también los archivos e informes que genera").'<td><input type="text" name="TMP" value="' . $this->datosConf['TMP'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<th colspan=2 class="danger"><center><b>Base de datos</b></center></th>';
$salida.='<tr>'.$this->creaTitulo("Servidor","Nombre o dirección IP del servidor MySQL. Normalmente localhost").'<td><input type="text" name="SERVIDOR" value="' . $this->datosConf['SERVIDOR'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Puerto","Número de puerto donde el servidor admite conexiones MySQL. Normalmente 3306").'<td><input type="text" name="PUERTO" value="' . $this->datosConf['PUERTO'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Base de datos","Nombre de la base de datos donde se almacenarán los datos de la aplicación").'<td><input type="text" name="BASEDATOS" value="' . $this->datosConf['BASEDATOS'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Base de datos Tests","Nombre de la base de datos donde se almacenarán los datos de prueba de la aplicación").'<td><input type="text" name="BASEDATOSTEST" value="' . $this->datosConf['BASEDATOSTEST'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Usuario","Usuario con permisos de lectura/escritura en la base de datos").'<td><input type="text" name="USUARIO" value="' . $this->datosConf['USUARIO'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("Clave","Contraseña del usuario con permisos sobre la base de datos").'<td><input type="text" name="CLAVE" value="' . $this->datosConf['CLAVE'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("mysqldump","Ruta completa a la utilidad mysqldump. Este programa es necesario para que se puedan hacer las copias de seguridad de la aplicación").'<td><input type="text" name="MYSQLDUMP" value="' . $this->datosConf['MYSQLDUMP'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr>'.$this->creaTitulo("gzip","Ruta completa a la utilidad gzip. Este programa es necesario para que se puedan comprimir las copias de seguridad de la aplicación").'<td><input type="text" name="GZIP" value="' . $this->datosConf['GZIP'] . '" maxlength="35" size="35" /></td></tr>';
$salida.='<tr align=center><td colspan=2>
<a class="btn btn-info" role="button" onClick="location.href=' . "'index.php'" . '"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
$salida .= '</select></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Directorio tmp', 'Directorio donde se almacenarán los archivos temporales de la aplicación y también los archivos e informes que genera').'<td><input type="text" name="TMP" value="'.$this->datosConf['TMP'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<th colspan=2 class="danger"><center><b>Base de datos</b></center></th>';
$salida .= '<tr>'.$this->creaTitulo('Servidor', 'Nombre o dirección IP del servidor MySQL. Normalmente localhost').'<td><input type="text" name="SERVIDOR" value="'.$this->datosConf['SERVIDOR'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Puerto', 'Número de puerto donde el servidor admite conexiones MySQL. Normalmente 3306').'<td><input type="text" name="PUERTO" value="'.$this->datosConf['PUERTO'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Base de datos', 'Nombre de la base de datos donde se almacenarán los datos de la aplicación').'<td><input type="text" name="BASEDATOS" value="'.$this->datosConf['BASEDATOS'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Base de datos Tests', 'Nombre de la base de datos donde se almacenarán los datos de prueba de la aplicación').'<td><input type="text" name="BASEDATOSTEST" value="'.$this->datosConf['BASEDATOSTEST'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Usuario', 'Usuario con permisos de lectura/escritura en la base de datos').'<td><input type="text" name="USUARIO" value="'.$this->datosConf['USUARIO'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('Clave', 'Contraseña del usuario con permisos sobre la base de datos').'<td><input type="text" name="CLAVE" value="'.$this->datosConf['CLAVE'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('mysqldump', 'Ruta completa a la utilidad mysqldump. Este programa es necesario para que se puedan hacer las copias de seguridad de la aplicación').'<td><input type="text" name="MYSQLDUMP" value="'.$this->datosConf['MYSQLDUMP'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr>'.$this->creaTitulo('gzip', 'Ruta completa a la utilidad gzip. Este programa es necesario para que se puedan comprimir las copias de seguridad de la aplicación').'<td><input type="text" name="GZIP" value="'.$this->datosConf['GZIP'].'" maxlength="35" size="35" /></td></tr>';
$salida .= '<tr align=center><td colspan=2>
<a class="btn btn-info" role="button" onClick="location.href='."'index.php'".'"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<button type="submit" class="btn btn-primary" name="aceptar"><span class="glyphicon glyphicon-ok"></span> Aceptar</td></tr></p>';
$salida.='</form></div></center>';
$salida.="<script>
$salida .= '</form></div></center>';
$salida .= "<script>
$(document).ready(function() {
$('select[name=" . '"COLORFON"' . "]').on('change', function() {
$(document.body).css('background-color', $('select[name=" . '"COLORFON"' . "]').val());
$('.main').css('background-color', $('select[name=" . '"COLORFON"' . "]').val());
$('select[name=".'"COLORFON"'."]').on('change', function() {
$(document.body).css('background-color', $('select[name=".'"COLORFON"'."]').val());
$('.main').css('background-color', $('select[name=".'"COLORFON"'."]').val());
});
$('select[name=" . '"COLORLAT"' . "]').on('change', function() {
$('.sidebar').css('background-color', $('select[name=" . '"COLORLAT"' . "]').val());
$('select[name=".'"COLORLAT"'."]').on('change', function() {
$('.sidebar').css('background-color', $('select[name=".'"COLORLAT"'."]').val());
});
$('select[name=" . '"COLORLAT"' . "]').simplecolorpicker({theme: 'glyphicons'});
$('select[name=" . '"COLORFON"' . "]').simplecolorpicker({theme: 'glyphicons'});
$('select[name=".'"COLORLAT"'."]').simplecolorpicker({theme: 'glyphicons'});
$('select[name=".'"COLORFON"'."]').simplecolorpicker({theme: 'glyphicons'});
$('.dato').popover({trigger: 'hover'});
});
</script>";
return $salida;
}
}
?>

View File

@@ -1,6 +1,5 @@
<?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.
@@ -8,25 +7,21 @@
* 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 CopiaSeguridad {
class CopiaSeguridad
{
private $mensaje;
private $baseDatos;
private $imagenes;
public function __construct()
{
$opcion = $_GET['opc'];
}
public function creaCopia()
{
if (!$this->copiaBaseDatos()) {
@@ -38,95 +33,106 @@ class CopiaSeguridad {
if (!$this->empaqueta()) {
return false;
}
return true;
}
public function dialogo()
{
$dialogo = '<div class="container col-5"><div class="jumbotron">
<h1>Copia de Seguridad</h1>
<p>¿Desea realizar una copia de seguridad de todos los datos de la Base de Datos y de todas las Imágenes?</p>
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href=' . "'index.php'" . '"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href=' . "'index.php?copiaseg&confirmado=1'" . '">
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href='."'index.php'".'"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href='."'index.php?copiaseg&confirmado=1'".'">
<span class="glyphicon glyphicon-cloud-download"></span> Continuar</a></p>
</div></div>';
return $dialogo;
}
private function copiaBaseDatos()
private function copiaBaseDatos()
{
$archivo_sql = TMP."/baseDatos" . BASEDATOS . ".sql";
$baseDatosComprimida = $archivo_sql . ".gz";
$archivo_sql = TMP.'/baseDatos'.BASEDATOS.'.sql';
$baseDatosComprimida = $archivo_sql.'.gz';
$this->baseDatos = $baseDatosComprimida;
if (file_exists($baseDatosComprimida)) {
unlink($baseDatosComprimida);
}
$comando = escapeshellcmd(MYSQLDUMP . ' -h ' . SERVIDOR . ' -P ' . PUERTO . ' -u ' . USUARIO . ' --password=' . CLAVE . ' --result-file=' . $archivo_sql . ' ' . BASEDATOS);
$comando2 = escapeshellcmd(GZIP . ' -9f ' . $archivo_sql);
$comando = escapeshellcmd(MYSQLDUMP.' -h '.SERVIDOR.' -P '.PUERTO.' -u '.USUARIO.' --password='.CLAVE.' --result-file='.$archivo_sql.' '.BASEDATOS);
$comando2 = escapeshellcmd(GZIP.' -9f '.$archivo_sql);
exec($comando);
exec($comando2);
if (filesize($baseDatosComprimida) < 1024) {
//No se ha realizado la copia de seguridad
$mensaje = "La copia de seguridad no se ha realizado correctamente.<br><br>";
$mensaje .= "Compruebe que las rutas a los programas mysqldump y gzip en configuraci&oacute;n est&aacute;n correctamente establecidas ";
$mensaje .= "y que los datos de acceso a la base de datos sean correctos.<br>";
$mensaje .= "mysqldump=[" . MYSQLDUMP . "]<br>";
$mensaje .= "gzip=[" . GZIP . "]";
$mensaje = 'La copia de seguridad no se ha realizado correctamente.<br><br>';
$mensaje .= 'Compruebe que las rutas a los programas mysqldump y gzip en configuraci&oacute;n est&aacute;n correctamente establecidas ';
$mensaje .= 'y que los datos de acceso a la base de datos sean correctos.<br>';
$mensaje .= 'mysqldump=['.MYSQLDUMP.']<br>';
$mensaje .= 'gzip=['.GZIP.']';
$this->mensaje = $mensaje;
$this->error = true;
return false;
}
return true;
}
private function copiaImagenes()
{
$copiaImagenes = TMP."/Imagenes.tbz";
$copiaImagenes = TMP.'/Imagenes.tbz';
$this->imagenes = $copiaImagenes;
if (file_exists($copiaImagenes)) {
unlink($copiaImagenes);
}
$comando = escapeshellcmd('tar cf ' . $copiaImagenes . ' ' . IMAGEDATA);
$comando = escapeshellcmd('tar cf '.$copiaImagenes.' '.IMAGEDATA);
exec($comando);
if (filesize($copiaImagenes) == 0) {
$this->error = true;
$mensaje = "No se ha podido comprimir el directorio de las imágenes " . IMAGEDATA . "<br>";
$mensaje .= "Compruebe que la ruta de acceso al programa tar en configuraci&oacute;n est&aacute; correctamente establecida";
$mensaje = 'No se ha podido comprimir el directorio de las imágenes '.IMAGEDATA.'<br>';
$mensaje .= 'Compruebe que la ruta de acceso al programa tar en configuraci&oacute;n est&aacute; correctamente establecida';
$this->mensaje = $mensaje;
return false;
}
return true;
}
private function empaqueta()
{
// Empaqueta los dos archivos en el que va a devolver
$nombreCopia = TMP."/Copia" . BASEDATOS . strftime("%Y%m%d%H%M") . ".tar";
{
// Empaqueta los dos archivos en el que va a devolver
$nombreCopia = TMP.'/Copia'.BASEDATOS.strftime('%Y%m%d%H%M').'.tar';
if (file_exists($nombreCopia)) {
unlink($nombreCopia);
}
$comando = escapeshellcmd('tar cf ' . $nombreCopia . ' ' . $this->baseDatos . ' ' . $this->imagenes);
$comando = escapeshellcmd('tar cf '.$nombreCopia.' '.$this->baseDatos.' '.$this->imagenes);
exec($comando);
if (filesize($nombreCopia) ==0 || !file_exists($nombreCopia)) {
if (filesize($nombreCopia) == 0 || !file_exists($nombreCopia)) {
$this->error = true;
$mensaje = "No se ha creado el paquete con los archivos de imágenes en [<b>" . $this->imagenes . "</b>] y <br>";
$mensaje .= " con el archivo de Base de Datos [<b>" . $this->baseDatos . "</b>]<br><br>";
$mensaje .= "Compruebe que los datos de configuración están correctamente establecidos <br>";
$mensaje .= "El comando de copia fue [" . $comando . "]<br>";
$mensaje .= "gzip=[" . GZIP . "]";
$mensaje = 'No se ha creado el paquete con los archivos de imágenes en [<b>'.$this->imagenes.'</b>] y <br>';
$mensaje .= ' con el archivo de Base de Datos [<b>'.$this->baseDatos.'</b>]<br><br>';
$mensaje .= 'Compruebe que los datos de configuración están correctamente establecidos <br>';
$mensaje .= 'El comando de copia fue ['.$comando.']<br>';
$mensaje .= 'gzip=['.GZIP.']';
$this->mensaje = $mensaje;
return false;
}
$this->error = false;
unlink ($this->baseDatos);
unlink ($this->imagenes);
unlink($this->baseDatos);
unlink($this->imagenes);
$mensaje = 'Copia de seguridad realizada con &eacute;xito.<br><br>Pulse sobre el siguiente enlace para descargar:<br><br>';
$mensaje .= '<a href="' . $nombreCopia . '">Descargar Copia de Seguridad de Datos</a><br><br>';
$mensaje .= '<a href="'.$nombreCopia.'">Descargar Copia de Seguridad de Datos</a><br><br>';
$mensaje .= 'El paquete de copia contiene un archivo con la copia de la información de la base de datos y un archivo que contiene el directorio de las fotografías e imágenes asociadas a los datos';
$this->mensaje = $mensaje;
return true;
}
public function mensaje ()
public function mensaje()
{
return $this->mensaje;
}
}
?>

210
Csv.php
View File

@@ -1,7 +1,6 @@
<?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.
@@ -9,28 +8,26 @@
* 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 Csv {
class Csv
{
/**
*
* @var String Nombre del fichero csv
* @var string Nombre del fichero csv
*/
private $nombre;
/**
* @var FILE manejador del fichero
*/
private $fichero = NULL;
private $fichero = null;
/**
* @var xml conulta asociada a este fichero
@@ -43,7 +40,6 @@ class Csv {
private $bdd;
/**
*
* @var int Número de registros en el fichero csv
*/
private $numRegistros;
@@ -59,8 +55,7 @@ class Csv {
private $datosFichero;
/**
* Indices a los campos correspondientes
*
* Indices a los campos correspondientes.
*/
private $idElemento;
private $idArticulo;
@@ -71,48 +66,54 @@ class Csv {
private $nSerie;
/**
// El constructor necesita saber cuál es la opción actual
/**
* Constructor de la clase.
* // El constructor necesita saber cuál es la opción actual.
* /**
* Constructor de la clase.
*
* @param BaseDatos $baseDatos Manejador de la base de datos
*/
public function __construct($baseDatos) {
public function __construct($baseDatos)
{
$this->bdd = $baseDatos;
}
/**
* Crea un fichero csv con el nombre especificado
* @param String $fichero Nombre del fichero
* Crea un fichero csv con el nombre especificado.
*
* @param string $fichero Nombre del fichero
*/
public function crea($fichero) {
public function crea($fichero)
{
$this->nombre = $fichero;
$this->fichero = fopen($this->nombre, "w") or die("No puedo abrir " . $this->nombre . " para escritura.");
$this->fichero = fopen($this->nombre, 'w') or die('No puedo abrir '.$this->nombre.' para escritura.');
}
/**
*
* @param array $datos escribe la línea en el archivo
*/
public function escribeLinea($datos) {
fputcsv($this->fichero, $datos, ',', '"') or die("No puedo escribir en el fichero csv");
public function escribeLinea($datos)
{
fputcsv($this->fichero, $datos, ',', '"') or die('No puedo escribir en el fichero csv');
}
public function __destruct() {
public function __destruct()
{
$this->cierra();
}
public function cierra() {
fclose($this->fichero) or die("No puedo cerrar el archivo csv");
public function cierra()
{
fclose($this->fichero) or die('No puedo cerrar el archivo csv');
}
/**
*
* @param String $fichero Archivo xml que contiene la definición de la consulta
* @param string $fichero Archivo xml que contiene la definición de la consulta
*/
public function ejecutaConsulta($fichero) {
$consulta = simplexml_load_file($fichero) or die("No puedo cargar el fichero xml " . $fichero . " al csv");
public function ejecutaConsulta($fichero)
{
$consulta = simplexml_load_file($fichero) or die('No puedo cargar el fichero xml '.$fichero.' al csv');
// Escribe la cabecera del fichero
$this->escribeLinea(array($consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto']));
$this->escribeLinea([$consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto']]);
foreach ($consulta->Pagina->Cuerpo->Col as $campo) {
$campos[] = $campo['Titulo'];
}
@@ -120,7 +121,7 @@ class Csv {
// Escribe los datos de los campos
$this->bdd->ejecuta($consulta->Datos->Consulta);
while ($fila = $this->bdd->procesaResultado()) {
$campos = array();
$campos = [];
foreach ($consulta->Pagina->Cuerpo->Col as $campo) {
$campos[] = $fila[(string) $campo['Nombre']];
}
@@ -129,12 +130,12 @@ class Csv {
}
/**
*
* @param String $ficheroCSV Nombre del archivo csv
* @param string $ficheroCSV Nombre del archivo csv
*/
public function cargaCSV($ficheroCSV) {
public function cargaCSV($ficheroCSV)
{
$this->nombre = $ficheroCSV;
$this->fichero = fopen($this->nombre, "r") or die('No puedo abrir el archivo ' . $this->nombre . " para lectura.");
$this->fichero = fopen($this->nombre, 'r') or die('No puedo abrir el archivo '.$this->nombre.' para lectura.');
list($archivo, $idCabecera, $cabecera) = fgetcsv($this->fichero);
while ($linea = fgetcsv($this->fichero)) {
$datosFichero[] = $linea;
@@ -146,113 +147,120 @@ class Csv {
}
/**
* Muestra un resumen de los datos del fichero csv cargado por pantalla
*
* Muestra un resumen de los datos del fichero csv cargado por pantalla.
*/
public function resumen() {
public function resumen()
{
//$mensaje .=
$mensaje = "<center><h1>Archivo [inventario" . $this->cabecera[0] . "]</h1>";
$mensaje .= "<h2>id=[" . $this->cabecera[1] . "] Descripci&oacute;n=[" . $this->cabecera[2] . "]</h2><br>";
$mensaje = '<center><h1>Archivo [inventario'.$this->cabecera[0].']</h1>';
$mensaje .= '<h2>id=['.$this->cabecera[1].'] Descripci&oacute;n=['.$this->cabecera[2].']</h2><br>';
$mensaje .= '<table border=1 class="table table-striped table-bordered table-condensed table-hover"><theader>';
foreach ($this->datosFichero[0] as $campo) {
$dato = $campo;
$mensaje .= "<th><b>$dato</b></th>";
}
$mensaje .= "<th><b>Acci&oacute;n</b></th>";
$mensaje .="</theader><tbody>";
$mensaje .= '<th><b>Acci&oacute;n</b></th>';
$mensaje .= '</theader><tbody>';
$this->cargaIndices($this->datosFichero[0]);
//echo "$mensaje contar Datosfichero=[".count($datosFichero)."]";
for ($i = 1; $i < count($this->datosFichero); $i++) {
$mensaje .= "<tr>";
$mensaje .= '<tr>';
$primero = true;
foreach ($this->datosFichero[$i] as $dato) {
if ($primero) {
$primero = false;
switch ($dato) {
case 'S': $estado = "-Baja-";
$color = "danger";
case 'S': $estado = '-Baja-';
$color = 'danger';
break;
case 'Alta': $estado = "-Alta-";
$color = "primary";
case 'Alta': $estado = '-Alta-';
$color = 'primary';
break;
case "N" : $estado = $this->compruebaCantidades($i);
case 'N': $estado = $this->compruebaCantidades($i);
if ($estado != 0) {
$color = "warning";
$color = 'warning';
if ($estado > 0) {
$estado = "+" . $estado;
$estado = '+'.$estado;
}
} else {
$estado = "igual";
$color = "info";
$estado = 'igual';
$color = 'info';
}
break;
default: throw new Exception("El archivo csv tiene un formato incorrecto.<br>Bajas=[$dato]");
}
}
$mensaje .= "<td>" . $dato . "</td>";
$mensaje .= '<td>'.$dato.'</td>';
}
$mensaje .= '<td align="center"><label class="label label-' . $color . '">' . $estado . '</label></td>';
$mensaje .= "</tr>";
$mensaje .= '<td align="center"><label class="label label-'.$color.'">'.$estado.'</label></td>';
$mensaje .= '</tr>';
}
$mensaje .= "</tbody></table></p><br>";
$mensaje .= '</tbody></table></p><br>';
$mensaje .= $this->panelMensaje('Si se produce cualquier error en el procesamiento del fichero, no se aplicar&aacute; ning&uacute;n cambio en la base de datos.');
$mensaje .= '<form method="post" name="Aceptar" action="index.php?importacion&opc=ejecutar">
<button type="button" name="Cancelar" value="Cancelar" onClick="location.href=' . "'index.php'" . '" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Cancelar</button>
<button type="button" name="Cancelar" value="Cancelar" onClick="location.href='."'index.php'".'" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Cancelar</button>
<button type="submit" name="Aceptar" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button>
<input type="hidden" name="ficheroCSV" value="' . $this->nombre . '">
<input type="hidden" name="ficheroCSV" value="'.$this->nombre.'">
</form></center>';
return $mensaje;
}
/**
*
* @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no
* @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no
*
* @return string
*/
private function compruebaCantidades($i) {
$ultimo = count($datos);
private function compruebaCantidades($i)
{
//$ultimo = count($datos);
return $this->datosFichero[$i][$this->cantidadReal] - $this->datosFichero[$i][$this->cantidad];
}
private function panelMensaje($info, $tipo = "danger", $cabecera = "&iexcl;Atenci&oacute;n!") {
$mensaje = '<div class="panel panel-' . $tipo . '"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">' . $cabecera . '</h3></div>';
private function panelMensaje($info, $tipo = 'danger', $cabecera = '&iexcl;Atenci&oacute;n!')
{
$mensaje = '<div class="panel panel-'.$tipo.'"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">'.$cabecera.'</h3></div>';
$mensaje .= '<div class="panel-body">';
$mensaje .= $info;
$mensaje .= '</div>';
$mensaje .= '</div>';
return $mensaje;
}
private function escribeLog($comando) {
$fp = fopen($this->nombre.".log", "a");
$linea = strftime("%Y/%m/%d")."|".$this->nombre."|".$comando;
fputs($fp, $linea . "\n");
private function escribeLog($comando)
{
$fp = fopen($this->nombre.'.log', 'a');
$linea = strftime('%Y/%m/%d').'|'.$this->nombre.'|'.$comando;
fwrite($fp, $linea."\n");
fclose($fp);
}
private function bajaElemento($i) {
private function bajaElemento($i)
{
$id = $this->datosFichero[$i][$this->idElemento];
$comando = 'delete from Elementos where id="' . $id . '";';
$comando = 'delete from Elementos where id="'.$id.'";';
$this->escribeLog($comando);
if (!$this->bdd->ejecuta($comando)) {
throw new Exception("Baja-".$this->bdd->mensajeError, $this->bdd->error);
throw new Exception('Baja-'.$this->bdd->mensajeError, $this->bdd->error);
}
}
private function modificaElemento($i) {
private function modificaElemento($i)
{
$id = $this->datosFichero[$i][$this->idElemento];
$comando = 'update Elementos set Cantidad=' . $this->datosFichero[$i][$this->cantidadReal] . ' where id="' . $id . '";';
$comando = 'update Elementos set Cantidad='.$this->datosFichero[$i][$this->cantidadReal].' where id="'.$id.'";';
$this->escribeLog($comando);
if (!$this->bdd->ejecuta($comando)) {
throw new Exception("Modifica-".$this->bdd->mensajeError, $this->bdd->error);
if (!$this->bdd->ejecuta($comando)) {
throw new Exception('Modifica-'.$this->bdd->mensajeError, $this->bdd->error);
}
}
private function altaElemento($i) {
if ($this->cabecera[0] == "Articulo") {
private function altaElemento($i)
{
if ($this->cabecera[0] == 'Articulo') {
$idUbicacion = $this->datosFichero[$i][$this->idUbicacion];
$idArticulo = $this->cabecera[1];
$comando = 'select id from Ubicaciones where Descripcion="'.$this->datosFichero[$i][$this->desUbicacion].'";';
@@ -261,30 +269,31 @@ class Csv {
$idArticulo = $this->datosFichero[$i][$this->idArticulo];
}
$idArt = $datosFichero[$i];
$comando = 'insert into Elementos () values (null,' . $idArticulo . ',' . $idUbicacion . ',"' . $this->datosFichero[$i][$this->nSerie];
$comando .= '",' . $this->datosFichero[$i][$this->cantidadReal] . ',"' . $this->datosFichero[$i][$this->fechaCompra] . '");';
$comando = 'insert into Elementos () values (null,'.$idArticulo.','.$idUbicacion.',"'.$this->datosFichero[$i][$this->nSerie];
$comando .= '",'.$this->datosFichero[$i][$this->cantidadReal].',"'.$this->datosFichero[$i][$this->fechaCompra].'");';
$this->escribeLog($comando);
if (!$this->bdd->ejecuta($comando)) {
throw new Exception("Alta-".$this->bdd->mensajeError, $this->bdd->error);
throw new Exception('Alta-'.$this->bdd->mensajeError, $this->bdd->error);
}
}
private function cargaIndices($campos) {
private function cargaIndices($campos)
{
for ($i = 0; $i < count($campos); $i++) {
switch ($campos[$i]) {
case "Cant. Real": $this->cantidadReal = $i;
case 'Cant. Real': $this->cantidadReal = $i;
break;
case "Fecha C.": $this->fechaCompra = $i;
case 'Fecha C.': $this->fechaCompra = $i;
break;
case "idUbic": $this->idUbicacion = $i;
case 'idUbic': $this->idUbicacion = $i;
break;
case "idArt": $this->idArticulo = $i;
case 'idArt': $this->idArticulo = $i;
break;
case "idElem": $this->idElemento = $i;
case 'idElem': $this->idElemento = $i;
break;
case "Cantidad": $this->cantidad = $i;
case 'Cantidad': $this->cantidad = $i;
break;
case "N Serie": $this->nSerie = $i;
case 'N Serie': $this->nSerie = $i;
break;
}
}
@@ -293,9 +302,10 @@ class Csv {
}
/**
* Procesa contra la base de datos todas las acciones del archivo
* Procesa contra la base de datos todas las acciones del archivo.
*/
public function ejecutaFichero() {
public function ejecutaFichero()
{
$this->cargaIndices($this->datosFichero[0]);
//Realiza una transacción para que no se ejecute parcialmente una actualización
try {
@@ -317,31 +327,31 @@ class Csv {
$acciones++;
}
break;
default: throw new Exception("Acci&oacute;n no reconocida en la importacion [" . $this->datosFichero[0] . "]");
default: throw new Exception('Acci&oacute;n no reconocida en la importacion ['.$this->datosFichero[0].']');
}
}
$mensaje = "Se han procesado correctamente $acciones acciones en la Base de Datos.";
$this->bdd->confirmaTransaccion();
return $this->panelMensaje($mensaje,"success", "Informaci&oacute;n");
return $this->panelMensaje($mensaje, 'success', 'Informaci&oacute;n');
} catch (Exception $e) {
$this->bdd->abortaTransaccion();
$mensaje = "Se ha producido el error [" . $e->getMessage() . "]<br>NO se ha realizado ning&uacute;n cambio en la Base de Datos.";
$mensaje = 'Se ha producido el error ['.$e->getMessage().']<br>NO se ha realizado ning&uacute;n cambio en la Base de Datos.';
return $this->panelMensaje($mensaje);
}
}
private function ejecutaFichero2() {
private function ejecutaFichero2()
{
echo '<script>visualizaProgreso();</script>';
for ($i = 1; $i < 80; $i++) {
//sleep(1);
$progreso = $i;
echo '<script>actProgreso(' . $progreso . ');</script>';
echo '<script>actProgreso('.$progreso.');</script>';
//echo str_repeat(' ',1024*64);
flush();
//echo '$(".bar").css("width", "'.$progreso.'");';
}
}
}
?>

View File

@@ -1,23 +1,21 @@
<?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/>.
*
*/
/**
* @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/>.
*/
//
// Esta clase procesará una página sustituyendo
// las marcas {} por el contenido que proceda.
@@ -27,46 +25,49 @@
// y una referencia al objeto cuyos métodos deberán
// aportar los contenidos.
//
class Distribucion {
// Variable para conservar la plantilla
private $plantilla;
// Matriz que contendrá los nombres de elementos
private $elementos;
// Referencia al objeto cuyos métodos serán
// invocados para aportar el contenido
private $objeto;
// Constructor de la clase
public function __construct($archivo, $objeto)
{
// Recuperamos el contenido del archivo
$this->plantilla=file_get_contents($archivo)
class Distribucion
{
// Variable para conservar la plantilla
private $plantilla;
// Matriz que contendrá los nombres de elementos
private $elementos;
// Referencia al objeto cuyos métodos serán
// invocados para aportar el contenido
private $objeto;
// Constructor de la clase
public function __construct($archivo, $objeto)
{
// Recuperamos el contenido del archivo
$this->plantilla = file_get_contents($archivo)
or die('Fallo en la apertura de la plantilla '.$archivo);
// y guardamos la referencia al objeto
$this->objeto=$objeto;
// Extraemos todas las marcas de contenido
preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla,$el, PREG_PATTERN_ORDER);
// Nos quedamos con la matriz de resultados
$this->elementos=$el[0];
}
// Este método es el encargado de procesar la plantilla
public function procesaPlantilla()
{
// Tomamos la plantilla en una variable local, para
// así no modificar el contenido original
$pagina=$this->plantilla;
// Recorremos la matriz de marcas de contenido
foreach($this->elementos as $el) {
// Eliminamos los delimitadores { y }
$el=substr($el,1,strlen($el)-2);
// invocamos a la función del objeto
$resultado=$this->objeto->$el();
// e introducimos su contenido en lugar de la marca
$pagina=str_replace('{'.$el.'}',$resultado,$pagina);
}
/**
* @todo Tratar de activar la compresión.
*/
// Si es posible comprimir
// y guardamos la referencia al objeto
$this->objeto = $objeto;
// Extraemos todas las marcas de contenido
preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla, $el, PREG_PATTERN_ORDER);
// Nos quedamos con la matriz de resultados
$this->elementos = $el[0];
}
// Este método es el encargado de procesar la plantilla
public function procesaPlantilla()
{
// Tomamos la plantilla en una variable local, para
// así no modificar el contenido original
$pagina = $this->plantilla;
// Recorremos la matriz de marcas de contenido
foreach ($this->elementos as $el) {
// Eliminamos los delimitadores { y }
$el = substr($el, 1, strlen($el) - 2);
// invocamos a la función del objeto
$resultado = $this->objeto->$el();
// e introducimos su contenido en lugar de la marca
$pagina = str_replace('{'.$el.'}', $resultado, $pagina);
}
/*
* @todo Tratar de activar la compresión.
*/
// Si es posible comprimir
// if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) {
// // introducimos la cabecera que indica que el contenido está comprimido
// header('Content-Encoding: gzip');
@@ -74,6 +75,5 @@ class Distribucion {
// return gzencode($pagina, 9);
// }
return $pagina; // enviamos sin comprimir
}
}
}
?>

View File

@@ -1,12 +1,13 @@
<?php
/**
* genera un documento PDF a partir de una descripción dada en un archivo XML
* genera un documento PDF a partir de una descripción dada en un archivo XML.
*
* @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0
* @package Inventario
*
* @copyright Copyright (c) 2008, Ricardo Montañana
* @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.
@@ -14,22 +15,20 @@
* 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/>.
*
*/
require_once 'phpqrcode.php';
class EtiquetasPDF {
class EtiquetasPDF
{
/**
*
* @var basedatos Controlador de la base de datos
*/
private $bdd;
@@ -39,19 +38,21 @@ class EtiquetasPDF {
private $nombreFichero;
/**
* El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente
* @param basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML
* @param boolean $registrado usuario registrado si/no
* El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente.
*
* @param basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF
* todo: cambiar este comentario
* todo: cambiar este comentario
*/
public function __construct($bdd, $definicion, $registrado)
{
if (!$registrado) {
return 'Debe registrarse para acceder a este apartado';
}
$this->nombreFichero = TMP."/informeEtiquetas.pdf";
$this->nombreFichero = TMP.'/informeEtiquetas.pdf';
// Recuperamos la definición del informe
$this->def = simplexml_load_file($definicion);
$this->bdd = $bdd;
@@ -61,7 +62,7 @@ class EtiquetasPDF {
$this->pdf->setAutoPageBreak(false);
//echo $def->Titulo.$def->Cabecera;
$this->pdf->setAuthor(AUTOR, true);
$creador = CENTRO . " " . PROGRAMA . VERSION;
$creador = CENTRO.' '.PROGRAMA.VERSION;
$this->pdf->setCreator(html_entity_decode($creador), true);
$this->pdf->setSubject($this->def->Titulo, true);
//$this->pdf->setAutoPageBreak(true, 10);
@@ -78,12 +79,13 @@ class EtiquetasPDF {
$this->pdf->AddPage();
$tamLinea = 5;
$fila = -1;
$primero = true; $i = 0;
$url = explode("/", $_SERVER['SCRIPT_NAME']);
$primero = true;
$i = 0;
$url = explode('/', $_SERVER['SCRIPT_NAME']);
$aplicacion = $url[1];
$protocolo = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://";
$enlace = $protocolo . $_SERVER['SERVER_NAME'] . "/" . $aplicacion . "/index.php?elementos&opc=editar&id=";
while($tupla = $this->bdd->procesaResultado()) {
$protocolo = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? 'https://' : 'http://';
$enlace = $protocolo.$_SERVER['SERVER_NAME'].'/'.$aplicacion.'/index.php?elementos&opc=editar&id=';
while ($tupla = $this->bdd->procesaResultado()) {
for ($j = 0; $j < $tupla['cantidad']; $j++) {
//Hay que generar tantas etiquetas como ponga la cantidad de cada elemento
if ($i % 2) {
@@ -104,31 +106,31 @@ class EtiquetasPDF {
$primero = false;
}
$py = 6 + 41 * $fila;
$enlace2=$enlace.$tupla['idEl'];
$fichero = TMP."/etiq".rand(1000,9999).".png";
$enlace2 = $enlace.$tupla['idEl'];
$fichero = TMP.'/etiq'.rand(1000, 9999).'.png';
QRcode::png($enlace2, $fichero);
$this->pdf->image($fichero, $etiq2, $py, 30, 30);
unlink($fichero);
$this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['articulo']));
$py+=$tamLinea;
$py += $tamLinea;
$this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['marca']));
$py+=$tamLinea;
$py += $tamLinea;
$this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['modelo']));
$py+=$tamLinea;
$py += $tamLinea;
$this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['numserie']));
$py+=$tamLinea;
$py += $tamLinea;
$this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, $tupla['fechaCompra']);
$py+=$tamLinea-1;
$py += $tamLinea - 1;
$this->pdf->setxy($etiq2, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['ubicacion']));
$py+=$tamLinea-1;
$py += $tamLinea - 1;
$this->pdf->setxy($etiq2, $py);
$cadena = "idElemento=" . $tupla['idEl'] . " / idArticulo=" . $tupla['idArt'] . " / idUbicacion=" . $tupla['idUbic'];
$cadena = 'idElemento='.$tupla['idEl'].' / idArticulo='.$tupla['idArt'].' / idUbicacion='.$tupla['idUbic'];
$this->pdf->Cell(30, 10, $cadena);
$i++;
}
@@ -149,15 +151,16 @@ class EtiquetasPDF {
public function getCabecera()
{
$cabecera = "Content-type: application/pdf";
$cabecera = $cabecera . "Content-length: " . strlen($this->docu);
$cabecera = $cabecera . "Content-Disposition: inline; filename=" . $this->nombreFichero;
$cabecera = 'Content-type: application/pdf';
$cabecera = $cabecera.'Content-length: '.strlen($this->docu);
$cabecera = $cabecera.'Content-Disposition: inline; filename='.$this->nombreFichero;
return $cabecera;
}
public function guardaArchivo($nombre)
{
$fichero = fopen($nombre, "w");
$fichero = fopen($nombre, 'w');
fwrite($fichero, $this->getCabecera());
fwrite($fichero, $this->getContenido(), strlen($this->getContenido()));
$this->nombreFichero = $nombre;
@@ -166,10 +169,10 @@ class EtiquetasPDF {
public function enviaCabecera()
{
header("Content-type: application/pdf");
header('Content-type: application/pdf');
$longitud = strlen($this->docu);
header("Content-length: $longitud");
header("Content-Disposition: inline; filename=" . $this->nombreFichero);
header('Content-Disposition: inline; filename='.$this->nombreFichero);
}
public function imprimeInforme()
@@ -178,5 +181,3 @@ class EtiquetasPDF {
echo $this->docu;
}
}
?>

3615
FPDF.php

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,5 @@
<?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.
@@ -16,36 +15,37 @@
*
* 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);
require_once 'Zebra_Image.php';
define('HAYQUEGRABAR', 1);
define('HAYQUEBORRAR', 2);
define('NOHACERNADA', 3);
class Imagen {
class Imagen
{
private $archivoSubido;
public $archivoComprimido;
private $extension;
private $dirData;
public $archivoCopiado;
public function __construct()
{
$this->dirData = IMAGEDATA;
}
public function determinaAccion($campo)
{
if (isset($_POST[$campo]) && $_POST[$campo] == "") {
if (isset($_POST[$campo]) && $_POST[$campo] == '') {
return HAYQUEBORRAR; //Hay que borrar el archivo de imagen
} elseif ($_FILES[$campo]['error'] == 0) {
} elseif (isset($_FILES[$campo]['error']) && $_FILES[$campo]['error'] == 0) {
return HAYQUEGRABAR; //Hay que guardar el archivo de imagen enviado
} else {
return NOHACERNADA; //No hay que hacer nada
}
}
public function procesaEnvio($campo, &$mensaje)
{
try {
@@ -76,11 +76,11 @@ class Imagen {
$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}');
@@ -97,35 +97,51 @@ class Imagen {
return true;
} catch (RuntimeException $e) {
$mensaje = $e->getMessage();
return false;
}
}
public static function borraImagenId($tabla, $id)
{
$extensiones = array ("png", "gif", "jpg");
$extensiones = ['png', 'gif', 'jpg'];
foreach ($extensiones as $extension) {
$archivo = IMAGEDATA . "/" . $tabla . "_" . $id . "." . $extension;
$archivo = IMAGEDATA.'/'.$tabla.'_'.$id.'.'.$extension;
if (file_exists($archivo)) {
unlink ($archivo);
unlink($archivo);
}
}
}
public function copiaImagenId($valorImagen, $tabla, $id, &$mensaje)
{
$extension = strrchr($valorImagen, '.');
$nombre = $this->dirData.'/'.$tabla.'_'.$id.$extension;
if (!@copy($valorImagen, $nombre)) {
$errors = error_get_last();
$mensaje = 'No pudo copiar el archivo '.$valorImagen.' en '.$nombre.' Error = ['.$errors['message'].']';
return false;
}
$this->archivoCopiado = $nombre;
return true;
}
public function mueveImagenId($tabla, $id, &$mensaje)
{
if (!$this->comprimeArchivo($tabla . "_" . $id, $mensaje)) {
if (!$this->comprimeArchivo($tabla.'_'.$id, $mensaje)) {
return false;
} else {
return true;
}
}
}
private function comprimeArchivo($id, &$mensaje)
private function comprimeArchivo($id, &$mensaje)
{
$zebra = new Zebra_Image();
$zebra->source_path = $this->archivoSubido;
$this->archivoComprimido = $this->dirData . "/" . $id . "." . $this->extension;
$this->archivoComprimido = $this->dirData.'/'.$id.'.'.$this->extension;
$zebra->target_path = $this->archivoComprimido;
$zebra->jpeg_quality = 100;
@@ -143,28 +159,28 @@ class Imagen {
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;
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;
case 3: $mensaje = 'No se pudo escribir el archivo destino '.$this->archivoComprimido;
break;
case 4: $mensaje = 'Formato de fichero origen no soportado ' . $this->archivoSubido;
case 4: $mensaje = 'Formato de fichero origen no soportado '.$this->archivoSubido;
break;
case 5: $mensaje = 'Formato de fichero destino no soportado ' . $this->archivoComprimido;
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;
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 {
//Borra el archivo subido
unlink($this->archivoSubido);
return true;
}
}
}
}
?>

View File

@@ -1,7 +1,6 @@
<?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.
@@ -17,20 +16,21 @@
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
class Importacion {
class Importacion
{
private $bdd;
public function __construct($baseDatos, $registrado) {
if (!$registrado) {
public function __construct($baseDatos, $registrado)
{
if (!$registrado) {
return 'Debe registrarse para acceder a este apartado';
}
$this->bdd = $baseDatos;
}
public function ejecuta() {
public function ejecuta()
{
$opc = '';
if (isset($_GET['opc'])) {
$opc = $_GET['opc'];
@@ -39,25 +39,29 @@ class Importacion {
case 'form':return $this->formulario();
case 'importar':return $this->importarFichero();
case 'ejecutar':return $this->ejecutaFichero();
default: return "Importacion: No entiendo qué me has pedido.";
default: return 'Importacion: No entiendo qué me has pedido.';
}
}
private function importarFichero() {
$uploadfile = TMP."/" . basename($_FILES['fichero']['name']);
private function importarFichero()
{
$uploadfile = TMP.'/'.basename($_FILES['fichero']['name']);
if (!move_uploaded_file($_FILES['fichero']['tmp_name'], $uploadfile)) {
die('No se pudo subir el fichero ' . $_FILES['userfile']['tmp_name']);
die('No se pudo subir el fichero '.$_FILES['userfile']['tmp_name']);
}
$csv = new Csv($this->bdd);
$csv->cargaCSV($uploadfile);
return $csv->resumen();
}
private function formulario() {
$accion = "index.php?importacion&opc=importar";
private function formulario()
{
$accion = 'index.php?importacion&opc=importar';
$salida = '';
//$salida .= '<script type="text/javascript" src="css/bootstrap-filestyle.min.js"> </script>';
$salida .='<div class="col-sm-6 col-md-6">';
$salida .= '<form enctype="multipart/form-data" name="importacion.form" method="post" action="' . $accion . '">' . "\n";
$salida .= '<div class="col-sm-6 col-md-6">';
$salida .= '<form enctype="multipart/form-data" name="importacion.form" method="post" action="'.$accion.'">'."\n";
$salida .= "<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige Archivo</b></legend></p>\n";
//$salida .= '<input type="file" name="fichero" id="fichero" onChange="seleccionFichero(this);" class="filestyle" data-classButton="btn btn-primary">';
//$salida .= '<input type="file" name="fichero" id="fichero" onChange="seleccionFichero(this);">';
@@ -75,7 +79,7 @@ class Importacion {
<a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">Eliminar</a>
</div>
</div></fieldset>';
$salida .= '<p align="center"><button class="btn btn-primary" type=submit><span class="glyphicon glyphicon-cloud-upload"></span> Aceptar</button></p><br>' . "\n";
$salida .= '<p align="center"><button class="btn btn-primary" type=submit><span class="glyphicon glyphicon-cloud-upload"></span> Aceptar</button></p><br>'."\n";
$salida .= '</div>';
$mensaje = 'Sólo se permiten archivos con extensión CSV';
$salida .= "<script type='text/javascript'>"."
@@ -89,14 +93,16 @@ class Importacion {
location.reload();
}}
</script>";
return $salida;
}
private function ejecutaFichero() {
private function ejecutaFichero()
{
$archivo = $_POST['ficheroCSV'];
$csv = new Csv($this->bdd);
$csv->cargaCSV($archivo);
return $csv->ejecutaFichero();
}
}
?>

View File

@@ -1,7 +1,6 @@
<?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.
@@ -17,10 +16,9 @@
*
* 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 {
class InformeInventario
{
private $bdd;
public function __construct($baseDatos)
@@ -48,67 +46,71 @@ class InformeInventario {
$informe = new InformePDF($this->bdd, $enlace, true);
$informe->crea($enlace);
$informe->cierraPDF();
return $this->devuelveInforme($informe);
}
private function devuelveInforme($informe)
{
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf";
$letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf';
$informe->guardaArchivo($nombre);
return '<div class="container">
<!--<a href="' . $nombre . '" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="' . $nombre . '" type="application/pdf" width="100%" height="700" style="float:left;">
<!--<a href="'.$nombre.'" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="'.$nombre.'" type="application/pdf" width="100%" height="700" style="float:left;">
</object>
</div>';
}
private function listarUbicacion()
{
$salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla';
switch ($salidaInforme) {
case "pantalla":
$fichero = "xml/inventarioUbicacion.xml";
$salida = TMP."/inventarioUbicacion.xml";
case 'pantalla':
$fichero = 'xml/inventarioUbicacion.xml';
$salida = TMP.'/inventarioUbicacion.xml';
break;
case "csv":
$fichero = "xml/inventarioUbicacionCSV.xml";
$salida = TMP."/inventarioUbicacionCSV.xml";
case 'csv':
$fichero = 'xml/inventarioUbicacionCSV.xml';
$salida = TMP.'/inventarioUbicacionCSV.xml';
break;
case "etiquetas":
$fichero = "xml/inventarioUbicacionEtiquetas.xml";
$salida = TMP."/inventarioUbicacionEtiquetas.xml";
case 'etiquetas':
$fichero = 'xml/inventarioUbicacionEtiquetas.xml';
$salida = TMP.'/inventarioUbicacionEtiquetas.xml';
break;
}
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$id = $_POST['id'] == NULL ? $_GET['id'] : $_POST['id'];
$comando = "select * from Ubicaciones where id='" . $id . "';";
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$id = $_POST['id'] == null ? $_GET['id'] : $_POST['id'];
$comando = "select * from Ubicaciones where id='".$id."';";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $id, $plantilla);
$plantilla = str_replace("{Descripcion}", $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$plantilla = str_replace('{id}', $id, $plantilla);
$plantilla = str_replace('{Descripcion}', $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
switch ($salidaInforme) {
case "pantalla":
case 'pantalla':
$informe = new InformePDF($this->bdd, $salida, true);
$informe->crea($salida);
$informe->cierraPDF();
return $this->devuelveInforme($informe);
case "csv":
case 'csv':
//Genera una hoja de cálculo en formato csv
$nombre = TMP."/Ubicacion" . strftime("%Y%m%d") . rand(100, 999) . ".csv";
$nombre = TMP.'/Ubicacion'.strftime('%Y%m%d').rand(100, 999).'.csv';
$hoja = new Csv($this->bdd);
$hoja->crea($nombre);
$hoja->ejecutaConsulta($salida);
echo '<script type="text/javascript"> window.open( "' . $nombre . '" ) </script>';
echo '<script type="text/javascript"> window.open( "'.$nombre.'" ) </script>';
break;
case "etiquetas":
case 'etiquetas':
$etiquetas = new EtiquetasPDF($this->bdd, $salida, true);
$etiquetas->crea($salida);
$etiquetas->cierraPDF();
return $this->devuelveInforme($etiquetas);
}
}
@@ -117,50 +119,52 @@ class InformeInventario {
{
$salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla';
switch ($salidaInforme) {
case "pantalla":
$fichero = "xml/inventarioArticulo.xml";
$salida = TMP."/inventarioArticulo.xml";
case 'pantalla':
$fichero = 'xml/inventarioArticulo.xml';
$salida = TMP.'/inventarioArticulo.xml';
break;
case "csv":
$fichero = "xml/inventarioArticuloCSV.xml";
$salida = TMP."/inventarioArticuloCSV.xml";
case 'csv':
$fichero = 'xml/inventarioArticuloCSV.xml';
$salida = TMP.'/inventarioArticuloCSV.xml';
break;
case "etiquetas":
$fichero = "xml/inventarioArticuloEtiquetas.xml";
$salida = TMP."/inventarioArticuloEtiquetas.xml";
case 'etiquetas':
$fichero = 'xml/inventarioArticuloEtiquetas.xml';
$salida = TMP.'/inventarioArticuloEtiquetas.xml';
break;
}
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero);
$id = $_POST['id'] == NULL ? $_GET['id'] : $_POST['id'];
$comando = "select * from Articulos where id='" . $id . "';";
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$id = $_POST['id'] == null ? $_GET['id'] : $_POST['id'];
$comando = "select * from Articulos where id='".$id."';";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
}
$fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $id, $plantilla);
$plantilla = str_replace("{Descripcion}", $fila['descripcion'], $plantilla);
$plantilla = str_replace("{Marca}", $fila['marca'], $plantilla);
$plantilla = str_replace("{Modelo}", $fila['modelo'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$plantilla = str_replace('{id}', $id, $plantilla);
$plantilla = str_replace('{Descripcion}', $fila['descripcion'], $plantilla);
$plantilla = str_replace('{Marca}', $fila['marca'], $plantilla);
$plantilla = str_replace('{Modelo}', $fila['modelo'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
switch ($salidaInforme) {
case "pantalla":
case 'pantalla':
$informe = new InformePDF($this->bdd, $salida, true);
$informe->crea($salida);
$informe->cierraPDF();
return $this->devuelveInforme($informe);
case "csv":
case 'csv':
//Genera una hoja de cálculo en formato csv
$nombre = TMP."/Articulo" . strftime("%Y%m%d") . rand(100, 999) . ".csv";
$nombre = TMP.'/Articulo'.strftime('%Y%m%d').rand(100, 999).'.csv';
$hoja = new Csv($this->bdd);
$hoja->crea($nombre);
$hoja->ejecutaConsulta($salida);
echo '<script type="text/javascript"> window.open( "' . $nombre . '" ) </script>';
echo '<script type="text/javascript"> window.open( "'.$nombre.'" ) </script>';
break;
case "etiquetas":
case 'etiquetas':
$etiquetas = new EtiquetasPDF($this->bdd, $salida, true);
$etiquetas->crea($salida);
$etiquetas->cierraPDF();
return $this->devuelveInforme($etiquetas);
}
}
@@ -168,63 +172,68 @@ class InformeInventario {
private function listaUbicaciones()
{
$salida = "<select class=\"selectpicker show-tick\" name=\"id\" data-live-search=\"true\" data-width=\"auto\">\n";
$comando = "select * from Ubicaciones order by Descripcion";
$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 .= '<option value='.$fila['id'].'>'.$fila['Descripcion']."</option><br>\n";
}
$salida.="</select>\n";
$salida .= "</select>\n";
return $salida;
}
private function listaArticulos()
{
$salida = "<select class=\"selectpicker show-tick\" name=\"id\" data-live-search=\"true\" data-width=\"auto\">\n";
$comando = "select * from Articulos order by descripcion, marca, modelo";
$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 .= '<option value='.$fila['id'].'>'.$fila['descripcion'].'-'.$fila['marca'].'-'.$fila['modelo']."</option><br>\n";
}
$salida.="</select>\n";
$salida .= "</select>\n";
return $salida;
}
private function formulario($accion, $etiqueta, $lista)
{
$salida = '<div class="col-sm-6 col-md-6"><form name="informeInventario.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>
$salida = '<div class="col-sm-6 col-md-6"><form name="informeInventario.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>
<label for='salida'>Salida del informe por:</label>";
$salida.='<div class="radio"><label><input type="radio" name="salida" value="pantalla" checked><span class="glyphicon glyphicon-list-alt"></span> Pantalla</label></div>';
$salida.='<div class="radio"><label><input type="radio" name="salida" value="csv"><span class="glyphicon glyphicon-cloud-download"></span> Archivo CSV</label></div>';
$salida.='<div class="radio"><label><input type="radio" name="salida" value="etiquetas"><span class="glyphicon glyphicon-qrcode"></span> Etiquetas (<a target="_new" href="http://www.apli.es/producto/ficha_producto.aspx?referencia=01275&stype=referencia&referenciaValue=01275&q=01275">Apli 1275</a>)</label></div>';
$salida.="<br><br></fieldset><p>";
$salida.='<p align="center"><button type=submit class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button></p><br></div>' . "\n";
$salida.="<script>$('.selectpicker').selectpicker();</script>";
$salida .= '<div class="radio"><label><input type="radio" name="salida" value="pantalla" checked><span class="glyphicon glyphicon-list-alt"></span> Pantalla</label></div>';
$salida .= '<div class="radio"><label><input type="radio" name="salida" value="csv"><span class="glyphicon glyphicon-cloud-download"></span> Archivo CSV</label></div>';
$salida .= '<div class="radio"><label><input type="radio" name="salida" value="etiquetas"><span class="glyphicon glyphicon-qrcode"></span> Etiquetas (<a target="_new" href="http://www.apli.es/producto/ficha_producto.aspx?referencia=01275&stype=referencia&referenciaValue=01275&q=01275">Apli 1275</a>)</label></div>';
$salida .= '<br><br></fieldset><p>';
$salida .= '<p align="center"><button type=submit class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button></p><br></div>'."\n";
$salida .= "<script>$('.selectpicker').selectpicker();</script>";
return $salida;
}
private function formularioUbicacion()
{
//Genera un formulario con las ubicaciones disponibles.
$accion = "index.php?informeInventario&opc=listarUbicacion";
$accion = 'index.php?informeInventario&opc=listarUbicacion';
return $this->formulario($accion, 'Ubicaci&oacute;n', $this->listaUbicaciones());
}
private function formularioArticulo()
{
$accion = "index.php?informeInventario&opc=listarArticulo";
$accion = 'index.php?informeInventario&opc=listarArticulo';
return $this->formulario($accion, 'Art&iacute;culo', $this->listaArticulos());
}
private function inventarioTotal()
{
return $this->dialogo();
@@ -235,18 +244,19 @@ class InformeInventario {
$dialogo = '<div class="container col-5"><div class="jumbotron">
<h1>Inventario Total</h1>
<p>¿Desea obtener el inventario de todo el centro?</p>
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href=' . "'index.php'" . '"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href=' . "'index.php?informeInventario&opc=listarTotal'" . '">
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href='."'index.php'".'"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href='."'index.php?informeInventario&opc=listarTotal'".'">
<span class="glyphicon glyphicon-list-alt"></span> Continuar</a></p>
</div></div>';
return $dialogo;
}
private function listarTotal()
{
$fichero = "xml/inventarioUbicacion.xml";
$salida = TMP."/inventarioUbicacion.xml";
$comando = "select * from Ubicaciones ;";
$fichero = 'xml/inventarioUbicacion.xml';
$salida = TMP.'/inventarioUbicacion.xml';
$comando = 'select * from Ubicaciones ;';
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->bdd->mensajeError($comando);
@@ -255,10 +265,10 @@ class InformeInventario {
$bdatos = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
$primero = true;
while ($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}", $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida);
$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}', $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
if ($primero) {
$primero = false;
$informe = new InformePDF($bdatos, $salida, true);
@@ -266,9 +276,7 @@ class InformeInventario {
$informe->crea($salida);
}
$informe->cierraPDF();
return $this->devuelveInforme($informe);
}
}
?>

View File

@@ -1,12 +1,13 @@
<?php
/**
* genera un documento PDF a partir de una descripción dada en un archivo XML
* genera un documento PDF a partir de una descripción dada en un archivo XML.
*
* @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0
* @package Inventario
*
* @copyright Copyright (c) 2008, Ricardo Montañana
* @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.
@@ -14,20 +15,18 @@
* 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 InformePDF {
class InformePDF
{
/**
*
* @var basedatos Controlador de la base de datos
*/
private $bdd;
@@ -36,14 +35,17 @@ class InformePDF {
private $def;
/**
* El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente
* @param basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML
* @param boolean $registrado usuario registrado si/no
* El constructor recibe como argumento el nombre del archivo XML con la definición, encargándose de recuperarla y guardar toda la información localmente.
*
* @param basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF
* todo: cambiar este comentario
* todo: cambiar este comentario
*/
public function __construct($bdd, $definicion, $registrado) {
public function __construct($bdd, $definicion, $registrado)
{
if (!$registrado) {
return 'Debe registrarse para acceder a este apartado';
}
@@ -53,15 +55,16 @@ class InformePDF {
$this->pdf = new Pdf_mysql_table($this->bdd->obtieneManejador(), (string) $this->def->Pagina['Orientacion'], (string) $this->def->Pagina['Formato'], (string) utf8_decode($this->def->Titulo['Texto']), (string) $this->def->Pagina->Cabecera);
//echo $def->Titulo.$def->Cabecera;
$this->pdf->Open();
$this->pdf->setAuthor(AUTOR,true);
$creador = CENTRO . " " . PROGRAMA . " v" . VERSION;
$this->pdf->setCreator(html_entity_decode($creador),true);
$this->pdf->setSubject($this->def->Titulo,true);
$this->pdf->setAuthor(AUTOR, true);
$creador = CENTRO.' '.PROGRAMA.' v'.VERSION;
$this->pdf->setCreator(html_entity_decode($creador), true);
$this->pdf->setSubject($this->def->Titulo, true);
$this->pdf->setAutoPageBreak(true, 10);
}
public function crea($definicion) {
public function crea($definicion)
{
//print_r($def);echo $bdd;die();
// Iniciamos la creación del documento
$this->def = simplexml_load_file($definicion);
@@ -74,50 +77,55 @@ class InformePDF {
foreach ($this->def->Pagina->Cuerpo->Col as $columna) {
$this->pdf->AddCol((string) $columna['Nombre'], (string) $columna['Ancho'], (string) $columna['Titulo'], (string) $columna['Ajuste'], (string) $columna['Total']);
}
$prop = array('HeaderColor' => array(255, 150, 100),
'color1' => array(210, 245, 255),
'color2' => array(255, 255, 210),
'padding' => 2);
$prop = ['HeaderColor' => [255, 150, 100],
'color1' => [210, 245, 255],
'color2' => [255, 255, 210],
'padding' => 2];
$this->pdf->Table($this->def->Datos->Consulta, $prop);
}
public function cierraPDF() {
public function cierraPDF()
{
$this->pdf->Close();
$this->docu = $this->pdf->Output('', 'S');
}
public function getContenido() {
public function getContenido()
{
return $this->docu;
}
public function getCabecera() {
$cabecera = "Content-type: application/pdf";
$cabecera = $cabecera . "Content-length: " . strlen($this->docu);
$cabecera = $cabecera . "Content-Disposition: inline; filename=".TMP."/Informe.pdf";
public function getCabecera()
{
$cabecera = 'Content-type: application/pdf';
$cabecera = $cabecera.'Content-length: '.strlen($this->docu);
$cabecera = $cabecera.'Content-Disposition: inline; filename='.TMP.'/Informe.pdf';
return $cabecera;
}
public function guardaArchivo($nombre) {
if (!isset($nombre))
$nombre = TMP . "/Informe.pdf";
$fichero = fopen($nombre, "w");
public function guardaArchivo($nombre)
{
if (!isset($nombre)) {
$nombre = TMP.'/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");
public function enviaCabecera()
{
header('Content-type: application/pdf');
$longitud = strlen($this->docu);
header("Content-length: $longitud");
header("Content-Disposition: inline; filename=".TMP."/Informe.pdf");
header('Content-Disposition: inline; filename='.TMP.'/Informe.pdf');
}
public function imprimeInforme() {
public function imprimeInforme()
{
$this->enviaCabecera();
echo $this->docu;
}
}
?>

View File

@@ -1,8 +1,8 @@
<?php
/**
* Programa de instalación que genera el entorno de ejecución
* tanto el fichero de configuración como la base de datos
* @package Inventario
* tanto el fichero de configuración como la base de datos.
*
* @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.
@@ -18,11 +18,11 @@
*
* You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/
//Se incluyen los módulos necesarios
function __autoload($class_name) {
require_once $class_name . '.php';
function __autoload($class_name)
{
require_once $class_name.'.php';
}
require_once 'inc/configuracion.inc';
@@ -37,22 +37,24 @@ define('INC', './inc');
$instalar = new Instalar();
if ($instalar->error) {
echo $instalar->panelError();
return;
}
echo $instalar->ejecuta();
class Instalar {
class Instalar
{
private $contenido;
private $plant;
public $error;
public $error_msj;
public $error_msj;
public function __construct()
{
//Selecciona la plantilla a utilizar
$this->plant='plant/';
$this->plant.=PLANTILLA;
$this->plant.='.html';
$this->plant = 'plant/';
$this->plant .= PLANTILLA;
$this->plant .= '.html';
$this->error = false;
$this->eror_msj = '';
if (INSTALADO != 'no') {
@@ -64,34 +66,38 @@ class Instalar {
$this->error_msj = "El indicador de instalación tiene 'no' pero la base de datos " . BASEDATOS . " contiene la tabla Articulos.";
}*/
}
private function existenDatos()
{
//Comprueba si existe la tabla Articulos
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($sql->error())
if ($sql->error()) {
return false;
}
$sql->ejecuta('select * from Articulos;');
if ($sql->error())
if ($sql->error()) {
return false;
}
return true;
}
public function ejecuta()
{
$paso = isset($_GET['paso']) ? $_GET['paso'] : 0;
$paso = $paso > NUMPASOS ? '0' : $paso;
$i=0;
$i = 0;
//Si quiere ir a un determinado paso se asegura que estén completos los anteriores
for ($i = 0; $i < $paso; $i++) {
$funcion = "validaPaso" . $i;
$funcion = 'validaPaso'.$i;
if (!$this->$funcion()) {
break;
}
}
$funcion = "paso" . $i;
$funcion = 'paso'.$i;
$this->contenido = $this->$funcion();
$salida = new Distribucion($this->plant, $this);
return $salida->procesaPlantilla();
}
@@ -102,100 +108,107 @@ class Instalar {
$info .= '<li class="list-group-item list-group-item-info">Configuración de PHP (php.ini)</li>';
// display_errors
$displayErr = ini_get('display_errors');
$displayErr = $displayErr == "1" || $displayErr == "on" ? "on" : "off";
$mensaje = $displayErr == "off" ? $this->retornaLabel(false,'Se debe deshabilitar la impresión de errores') :
$this->retornaLabel(true, 'Se debe deshabilitar la impresión de errores', "warning");
$displayErr = $displayErr == '1' || $displayErr == 'on' ? 'on' : 'off';
$mensaje = $displayErr == 'off' ? $this->retornaLabel(false, 'Se debe deshabilitar la impresión de errores') :
$this->retornaLabel(true, 'Se debe deshabilitar la impresión de errores', 'warning');
$info .= $this->retornaElemento($mensaje, 'display_errors', $displayErr);
// post_max_size
$postMax = ini_get('post_max_size');
$mensaje = $this->retornaBytes($postMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: ' . CADENAMINBYTES) :
$this->retornaLabel(true, 'Mínimo: ' . CADENAMINBYTES);
$mensaje = $this->retornaBytes($postMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: '.CADENAMINBYTES) :
$this->retornaLabel(true, 'Mínimo: '.CADENAMINBYTES);
$info .= $this->retornaElemento($mensaje, 'post_max_size', $postMax);
// upload_max_filesize
$uploadMax = ini_get('upload_max_filesize');
$mensaje = $this->retornaBytes($uploadMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: ' . CADENAMINBYTES) :
$this->retornaLabel(true, 'Mínimo: ' . CADENAMINBYTES);
$mensaje = $this->retornaBytes($uploadMax) >= MINBYTES ? $this->retornaLabel(false, 'Mínimo: '.CADENAMINBYTES) :
$this->retornaLabel(true, 'Mínimo: '.CADENAMINBYTES);
$info .= $this->retornaElemento($mensaje, 'upload_max_filesize', $uploadMax);
// mysqli
$mysql = extension_loaded('mysqli');
$mysql = $mysql ? "on" : "off";
$mysql = $mysql ? 'on' : 'off';
$mensaje = $mysql ? $this->retornaLabel(false, 'Tiene que estar cargada la extensión MySQLi para poder funcionar') :
$this->retornaLabel(true, 'Tiene que estar cargada la extensión MySQLi para poder funcionar');
$info .= $this->retornaElemento($mensaje, 'extensión MySQLi', $mysql);
$info .= '<li class="list-group-item list-group-item-info">Configuración de la Aplicación</li>';
// img.dat
$mensaje = is_writable(IMAGEDATA) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . IMAGEDATA) :
$this->retornaLabel(true, "Se debe poder escribir en el directorio " . IMAGEDATA);
$valor = is_writable(IMAGEDATA) ? "" : "No";
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . IMAGEDATA, $valor);
$mensaje = is_writable(IMAGEDATA) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.IMAGEDATA) :
$this->retornaLabel(true, 'Se debe poder escribir en el directorio '.IMAGEDATA);
$valor = is_writable(IMAGEDATA) ? 'Sí' : 'No';
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.IMAGEDATA, $valor);
// tmp
$mensaje = is_writable(TMP) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . TMP) :
$this->retornaLabel(true, "Se debe poder escribir en el directorio " . TMP);
$valor = is_writable(TMP) ? "" : "No";
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . TMP, $valor);
$mensaje = is_writable(TMP) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.TMP) :
$this->retornaLabel(true, 'Se debe poder escribir en el directorio '.TMP);
$valor = is_writable(TMP) ? 'Sí' : 'No';
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.TMP, $valor);
// inc
$mensaje = is_writable(INC) ? $this->retornaLabel(false, "Se debe poder escribir en el directorio " . INC) :
$this->retornaLabel(true, "Se debe poder escribir en el directorio " . INC);
$valor = is_writable(INC) ? "" : "No";
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . INC, $valor);
$mensaje = is_writable(INC) ? $this->retornaLabel(false, 'Se debe poder escribir en el directorio '.INC) :
$this->retornaLabel(true, 'Se debe poder escribir en el directorio '.INC);
$valor = is_writable(INC) ? 'Sí' : 'No';
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.INC, $valor);
// configuracion.inc
$mensaje = is_writable(CONFIGURACION) ? $this->retornaLabel(false, "Se debe poder escribir en el fichero de configuración ". CONFIGURACION) :
$this->retornaLabel(true, "Se debe poder escribir en el fichero de configuración ". CONFIGURACION);
$valor = is_writable(CONFIGURACION) ? "" : "No";
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en ' . CONFIGURACION, $valor);
$mensaje = is_writable(CONFIGURACION) ? $this->retornaLabel(false, 'Se debe poder escribir en el fichero de configuración '.CONFIGURACION) :
$this->retornaLabel(true, 'Se debe poder escribir en el fichero de configuración '.CONFIGURACION);
$valor = is_writable(CONFIGURACION) ? 'Sí' : 'No';
$info .= $this->retornaElemento($mensaje, 'Se puede escribir en '.CONFIGURACION, $valor);
// Final del paso
$info .='</ul>';
$info .= $this->validaPaso0() ? $this->retornaBoton(false, "instalar.php?paso=1") : $this->retornaBoton(true, "instalar.php");
$info .= '</ul>';
$info .= $this->validaPaso0() ? $this->retornaBoton(false, 'Instalar.php?paso=1') : $this->retornaBoton(true, 'Instalar.php');
$panel = $this->panelMensaje($info, 'primary', 'PASO 1: Configuración del servidor y la aplicación');
return $panel;
}
private function retornaElemento($validacion, $mensaje, $valor)
{
$info = '<li class="list-group-item">';
$info .= $validacion . ' ' . $mensaje . ': <span class="badge">' . $valor . '</span>';
$info .= $validacion.' '.$mensaje.': <span class="badge">'.$valor.'</span>';
$info .= '</li>';
return $info;
}
private function retornaBoton($error, $paso, $javascript = true)
{
$anadido = $javascript ? 'onclick="location.href=' . "'" . $paso . "'". '"' : '';
$anadido = $javascript ? 'onclick="location.href='."'".$paso."'".'"' : '';
if (!$error) {
return '<button ' . $anadido . ' type="submit" class="btn btn-success btn-lg pull-right">Continuar <span class="glyphicon glyphicon-arrow-right"></span></button>';
return '<button '.$anadido.' type="submit" class="btn btn-success btn-lg pull-right">Continuar <span class="glyphicon glyphicon-arrow-right"></span></button>';
} else {
return '<button ' . $anadido . ' type="submit" class="btn btn-danger btn-lg pull-right">Comprobar de nuevo <span class="glyphicon glyphicon-repeat"></span></button>';
return '<button '.$anadido.' type="submit" class="btn btn-danger btn-lg pull-right">Comprobar de nuevo <span class="glyphicon glyphicon-repeat"></span></button>';
}
}
private function botonVolver($enlace)
{
$boton = '<button type="button" onClick="location.href=' . "'$enlace'" . '" class="btn btn-success btn-lg pull-left">Paso anterior <span class="glyphicon glyphicon-arrow-left"></span></button>';
$boton = '<button type="button" onClick="location.href='."'$enlace'".'" class="btn btn-success btn-lg pull-left">Paso anterior <span class="glyphicon glyphicon-arrow-left"></span></button>';
return $boton;
}
private function retornaLabel($error, $mensaje, $tipo = "danger")
private function retornaLabel($error, $mensaje, $tipo = 'danger')
{
if ($error) {
$nombre1 = $tipo; $nombre2 = "remove";
$nombre1 = $tipo;
$nombre2 = 'remove';
} else {
$nombre1 = "success"; $nombre2 = "ok";
$nombre1 = 'success';
$nombre2 = 'ok';
}
$mensaje = '<a href="#" data-placement="right" data-toggle="popover" data-content="' . $mensaje .
'"><span class="label label-' . $nombre1 . '"><span class="glyphicon glyphicon-' . $nombre2 .
$mensaje = '<a href="#" data-placement="right" data-toggle="popover" data-content="'.$mensaje.
'"><span class="label label-'.$nombre1.'"><span class="glyphicon glyphicon-'.$nombre2.
'"></span></a>';
$mensaje .='<script>$(function () { $("[data-toggle=\'popover\']").popover(); });</script>';
$mensaje .= '<script>$(function () { $("[data-toggle=\'popover\']").popover(); });</script>';
return $mensaje;
}
private function retornaBytes($val)
private function retornaBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
$last = strtolower($val[strlen($val) - 1]);
switch ($last) {
// El modificador 'G' está disponble desde PHP 5.1.0
case 'g':
$val *= 1024;
@@ -204,12 +217,13 @@ class Instalar {
case 'k':
$val *= 1024;
}
return $val;
}
private function validaPaso0()
{
$validar = true;
$validar = true;
$postMax = ini_get('post_max_size');
$uploadMax = ini_get('upload_max_filesize');
$mysql = extension_loaded('mysqli');
@@ -217,33 +231,41 @@ class Instalar {
$escInc = is_writable(INC);
$escTMP = is_writable(TMP);
$escIMG = is_writable(IMAGEDATA);
if ($this->retornaBytes($postMax) < MINBYTES)
if ($this->retornaBytes($postMax) < MINBYTES) {
$validar = false;
if ($this->retornaBytes($uploadMax) < MINBYTES)
}
if ($this->retornaBytes($uploadMax) < MINBYTES) {
$validar = false;
if (!$mysql)
}
if (!$mysql) {
$validar = false;
if (!$escConfig)
}
if (!$escConfig) {
$validar = false;
if (!$escTMP)
}
if (!$escTMP) {
$validar = false;
if (!$escIMG)
}
if (!$escIMG) {
$validar = false;
if (!$escInc)
}
if (!$escInc) {
$validar = false;
}
return $validar;
}
private function actualizaConfiguracion($grabar, $campos, &$datos)
{
$conf = new Configuracion();
$fichero = $conf->obtieneFichero();
$datosFichero = explode("\n", $fichero);
if ($grabar) {
$fsalida = @fopen(CONFIGTMP, "wb");
$fsalida = @fopen(CONFIGTMP, 'wb');
}
foreach ($datosFichero as $linea) {
if (stripos($linea, "DEFINE") !== false) {
if (stripos($linea, 'DEFINE') !== false) {
$conf->obtieneDatos($linea, $clave, $valor);
if (stripos($campos, $clave) !== false) {
if ($grabar) {
@@ -253,7 +275,7 @@ class Instalar {
}
$datos[$clave] = $valor;
}
$registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n";
$registro = substr($linea, 0, 2) == '?>' ? $linea : $linea."\n";
if ($grabar) {
fwrite($fsalida, $registro);
}
@@ -261,10 +283,10 @@ class Instalar {
if ($grabar) {
fclose($fsalida);
unlink(CONFIGURACION);
rename(CONFIGTMP, CONFIGURACION);
rename(CONFIGTMP, CONFIGURACION);
}
}
// Cuestiones de la base de datos
private function paso1()
{
@@ -276,35 +298,37 @@ class Instalar {
$datos[$clave] = $valor;
}
} else {
$datos = array();
$datos = [];
}
$this->actualizaConfiguracion($grabar, $campos, $datos);
if ($grabar && $this->validaPaso1()) {
//Pasa al paso siguiente
return $this->paso2();
//Pasa al paso siguiente
return $this->paso2();
}
$info = '<form method="post" name="conf" action="instalar.php?paso=1">';
$info = '<form method="post" name="conf" action="Instalar.php?paso=1">';
$info .= '<ul class="list-group">';
$info .= '<li class="list-group-item list-group-item-info">Datos de configuración</li>';
$info .= '<li class="list-group-item">Servidor <input type="text" name="SERVIDOR" class="form-control" placeholder="Nombre del servidor o dirección IP" value="'. $datos['SERVIDOR'] .'"></li>';
$info .= '<li class="list-group-item">Puerto <input type="text" name="PUERTO" class="form-control" placeholder="Puerto de conexión" value="'. $datos['PUERTO'] .'"></li>';
$info .= '<li class="list-group-item">Base de Datos <input type="text" name="BASEDATOS" class="form-control" placeholder="Nombre de la Base de Datos" value="'. $datos['BASEDATOS'] .'"></li>';
$info .= '<li class="list-group-item">Usuario <input type="text" name="USUARIO" class="form-control" placeholder="Usuario" value="'. $datos['USUARIO'] .'"></li>';
$info .= '<li class="list-group-item">Contraseña <input type="text" name="CLAVE" class="form-control" placeholder="Contraseña" value="'. $datos['CLAVE'] .'"></li>';
$info .= '<li class="list-group-item">Servidor <input type="text" name="SERVIDOR" class="form-control" placeholder="Nombre del servidor o dirección IP" value="'.$datos['SERVIDOR'].'"></li>';
$info .= '<li class="list-group-item">Puerto <input type="text" name="PUERTO" class="form-control" placeholder="Puerto de conexión" value="'.$datos['PUERTO'].'"></li>';
$info .= '<li class="list-group-item">Base de Datos <input type="text" name="BASEDATOS" class="form-control" placeholder="Nombre de la Base de Datos" value="'.$datos['BASEDATOS'].'"></li>';
$info .= '<li class="list-group-item">Usuario <input type="text" name="USUARIO" class="form-control" placeholder="Usuario" value="'.$datos['USUARIO'].'"></li>';
$info .= '<li class="list-group-item">Contraseña <input type="text" name="CLAVE" class="form-control" placeholder="Contraseña" value="'.$datos['CLAVE'].'"></li>';
$info .= '</ul>';
$info .= $this->botonVolver("instalar.php");
$info .= $this->validaPaso1() ? $this->retornaBoton(false, "instalar.php?paso=1", false) : $this->retornaBoton(true, "instalar.php?paso=1", false);
$info .= $this->botonVolver('Instalar.php');
$info .= $this->validaPaso1() ? $this->retornaBoton(false, 'Instalar.php?paso=1', false) : $this->retornaBoton(true, 'Instalar.php?paso=1', false);
$info .= '</form>';
$panel = $this->panelMensaje($info, 'primary', 'PASO 2: Configuración de la Base de Datos.');
return $panel;
}
private function validaPaso1()
{
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, '');
if ($sql->error())
if ($sql->error()) {
return false;
}
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($sql->error()) {
return false;
@@ -319,17 +343,18 @@ class Instalar {
if ($sql->error()) {
return false;
}
return true;
return true;
}
// Usuario administrador
private function paso2()
{
if (isset($_POST['usuario'])) {
//ha enviado el formulario.
//Crea la base de datos
$borra_database = "DROP DATABASE " . BASEDATOS . " ;";
$database = "CREATE DATABASE " . BASEDATOS . " DEFAULT CHARACTER SET utf8;";
$borra_database = 'DROP DATABASE '.BASEDATOS.' ;';
$database = 'CREATE DATABASE '.BASEDATOS.' DEFAULT CHARACTER SET utf8;';
$articulos = "CREATE TABLE `Articulos` (
`id` smallint(6) NOT NULL auto_increment COMMENT 'ordenable,link/Articulo',
`descripcion` varchar(60) NOT NULL COMMENT 'ordenable,ajax/text',
@@ -379,43 +404,44 @@ class Instalar {
KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
";
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$sesion = substr(str_shuffle($letras), 0, 8);
$usuario = $_POST['usuario'];
$clave = $_POST['clave'];
$administrador = "insert into Usuarios values (null,'$usuario','$clave','$sesion','1','1','1','1','1','1','1');";
@mysqli_query($borra_database);
@mysqli_query($database);
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
$sql->ejecuta($ubicaciones);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$sql->ejecuta($articulos);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$sql->ejecuta($elementos);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$sql->ejecuta($usuarios);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$sql->ejecuta($administrador);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$campos="INSTALADO";
$datos['INSTALADO'] = "";
$campos = 'INSTALADO';
$datos['INSTALADO'] = 'sí';
$this->actualizaConfiguracion(true, $campos, $datos);
return $this->resumen();
}
$info = '
<form data-toggle="validator" role="form" class="form-horizontal" method="post" action="instalar.php?paso=2">
<form data-toggle="validator" role="form" class="form-horizontal" method="post" action="Instalar.php?paso=2">
<div class="form-group">
<label for="usuario" class="control-label col-sm-2">Usuario</label>
<div class="form-group col-sm-10">
@@ -435,69 +461,74 @@ class Instalar {
</div>
<div class="form-group col-sm-12">
' . $this->botonVolver("instalar.php?paso=1") . '
'.$this->botonVolver('Instalar.php?paso=1').'
<button type="submit" class="btn btn-primary pull-right btn-lg" disabled="disabled">Crear base de datos y usuario <span class="glyphicon glyphicon-arrow-right"></button>
</div>
</div>
</form>
<script type="text/javascript" src="./css/validator.min.js"></script>';
$panel = $this->panelMensaje($info, 'primary', 'PASO 3: Creación de la base de datos y el usuario administrador.');
return $panel;
return $panel;
}
private function validaPaso2()
{
//La validación de este paso se hace con la del formulario en javascript
return true;
}
public function panelMensaje($info, $tipo = "info", $cabecera = "&iexcl;Atenci&oacute;n!") {
$mensaje = '<div class="panel panel-' . $tipo . ' col-sm-6"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">' . $cabecera . '</h3></div>';
public function panelMensaje($info, $tipo = 'info', $cabecera = '&iexcl;Atenci&oacute;n!')
{
$mensaje = '<div class="panel panel-'.$tipo.' col-sm-6"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">'.$cabecera.'</h3></div>';
$mensaje .= '<div class="panel-body">';
$mensaje .= $info;
$mensaje .= '</div>';
$mensaje .= '</div>';
return $mensaje;
}
public function contenido()
{
return $this->contenido;
}
public function menu()
{
return '';
}
public function opcion()
{
return 'INSTALACI&Oacute;N';
}
public function control()
{
return '';
}
public function aplicacion()
{
return PROGRAMA . ' v' . VERSION;
return PROGRAMA.' v'.VERSION;
}
public function usuario()
{
return '';
}
public function fecha()
{
$idioma = 'es_ES';
$formato = "%d-%b-%y";
$formato = '%d-%b-%y';
setlocale(LC_TIME, $idioma);
return strftime($formato);
}
public function cabecera()
{
return '<!DOCTYPE html>
@@ -527,32 +558,31 @@ class Instalar {
</head>
<body>';
}
public function panelError()
{
$mensaje = $this->cabecera();
$mensaje .= $this->panelMensaje($this->error_msj, "danger", "&iexcl;ERROR!");
$mensaje .= "</body></html>";
$mensaje .= $this->panelMensaje($this->error_msj, 'danger', '&iexcl;ERROR!');
$mensaje .= '</body></html>';
return $mensaje;
}
private function resumen()
{
$info = '<ul class="list-group">';
$info .= '<li class="list-group-item list-group-item-info">Paso 1</li>';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de PHP");
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la aplicación");
$info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de PHP');
$info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de la aplicación');
$info .= '<li class="list-group-item list-group-item-info">Paso 2</li>';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la base de datos");
$info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Configuración de la base de datos');
$info .= '<li class="list-group-item list-group-item-info">Paso 3</li>';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación de Base de datos");
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación del usuario administrador");
$info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Creación de Base de datos');
$info .= $this->retornaElemento($this->retornaLabel(false, ''), 'Creación del usuario administrador');
$info .= '</ul>';
$info .= $this->retornaBoton(false, "index.php", true);
$info .= $this->retornaBoton(false, 'index.php', true);
$panel = $this->panelMensaje($info, 'success', 'Instalación finalizada.');
return $panel;
}
}
?>

View File

@@ -2,9 +2,11 @@
/**
* Clase Inventario que controla la ejecución principal del programa.
*
* @author Ricardo Montañana Gómez <rmontanana@gmail.com>
*
* @version 1.0
* @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.
@@ -12,23 +14,22 @@
* 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 del objeto principal de la aplicación
class Inventario {
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.
@@ -36,13 +37,15 @@ class Inventario {
private $plant;
// 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'];
//Si el programa no está instalado, llama al instalador.
if (INSTALADO == "no") {
header('location: instalar.php');
if (INSTALADO == 'no') {
header('location: Instalar.php');
return;
}
// Iniciamos una sesión
@@ -50,25 +53,25 @@ class Inventario {
//Conexión con la base de datos.
$this->bdd = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($this->bdd->error()) {
echo '<h1>Fallo al conectar con el servidor MySQL.</h1>';
echo "Servidor [ " . SERVIDOR . " ] base de datos [" . BASEDATOS . "]";
echo 'Servidor [ '.SERVIDOR.' ] base de datos ['.BASEDATOS.']';
$this->estado = false;
return;
} else {
$this->estado = true;
}
//Selecciona la plantilla a utilizar
$this->plant='plant/';
$this->plant.=PLANTILLA;
$this->plant.='.html';
$this->plant = 'plant/';
$this->plant .= PLANTILLA;
$this->plant .= '.html';
// Comprobamos si el usuario ya está registrado en esta sesión
$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
// 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']);
@@ -77,14 +80,16 @@ class Inventario {
}
}
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
@@ -118,7 +123,7 @@ class Inventario {
header('location:index.php?usuario_incorrecto');
exit;
case 'usuario_incorrecto':
$this->opcActual = "principal";
$this->opcActual = 'principal';
$contenido = $this->creaContenido();
$contenido->usuario_incorrecto();
$salida = new Distribucion($this->plant, $contenido);
@@ -132,18 +137,20 @@ class Inventario {
$salida = new Distribucion($this->plant, $this->creaContenido());
echo $salida->procesaPlantilla();
break;
}
}
private function creaContenido() {
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() {
private function usuarioRegistrado()
{
$this->usuario = $_POST['usuario'];
$this->clave = $_POST['clave'];
// ejecuta la consulta para buscar el usuario
@@ -167,10 +174,11 @@ class Inventario {
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 ['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
@@ -178,7 +186,8 @@ class Inventario {
// 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'");
// Si no hemos encontrado el ID
@@ -204,5 +213,3 @@ class Inventario {
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1,54 +1,57 @@
<?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/>.
*
*/
/**
* @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/>.
*/
//
// Esta clase generará el menú de la aplicación.
class Menu {
class Menu
{
private $opciones;
public function __construct($fichero)
{
$contenido=@file_get_contents($fichero) or
$contenido = @file_get_contents($fichero) or
die("<h1>No puedo generar el menú. No puedo acceder al fichero $fichero</h1>");
// Obtenemos la lista de pares Opción|Enlace
$elementos=explode("\n", $contenido);
foreach($elementos as $elemento) {
list($tipo, $opcion, $enlace, $destino, $titulo)=explode('|', $elemento);
$elementos = explode("\n", $contenido);
foreach ($elementos as $elemento) {
list($tipo, $opcion, $enlace, $destino, $titulo) = explode('|', $elemento);
// Los guardamos en la matriz de opciones
if ($tipo)
$this->opciones[]=$tipo.",".$opcion.",".$enlace.",".$destino.",".$titulo;
if ($tipo) {
$this->opciones[] = $tipo.','.$opcion.','.$enlace.','.$destino.','.$titulo;
}
}
}
public function insertaMenu()
{
$salida="";
$salida = '';
reset($this->opciones);
foreach($this->opciones as $opcion) {
list($tipo,$opcion,$enlace,$destino,$titulo)=explode(",",$opcion);
if ($tipo==2)
$salida.='<li class="active"><a href="'.$enlace.'" target="'.$destino.'" title="'.$titulo.'">'.$opcion.'</a><br /></li>';
else
$salida.=
foreach ($this->opciones as $opcion) {
list($tipo, $opcion, $enlace, $destino, $titulo) = explode(',', $opcion);
if ($tipo == 2) {
$salida .= '<li class="active"><a href="'.$enlace.'" target="'.$destino.'" title="'.$titulo.'">'.$opcion.'</a><br /></li>';
} else {
$salida .=
//'<span class="label label-default">'.$opcion.'</span><br>';
'<label class="">'.$opcion.'</label><br/>';
}
}
return $salida;
}
}
?>

View File

@@ -9,232 +9,259 @@
* 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 Pdf_mysql_table extends FPDF
{
/**
* Modificado por Ricardo Montañana 05/2008 para añadir la posibilidad de cálculo de totales
* @var $totales float[] Vector de totales de las columnas que lo necesiten
* Modificado por Ricardo Montañana 05/2008 para añadir la posibilidad de cálculo de totales.
*
* @var float[] Vector de totales de las columnas que lo necesiten
*/
private $ProcessingTable=false,$aCols=array(),$TableX,$HeaderColor;
private $RowColors,$ColorIndex;
private $bdd,$titulo,$cabecera;
private $totales=array(),$procesandoTotales=false;
/**
*
* @param mixed $bdd Controlador de la base de datos
* @param string $orientacion Orientación de la página P/L
* @param string $formato Tamaño de la página p. ej. A4
* @param string $titulo Título del informe
* @param string $cabecera Texto para la cabecera
*/
private $ProcessingTable = false;
private $aCols = [];
private $TableX;
private $HeaderColor;
private $RowColors;
private $ColorIndex;
private $bdd;
private $titulo;
private $cabecera;
private $totales = [];
private $procesandoTotales = false;
public function __construct($bdd,$orientacion,$formato,$titulo='',$cabecera='')
/**
* @param mixed $bdd Controlador de la base de datos
* @param string $orientacion Orientación de la página P/L
* @param string $formato Tamaño de la página p. ej. A4
* @param string $titulo Título del informe
* @param string $cabecera Texto para la cabecera
*/
public function __construct($bdd, $orientacion, $formato, $titulo = '', $cabecera = '')
{
$this->bdd=$bdd;
$this->titulo=$titulo;
$this->cabecera=$cabecera;
parent::__construct($orientacion,'mm',$formato);
$this->bdd = $bdd;
$this->titulo = $titulo;
$this->cabecera = $cabecera;
parent::__construct($orientacion, 'mm', $formato);
}
public function setTitulo($titulo)
{
$this->titulo=$titulo;
}
public function iniciaTotales()
{
$this->totales = array();
}
function Header()
{
//Modficada por Ricardo Montañana
//Titulo
$fecha=strftime("%d-%b-%Y %H:%M");
$this->SetFont('Arial','',8);
$this->Cell(0,4,html_entity_decode(CENTRO . " " . PROGRAMA . " v" . VERSION,ENT_COMPAT | ENT_HTML401,'ISO-8859-1'),0,1,'L');
$this->SetFont('Arial','',18);
$this->Cell(0,6,utf8_decode($this->titulo),0,1,'C');
$this->SetFont('Arial','',8);
$this->Cell(0,3,$fecha,0,1,'R');
$this->Cell(0,5,utf8_decode($this->cabecera),0,1,'C');
$this->Ln(10);
//Print the table header if necessary
if($this->ProcessingTable)
$this->TableHeader();
//Ensure table header is output
parent::Header();
}
public function Footer()
{
$this->SetFont('Arial','',8);
$this->setY($this->h-10);
$this->Cell(0,6,'-'.$this->PageNo().'-',0,1,'C');
parent::Footer();
$this->titulo = $titulo;
}
function TableHeader()
public function iniciaTotales()
{
$this->SetFont('Arial','B',12);
$this->totales = [];
}
public function Header()
{
//Modficada por Ricardo Montañana
//Titulo
$fecha = strftime('%d-%b-%Y %H:%M');
$this->SetFont('Arial', '', 8);
$this->Cell(0, 4, html_entity_decode(CENTRO.' '.PROGRAMA.' v'.VERSION, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'), 0, 1, 'L');
$this->SetFont('Arial', '', 18);
$this->Cell(0, 6, utf8_decode($this->titulo), 0, 1, 'C');
$this->SetFont('Arial', '', 8);
$this->Cell(0, 3, $fecha, 0, 1, 'R');
$this->Cell(0, 5, utf8_decode($this->cabecera), 0, 1, 'C');
$this->Ln(10);
//Print the table header if necessary
if ($this->ProcessingTable) {
$this->TableHeader();
}
//Ensure table header is output
parent::Header();
}
public function Footer()
{
$this->SetFont('Arial', '', 8);
$this->setY($this->h - 10);
$this->Cell(0, 6, '-'.$this->PageNo().'-', 0, 1, 'C');
parent::Footer();
}
public function TableHeader()
{
$this->SetFont('Arial', 'B', 12);
$this->SetX($this->TableX);
$fill=!empty($this->HeaderColor);
if($fill)
$this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]);
foreach($this->aCols as $col)
$this->Cell($col['w'],6,utf8_decode($col['c']),1,0,'C',$fill);
$fill = !empty($this->HeaderColor);
if ($fill) {
$this->SetFillColor($this->HeaderColor[0], $this->HeaderColor[1], $this->HeaderColor[2]);
}
foreach ($this->aCols as $col) {
$this->Cell($col['w'], 6, utf8_decode($col['c']), 1, 0, 'C', $fill);
}
$this->Ln();
}
function Row($data)
public function Row($data)
{
$this->SetX($this->TableX);
$ci=$this->ColorIndex;
$fill=!empty($this->RowColors[$ci]);
if($fill)
$this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]);
foreach($this->aCols as $col) {
$ci = $this->ColorIndex;
$fill = !empty($this->RowColors[$ci]);
if ($fill) {
$this->SetFillColor($this->RowColors[$ci][0], $this->RowColors[$ci][1], $this->RowColors[$ci][2]);
}
foreach ($this->aCols as $col) {
switch ($col['a']) {
case 'D':$alin='R';break;
case 'I':$alin='L';break;
case 'C':$alin='C';break;
default:$alin='L';break;
case 'D':$alin = 'R'; break;
case 'I':$alin = 'L'; break;
case 'C':$alin = 'C'; break;
default:$alin = 'L'; break;
}
if ($this->procesandoTotales) {
$this->SetFont('Arial','B',12);
$this->SetFont('Arial', 'B', 12);
}
$this->Cell($col['w'],5,utf8_decode($data[$col['f']]),1,0,$alin,$fill);
$dato = isset($data[$col['f']]) ? $data[$col['f']] : '';
$this->Cell($col['w'], 5, utf8_decode($dato), 1, 0, $alin, $fill);
//$this->Cell($col['w'],5,utf8_decode($data[$col['f']]),1,0,$alin,$fill);
//$this->Cell($col['w'],5,utf8_decode($data['proveedor']),1,0,$alin,$fill);
//$this->Write(5,"nombre=".$col['f'].",titulo=".$col['c'].",ancho=".$col['w'].",alin=".$col['a']);
//$this->Write(5,$data[$col['f']].$col['f']);
//print_r($data);
//print_r($this->aCols);
if ($col['t']=='S' && !$this->procesandoTotales) {
$this->totales[$col['f']]+=$data[$col['f']];
if ($col['t'] == 'S' && !$this->procesandoTotales) {
if (isset($this->totales[$col['f']])) {
$this->totales[$col['f']] += $data[$col['f']];
} else {
$this->totales[$col['f']] = $data[$col['f']];
}
}
}
$this->Ln();
$this->ColorIndex=1-$ci;
$this->ColorIndex = 1 - $ci;
}
function CalcWidths($width,$align)
public function CalcWidths($width, $align)
{
//Compute the widths of the columns
$TableWidth=0;
foreach($this->aCols as $i=>$col)
{
$w=$col['w'];
if($w==-1)
$w=$width/count($this->aCols);
elseif(substr($w,-1)=='%')
$w=$w/100*$width;
$this->aCols[$i]['w']=$w;
$TableWidth+=$w;
$TableWidth = 0;
foreach ($this->aCols as $i=>$col) {
$w = $col['w'];
if ($w == -1) {
$w = $width / count($this->aCols);
} elseif (substr($w, -1) == '%') {
$w = $w / 100 * $width;
}
$this->aCols[$i]['w'] = $w;
$TableWidth += $w;
}
//Compute the abscissa of the table
if($align=='C')
$this->TableX=max(($this->w-$TableWidth)/2,0);
elseif($align=='R')
$this->TableX=max($this->w-$this->rMargin-$TableWidth,0);
else
$this->TableX=$this->lMargin;
if ($align == 'C') {
$this->TableX = max(($this->w - $TableWidth) / 2, 0);
} elseif ($align == 'R') {
$this->TableX = max($this->w - $this->rMargin - $TableWidth, 0);
} else {
$this->TableX = $this->lMargin;
}
}
function AddCol($field=-1,$width=-1,$caption='',$align='I',$total='N')
public function AddCol($field = -1, $width = -1, $caption = '', $align = 'I', $total = 'N')
{
//Add a column to the table
if($field==-1)
$field=count($this->aCols);
$this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align,'t'=>$total);
if ($field == -1) {
$field = count($this->aCols);
}
$this->aCols[] = ['f'=>$field, 'c'=>$caption, 'w'=>$width, 'a'=>$align, 't'=>$total];
}
function Table($query,$prop=array())
public function Table($query, $prop = [])
{
//Issue query
$res=$this->bdd->query($query) or die('Error: '.$this->bdd->error."<BR>Query: $query");
$res = $this->bdd->query($query) or die('Error: '.$this->bdd->error."<BR>Query: $query");
//Add all columns if none was specified
if(count($this->aCols)==0)
{
$nb=$res->field_count;
for($i=0;$i<$nb;$i++)
if (count($this->aCols) == 0) {
$nb = $res->field_count;
for ($i = 0; $i < $nb; $i++) {
$this->AddCol();
}
}
//Retrieve column names when not specified
$i=0;
foreach($this->aCols as $i=>$col)
{
if($col['c']=='')
{
if(is_string($col['f']))
$this->aCols[$i]['c']=ucfirst($col['f']);
else
$this->aCols[$i]['c']=ucfirst($res->field_seek($i));
$i = 0;
foreach ($this->aCols as $i=>$col) {
if ($col['c'] == '') {
if (is_string($col['f'])) {
$this->aCols[$i]['c'] = ucfirst($col['f']);
} else {
$this->aCols[$i]['c'] = ucfirst($res->field_seek($i));
}
}
$i++;
}
//Handle properties
if(!isset($prop['width']))
$prop['width']=0;
if($prop['width']==0)
$prop['width']=$this->w-$this->lMargin-$this->rMargin;
if(!isset($prop['align']))
$prop['align']='C';
if(!isset($prop['padding']))
$prop['padding']=$this->cMargin;
$cMargin=$this->cMargin;
$this->cMargin=$prop['padding'];
if(!isset($prop['HeaderColor']))
$prop['HeaderColor']=array();
$this->HeaderColor=$prop['HeaderColor'];
if(!isset($prop['color1']))
$prop['color1']=array();
if(!isset($prop['color2']))
$prop['color2']=array();
$this->RowColors=array($prop['color1'],$prop['color2']);
if (!isset($prop['width'])) {
$prop['width'] = 0;
}
if ($prop['width'] == 0) {
$prop['width'] = $this->w - $this->lMargin - $this->rMargin;
}
if (!isset($prop['align'])) {
$prop['align'] = 'C';
}
if (!isset($prop['padding'])) {
$prop['padding'] = $this->cMargin;
}
$cMargin = $this->cMargin;
$this->cMargin = $prop['padding'];
if (!isset($prop['HeaderColor'])) {
$prop['HeaderColor'] = [];
}
$this->HeaderColor = $prop['HeaderColor'];
if (!isset($prop['color1'])) {
$prop['color1'] = [];
}
if (!isset($prop['color2'])) {
$prop['color2'] = [];
}
$this->RowColors = [$prop['color1'], $prop['color2']];
//Compute column widths
$this->CalcWidths($prop['width'],$prop['align']);
$this->CalcWidths($prop['width'], $prop['align']);
//Print header
$this->TableHeader();
//Print rows
$this->SetFont('Arial','',11);
$this->ColorIndex=0;
$this->ProcessingTable=true;
$this->procesandoTotales=false;
while($row=$res->fetch_assoc()) {
$this->SetFont('Arial', '', 11);
$this->ColorIndex = 0;
$this->ProcessingTable = true;
$this->procesandoTotales = false;
while ($row = $res->fetch_assoc()) {
$this->Row($row);
}
$this->procesandoTotales=true;
$this->procesandoTotales = true;
// Procesa los totales
if ($this->procesaTotales()) {
$this->Row($this->totales);
}
$this->ProcessingTable=false;
$this->cMargin=$cMargin;
$this->aCols=array();
$this->ProcessingTable = false;
$this->cMargin = $cMargin;
$this->aCols = [];
}
/**
* Se encarga de generar una línea de totalización si es necesario
* Se encarga de generar una línea de totalización si es necesario.
*
* @param array $datos Línea con los totales a imprimir o NULL
* @return boolean Si hay que generar la línea o no
*
* @return bool Si hay que generar la línea o no
*/
private function procesaTotales()
{
foreach($this->aCols as $col) {
if ($col['t']=='S') {
foreach ($this->aCols as $col) {
if ($col['t'] == 'S') {
return true;
}
}
return false;
}
}
?>

View File

@@ -1,4 +1,4 @@
# Inventario de Centro Educativo
# Inventario de Centro Educativo [![Project Stats](https://www.ohloh.net/p/inventario2/widgets/project_thin_badge.gif)](https://www.ohloh.net/p/inventario2)
Copyright (c) 2008-2014, Ricardo Montañana Gómez
Inventario2 is free software: you can redistribute it and/or modify
@@ -15,7 +15,9 @@ Utiliza:
[Manual de Usuario](http://rmontanana.gitbooks.io/inventario2/)
[Instalación de ejemplo](http://inventario2.rmontanana.es)
[Instalación de ejemplo](https://inventario.rmontanana.es)
[Estadísticas del proyecto](https://www.ohloh.net/p/inventario2)
##Instalación
Para instalar la aplicación basta con seguir estos pasos:
@@ -30,7 +32,8 @@ Para instalar la aplicación basta con seguir estos pasos:
###2. Crear un directorio temporal y dar derechos de escritura a los ficheros de configuración.
mkdir tmp
chown apache tmp
mkdir img.data
chown apache tmp img.data
chown apache inc/configuracion.inc
chown apache inc

240
Sql.php
View File

@@ -1,82 +1,89 @@
<?php
/**
* Gestión de una base de datos MySQL
* @author Ricardo Montañana <rmontanana@gmail.com>
* @version 1.0
* @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 Sql {
/**
* Gestión de una base de datos MySQL.
*
* @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0
*
* @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 Sql
{
/**
* @var mixed Manejador de la base de datos.
*/
private $bdd=NULL;
private $bdd = null;
/**
* @var string Mensaje del último mensaje de error generado
*/
private $mensajeError='';
private $mensajeError = '';
/**
* @var boolean Almacena el estado de error o no de la última acción.
* @var bool Almacena el estado de error o no de la última acción.
*/
private $error=false;
private $error = false;
/**
* @var boolean Estado de la conexión con la base de datos.
* @var bool Estado de la conexión con la base de datos.
*/
private $estado=false;
private $estado = false;
/**
* @var mixed Objeto que alberga la última consulta ejecutada.
*/
private $peticion=NULL;
private $peticion = null;
/**
* @var integer Número de tuplas afectadas en la última consulta.
* @var int Número de tuplas afectadas en la última consulta.
*/
private $numero=0;
private $numero = 0;
/**
* @var string vector de cadenas con los resultados de la petición.
*/
private $datos=array();
private $datos = [];
/**
* Id del último registro insertado
* @var integer mysql_
* Id del último registro insertado.
*
* @var int mysql_
*/
private $id;
/**
* Crea un objeto Sql y conecta con la Base de Datos.
*
* @param string $servidor
* @param string $usuario
* @param string $baseDatos
*/
public function __construct($servidor,$usuario,$clave,$baseDatos)
public function __construct($servidor, $usuario, $clave, $baseDatos)
{
$this->bdd = @new mysqli($servidor,$usuario,$clave,$baseDatos);
$this->bdd = @new mysqli($servidor, $usuario, $clave, $baseDatos);
if (mysqli_connect_errno()) {
$this->mensajeError='<h1>Fallo al conectar con el servidor MySQL.</h1>';
$this->mensajeError.="Servidor [".$servidor ."] base de datos [".$baseDatos."]";
$this->error=true;
$this->estado=false;
$this->mensajeError = '<h1>Fallo al conectar con el servidor MySQL.</h1>';
$this->mensajeError .= 'Servidor ['.$servidor.'] base de datos ['.$baseDatos.']';
$this->error = true;
$this->estado = false;
} else {
$this->mensajeError='';
$this->error=false;
$this->estado=true;
$this->mensajeError = '';
$this->error = false;
$this->estado = true;
}
$this->peticion=NULL;
$this->peticion = null;
return $this;
}
public function __destruct()
{
//Libera la memoria de una posible consulta.
@@ -88,103 +95,132 @@ class Sql {
$this->bdd->close();
}
}
public function filtra($cadena)
public function filtra($cadena)
{
return $this->bdd->real_escape_string($cadena);
return $this->bdd->real_escape_string($cadena);
}
public function ejecuta($comando)
{
if (!$this->estado) {
$this->error=true;
$this->mensajeError='No est&aacute; conectado';
$this->error = true;
$this->mensajeError = 'No est&aacute; conectado';
return false;
}
if (!$this->peticion=$this->bdd->query($comando)) {
$this->error=true;
$this->mensajeError='No pudo ejecutar la petici&oacute;n: '.$comando;
if (!$this->peticion = $this->bdd->query($comando)) {
$this->error = true;
$this->mensajeError = 'No pudo ejecutar la petici&oacute;n: '.$comando;
return false;
}
$this->numero=$this->bdd->affected_rows;
$this->id=$this->bdd->insert_id;
$this->error=false;
$this->mensajeError='';
$this->numero = $this->bdd->affected_rows;
$this->id = $this->bdd->insert_id;
$this->error = false;
$this->mensajeError = '';
return true;
}
public function procesaResultado()
{
if (!$this->estado) {
$this->error=true;
$this->mensajeError='No está conectado a una base de datos';
return NULL;
$this->error = true;
$this->mensajeError = 'No está conectado a una base de datos';
return;
}
if (!$this->peticion) {
$this->error=true;
$this->mensajeError='No hay un resultado disponible';
return NULL;
$this->error = true;
$this->mensajeError = 'No hay un resultado disponible';
return;
}
$datos=$this->peticion->fetch_assoc();
$this->error=false;
$this->mensajeError='';
return ($datos);
$datos = $this->peticion->fetch_assoc();
$this->error = false;
$this->mensajeError = '';
return $datos;
}
public function camposResultado()
public function camposResultado()
{
if (!$this->estado) {
$this->error=true;
$this->mensajeError='No está conectado a una base de datos';
return NULL;
$this->error = true;
$this->mensajeError = 'No está conectado a una base de datos';
return;
}
if (!$this->peticion) {
$this->error=true;
$this->mensajeError='No hay un resultado disponible';
return NULL;
$this->error = true;
$this->mensajeError = 'No hay un resultado disponible';
return;
}
$datos=$this->peticion->fetch_field();
$this->error=false;
$this->mensajeError='';
return ($datos);
$datos = $this->peticion->fetch_field();
$this->error = false;
$this->mensajeError = '';
return $datos;
}
/**
/**
* Devuelve el número de tuplas afectadas en la última petición.
* @return integer Número de tuplas.
*
* @return int Número de tuplas.
*/
public function numeroTuplas() {
public function numeroTuplas()
{
return $this->numero;
}
/**
* Devuelve el número de tuplas total si se ha hecho una consulta select
* con SELECT SQL_CALC_FOUND_ROWS * ...
* @return integer Número de tuplas.
*
* @return int Número de tuplas.
*/
public function numeroTotalTuplas()
public function numeroTotalTuplas()
{
$comando = "select found_rows();";
if (!$peticion=$this->bdd->query($comando)) {
$this->error=true;
$this->mensajeError='No pudo ejecutar la petici&oacute;n: '.$comando;
$comando = 'select found_rows();';
if (!$peticion = $this->bdd->query($comando)) {
$this->error = true;
$this->mensajeError = 'No pudo ejecutar la petici&oacute;n: '.$comando;
return false;
}
$numero = $peticion->fetch_row();
return $numero[0] ;
return $numero[0];
}
/**
* Devuelve la condición de error de la última petición
* @return boolean condición de error.
* Devuelve la condición de error de la última petición.
*
* @return bool condición de error.
*/
public function error() {
public function error()
{
return $this->error;
}
/**
* Devuelve el mensaje de error de la última petición
* Devuelve el mensaje de error de la última petición.
*
* @return <type>
*/
public function mensajeError() {
public function mensajeError()
{
return $this->mensajeError.$this->bdd->error;
}
/**
* Devuelve la estructura de campos de una tabla.
*
* @param string $tabla Nombre de la tabla.
*
* @return string vector asociativo con la descripción de la tabla [campo]->valor
*/
public function estructura($tabla)
@@ -192,40 +228,46 @@ class Sql {
if ($this->peticion) {
$this->peticion->free_result();
}
$comando="show full columns from $tabla";
$comando = "show full columns from $tabla";
if (!$this->ejecuta($comando)) {
return false;
}
while ($dato=$this->procesaResultado()) {
$salida[]=$dato;
while ($dato = $this->procesaResultado()) {
$salida[] = $dato;
}
return $salida;
}
public function ultimoId()
{
return $this->id;
}
public function obtieneManejador()
{
return $this->bdd;
}
public function comienzaTransaccion()
{
return $this->bdd->autocommit(false);
}
public function abortaTransaccion()
{
$codigo = $this->bdd->rollback();
$this->bdd->autocommit(true);
return $codigo;
return $codigo;
}
public function confirmaTransaccion()
{
$codigo = $this->bdd->commit();
$this->bdd->autocommit(true);
$this->peticion = null;
return $codigo;
}
}
?>

View File

@@ -37,14 +37,14 @@ ini_set('gd.jpeg_ignore_warning', true);
* For more resources visit {@link http://stefangabos.ro/}
*
* @author Stefan Gabos <contact@stefangabos.ro>
*
* @version 2.2.3 (last revision: July 14, 2013)
*
* @copyright (c) 2006 - 2013 Stefan Gabos
* @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LESSER GENERAL PUBLIC LICENSE
* @package Zebra_Image
*/
class Zebra_Image
{
/**
* Indicates the file system permissions to be set for newly created images.
*
@@ -64,9 +64,9 @@ class Zebra_Image
*
* Default is 0755
*
* @var integer
* @var int
*/
var $chmod_value;
public $chmod_value;
/**
* If set to FALSE, images having both width and height smaller than the required width and height, will be left
@@ -76,9 +76,9 @@ class Zebra_Image
*
* Default is TRUE
*
* @var boolean
* @var bool
*/
var $enlarge_smaller_images;
public $enlarge_smaller_images;
/**
* In case of an error read this property's value to see the error's code.
@@ -96,9 +96,9 @@ class Zebra_Image
*
* Default is 0 (no error).
*
* @var integer
* @var int
*/
var $error;
public $error;
/**
* Indicates the quality of the output image (better quality means bigger file size).
@@ -109,9 +109,9 @@ class Zebra_Image
*
* Default is 85
*
* @var integer
* @var int
*/
var $jpeg_quality;
public $jpeg_quality;
/**
* Indicates the compression level of the output image (lower compression means bigger file size).
@@ -125,9 +125,9 @@ class Zebra_Image
*
* @since 2.2
*
* @var integer
* @var int
*/
var $png_compression;
public $png_compression;
/**
* Specifies whether, upon resizing, images should preserve their aspect ratio.
@@ -136,9 +136,9 @@ class Zebra_Image
*
* Default is TRUE
*
* @var boolean
* @var bool
*/
var $preserve_aspect_ratio;
public $preserve_aspect_ratio;
/**
* Indicates whether a target files should preserve the source file's date/time.
@@ -147,9 +147,9 @@ class Zebra_Image
*
* @since 1.0.4
*
* @var boolean
* @var bool
*/
var $preserve_time;
public $preserve_time;
/**
* Indicates whether the target image should have a "sharpen" filter applied to it.
@@ -163,9 +163,9 @@ class Zebra_Image
*
* @since 2.2
*
* @var boolean
* @var bool
*/
var $sharpen_images;
public $sharpen_images;
/**
* Path to an image file to apply the transformations to.
@@ -174,7 +174,7 @@ class Zebra_Image
*
* @var string
*/
var $source_path;
public $source_path;
/**
* Path (including file name) to where to save the transformed image.
@@ -184,7 +184,7 @@ class Zebra_Image
*
* @var string
*/
var $target_path;
public $target_path;
/**
* Constructor of the class.
@@ -193,7 +193,7 @@ class Zebra_Image
*
* @return void
*/
function Zebra_Image()
public function Zebra_Image()
{
// set default values for properties
@@ -210,7 +210,6 @@ class Zebra_Image
$this->sharpen_images = false;
$this->source_path = $this->target_path = '';
}
/**
@@ -292,21 +291,17 @@ class Zebra_Image
* others weight of 1.0. the result is normalized by dividing
* the sum with <b>arg1</b> + 8.0 (sum of the matrix).
* any float is accepted;
*
* @param mixed $arg1 Used by the following filters:
* - <b>brightness</b> - sets the brightness level (-255 to 255)
* - <b>contrast</b> - sets the contrast level (-100 to 100)
* - <b>colorize</b> - sets the value of the red component (-255 to 255)
* - <b>smooth</b> - sets the smoothness level
* - <b>pixelate</b> - sets the block size, in pixels
*
* @param mixed $arg2 Used by the following filters:
* - <b>colorize</b> - sets the value of the green component (-255 to 255)
* - <b>pixelate</b> - whether to use advanced pixelation effect or not (defaults to FALSE).
*
* @param mixed $arg3 Used by the following filters:
* - <b>colorize</b> - sets the value of the blue component (-255 to 255)
*
* @param mixed $arg4 Used by the following filters:
* - <b>colorize</b> - alpha channel; a value between 0 and 127. 0 indicates
* completely opaque while 127 indicates completely
@@ -314,7 +309,7 @@ class Zebra_Image
*
* @since 2.2.2
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If {@link http://php.net/manual/en/function.imagefilter.php imagefilter} is not
* available the method will return FALSE without setting an {@link error} code.
@@ -326,11 +321,11 @@ class Zebra_Image
* {@link http://php.net/manual/en/function.imagefilter.php imagefilter} exists and that
* the requested filter is valid, check the {@link error} property to see the error code.
*/
function apply_filter($filter, $arg1 = '', $arg2 = '', $arg3 = '', $arg4 = '')
public function apply_filter($filter, $arg1 = '', $arg2 = '', $arg3 = '', $arg4 = '')
{
// if "imagefilter" function exists and the requested filter exists
if (function_exists('imagefilter'))
if (function_exists('imagefilter')) {
// if image resource was successfully created
if ($this->_create_from_source()) {
@@ -358,45 +353,51 @@ class Zebra_Image
if (is_array($filter)) {
// iterate through the filters
foreach ($filter as $arguments)
foreach ($filter as $arguments) {
// if filter exists
if (defined('IMG_FILTER_' . strtoupper($arguments[0]))) {
if (defined('IMG_FILTER_'.strtoupper($arguments[0]))) {
// try to apply the filter...
if (!@call_user_func_array('imagefilter', array_merge(array($target_identifier, constant('IMG_FILTER_' . strtoupper($arguments[0]))), array_slice($arguments, 1))))
if (!@call_user_func_array('imagefilter', array_merge([$target_identifier, constant('IMG_FILTER_'.strtoupper($arguments[0]))], array_slice($arguments, 1)))) {
// ...and trigger an error if the filter could not be applied
trigger_error('Invalid arguments used for "' . strtoupper($arguments[0]) . '" filter', E_USER_WARNING);
trigger_error('Invalid arguments used for "'.strtoupper($arguments[0]).'" filter', E_USER_WARNING);
}
// if filter doesn't exists, trigger an error
} else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
// if filter doesn't exists, trigger an error
} else {
trigger_error('Filter "'.strtoupper($arguments[0]).'" is not available', E_USER_WARNING);
}
}
// if a single filter is to be applied and it is available
} elseif (defined('IMG_FILTER_' . strtoupper($filter))) {
// if a single filter is to be applied and it is available
} elseif (defined('IMG_FILTER_'.strtoupper($filter))) {
// get all the arguments passed to the method
$arguments = func_get_args();
// try to apply the filter...
if (!@call_user_func_array('imagefilter', array_merge(array($target_identifier, constant('IMG_FILTER_' . strtoupper($filter))), array_slice($arguments, 1))))
if (!@call_user_func_array('imagefilter', array_merge([$target_identifier, constant('IMG_FILTER_'.strtoupper($filter))], array_slice($arguments, 1)))) {
// ...and trigger an error if the filter could not be applied
trigger_error('Invalid arguments used for "' . strtoupper($arguments[0]) . '" filter', E_USER_WARNING);
trigger_error('Invalid arguments used for "'.strtoupper($arguments[0]).'" filter', E_USER_WARNING);
}
// if filter doesn't exists, trigger an error
} else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
// if filter doesn't exists, trigger an error
} else {
trigger_error('Filter "'.strtoupper($arguments[0]).'" is not available', E_USER_WARNING);
}
// write image
return $this->_write_image($target_identifier);
}
}
// if script gets this far, return false
// note that we do not set the error level as it has been already set
// by the _create_from_source() method earlier, if the case
return false;
}
/**
@@ -421,21 +422,18 @@ class Zebra_Image
* $img->crop(0, 0, 100, 100);
* </code>
*
* @param integer $start_x x coordinate to start cropping from
*
* @param integer $start_y y coordinate to start cropping from
*
* @param integer $end_x x coordinate where to end the cropping
*
* @param integer $end_y y coordinate where to end the cropping
* @param int $start_x x coordinate to start cropping from
* @param int $start_y y coordinate to start cropping from
* @param int $end_x x coordinate where to end the cropping
* @param int $end_y y coordinate where to end the cropping
*
* @since 1.0.4
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*/
function crop($start_x, $start_y, $end_x, $end_y)
public function crop($start_x, $start_y, $end_x, $end_y)
{
// this method might be also called internally
@@ -453,7 +451,9 @@ class Zebra_Image
// if method is called as usually
// try to create an image resource from source path
} else $result = $this->_create_from_source();
} else {
$result = $this->_create_from_source();
}
// if image resource was successfully created
if ($result !== false) {
@@ -479,19 +479,17 @@ class Zebra_Image
// write image
return $this->_write_image($target_identifier);
}
// if script gets this far, return false
// note that we do not set the error level as it has been already set
// by the _create_from_source() method earlier
return false;
}
/**
* Flips both horizontally and vertically the image given as {@link source_path} and outputs the resulted image as
* {@link target_path}
* {@link target_path}.
*
* <code>
* // include the Zebra_Image library
@@ -514,19 +512,17 @@ class Zebra_Image
*
* @since 2.1
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*/
function flip_both()
public function flip_both()
{
return $this->_flip('both');
}
/**
* Flips horizontally the image given as {@link source_path} and outputs the resulted image as {@link target_path}
* Flips horizontally the image given as {@link source_path} and outputs the resulted image as {@link target_path}.
*
* <code>
* // include the Zebra_Image library
@@ -547,19 +543,17 @@ class Zebra_Image
* $img->flip_horizontal();
* </code>
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*/
function flip_horizontal()
public function flip_horizontal()
{
return $this->_flip('horizontal');
}
/**
* Flips vertically the image given as {@link source_path} and outputs the resulted image as {@link target_path}
* Flips vertically the image given as {@link source_path} and outputs the resulted image as {@link target_path}.
*
* <code>
* // include the Zebra_Image library
@@ -580,15 +574,13 @@ class Zebra_Image
* $img->flip_vertical();
* </code>
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*/
function flip_vertical()
public function flip_vertical()
{
return $this->_flip('vertical');
}
/**
@@ -616,7 +608,7 @@ class Zebra_Image
* $img->resize(150, 150, ZEBRA_IMAGE_CROP_CENTER);
* </code>
*
* @param integer $width The width to resize the image to.
* @param int $width The width to resize the image to.
*
* If set to <b>0</b>, the width will be automatically adjusted, depending
* on the value of the <b>height</b> argument so that the image preserves
@@ -638,8 +630,7 @@ class Zebra_Image
* If either <b>width</b> or <b>height</b> are set to <b>0</b>, the script
* will consider the value of the {@link preserve_aspect_ratio} to bet set
* to TRUE regardless of its actual value!
*
* @param integer $height The height to resize the image to.
* @param int $height The height to resize the image to.
*
* If set to <b>0</b>, the height will be automatically adjusted, depending
* on the value of the <b>width</b> argument so that the image preserves
@@ -661,7 +652,6 @@ class Zebra_Image
* If either <b>height</b> or <b>width</b> are set to <b>0</b>, the script
* will consider the value of the {@link preserve_aspect_ratio} to bet set
* to TRUE regardless of its actual value!
*
* @param int $method (Optional) Method to use when resizing images to exact width and height
* while preserving aspect ratio.
*
@@ -698,7 +688,6 @@ class Zebra_Image
* indicated region of the resulted image.
*
* Default is ZEBRA_IMAGE_CROP_CENTER
*
* @param hexadecimal $background_color (Optional) The hexadecimal color (like "#FFFFFF" or "#FFF") of the
* blank area. See the <b>method</b> argument.
*
@@ -708,12 +697,12 @@ class Zebra_Image
*
* Default is #FFFFFF.
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see what went
* wrong
*/
function resize($width = 0, $height = 0, $method = ZEBRA_IMAGE_CROP_CENTER, $background_color = '#FFFFFF')
public function resize($width = 0, $height = 0, $method = ZEBRA_IMAGE_CROP_CENTER, $background_color = '#FFFFFF')
{
// if image resource was successfully created
@@ -722,7 +711,9 @@ class Zebra_Image
// if either width or height is to be adjusted automatically
// set a flag telling the script that, even if $preserve_aspect_ratio is set to false
// treat everything as if it was set to true
if ($width == 0 || $height == 0) $auto_preserve_aspect_ratio = true;
if ($width == 0 || $height == 0) {
$auto_preserve_aspect_ratio = true;
}
// if aspect ratio needs to be preserved
if ($this->preserve_aspect_ratio || isset($auto_preserve_aspect_ratio)) {
@@ -775,15 +766,14 @@ class Zebra_Image
// compute the target image's width so that the image will stay inside the bounding box
$target_width = round($vertical_aspect_ratio * $this->source_width);
}
// if both width and height are given and image is to be cropped in order to get to the required size
// if both width and height are given and image is to be cropped in order to get to the required size
} elseif ($width > 0 && $height > 0 && $method > 1 && $method < 11) {
// compute the horizontal and vertical aspect ratios
$vertical_aspect_ratio = $this->source_height / $height;
$horizontal_aspect_ratio = $this->source_width / $width;
$horizontal_aspect_ratio = $this->source_width / $width;
// we'll use one of the two
$aspect_ratio =
@@ -806,10 +796,9 @@ class Zebra_Image
// we will create a copy of the source image
$target_width = $this->source_width;
$target_height = $this->source_height;
}
// if aspect ratio does not need to be preserved
// if aspect ratio does not need to be preserved
} else {
// compute the target image's width
@@ -817,7 +806,6 @@ class Zebra_Image
// compute the target image's height
$target_height = ($height > 0 ? $height : $this->source_height);
}
// if
@@ -1013,7 +1001,7 @@ class Zebra_Image
}
// if aspect ratio doesn't need to be preserved or
// if aspect ratio doesn't need to be preserved or
// it needs to be preserved and method is ZEBRA_IMAGE_BOXED or ZEBRA_IMAGE_NOT_BOXED
} else {
@@ -1041,21 +1029,20 @@ class Zebra_Image
// if script gets this far, write the image to disk
return $this->_write_image($target_identifier);
}
// if we get here it means that
// if we get here it means that
// smaller images than the given width/height are to be left untouched
// therefore, we save the image as it is
} else return $this->_write_image($this->source_identifier);
} else {
return $this->_write_image($this->source_identifier);
}
}
// if script gets this far return false
// note that we do not set the error level as it has been already set
// by the _create_from_source() method earlier
return false;
}
/**
@@ -1080,10 +1067,9 @@ class Zebra_Image
* $img->rotate(45);
* </code>
*
* @param double $angle Angle by which to rotate the image clockwise.
* @param float $angle Angle by which to rotate the image clockwise.
*
* Between 0 and 360.
*
* @param mixed $background_color (Optional) The hexadecimal color (like "#FFFFFF" or "#FFF") of the
* uncovered zone after the rotation.
*
@@ -1093,12 +1079,12 @@ class Zebra_Image
*
* Default is -1.
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error
* code.
*/
function rotate($angle, $background_color = -1)
public function rotate($angle, $background_color = -1)
{
// if image resource was successfully created
@@ -1119,10 +1105,9 @@ class Zebra_Image
// rotate the image
$target_identifier = imagerotate($this->source_identifier, $angle, $background_color);
}
// if source image is a transparent GIF
// if source image is a transparent GIF
} elseif ($this->source_type == IMAGETYPE_GIF && $this->source_transparent_color_index >= 0) {
// convert the background color to RGB values
@@ -1172,28 +1157,23 @@ class Zebra_Image
// rotate the image
$target_identifier = imagerotate($this->source_identifier, $angle, $background_color);
}
// write image
$this->_write_image($target_identifier);
}
// if script gets this far return false
// note that we do not set the error level as it has been already set
// by the _create_from_source() method earlier
return false;
return false;
}
/**
* Returns an array containing the image identifier representing the image obtained from {@link $source_path}, the
* image's width and height and the image's type
*
* @access private
* image's width and height and the image's type.
*/
function _create_from_source()
public function _create_from_source()
{
// perform some error checking first
@@ -1255,13 +1235,14 @@ class Zebra_Image
$identifier = imagecreatefromgif($this->source_path);
// get the index of the transparent color (if any)
if (($this->source_transparent_color_index = imagecolortransparent($identifier)) >= 0)
if (($this->source_transparent_color_index = imagecolortransparent($identifier)) >= 0) {
// get the transparent color's RGB values
// we have to mute errors because there are GIF images which *are* transparent and everything
// works as expected, but imagecolortransparent() returns a color that is outside the range of
// colors in the image's pallette...
$this->source_transparent_color = @imagecolorsforindex($identifier, $this->source_transparent_color_index);
}
break;
@@ -1294,18 +1275,18 @@ class Zebra_Image
return false;
}
}
// if target file has to have the same timestamp as the source image
// save it as a global property of the class
if ($this->preserve_time) $this->source_image_time = filemtime($this->source_path);
if ($this->preserve_time) {
$this->source_image_time = filemtime($this->source_path);
}
// make available the source image's identifier
$this->source_identifier = $identifier;
return true;
}
/**
@@ -1314,50 +1295,48 @@ class Zebra_Image
* The RGB values will be a value between 0 and 255 each.
*
* @param string $color Hexadecimal representation of a color (i.e. #123456 or #AAA).
*
* @param string $default_on_error Hexadecimal representation of a color to be used in case $color is not
* recognized as a hexadecimal color.
*
* @return array Returns an associative array with the values of (R)ed, (G)reen and (B)lue
*
* @access private
*/
function _hex2rgb($color, $default_on_error = '#FFFFFF')
public function _hex2rgb($color, $default_on_error = '#FFFFFF')
{
// if color is not formatted correctly
// use the default color
if (preg_match('/^#?([a-f]|[0-9]){3}(([a-f]|[0-9]){3})?$/i', $color) == 0) $color = $default_on_error;
if (preg_match('/^#?([a-f]|[0-9]){3}(([a-f]|[0-9]){3})?$/i', $color) == 0) {
$color = $default_on_error;
}
// trim off the "#" prefix from $background_color
$color = ltrim($color, '#');
// if color is given using the shorthand (i.e. "FFF" instead of "FFFFFF")
if (strlen($color) == 3) {
$tmp = '';
// take each value
// and duplicate it
for ($i = 0; $i < 3; $i++) $tmp .= str_repeat($color[$i], 2);
for ($i = 0; $i < 3; $i++) {
$tmp .= str_repeat($color[$i], 2);
}
// the color in it's full, 6 characters length notation
$color = $tmp;
}
// decimal representation of the color
$int = hexdec($color);
// extract and return the RGB values
return array(
return [
'r' => 0xFF & ($int >> 0x10),
'g' => 0xFF & ($int >> 0x8),
'b' => 0xFF & $int
);
'r' => 0xFF & ($int >> 0x10),
'g' => 0xFF & ($int >> 0x8),
'b' => 0xFF & $int
];
}
/**
@@ -1365,13 +1344,11 @@ class Zebra_Image
*
* @since 2.1
*
* @access private
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*/
function _flip($orientation)
public function _flip($orientation)
{
// if image resource was successfully created
@@ -1444,23 +1421,19 @@ class Zebra_Image
// write image
return $this->_write_image($target_identifier);
}
// if script gets this far, return false
// note that we do not set the error level as it has been already set
// by the _create_from_source() method earlier
return false;
}
/**
* Creates a blank image of given width, height and background color.
*
* @param integer $width Width of the new image.
*
* @param integer $height Height of the new image.
*
* @param int $width Width of the new image.
* @param int $height Height of the new image.
* @param string $background_color (Optional) The hexadecimal color of the background.
*
* Can also be -1 case in which the script will try to create a transparent
@@ -1469,14 +1442,12 @@ class Zebra_Image
* Default is "#FFFFFF".
*
* @return Returns the identifier of the newly created image.
*
* @access private
*/
function _prepare_image($width, $height, $background_color = '#FFFFFF')
public function _prepare_image($width, $height, $background_color = '#FFFFFF')
{
// create a blank image
$identifier = imagecreatetruecolor((int)$width <= 0 ? 1 : (int)$width, (int)$height <= 0 ? 1 : (int)$height);
$identifier = imagecreatetruecolor((int) $width <= 0 ? 1 : (int) $width, (int) $height <= 0 ? 1 : (int) $height);
// if we are creating a PNG image
if ($this->target_type == 'png' && $background_color == -1) {
@@ -1488,10 +1459,10 @@ class Zebra_Image
$transparent_color = imagecolorallocatealpha($identifier, 0, 0, 0, 127);
// fill the image with the transparent color
imagefill($identifier, 0, 0, $transparent_color);
imagefill($identifier, 0, 0, $transparent_color);
//save full alpha channel information
imagesavealpha($identifier, true);
imagesavealpha($identifier, true);
// if source image is a transparent GIF
} elseif ($this->target_type == 'gif' && $background_color == -1 && $this->source_transparent_color_index >= 0) {
@@ -1514,7 +1485,9 @@ class Zebra_Image
} else {
// if transparent background color specified, revert to white
if ($background_color == -1) $background_color = '#FFFFFF';
if ($background_color == -1) {
$background_color = '#FFFFFF';
}
// convert hex color to rgb
$background_color = $this->_hex2rgb($background_color);
@@ -1524,12 +1497,10 @@ class Zebra_Image
// fill the image with the background color
imagefill($identifier, 0, 0, $background_color);
}
// return the image's identifier
return $identifier;
}
/**
@@ -1541,10 +1512,8 @@ class Zebra_Image
* versions!</i>
*
* @param $identifier identifier An image identifier
*
* @access private
*/
function _sharpen_image($image)
public function _sharpen_image($image)
{
// if the "sharpen_images" is set to true and we're running an appropriate version of PHP
@@ -1552,11 +1521,11 @@ class Zebra_Image
if ($this->sharpen_images && version_compare(PHP_VERSION, '5.1.0') >= 0) {
// the convolution matrix as an array of three arrays of three floats
$matrix = array(
array(-1.2, -1, -1.2),
array(-1, 20, -1),
array(-1.2, -1, -1.2),
);
$matrix = [
[-1.2, -1, -1.2],
[-1, 20, -1],
[-1.2, -1, -1.2],
];
// the divisor of the matrix
$divisor = array_sum(array_map('array_sum', $matrix));
@@ -1566,12 +1535,10 @@ class Zebra_Image
// sharpen image
imageconvolution($image, $matrix, $divisor, $offset);
}
// return the image's identifier
return $image;
}
/**
@@ -1579,13 +1546,11 @@ class Zebra_Image
*
* @param $identifier identifier An image identifier
*
* @return boolean Returns TRUE on success or FALSE on error.
* @return bool Returns TRUE on success or FALSE on error.
*
* If FALSE is returned, check the {@link error} property to see the error code.
*
* @access private
*/
function _write_image($identifier)
public function _write_image($identifier)
{
// sharpen image if it's required
@@ -1614,7 +1579,6 @@ class Zebra_Image
$this->error = 3;
return false;
}
break;
@@ -1638,7 +1602,6 @@ class Zebra_Image
$this->error = 3;
return false;
}
break;
@@ -1664,7 +1627,6 @@ class Zebra_Image
$this->error = 3;
return false;
}
break;
@@ -1689,19 +1651,18 @@ class Zebra_Image
chmod($this->target_path, intval($this->chmod_value, 8));
// save the error level
} else $this->error = 8;
} else {
$this->error = 8;
}
// if target file has to have the same timestamp as the source image
if ($this->preserve_time && isset($this->source_image_time)) {
// touch the newly created file
@touch($this->target_path, $this->source_image_time);
}
// return true
return true;
}
}

View File

@@ -1,6 +1,6 @@
<?php
include('../inc/configuracion.inc');
header("Content-type: text/css");
include '../inc/configuracion.inc';
header('Content-type: text/css');
?>
/*
* Base structure

BIN
img/bluecurve/clonar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 560 B

BIN
img/clonar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

BIN
img/cristal/clonar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 635 B

BIN
img/personal/clonar.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 642 B

View File

@@ -23,5 +23,5 @@
*/
define('AUTOR', 'Ricardo Montañana Gómez');
define('VERSION', '1.14.1');
define('VERSION', '1.17');
?>

View File

@@ -1,9 +1,11 @@
<?php
/**
/**
* Genera una instancia de la aplicación y la ejecuta.
*
* @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0
* @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.
@@ -11,23 +13,23 @@
* 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/>.
*
*/
//Se incluyen los módulos necesarios
function __autoload($class_name) {
require_once $class_name . '.php';
function __autoload($class_name)
{
require_once $class_name.'.php';
}
include('inc/configuracion.inc');
include 'inc/configuracion.inc';
$aplicacion=new Inventario();
if ($aplicacion->estado())
$aplicacion = new Inventario();
if ($aplicacion->estado()) {
$aplicacion->Ejecuta();
?>
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
<?php
/**
* Migra los datos de la versión anterior de Inventario a la actual.
* @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.
@@ -9,81 +9,84 @@
* 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/>.
*
*/
$host="localhost";
$baseAnt="Inventario";
$baseNueva="Inventario2";
$usuario="test";
$claveUsuario="tset";
$probar=false;
$host = 'localhost';
$baseAnt = 'Inventario';
$baseNueva = 'Inventario2';
$usuario = 'test';
$claveUsuario = 'tset';
$probar = false;
// No se debería modificar nada después de este comentario
function creaUbicacion($bd1,$bd2,$clave)
function creaUbicacion($bd1, $bd2, $clave)
{
global $probar;
$comando="select nombre from Ubicaciones where codigo=".$clave.";";
$resultado=$bd1->query($comando);
if ($bd1->affected_rows==0) {
$comando = 'select nombre from Ubicaciones where codigo='.$clave.';';
$resultado = $bd1->query($comando);
if ($bd1->affected_rows == 0) {
echo $comando;
die("No encontró la ubicación ".$clave);
die('No encontró la ubicación '.$clave);
}
$dato=$resultado->fetch_assoc();
$valor=$dato['nombre'];
$comando="insert into Ubicaciones values (NULL,'".$valor."');";
$dato = $resultado->fetch_assoc();
$valor = $dato['nombre'];
$comando = "insert into Ubicaciones values (NULL,'".$valor."');";
if ($probar) {
echo $comando;
return 1;
} else {
$test=$bd2->query($comando);
$test = $bd2->query($comando);
if (!$test) {
die("**No pudo insertar ubicacion.".$comando);
die('**No pudo insertar ubicacion.'.$comando);
}
return $bd2->insert_id;
}
}
}
function creaArticulo($bd1,$bd2,$clave)
function creaArticulo($bd1, $bd2, $clave)
{
global $probar;
$comando="select * from Articulos where codigo='".$clave."';";
$resultado=$bd1->query($comando);
if ($bd1->affected_rows==0) {
$comando = "select * from Articulos where codigo='".$clave."';";
$resultado = $bd1->query($comando);
if ($bd1->affected_rows == 0) {
echo $comando;
die("No encontró el artículo ".$clave);
die('No encontró el artículo '.$clave);
}
$dato=$resultado->fetch_assoc();
$valor1=$dato['descripcion'];
$valor2=$dato['marca'];
$valor3=$dato['modelo'];
$valor4=$dato['cantidad'];
$comando="insert into Articulos values (NULL,'".$valor1."','".$valor2."','".$valor3."',".$valor4.");";
$dato = $resultado->fetch_assoc();
$valor1 = $dato['descripcion'];
$valor2 = $dato['marca'];
$valor3 = $dato['modelo'];
$valor4 = $dato['cantidad'];
$comando = "insert into Articulos values (NULL,'".$valor1."','".$valor2."','".$valor3."',".$valor4.');';
if ($probar) {
echo $comando;
return 1;
} else {
$test=$bd2->query($comando);
$test = $bd2->query($comando);
if (!$test) {
die("**No pudo insertar artículo.".$comando);
die('**No pudo insertar artículo.'.$comando);
}
return $bd2->insert_id;
}
}
function generaSesion()
{
$long=10;
$cadena="";
for ($i=0;$i<$long;$i++) {
$cadena.=chr(rand(40,126));
$long = 10;
$cadena = '';
for ($i = 0; $i < $long; $i++) {
$cadena .= chr(rand(40, 126));
}
return $cadena;
}
/*
@@ -91,64 +94,64 @@ function generaSesion()
* Comienzo del programa principal.
*
*/
$bd1=new mysqli($host,$usuario,$claveUsuario,$baseAnt);
if(mysqli_connect_errno()) {
die("**Error conectando a la base de datos antigua.".$bd1->error);
$bd1 = new mysqli($host, $usuario, $claveUsuario, $baseAnt);
if (mysqli_connect_errno()) {
die('**Error conectando a la base de datos antigua.'.$bd1->error);
}
$bd2=new mysqli($host,$usuario,$claveUsuario,$baseNueva);
if(mysqli_connect_errno()) {
die("**Error conectando a la base de datos nueva.".$bd2->error);
$bd2 = new mysqli($host, $usuario, $claveUsuario, $baseNueva);
if (mysqli_connect_errno()) {
die('**Error conectando a la base de datos nueva.'.$bd2->error);
}
$bd2->autocommit(false);
$datos=$bd1->query("select * from Elementos;");
$datos = $bd1->query('select * from Elementos;');
if (!$datos) {
die("**No encontró datos en la tabla de elementos.");
die('**No encontró datos en la tabla de elementos.');
}
$numRegistros=$bd1->affected_rows;
$contador=0;
$ubicaciones=array();
$articulos=array();
echo "++Comenzando proceso de actualización de Elementos con ".$numRegistros." registros por procesar.<br>\n";
while($fila=$datos->fetch_assoc()) {
$numRegistros = $bd1->affected_rows;
$contador = 0;
$ubicaciones = [];
$articulos = [];
echo '++Comenzando proceso de actualización de Elementos con '.$numRegistros." registros por procesar.<br>\n";
while ($fila = $datos->fetch_assoc()) {
$contador++;
echo "Procesando registro ".$contador." de ".$numRegistros."<br>\n";
if (!isset($ubicaciones[$fila['codUbicacion']])) {
$ubicaciones[$fila['codUbicacion']]=creaUbicacion($bd1,$bd2,$fila['codUbicacion']);
echo 'Procesando registro '.$contador.' de '.$numRegistros."<br>\n";
if (!isset($ubicaciones[$fila['codUbicacion']])) {
$ubicaciones[$fila['codUbicacion']] = creaUbicacion($bd1, $bd2, $fila['codUbicacion']);
}
if (!isset($articulos[$fila['codArticulo']])) {
$articulos[$fila['codArticulo']]=creaArticulo($bd1,$bd2,$fila['codArticulo']);
$articulos[$fila['codArticulo']] = creaArticulo($bd1, $bd2, $fila['codArticulo']);
}
$comando="insert into Elementos values (NULL,".$articulos[$fila['codArticulo']].",".$ubicaciones[$fila['codUbicacion']];
$comando.=",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');";
$comando = 'insert into Elementos values (NULL,'.$articulos[$fila['codArticulo']].','.$ubicaciones[$fila['codUbicacion']];
$comando .= ",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');";
if ($probar) {
echo $comando."<br>";
echo $comando.'<br>';
} else {
$res=$bd2->query($comando);
$res = $bd2->query($comando);
if (!$res) {
die("**Error ejecutando el comando de actualización. ".$comando." ".$bd2->error);
die('**Error ejecutando el comando de actualización. '.$comando.' '.$bd2->error);
}
}
}
//Traspasa los usuarios
$datos=$bd1->query("select * from Usuarios;");
$datos = $bd1->query('select * from Usuarios;');
if (!$datos) {
die("**No encontró datos en la tabla de Usuarios.");
die('**No encontró datos en la tabla de Usuarios.');
}
$numRegistros=$bd1->affected_rows;
$contador=0;
while ($fila=$datos->fetch_assoc()) {
$numRegistros = $bd1->affected_rows;
$contador = 0;
while ($fila = $datos->fetch_assoc()) {
$contador++;
echo "Procesando registro ".$contador." de ".$numRegistros."<br>\n";
$sesion=generaSesion();
$comando="insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion;
$comando.="',".$fila['altas'].",".$fila['modificaciones'].",".$fila['bajas'].",".$fila['consultas'].",";
$comando.=$fila['informes'].",".$fila['usuarios'].",1);";
echo 'Procesando registro '.$contador.' de '.$numRegistros."<br>\n";
$sesion = generaSesion();
$comando = "insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion;
$comando .= "',".$fila['altas'].','.$fila['modificaciones'].','.$fila['bajas'].','.$fila['consultas'].',';
$comando .= $fila['informes'].','.$fila['usuarios'].',1);';
if ($probar) {
echo $comando."<br>";
echo $comando.'<br>';
} else {
$res=$bd2->query($comando);
$res = $bd2->query($comando);
if (!$res) {
die("**Error ejecutando el comando de actualización. ".$comando." ".$bd2->error);
die('**Error ejecutando el comando de actualización. '.$comando.' '.$bd2->error);
}
}
}
@@ -156,4 +159,3 @@ echo "++Fin del proceso.<br>\n";
$bd2->commit();
$bd1->close();
$bd2->close();
?>

View File

@@ -3,7 +3,7 @@
<Titulo Texto="{Descripcion}" id="{id}"/>
<Datos>
<Consulta>
select A.id as id, A.Descripcion as articulo, A.Marca as marca, A.Modelo as modelo, E.id as idEl, U.id as idUbic,U.Descripcion as ubicacion,E.numserie as numserie,
select A.id as idArt, A.Descripcion as articulo, A.Marca as marca, A.Modelo as modelo, E.id as idEl, U.id as idUbic,U.Descripcion as ubicacion,E.numserie as numserie,
E.fechaCompra as fechaCompra,E.Cantidad as cantidad, E.Cantidad as cantReal, 'N' as Baja
from Elementos E, Articulos A, Ubicaciones U where A.id=E.id_Articulo and U.id=E.id_Ubicacion
and A.id='{id}' order by U.Descripcion,numserie;