3 Commits

24 changed files with 4780 additions and 4535 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,7 +23,8 @@ require_once 'Sql.php';
$ajax = new Ajax();
echo $ajax->procesa();
class Ajax {
class Ajax
{
private $sql;
private $tabla;
@@ -34,55 +33,61 @@ class Ajax {
$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']). "';";
$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);
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;";
$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();
$filas = [];
while ($r = $this->sql->procesaResultado()) {
$filas[] = array($r['id'] => $r['descripcion']);
$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.
@@ -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/>.
*
*/
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>'.
@@ -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 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
* @param string $opcion Opción elegida por el usuario
*/
public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion)
{
@@ -115,12 +113,12 @@ class AportaContenido {
/**
* 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
* 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>';
@@ -139,25 +137,29 @@ class AportaContenido {
$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
*
* @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,20 +169,24 @@ 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 $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 () {
@@ -191,13 +197,15 @@ class AportaContenido {
});
});
</script>";
$campo = '<input type="hidden" name="fechaCabecera" id="fechaCabecera" value="' . $this->fechaActual("%d/%m/%Y") . '">';
$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 = explode(' ', PROGRAMA);
$nombre = $nombre[2];
return $nombre . " v" . VERSION;
return $nombre.' v'.VERSION;
case 'menu': // el menú
if ($this->registrado) {
return $this->miMenu->insertaMenu();
@@ -210,35 +218,38 @@ class AportaContenido {
return $salida;
}
case 'opcion':
if (strstr($this->opcionActual, "&")) {
list($opcion, $parametro) = explode("&", $this->opcionActual);
if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode('&', $this->opcionActual);
} else {
$opcion = $this->opcionActual; $parametro = "";
$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
@@ -248,22 +259,24 @@ class AportaContenido {
// if (!$this->registrado) {
// return $this->mensajeRegistro();
// }
if (strstr($this->opcionActual, "&")) {
list($opcion, $parametro) = explode("&", $this->opcionActual);
if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode('&', $this->opcionActual);
} else {
$opcion = $this->opcionActual; $parametro = "";
$opcion = $this->opcionActual;
$parametro = '';
}
switch ($opcion) {
case 'bienvenido':
$mensaje = '<div class="alert alert-success">';
$mensaje .= 'Bienvenid@ '.$this->usuario.'</div>';
case 'principal': // contenido inicial
$mensaje = "";
$mensaje = '';
$creditos = "$('#creditos').modal({keyboard: false});";
$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;
case 'articulos':
@@ -271,29 +284,31 @@ class AportaContenido {
case 'test':
case 'elementos':
$this->cargaDatosURL();
if ($this->datosURL['opc'] == "informe") {
if ($this->datosURL['opc'] == 'informe') {
if ($this->perfil['Informe']) {
$this->procesaURL();
$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);
$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));
@@ -301,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';
//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);
$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');
@@ -330,6 +347,7 @@ class AportaContenido {
case 'configuracion':
if ($this->perfil['Config']) {
$conf = new Configuracion();
return $conf->ejecuta();
} else {
return $this->mensajePermisos('Configuraci&oacute;n');
@@ -337,6 +355,7 @@ class AportaContenido {
case 'informeInventario':
if ($this->perfil['Informe']) {
$info = new InformeInventario($this->bdd);
return $info->ejecuta();
} else {
return $this->mensajePermisos('Informes');
@@ -344,31 +363,34 @@ 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 (isset($_GET['confirmado']) && $_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
@@ -394,20 +416,21 @@ 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;">
@@ -422,7 +445,7 @@ class AportaContenido {
$panel .= '<div class="panel-body">';
$panel .= $mensaje;
$panel .= '</div>';
return $panel;
}
}
?>

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,20 +15,20 @@
*
* 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.
@@ -45,11 +44,11 @@ class Configuracion {
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);
}
@@ -58,15 +57,16 @@ class Configuracion {
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->datosConf[$clave] = $valor;
@@ -78,7 +78,7 @@ 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);
}
}
@@ -91,64 +91,66 @@ class Configuracion {
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 .= '<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 .= '<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 .= '<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 .= '</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 .= '<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 .= '</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 .= '<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>'.$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>';
@@ -167,7 +169,7 @@ class Configuracion {
$('.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.
@@ -16,9 +15,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 CopiaSeguridad {
class CopiaSeguridad
{
private $mensaje;
private $baseDatos;
private $imagenes;
@@ -34,8 +33,10 @@ class CopiaSeguridad {
if (!$this->empaqueta()) {
return false;
}
return true;
}
public function dialogo()
{
$dialogo = '<div class="container col-5"><div class="jumbotron">
@@ -45,12 +46,14 @@ class CopiaSeguridad {
<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()
{
$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);
@@ -61,20 +64,23 @@ class CopiaSeguridad {
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);
@@ -84,17 +90,20 @@ class CopiaSeguridad {
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";
$nombreCopia = TMP.'/Copia'.BASEDATOS.strftime('%Y%m%d%H%M').'.tar';
if (file_exists($nombreCopia)) {
unlink($nombreCopia);
}
@@ -102,12 +111,13 @@ class CopiaSeguridad {
exec($comando);
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;
@@ -117,12 +127,12 @@ class CopiaSeguridad {
$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()
{
return $this->mensaje;
}
}
?>

129
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.
@@ -17,20 +16,18 @@
*
* 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,9 +66,10 @@ class Csv {
private $nSerie;
/**
// El constructor necesita saber cuál es la opción actual
/**
* // 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)
@@ -82,22 +78,22 @@ class Csv {
}
/**
* 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)
{
$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");
fputcsv($this->fichero, $datos, ',', '"') or die('No puedo escribir en el fichero csv');
}
public function __destruct()
@@ -107,18 +103,17 @@ class Csv {
public function cierra()
{
fclose($this->fichero) or die("No puedo cerrar el archivo csv");
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");
$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'];
}
@@ -126,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']];
}
@@ -135,13 +130,12 @@ class Csv {
}
/**
*
* @param String $ficheroCSV Nombre del archivo csv
* @param string $ficheroCSV Nombre del archivo csv
*/
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;
@@ -153,56 +147,55 @@ 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()
{
//$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 .= '</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">
@@ -215,8 +208,8 @@ class Csv {
}
/**
*
* @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)
@@ -225,7 +218,7 @@ class Csv {
return $this->datosFichero[$i][$this->cantidadReal] - $this->datosFichero[$i][$this->cantidad];
}
private function panelMensaje($info, $tipo = "danger", $cabecera = "&iexcl;Atenci&oacute;n!")
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>';
@@ -233,14 +226,15 @@ class Csv {
$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");
$fp = fopen($this->nombre.'.log', 'a');
$linea = strftime('%Y/%m/%d').'|'.$this->nombre.'|'.$comando;
fwrite($fp, $linea."\n");
fclose($fp);
}
@@ -250,7 +244,7 @@ class Csv {
$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);
}
}
@@ -260,13 +254,13 @@ class Csv {
$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);
throw new Exception('Modifica-'.$this->bdd->mensajeError, $this->bdd->error);
}
}
private function altaElemento($i)
{
if ($this->cabecera[0] == "Articulo") {
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].'";';
@@ -279,7 +273,7 @@ class Csv {
$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);
}
}
@@ -287,19 +281,19 @@ class Csv {
{
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;
}
}
@@ -308,7 +302,7 @@ 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()
{
@@ -333,15 +327,17 @@ 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);
}
}
@@ -358,7 +354,4 @@ class Csv {
//echo '$(".bar").css("width", "'.$progreso.'");';
}
}
}
?>

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/>.
*
*/
//
// Esta clase procesará una página sustituyendo
@@ -27,7 +25,8 @@
// y una referencia al objeto cuyos métodos deberán
// aportar los contenidos.
//
class Distribucion {
class Distribucion
{
// Variable para conservar la plantilla
private $plantilla;
// Matriz que contendrá los nombres de elementos
@@ -35,6 +34,7 @@ class Distribucion {
// Referencia al objeto cuyos métodos serán
// invocados para aportar el contenido
private $objeto;
// Constructor de la clase
public function __construct($archivo, $objeto)
{
@@ -48,6 +48,7 @@ class Distribucion {
// Nos quedamos con la matriz de resultados
$this->elementos = $el[0];
}
// Este método es el encargado de procesar la plantilla
public function procesaPlantilla()
{
@@ -63,7 +64,7 @@ class Distribucion {
// 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
@@ -76,4 +77,3 @@ class Distribucion {
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.
@@ -22,14 +23,12 @@
*
* 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,10 +38,12 @@ 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
* 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
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF
* todo: cambiar este comentario
*/
@@ -51,7 +52,7 @@ class EtiquetasPDF {
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,11 +79,12 @@ 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=";
$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
@@ -105,7 +107,7 @@ class EtiquetasPDF {
}
$py = 6 + 41 * $fila;
$enlace2 = $enlace.$tupla['idEl'];
$fichero = TMP."/etiq".rand(1000,9999).".png";
$fichero = TMP.'/etiq'.rand(1000, 9999).'.png';
QRcode::png($enlace2, $fichero);
$this->pdf->image($fichero, $etiq2, $py, 30, 30);
unlink($fichero);
@@ -128,7 +130,7 @@ class EtiquetasPDF {
$this->pdf->Cell(30, 10, utf8_decode($tupla['ubicacion']));
$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;
}
}
?>

1205
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,15 +15,15 @@
*
* 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;
@@ -38,7 +37,7 @@ class Imagen {
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 (isset($_FILES[$campo]['error']) && $_FILES[$campo]['error'] == 0) {
return HAYQUEGRABAR; //Hay que guardar el archivo de imagen enviado
@@ -77,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}');
@@ -98,36 +97,40 @@ 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);
}
}
}
public function copiaImagenId($valorImagen, $tabla, $id, &$mensaje)
{
$extension = strrchr($valorImagen, ".");
$nombre = $this->dirData . "/" . $tabla . "_" . $id . $extension;
$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'] . "]";
$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;
@@ -138,7 +141,7 @@ class Imagen {
{
$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;
@@ -171,13 +174,13 @@ class Imagen {
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) {
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,23 +39,26 @@ 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']);
}
$csv = new Csv($this->bdd);
$csv->cargaCSV($uploadfile);
return $csv->resumen();
}
private function formulario() {
$accion = "index.php?importacion&opc=importar";
$salida = "";
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";
@@ -90,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,14 +46,16 @@ 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;">
@@ -67,48 +67,50 @@ class InformeInventario {
{
$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'];
$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);
$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>';
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'];
$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);
$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>';
break;
case "etiquetas":
case 'etiquetas':
$etiquetas = new EtiquetasPDF($this->bdd, $salida, true);
$etiquetas->crea($salida);
$etiquetas->cierraPDF();
return $this->devuelveInforme($etiquetas);
}
}
@@ -168,30 +172,32 @@ 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";
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";
return $salida;
}
@@ -206,22 +212,25 @@ class InformeInventario {
$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 .= '<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());
}
@@ -239,14 +248,15 @@ class InformeInventario {
<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);
@@ -256,8 +266,8 @@ class InformeInventario {
$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);
$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;
@@ -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.
@@ -22,12 +23,10 @@
*
* 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
* 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
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF
* 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';
}
@@ -54,13 +56,14 @@ class InformePDF {
//echo $def->Titulo.$def->Cabecera;
$this->pdf->Open();
$this->pdf->setAuthor(AUTOR, true);
$creador = CENTRO . " " . PROGRAMA . " v" . VERSION;
$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
@@ -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,10 +18,10 @@
*
* 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) {
function __autoload($class_name)
{
require_once $class_name.'.php';
}
@@ -37,11 +37,13 @@ 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;
@@ -69,11 +71,14 @@ class Instalar {
{
//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;
}
@@ -84,14 +89,15 @@ class Instalar {
$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,9 +108,9 @@ 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');
@@ -118,46 +124,49 @@ class Instalar {
$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";
$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";
$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";
$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";
$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 .= $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 .= '</li>';
return $info;
}
@@ -174,20 +183,24 @@ class Instalar {
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>';
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.
'"></span></a>';
$mensaje .= '<script>$(function () { $("[data-toggle=\'popover\']").popover(); });</script>';
return $mensaje;
}
@@ -204,6 +217,7 @@ class Instalar {
case 'k':
$val *= 1024;
}
return $val;
}
@@ -217,20 +231,28 @@ 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;
}
@@ -240,10 +262,10 @@ class Instalar {
$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);
}
@@ -276,7 +298,7 @@ class Instalar {
$datos[$clave] = $valor;
}
} else {
$datos = array();
$datos = [];
}
$this->actualizaConfiguracion($grabar, $campos, $datos);
if ($grabar && $this->validaPaso1()) {
@@ -293,18 +315,20 @@ class Instalar {
$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,6 +343,7 @@ class Instalar {
if ($sql->error()) {
return false;
}
return true;
}
@@ -328,8 +353,8 @@ class Instalar {
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,7 +404,7 @@ 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'];
@@ -390,27 +415,28 @@ class Instalar {
$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");
return $this->panelMensaje($sql->mensajeError(), 'danger', 'ERROR');
}
$campos="INSTALADO";
$datos['INSTALADO'] = "";
$campos = 'INSTALADO';
$datos['INSTALADO'] = 'sí';
$this->actualizaConfiguracion(true, $campos, $datos);
return $this->resumen();
}
@@ -435,13 +461,14 @@ 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;
}
@@ -451,13 +478,15 @@ class Instalar {
return true;
}
public function panelMensaje($info, $tipo = "info", $cabecera = "&iexcl;Atenci&oacute;n!") {
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;
}
@@ -494,10 +523,12 @@ class Instalar {
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>
@@ -531,8 +562,9 @@ class Instalar {
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;
}
@@ -540,19 +572,17 @@ class Instalar {
{
$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.
@@ -20,15 +22,14 @@
*
* 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") {
if (INSTALADO == 'no') {
header('location: Instalar.php');
return;
}
// Iniciamos una sesión
@@ -50,10 +53,10 @@ 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;
@@ -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);
@@ -136,14 +141,16 @@ class Inventario {
}
}
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 {
}
}
}
?>

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,7 +16,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 que se encargará de manejar los elementos del modelo de datos.
define('EDICION', 'Edici&oacute;n');
@@ -25,20 +23,20 @@ define('BORRADO', '<i>Borrado</i>');
define('ANADIR', 'Inserci&oacute;n');
define('CLONAR', 'Clonar');
class Mantenimiento {
class Mantenimiento
{
private $descripcion;
protected $bdd;
protected $url;
protected $tabla;
protected $cadenaBusqueda;
protected $campos = array();
protected $foraneas = array();
protected $campoBusca = "Descripcion";
protected $comandoConsulta = "";
protected $campos = [];
protected $foraneas = [];
protected $campoBusca = 'Descripcion';
protected $comandoConsulta = '';
protected $perfil;
protected $datosURL = array();
protected $datosURLb = array(); //para hacer una copia
protected $datosURL = [];
protected $datosURLb = []; //para hacer una copia
public function __construct($baseDatos, $perfil, $nombre)
{
@@ -59,7 +57,7 @@ class Mantenimiento {
* - pag = nº página 0, 1, 2, ...
* Los datos opcionales de la URL son:
* - buscar = cadena de búsqueda
* - id = nº de la clave necesario para la edición o el borrado
* - id = nº de la clave necesario para la edición o el borrado.
*/
public function cargaDatosURL()
{
@@ -87,17 +85,18 @@ class Mantenimiento {
private function montaURL()
{
//Primero los datos obligatorios
$opc = "&opc=" . $this->datosURL['opc'];
$orden = "&orden=" . $this->datosURL['orden'];
$sentido = "&sentido=" . $this->datosURL['sentido'];
$pag = "&pag=" . $this->datosURL['pag'];
$opc = '&opc='.$this->datosURL['opc'];
$orden = '&orden='.$this->datosURL['orden'];
$sentido = '&sentido='.$this->datosURL['sentido'];
$pag = '&pag='.$this->datosURL['pag'];
//Ahora los datos opcionales
//$buscar = isset($this->cadenaBusqueda) ? '&buscar="'.$this->cadenaBusqueda.'"' : null;
//$buscar = isset($this->cadenaBusqueda) ? "&buscar='$this->cadenaBusqueda'" : null;
//$buscar = isset($this->cadenaBusqueda) ? "&buscar=$this->cadenaBusqueda" : null;
$buscar = isset($this->cadenaBusqueda) ? "&buscar=" . urlencode($this->cadenaBusqueda) : null;
$id = isset($this->datosURL['id']) ? "&id=" . $this->datosURL['id'] : null;
$buscar = isset($this->cadenaBusqueda) ? '&buscar='.urlencode($this->cadenaBusqueda) : null;
$id = isset($this->datosURL['id']) ? '&id='.$this->datosURL['id'] : null;
$enlace = $this->url.$opc.$orden.$sentido.$pag.$buscar.$id;
return $enlace;
}
@@ -114,27 +113,27 @@ class Mantenimiento {
case 'modificar':return $this->modificar();
case 'borrar':return $this->borrar();
case 'clonar': return $this->muestra(CLONAR);
default: return "La clase Mantenimiento No entiende lo solicitado [" . $this->datosURL['opc'] . "]";
default: return 'La clase Mantenimiento No entiende lo solicitado ['.$this->datosURL['opc'].']';
}
}
private function clonar()
{
}
protected function obtieneClavesForaneas()
{
$salida = null;
foreach ($this->campos as $clave => $valor) {
$trozos = explode(",", $valor["Comment"]);
$trozos = explode(',', $valor['Comment']);
foreach ($trozos as $trozo) {
if (strstr($trozo, "foreign")) {
if (strstr($trozo, 'foreign')) {
$temp = substr($trozo, 8, -1);
list($tabla, $atributos) = explode("->", $temp);
list($clave, $resto) = explode(";", $atributos);
list($tabla, $atributos) = explode('->', $temp);
list($clave, $resto) = explode(';', $atributos);
//Quita el paréntesis final
$atributos = substr($atributos, 0, -1);
$salida[$valor['Campo']] = $tabla . "," . $resto;
$salida[$valor['Campo']] = $tabla.','.$resto;
}
}
}
@@ -162,8 +161,8 @@ class Mantenimiento {
}
//Trata con el orden de mostrar los datos
if (strlen($orden) > 0) {
$comando = str_replace('{orden}', "order by " . $orden . " " . $sentido, $comando);
$sufijoOrden = "&orden=" . $orden . "&sentido=" . $sentido;
$comando = str_replace('{orden}', 'order by '.$orden.' '.$sentido, $comando);
$sufijoOrden = '&orden='.$orden.'&sentido='.$sentido;
} else {
$comando = str_replace('{orden}', ' ', $comando);
}
@@ -204,38 +203,38 @@ class Mantenimiento {
while ($fila = $this->bdd->procesaResultado()) {
$salida .= '<tr bottom="middle">';
foreach ($fila as $clave => $valor) {
if ($clave == "id") {
if ($clave == 'id') {
$id = $valor;
}
if ($this->campos[$clave]['Visible'] == "no") {
if ($this->campos[$clave]['Visible'] == 'no') {
continue;
}
// Comprueba si tiene que añadir el enlace de inventario
if (strstr($this->campos[$clave]['Comment'], "link")) {
$comen = explode(",", $this->campos[$clave]['Comment']);
if (strstr($this->campos[$clave]['Comment'], 'link')) {
$comen = explode(',', $this->campos[$clave]['Comment']);
foreach ($comen as $co) {
if (strstr($co, "link")) {
$tmpco = explode("/", $co);
if (strstr($co, 'link')) {
$tmpco = explode('/', $co);
$datoEnlace = $tmpco[1];
}
}
$this->campoBusca = isset($dato[1]) ? $dato[1] : "";
$this->campoBusca = isset($dato[1]) ? $dato[1] : '';
$valor = '<a title="Inventario de '.$valor.'" $target="_blank" href="index.php?informeInventario&opc=listar'.$datoEnlace.'&id='.$id.'">'.$valor;
}
if (strstr($this->campos[$clave]['Comment'], "imagen") && isset($valor)) {
if (strstr($this->campos[$clave]['Comment'], 'imagen') && isset($valor)) {
$msj = '<button class="btn btn-info btn-xs" type="button" data-toggle="modal" data-target="#mensajeModal'.$id.'">Imagen</button>';
$msj .= $this->creaModal($valor, $id);
$valor = $msj;
}
if ($this->campos[$clave]['Type'] == "Boolean(1)") {
if ($this->campos[$clave]['Type'] == 'Boolean(1)') {
$checked = $valor == '1' ? 'checked' : '';
$valor = '<input type="checkbox" disabled '.$checked.'>';
}
if (strstr($this->campos[$clave]['Comment'], "ajax") && $this->perfil['Modificacion']) {
$comen = explode(",", $this->campos[$clave]['Comment']);
if (strstr($this->campos[$clave]['Comment'], 'ajax') && $this->perfil['Modificacion']) {
$comen = explode(',', $this->campos[$clave]['Comment']);
foreach ($comen as $co) {
if (strstr($co, "ajax")) {
$tmpco = explode("/", $co);
if (strstr($co, 'ajax')) {
$tmpco = explode('/', $co);
$tipo = $tmpco[1];
}
}
@@ -257,7 +256,9 @@ class Mantenimiento {
//Añade el icono de clonar
if ($this->perfil['Alta']) {
//$salida.='<a href="index.php?' . $tabla . '&opc=editar&id=' . $id . "&pag=" . $pagina . $sufijoOrden . $sufijoEnlace .
$this->backupURL(); $this->datosURL['opc'] = "clonar"; $this->datosURL['id'] = $id;
$this->backupURL();
$this->datosURL['opc'] = 'clonar';
$this->datosURL['id'] = $id;
if (ESTILO == 'bootstrap') {
$salida .= '<a href="'.$this->montaURL().'" title="Clonar"><span class="glyphicon glyphicon-copyright-mark"></span></a>&nbsp;&nbsp;';
} else {
@@ -269,7 +270,9 @@ class Mantenimiento {
//Añade el icono de editar
if ($this->perfil['Modificacion']) {
//$salida.='<a href="index.php?' . $tabla . '&opc=editar&id=' . $id . "&pag=" . $pagina . $sufijoOrden . $sufijoEnlace .
$this->backupURL(); $this->datosURL['opc'] = "editar"; $this->datosURL['id'] = $id;
$this->backupURL();
$this->datosURL['opc'] = 'editar';
$this->datosURL['id'] = $id;
if (ESTILO == 'bootstrap') {
$salida .= '<a href="'.$this->montaURL().'" title="Editar"><span class="glyphicon glyphicon-pencil"></span></a>';
} else {
@@ -281,7 +284,9 @@ class Mantenimiento {
//Añade el icono de eliminar
if ($this->perfil['Borrado']) {
//$salida.='&nbsp;&nbsp;<a href="index.php?' . $tabla . '&opc=eliminar&id=' . $id . $sufijoEnlace .
$this->backupURL(); $this->datosURL['opc'] = "eliminar"; $this->datosURL['id'] = $id;
$this->backupURL();
$this->datosURL['opc'] = 'eliminar';
$this->datosURL['id'] = $id;
if (ESTILO == 'bootstrap') {
$salida .= '&nbsp;&nbsp;<a href="'.$this->montaURL().'" title="Eliminar"><span class="glyphicon glyphicon-remove"></span></a>';
} else {
@@ -290,9 +295,9 @@ class Mantenimiento {
}
$this->restoreURL();
}
$salida .= "</td></tr>";
$salida .= '</td></tr>';
}
$salida.="</tbody></table></center></p>";
$salida .= '</tbody></table></center></p>';
//Añade botones de comandos
if ($numRegistros) {
@@ -306,11 +311,11 @@ class Mantenimiento {
$this->datosURL['pag'] = $pagRew;
$rew = $this->montaURL();
$this->restoreURL();
$this->datosURL['sentido'] = "asc";
$this->datosURL['sentido'] = 'asc';
$az = $this->montaURL();
//
//$az = '<a href="' . $az . '" title="Orden ascendente"><h1><span class="glyphicon glyphicon-sort-by-alphabet"></span></h1></a>';
$this->datosURL['sentido'] = "desc";
$this->datosURL['sentido'] = 'desc';
$za = $this->montaURL();
//
//$za = '<a href="' . $za . '" title="Orden descendente"><h1><span class="glyphicon glyphicon-sort-by-alphabet-alt"></span></h1></a>';
@@ -322,16 +327,16 @@ class Mantenimiento {
$az = '<button type="button" class="btn btn-default btn-lg" title="Orden ascendente" onClick="location.href='."'$az'".'"><span class="glyphicon glyphicon-sort-by-alphabet"></span></button>';
$za = '<button type="button" class="btn btn-default btn-lg" title="Orden descendente" onClick="location.href='."'$za'".'"><span class="glyphicon glyphicon-sort-by-alphabet-alt"></span></button>';
} else {
$anterior = '<a href="' . $anterior . "\"><img title=\"Pag. Anterior\" alt=\"anterior\" src=\"img/" . ESTILO . "/anterior.png\"></a>\n";
$siguiente = '<a href="' . $siguiente . "\"><img title=\"Pag. Siguiente\" alt=\"siguiente\" src=\"img/" . ESTILO . "/siguiente.png\"></a>\n";
$fwd = '<a href="' . $fwd . "\"><img title=\"+4 Pags.\" alt=\"mas4pags\" src=\"img/" . ESTILO . "/fwd.png\"></a>\n";
$rew = '<a href="' . $rew . "\"><img title=\"-4 Pags.\" alt=\"menos4pags\" src=\"img/" . ESTILO . "/rew.png\"></a>\n";
$anterior = '<a href="'.$anterior.'"><img title="Pag. Anterior" alt="anterior" src="img/'.ESTILO."/anterior.png\"></a>\n";
$siguiente = '<a href="'.$siguiente.'"><img title="Pag. Siguiente" alt="siguiente" src="img/'.ESTILO."/siguiente.png\"></a>\n";
$fwd = '<a href="'.$fwd.'"><img title="+4 Pags." alt="mas4pags" src="img/'.ESTILO."/fwd.png\"></a>\n";
$rew = '<a href="'.$rew.'"><img title="-4 Pags." alt="menos4pags" src="img/'.ESTILO."/rew.png\"></a>\n";
$az = '<a href="'.$az.'"><img alt="asc" title="Orden ascendente" src="img/'.ESTILO.'/ascendente.png"></a>';
$za = '<a href="'.$za.'"><img alt="desc" title="Orden descendente" src="img/'.ESTILO.'/descendente.png"></a>';
}
$this->restoreURL();
if ($this->perfil['Informe']) {
$this->datosURL['opc'] = "informe";
$this->datosURL['opc'] = 'informe';
$inf = $this->montaURL();
if (ESTILO == 'bootstrap') {
$informe = '<button type="button" class="btn btn-default btn-lg" title="Informe de '.$this->tabla.'" onClick="location.href='."'$inf.'".'"><span class="glyphicon glyphicon-list-alt"></span></button>';
@@ -342,11 +347,11 @@ class Mantenimiento {
//$informe = '<a href="'.$inf.'" title="Informe de '.$this->tabla.'"><h1><span class="glyphicon glyphicon-list-alt"></span></h1></a>';
} else {
$informe = "";
$informe = '';
}
$this->restoreURL();
} else {
$anterior = $rew = $az = $informe = $za = $siguiente = $fwd = "";
$anterior = $rew = $az = $informe = $za = $siguiente = $fwd = '';
}
if ($this->perfil['Alta']) {
$this->datosURL['opc'] = 'nuevo';
@@ -358,10 +363,11 @@ class Mantenimiento {
}
//$anadir = '<a href="'.$this->montaURL() . '"title="Añade '.$this->tabla.'"><h1><span class="glyphicon glyphicon-plus-sign"></span></h1></a>';
} else {
$anadir = "";
$anadir = '';
}
$salida .= '<p align="center">'.
"$rew&nbsp&nbsp$anterior&nbsp&nbsp$az&nbsp&nbsp$anadir&nbsp&nbsp$informe&nbsp&nbsp$za&nbsp&nbsp$siguiente&nbsp&nbsp$fwd</p>";
return $salida;
}
@@ -374,6 +380,7 @@ class Mantenimiento {
</span></div></div></form>';
$salida .= '<button class="btn btn-info pull-right" type="button">P&aacute;gina <span class="badge">'
.$pagina.'</span></button>';
return $salida;
}
@@ -381,7 +388,7 @@ class Mantenimiento {
{
//@todo hay que tener en cuenta aquí la cadena de búsqueda y la página en la url
$id = $this->datosURL['id'];
$comando = "delete from " . $this->tabla . " where id=\"$id\"";
$comando = 'delete from '.$this->tabla." where id=\"$id\"";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
@@ -391,55 +398,55 @@ class Mantenimiento {
Imagen::borraImagenId($this->tabla, $id);
$url = $this->montaURL();
header('Location: '.$url);
return;
}
protected function insertar()
{
$comando = "insert into " . $this->tabla . " (";
$lista = explode("&", $_POST['listacampos']);
$comando = 'insert into '.$this->tabla.' (';
$lista = explode('&', $_POST['listacampos']);
$primero = true;
$hayImagen = false;
//Añade la lista de campos
foreach ($lista as $campo) {
if ($campo == "") {
if ($campo == '') {
continue;
}
if ($primero) {
$primero = false;
$coma = " ";
$coma = ' ';
} else {
$coma = ",";
$coma = ',';
}
$comando .= "$coma $campo";
}
$comando.=") values (";
$comando .= ') values (';
//Añade la lista de valores
$primero = true;
foreach ($lista as $campo) {
if ($campo == "")
if ($campo == '') {
continue;
}
if ($primero) {
$primero = false;
$coma = " ";
$coma = ' ';
} else {
$coma = ",";
$coma = ',';
}
if (isset($this->campos[$campo]['Type']) && $this->campos[$campo]['Type'] == 'Boolean(1)') {
$valor = "";
$valor = '';
if (empty($_POST[$campo])) {
$valor = "0";
$valor = '0';
}
$valor = $_POST[$campo] == "on" ? '1' : $valor;
$valor = $_POST[$campo] == 'on' ? '1' : $valor;
} else {
if (isset($this->campos[$campo]['Comment']) && stristr($this->campos[$campo]['Comment'], "imagen")) {
if (isset($this->campos[$campo]['Comment']) && stristr($this->campos[$campo]['Comment'], 'imagen')) {
//procesa el envío de la imagen
$imagen = new Imagen();
$accion = $imagen->determinaAccion($campo);
if ($accion != NOHACERNADA) { // && $_POST['tipoOperacion'] != CLONAR) {
$mensaje = "";
$mensaje = '';
if (!$imagen->procesaEnvio($campo, $mensaje)) {
return $this->panelMensaje($mensaje, "danger", "ERROR PROCESANDO IMAGEN");
return $this->panelMensaje($mensaje, 'danger', 'ERROR PROCESANDO IMAGEN');
}
$hayImagen = true;
$campoImagen = $campo;
@@ -448,54 +455,55 @@ class Mantenimiento {
if (isset($_POST[$campo])) {
$valor = $_POST[$campo];
} else {
$valor = "";
$valor = '';
}
if ($_POST['tipoOperacion'] == CLONAR && file_exists($valor)) {
$hayImagen = true;
$campoImagen = $campo;
$valorImagen = $valor;
$valor = "null";
$valor = 'null';
} else {
$valor = "null";
$valor = 'null';
}
}
} else {
$valor = $_POST[$campo] == "" ? "null" : '"' . $this->bdd->filtra($_POST[$campo]) . '"';
$valor = $_POST[$campo] == '' ? 'null' : '"'.$this->bdd->filtra($_POST[$campo]).'"';
}
}
$comando .= "$coma ".$valor;
}
$comando.=")";
$comando .= ')';
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
$id = $this->bdd->ultimoId();
if ($hayImagen) {
$mensaje = " ";
$mensaje = ' ';
//Tiene que recuperar el id del registro insertado y actualizar el archivo de imagen
if ($_POST['tipoOperacion'] == CLONAR) {
//Tiene que copiar el archivo original.
if (!$imagen->copiaImagenId($valorImagen, $this->tabla, $id, $mensaje)) {
return $this->panelMensaje($mensaje, "danger", "ERROR COPIANDO IMAGEN");
return $this->panelMensaje($mensaje, 'danger', 'ERROR COPIANDO IMAGEN');
}
$archivoImagen = $imagen->archivoCopiado;
} else {
//Crea el archivo de imagen
if (!$imagen->mueveImagenId($this->tabla, $id, $mensaje)) {
return $this->panelMensaje($mensaje, "danger", "ERROR COMPRIMIENDO IMAGEN");
return $this->panelMensaje($mensaje, 'danger', 'ERROR COMPRIMIENDO IMAGEN');
}
$archivoImagen = $imagen->archivoComprimido;
}
$comando = "update " . $this->tabla . " set " . $campoImagen . "='" . $archivoImagen . "' where id='" . $id ."';";
$comando = 'update '.$this->tabla.' set '.$campoImagen."='".$archivoImagen."' where id='".$id."';";
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
}
$this->datosURL['opc'] = 'inicial';
$this->datosURL['id'] = null;
$cabecera = "refresh:".PAUSA.";url=".$this->montaURL();
$cabecera = 'refresh:'.PAUSA.';url='.$this->montaURL();
header($cabecera);
return $this->panelMensaje("Se ha insertado el registro con la clave " . $id, "info", "Informaci&oacute;n");
return $this->panelMensaje('Se ha insertado el registro con la clave '.$id, 'info', 'Informaci&oacute;n');
//return "<h1><a href=\"".$this->montaURL()."\">Se ha insertado el registro con la clave " . $this->bdd->ultimoId() . "</a></h1>";
}
@@ -506,45 +514,46 @@ class Mantenimiento {
//print_r($_GET);
//echo "id=$id pag=$pag orden=$orden sentido=$sentido";die();
//@todo hay que tener en cuenta aquí la página en la que se encuentra y la cadena de búsqueda
$comando = "update " . $this->tabla . " set ";
$lista = explode("&", $_POST['listacampos']);
$comando = 'update '.$this->tabla.' set ';
$lista = explode('&', $_POST['listacampos']);
$primero = true;
foreach ($lista as $campo) {
if ($campo == "id" || $campo == "")
if ($campo == 'id' || $campo == '') {
continue;
}
if ($primero) {
$primero = false;
$coma = " ";
$coma = ' ';
} else {
$coma = ",";
$coma = ',';
}
if ($this->campos[$campo]['Type'] == 'Boolean(1)') {
$valor = "";
$valor = '';
if (empty($_POST[$campo])) {
$valor = "0";
$valor = '0';
}
$valor = $_POST[$campo] == "on" ? '1' : $valor;
$valor = $_POST[$campo] == 'on' ? '1' : $valor;
$comando .= $coma.' '.$campo.'="'.$valor.'"';
} else {
if (stristr($this->campos[$campo]['Comment'], "imagen")) {
if (stristr($this->campos[$campo]['Comment'], 'imagen')) {
$valor = $_POST[$campo];
$imagen = new Imagen();
$accion = $imagen->determinaAccion($campo);
if ($accion != NOHACERNADA) {
if ($accion == HAYQUEGRABAR) {
$mensaje = "";
$mensaje = '';
if (!$imagen->procesaEnvio($campo, $mensaje)) {
return $this->panelMensaje($mensaje, "danger", "ERROR PROCESANDO IMAGEN");
return $this->panelMensaje($mensaje, 'danger', 'ERROR PROCESANDO IMAGEN');
}
$mensaje = "";
$mensaje = '';
if (!$imagen->mueveImagenId($this->tabla, $this->datosURL['id'], $mensaje)) {
return $this->panelMensaje($mensaje, "danger", "ERROR COMPRIMIENDO IMAGEN");
return $this->panelMensaje($mensaje, 'danger', 'ERROR COMPRIMIENDO IMAGEN');
}
$comando .= "$coma $campo='".$imagen->archivoComprimido."'";
} else {
//Hay que borrar
Imagen::borraImagenId($this->tabla, $this->datosURL['id']);
$extensiones = array("png", "jpg", "gif");
$extensiones = ['png', 'jpg', 'gif'];
$comando .= "$coma $campo=null";
}
}
@@ -557,24 +566,23 @@ class Mantenimiento {
}
}
}
$comando.=" where id=\"" . $this->datosURL['id'] . "\"";
$comando .= ' where id="'.$this->datosURL['id'].'"';
if (!$this->bdd->ejecuta($comando)) {
return $this->errorBD($comando);
}
$this->datosURL['id'] = null;
$this->datosURL['opc'] = inicial;
header('Location: '.$this->montaURL());
return;
}
protected function muestra($tipoAccion)
{
$id = $this->datosURL['id'];
if ($tipoAccion != ANADIR) {
$comando = "select * from " . $this->tabla . " where id='$id'";
$comando = 'select * from '.$this->tabla." where id='$id'";
$resultado = $this->bdd->ejecuta($comando);
if (!$resultado) {
return $this->errorBD("", "No se han podido encontrar datos del identificador $id");
return $this->errorBD('', "No se han podido encontrar datos del identificador $id");
}
$fila = $this->bdd->procesaResultado();
} else {
@@ -588,10 +596,10 @@ class Mantenimiento {
//tabla a la cual pertenece la clave foránea.
protected function generaLista($datos, $campo, $valorInicial, $modo)
{
$modoEfectivo = $modo == "readonly" ? "disabled" : "";
$modoEfectivo = $modo == 'readonly' ? 'disabled' : '';
$salida = "<select class=\"selectpicker show-tick\" data-live-search=\"true\" data-width=\"auto\" name=\"$campo\" $modoEfectivo>\n";
list($tabla, $atributos) = explode(",", $datos);
$atributos = str_replace("/", ",", $atributos);
list($tabla, $atributos) = explode(',', $datos);
$atributos = str_replace('/', ',', $atributos);
// Elimina las llaves
$atributos = substr($atributos, 1, -1);
$comando = "select id,$atributos from $tabla order by $atributos";
@@ -602,57 +610,58 @@ class Mantenimiento {
$primero = true;
while ($fila = $this->bdd->procesaResultado()) {
foreach ($fila as $clave => $valor) {
if ($clave == "id") {
if ($clave == 'id') {
if ($primero) {
$primero = false;
} else {
$salida = substr($salida, 0, -1);
$salida .= "</option>\n";
}
$seleccionado = $valor == $valorInicial ? " selected " : "";
$seleccionado = $valor == $valorInicial ? ' selected ' : '';
$salida .= '<option value="'.$valor.'" '.$seleccionado.$modoEfectivo.' >';
} else {
$salida.=$valor . "-";
$salida .= $valor.'-';
}
}
}
$salida .= "</select>\n<br><br>";
$salida .= "<script>$('.selectpicker').selectpicker();</script>";
return $salida;
}
private function obtenerCampos()
{
//Si hay un fichero de descripción xml lo utiliza.
$nombre = "xml/mantenimiento" . $this->tabla . ".xml";
$nombre = 'xml/mantenimiento'.$this->tabla.'.xml';
if (file_exists($nombre)) {
$def = simplexml_load_file($nombre);
foreach ($def->Campos->Col as $columna) {
$this->campos[(string) $columna['Nombre']] = array("Field" => (string) $columna['Titulo'], "Comment" => (string) $columna['Varios'],
"Type" => (string) $columna['Tipo'] . "(" . $columna['Ancho'] . ")", "Editable" => (string) $columna['Editable'],
"Campo" => (string) $columna['Campo'], "Visible" => (string) $columna['Visible'], "Ajuste" => (string) $columna['Ajuste'],
"Titulo" => (string) $columna['Titulo']);
$this->campos[(string) $columna['Nombre']] = ['Field' => (string) $columna['Titulo'], 'Comment' => (string) $columna['Varios'],
'Type' => (string) $columna['Tipo'].'('.$columna['Ancho'].')', 'Editable' => (string) $columna['Editable'],
'Campo' => (string) $columna['Campo'], 'Visible' => (string) $columna['Visible'], 'Ajuste' => (string) $columna['Ajuste'],
'Titulo' => (string) $columna['Titulo']];
}
$this->comandoConsulta = $def->Consulta;
} else {
//Toma los datos de la tabla.
$datos = $this->bdd->estructura($this->tabla);
for ($i = 0; $i < count($datos); $i++) {
$this->campos[$datos[$i]["Field"]][] = $datos[$i];
$this->campos[$datos[$i]["Field"]] = $this->campos[$datos[$i]["Field"]][0];
$this->campos[$datos[$i]["Field"]]["Campo"] = $datos[$i]["Field"];
$this->campos[$datos[$i]["Field"]]["Editable"] = "si";
if (strstr($datos[$i]["Type"],"int")) {
$ajuste = "D";
} else if (strstr($datos[$i]["Type"],"char")) {
$ajuste = "L";
$this->campos[$datos[$i]['Field']][] = $datos[$i];
$this->campos[$datos[$i]['Field']] = $this->campos[$datos[$i]['Field']][0];
$this->campos[$datos[$i]['Field']]['Campo'] = $datos[$i]['Field'];
$this->campos[$datos[$i]['Field']]['Editable'] = 'si';
if (strstr($datos[$i]['Type'], 'int')) {
$ajuste = 'D';
} elseif (strstr($datos[$i]['Type'], 'char')) {
$ajuste = 'L';
}
if (strstr($datos[$i]["Comment"],"imagen")) {
$ajuste = "C";
if (strstr($datos[$i]['Comment'], 'imagen')) {
$ajuste = 'C';
}
$this->campos[$datos[$i]["Field"]]["Ajuste"] = $ajuste;
$this->campos[$datos[$i]['Field']]['Ajuste'] = $ajuste;
}
$this->comandoConsulta = "select SQL_CALC_FOUND_ROWS * from " . $this->tabla . " {buscar} {orden} limit {inferior},{superior}";
$this->comandoConsulta = 'select SQL_CALC_FOUND_ROWS * from '.$this->tabla.' {buscar} {orden} limit {inferior},{superior}';
}
}
@@ -667,17 +676,17 @@ class Mantenimiento {
}
$flecha = '<span class="glyphicon glyphicon-chevron-'.$sentidoFlecha.'"></span>';
foreach ($this->campos as $clave => $datos) {
if ($this->campos[$clave]['Visible'] == "no") {
if ($this->campos[$clave]['Visible'] == 'no') {
continue;
}
$comen = explode(",", $datos["Comment"]);
$comen = explode(',', $datos['Comment']);
$ordenable = false;
foreach ($comen as $co) {
if (strstr($co, "ordenable")) {
if (strstr($co, 'ordenable')) {
$ordenable = true;
}
if (strstr($co, "buscable")) {
$dato = explode("/", $co);
if (strstr($co, 'buscable')) {
$dato = explode('/', $co);
$this->campoBusca = $dato[1];
}
}
@@ -690,48 +699,49 @@ class Mantenimiento {
$this->backupURL();
$this->datosURL['orden'] = $clave2;
$resFlecha = $clave2 == $ordenActual ? $flecha : '';
$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"". $this->montaURL() . "\"> " . $datos["Titulo"] . $resFlecha . " </a></b></th>\n";
$salida .= "<th><b><a title=\"Establece orden por $clave \" href=\"".$this->montaURL().'"> '.$datos['Titulo'].$resFlecha." </a></b></th>\n";
//$salida.="<th><b><a title=\"Establece orden por $clave \" href=\"". $this->montaURL() . "\"> " . ucfirst($clave) . $resFlecha . " </a></b></th>\n";
$this->restoreURL();
} else {
$salida.='<th><b>' . $datos["Titulo"] . '</b></th>' . "\n";
$salida .= '<th><b>'.$datos['Titulo'].'</b></th>'."\n";
//$salida.='<th><b>' . ucfirst($clave) . '</b></th>' . "\n";
}
}
$salida .= "<th><b>Acci&oacute;n</b></th>\n";
return $salida;
}
/**
*
* @param string $tipo ANADIR,EDICION,BORRADO,CLONAR
* @param array $datos Vector con los datos del registro
*
* @return array lista de campos y formulario de entrada
*/
private function formularioCampos($tipo, $datos)
{
$modo = $tipo == BORRADO ? "readonly" : "";
$modo = $tipo == BORRADO ? 'readonly' : '';
$nfechas = 0;
switch ($tipo) {
case CLONAR:
case ANADIR:
$this->datosURL['opc'] = "insertar"; $this->datosURL['id'] = null;
$this->datosURL['opc'] = 'insertar'; $this->datosURL['id'] = null;
break;
case EDICION:
$this->datosURL['opc'] = "modificar";
$this->datosURL['opc'] = 'modificar';
break;
case BORRADO:
$this->datosURL['opc'] = "borrar";
$this->datosURL['opc'] = 'borrar';
break;
}
$accion = $this->montaURL();
$salida = '<div class="col-sm-8"><form name="mantenimiento.form" enctype="multipart/form-data" class="form-horizontal" role="form" method="post" action="'.$accion.'">'."\n";
$salida .= "<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>$tipo</b></legend>\n";
//$salida.= var_export($datos,true);
$campos = "";
$campos = '';
foreach ($this->campos as $clave => $valor) {
if ($valor["Editable"] == "no") {
if ($valor['Editable'] == 'no') {
//Se salta los campos que no deben aparecer
continue;
}
@@ -739,12 +749,12 @@ class Mantenimiento {
$salida .= '<div class="form-group">';
$campo = $valor['Campo'];
$campos .= "$campo&";
$salida.='<label class="col-sm-2 control-label" for="' . $campo . '">' . $valor['Titulo'] . "</label> ";
$salida .= '<label class="col-sm-2 control-label" for="'.$campo.'">'.$valor['Titulo'].'</label> ';
//$salida.='<label class="col-sm-2 control-label" for="' . $campo . '">' . ucfirst($clave) . "</label> ";
$salida .= '<div class="col-sm-5">';
//Se asegura que el id no se pueda modificar.
$modoEfectivo = $clave == 'id' ? "readonly" : $modo;
$valorDato = $datos == null ? "" : $datos[$campo];
$modoEfectivo = $clave == 'id' ? 'readonly' : $modo;
$valorDato = $datos == null ? '' : $datos[$campo];
if ($clave == 'id' && ($tipo == ANADIR || $tipo == CLONAR)) {
$valorDato = null;
}
@@ -752,21 +762,21 @@ class Mantenimiento {
$tipoCampo = $valor['Type'];
//Si es un campo fecha u hora y está insertando pone la fecha actual o la hora actual
if ($tipo == ANADIR) {
if (stripos($tipoCampo, "echa") <> 0 || stripos($tipoCampo, "ate") <> 0) {
$valorDato = strftime("%Y/%m/%d");
if (stripos($tipoCampo, 'echa') != 0 || stripos($tipoCampo, 'ate') != 0) {
$valorDato = strftime('%Y/%m/%d');
}
}
// Calcula el tamaño y el tipo
$tipo_campo = "text";
if (stripos($tipoCampo, "echa") || stripos($tipoCampo, "ate")) {
$tamano = "19";
$tipo_campo = "datetime";
$tipo_campo = 'text';
if (stripos($tipoCampo, 'echa') || stripos($tipoCampo, 'ate')) {
$tamano = '19';
$tipo_campo = 'datetime';
$nfechas++;
$salida .= '<div class="input-group date" id="datetimepicker'.$nfechas.'">
<input type="text" name="'.$campo.'" data-format="YYYY/MM/DD" value="'.$valorDato.'" '.$modoEfectivo.' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
</div>';
if ($modo != "readonly") {
if ($modo != 'readonly') {
$salida .= '<script type="text/javascript">
$(function () {
$('."'#datetimepicker".$nfechas."').datetimepicker({
@@ -777,23 +787,23 @@ class Mantenimiento {
});
</script>";
}
$salida .= "</div></div>";
$salida .= '</div></div>';
continue;
} else {
list($resto, $tamano) = explode("(", $tipoCampo);
list($resto, $tamano) = explode('(', $tipoCampo);
$tamano = substr($tamano, 0, -1);
}
if ($tipoCampo == "Password") {
$tipo_campo = "password";
if ($tipoCampo == 'Password') {
$tipo_campo = 'password';
}
if ($tipoCampo == "Boolean(1)") {
if ($tipoCampo == 'Boolean(1)') {
$checked = $valorDato == '1' ? 'checked' : '';
$modocheck = $modoEfectivo == "readonly" ? 'onclick="javascript: return false;" readonly ' : '';
$modocheck = $modoEfectivo == 'readonly' ? 'onclick="javascript: return false;" readonly ' : '';
$salida .= '<input type="checkbox" name="'.$campo.'" '.$checked.' '.$modocheck.' class="form-control">';
$salida .= '</div></div>';
continue;
}
if (stristr($this->campos[$campo]['Comment'], "imagen")) {
if (stristr($this->campos[$campo]['Comment'], 'imagen')) {
/*if ($tipo == CLONAR) {
// De momento no deja clonar las imágenes
$valorDato = null;
@@ -801,8 +811,8 @@ class Mantenimiento {
$salida .= $this->creaCampoImagen($campo, $valorDato, $tipo);
continue;
}
if (stristr($this->campos[$campo]['Type'], "int")) {
$tipo_campo = "number";
if (stristr($this->campos[$campo]['Type'], 'int')) {
$tipo_campo = 'number';
$modoEfectivo .= ' onkeypress = "if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;" ';
}
//Si no es una clave foránea añade un campo de texto normal
@@ -811,32 +821,32 @@ class Mantenimiento {
$salida .= '</div></div>';
} else {
$salida .= $this->generaLista($this->foraneas[$campo], $campo, $valorDato, $modoEfectivo);
$salida.="</div></div>";
$salida .= '</div></div>';
}
}
//genera un campo oculto con la lista de campos a modificar.
$salida .= '<input name="listacampos" type="hidden" value="'.$campos."\">\n";
//genera un campo oculto con el tipo de operación asociado al formulario
$salida .= '<input name="tipoOperacion" type="hidden" value="'.$tipo."\">\n";
$salida .= "</fieldset><p>";
$salida .= '</fieldset><p>';
$salida .= '<center>';
$this->datosURL['opc'] = 'inicial';
$salida .= '<button type="button" onClick="location.href='."'".$this->montaURL()."'".'" class="btn btn-info"><span class="glyphicon glyphicon-arrow-left"></span> Volver</button>';
$salida .= '&nbsp;&nbsp;<button type="reset" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Cancelar</button>';
$salida .= '&nbsp;&nbsp;<button type=submit class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button>';
$salida .= '<br></center></div>';
return $salida;
}
protected function creaCampoImagen($campo, $valor, $tipoAccion)
{
if (file_exists($valor)) {
//El fichero existe.
$existe = true;
$tipo = "fileinput-exists";
$tipo = 'fileinput-exists';
} else {
$tipo = "fileinput-new";
$tipo = 'fileinput-new';
$existe = false;
}
$mensaje = '
@@ -862,8 +872,8 @@ class Mantenimiento {
$mensaje .= '</div>';
}
$mensaje .= $this->creaModal($valor, 1);
return $mensaje;
return $mensaje;
}
private function creaModal($valor, $id)
@@ -877,27 +887,31 @@ class Mantenimiento {
</div>
</div>
</div>';
return $mensaje;
}
protected function errorBD($comando, $texto = "")
protected function errorBD($comando, $texto = '')
{
if (!$texto) {
$texto = "No pudo ejecutar correctamente el comando $comando error=".$this->bdd->mensajeError();
} else {
$texto = "$texto error=".$this->bdd->mensajeError();
}
$cabecera="&iexcl;Error!";
return $this->panelMensaje($texto, "danger", $cabecera);
$cabecera = '&iexcl;Error!';
return $this->panelMensaje($texto, 'danger', $cabecera);
}
private function panelMensaje($info, $tipo = "danger", $cabecera = "&iexcl;Atenci&oacute;n!") {
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;
}
@@ -912,15 +926,16 @@ class Mantenimiento {
{
//url: 'ajax.php?tabla=". $this->tabla . "',
//url: '" . $this->montaURL() . "&tabla=" . $this->tabla "',
$formato = $tipo == "combodate" ? 'data-format="YYYY-MM-DD" data-viewformat="DD/MM/YYYY"' : '';
$remoto = ""; $select2 = "";
$formato = $tipo == 'combodate' ? 'data-format="YYYY-MM-DD" data-viewformat="DD/MM/YYYY"' : '';
$remoto = '';
$select2 = '';
$titulo = $clave;
if (strstr($tipo, "select")) {
$datos = explode("-", $tipo);
if (strstr($tipo, 'select')) {
$datos = explode('-', $tipo);
$tipo = $datos[0];
$tabla2 = $datos[1];
$clave = "id_".$clave;
$indice = "id".$tabla2;
$clave = 'id_'.$clave;
$indice = 'id'.$tabla2;
$valorDato = $datosFila[$indice];
$valorSelect = 'data-value="'.$valorDato.'" ';
$remoto = $valorSelect.' data-sourceCache="true" data-sourceError="Error cargando datos" data-source="Ajax.php?opc=get&tabla='.$tabla2.'"';
@@ -948,8 +963,7 @@ class Mantenimiento {
});
});
</script>";
return $mensaje;
}
}
?>

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,12 +15,13 @@
*
* 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
@@ -31,24 +31,27 @@ class Menu {
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)
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
} else {
$salida .=
//'<span class="label label-default">'.$opcion.'</span><br>';
'<label class="">'.$opcion.'</label><br/>';
}
}
return $salida;
}
}
?>

View File

@@ -17,29 +17,33 @@
*
* 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
*/
private $ProcessingTable=false,$aCols=array(),$TableX,$HeaderColor;
private $RowColors,$ColorIndex;
private $bdd,$titulo,$cabecera;
private $totales=array(),$procesandoTotales=false;
/**
* 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;
private $aCols = [];
private $TableX;
private $HeaderColor;
private $RowColors;
private $ColorIndex;
private $bdd;
private $titulo;
private $cabecera;
private $totales = [];
private $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
*/
public function __construct($bdd, $orientacion, $formato, $titulo = '', $cabecera = '')
{
$this->bdd = $bdd;
@@ -47,21 +51,24 @@ class Pdf_mysql_table extends FPDF
$this->cabecera = $cabecera;
parent::__construct($orientacion, 'mm', $formato);
}
public function setTitulo($titulo)
{
$this->titulo = $titulo;
}
public function iniciaTotales()
{
$this->totales = array();
$this->totales = [];
}
function Header()
public function Header()
{
//Modficada por Ricardo Montañana
//Titulo
$fecha=strftime("%d-%b-%Y %H:%M");
$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->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);
@@ -69,11 +76,13 @@ class Pdf_mysql_table extends FPDF
$this->Cell(0, 5, utf8_decode($this->cabecera), 0, 1, 'C');
$this->Ln(10);
//Print the table header if necessary
if($this->ProcessingTable)
if ($this->ProcessingTable) {
$this->TableHeader();
}
//Ensure table header is output
parent::Header();
}
public function Footer()
{
$this->SetFont('Arial', '', 8);
@@ -82,25 +91,28 @@ class Pdf_mysql_table extends FPDF
parent::Footer();
}
function TableHeader()
public function TableHeader()
{
$this->SetFont('Arial', 'B', 12);
$this->SetX($this->TableX);
$fill = !empty($this->HeaderColor);
if($fill)
if ($fill) {
$this->SetFillColor($this->HeaderColor[0], $this->HeaderColor[1], $this->HeaderColor[2]);
foreach($this->aCols as $col)
}
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)
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;
@@ -111,7 +123,7 @@ class Pdf_mysql_table extends FPDF
if ($this->procesandoTotales) {
$this->SetFont('Arial', 'B', 12);
}
$dato = isset($data[$col['f']]) ? $data[$col['f']] : "";
$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);
@@ -120,91 +132,99 @@ class Pdf_mysql_table extends FPDF
//print_r($data);
//print_r($this->aCols);
if ($col['t'] == 'S' && !$this->procesandoTotales) {
if (isset($this->totales[$col['f']]))
if (isset($this->totales[$col['f']])) {
$this->totales[$col['f']] += $data[$col['f']];
else
} else {
$this->totales[$col['f']] = $data[$col['f']];
}
}
}
$this->Ln();
$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)
{
foreach ($this->aCols as $i=>$col) {
$w = $col['w'];
if($w==-1)
if ($w == -1) {
$w = $width / count($this->aCols);
elseif(substr($w,-1)=='%')
} elseif (substr($w, -1) == '%') {
$w = $w / 100 * $width;
}
$this->aCols[$i]['w'] = $w;
$TableWidth += $w;
}
//Compute the abscissa of the table
if($align=='C')
if ($align == 'C') {
$this->TableX = max(($this->w - $TableWidth) / 2, 0);
elseif($align=='R')
} elseif ($align == 'R') {
$this->TableX = max($this->w - $this->rMargin - $TableWidth, 0);
else
} else {
$this->TableX = $this->lMargin;
}
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);
}
function Table($query,$prop=array())
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[] = ['f'=>$field, 'c'=>$caption, 'w'=>$width, 'a'=>$align, 't'=>$total];
}
public function Table($query, $prop = [])
{
//Issue 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)
{
if (count($this->aCols) == 0) {
$nb = $res->field_count;
for($i=0;$i<$nb;$i++)
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']))
foreach ($this->aCols as $i=>$col) {
if ($col['c'] == '') {
if (is_string($col['f'])) {
$this->aCols[$i]['c'] = ucfirst($col['f']);
else
} else {
$this->aCols[$i]['c'] = ucfirst($res->field_seek($i));
}
}
$i++;
}
//Handle properties
if(!isset($prop['width']))
if (!isset($prop['width'])) {
$prop['width'] = 0;
if($prop['width']==0)
}
if ($prop['width'] == 0) {
$prop['width'] = $this->w - $this->lMargin - $this->rMargin;
if(!isset($prop['align']))
}
if (!isset($prop['align'])) {
$prop['align'] = 'C';
if(!isset($prop['padding']))
}
if (!isset($prop['padding'])) {
$prop['padding'] = $this->cMargin;
}
$cMargin = $this->cMargin;
$this->cMargin = $prop['padding'];
if(!isset($prop['HeaderColor']))
$prop['HeaderColor']=array();
if (!isset($prop['HeaderColor'])) {
$prop['HeaderColor'] = [];
}
$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['color1'])) {
$prop['color1'] = [];
}
if (!isset($prop['color2'])) {
$prop['color2'] = [];
}
$this->RowColors = [$prop['color1'], $prop['color2']];
//Compute column widths
$this->CalcWidths($prop['width'], $prop['align']);
//Print header
@@ -224,12 +244,15 @@ class Pdf_mysql_table extends FPDF
}
$this->ProcessingTable = false;
$this->cMargin = $cMargin;
$this->aCols=array();
$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()
{
@@ -238,7 +261,7 @@ class Pdf_mysql_table extends FPDF
return true;
}
}
return false;
}
}
?>

View File

@@ -15,7 +15,7 @@ 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)

104
Sql.php
View File

@@ -1,9 +1,11 @@
<?php
/**
* Gestión de una base de datos MySQL
* 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.
@@ -19,44 +21,47 @@
*
* 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 {
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 = '';
/**
* @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;
/**
* @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;
/**
* @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;
/**
* @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
@@ -66,7 +71,7 @@ class Sql {
$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->mensajeError .= 'Servidor ['.$servidor.'] base de datos ['.$baseDatos.']';
$this->error = true;
$this->estado = false;
} else {
@@ -74,9 +79,11 @@ class Sql {
$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)
{
return $this->bdd->real_escape_string($cadena);
}
public function ejecuta($comando)
{
if (!$this->estado) {
$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;
return false;
}
$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;
return;
}
if (!$this->peticion) {
$this->error = true;
$this->mensajeError = 'No hay un resultado disponible';
return NULL;
return;
}
$datos = $this->peticion->fetch_assoc();
$this->error = false;
$this->mensajeError = '';
return ($datos);
return $datos;
}
public function camposResultado()
{
if (!$this->estado) {
$this->error = true;
$this->mensajeError = 'No está conectado a una base de datos';
return NULL;
return;
}
if (!$this->peticion) {
$this->error = true;
$this->mensajeError = 'No hay un resultado disponible';
return NULL;
return;
}
$datos = $this->peticion->fetch_field();
$this->error = false;
$this->mensajeError = '';
return ($datos);
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()
{
$comando = "select found_rows();";
$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];
}
/**
* 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)
@@ -199,33 +235,39 @@ class Sql {
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;
}
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,19 +353,23 @@ 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]))) {
// 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);
}
// if filter doesn't exists, trigger an error
} else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
} 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))) {
@@ -379,24 +378,26 @@ class Zebra_Image
$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);
}
// if filter doesn't exists, trigger an error
} else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
} 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,7 +766,6 @@ 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
@@ -806,7 +796,6 @@ 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
@@ -817,7 +806,6 @@ class Zebra_Image
// compute the target image's height
$target_height = ($height > 0 ? $height : $this->source_height);
}
// if
@@ -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
// 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,7 +1105,6 @@ class Zebra_Image
// rotate the image
$target_identifier = imagerotate($this->source_identifier, $angle, $background_color);
}
// if source image is a transparent GIF
@@ -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;
}
/**
* 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
);
];
}
/**
@@ -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,10 +1442,8 @@ 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
@@ -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

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.
@@ -19,15 +21,15 @@
*
* 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) {
function __autoload($class_name)
{
require_once $class_name.'.php';
}
include('inc/configuracion.inc');
include 'inc/configuracion.inc';
$aplicacion = new Inventario();
if ($aplicacion->estado())
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.
@@ -17,37 +17,37 @@
*
* 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";
$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)
{
global $probar;
$comando="select nombre from Ubicaciones where codigo=".$clave.";";
$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."');";
if ($probar) {
echo $comando;
return 1;
} else {
$test = $bd2->query($comando);
if (!$test) {
die("**No pudo insertar ubicacion.".$comando);
die('**No pudo insertar ubicacion.'.$comando);
}
return $bd2->insert_id;
}
}
@@ -58,32 +58,35 @@ function creaArticulo($bd1,$bd2,$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.");";
$comando = "insert into Articulos values (NULL,'".$valor1."','".$valor2."','".$valor3."',".$valor4.');';
if ($probar) {
echo $comando;
return 1;
} else {
$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="";
$cadena = '';
for ($i = 0; $i < $long; $i++) {
$cadena .= chr(rand(40, 126));
}
return $cadena;
}
/*
@@ -93,62 +96,62 @@ function generaSesion()
*/
$bd1 = new mysqli($host, $usuario, $claveUsuario, $baseAnt);
if (mysqli_connect_errno()) {
die("**Error conectando a la base de datos antigua.".$bd1->error);
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);
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";
$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";
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']);
}
$comando="insert into Elementos values (NULL,".$articulos[$fila['codArticulo']].",".$ubicaciones[$fila['codUbicacion']];
$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);
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()) {
$contador++;
echo "Procesando registro ".$contador." de ".$numRegistros."<br>\n";
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);";
$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);
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();
?>