3 Commits

24 changed files with 4780 additions and 4535 deletions

View File

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

View File

@@ -1,6 +1,5 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -8,22 +7,21 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * 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>' . define('PIE', '<center><a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0-standalone.html"><img src="img/gplv3.png" alt="GPL v3"/></a>'.
'<a target="_blank" href="http://www.apache.org"><img src="img/apache.gif" alt="Sitio web creado con Apache" /></a>' . '<a target="_blank" href="http://www.apache.org"><img src="img/apache.gif" alt="Sitio web creado con Apache" /></a>'.
'<a target="_blank" href="http://www.mysql.org"><img src="img/mysql.png" width=125 height=47 alt="Gestor de bases de datos mySQL" /></a>' . '<a target="_blank" href="http://www.mysql.org"><img src="img/mysql.png" width=125 height=47 alt="Gestor de bases de datos mySQL" /></a>'.
'<a target="_blank" href="http://www.php.net"><img src="img/php.gif" alt="PHP Language" /></a> </center>'); '<a target="_blank" href="http://www.php.net"><img src="img/php.gif" alt="PHP Language" /></a> </center>');
define('FORMULARIO_ACCESO', '<form name="formulario_acceso" action="index.php?registrarse" method="POST">' . define('FORMULARIO_ACCESO', '<form name="formulario_acceso" action="index.php?registrarse" method="POST">'.
'Usuario<br><input type="text" name="usuario" value="" size="8" /><br><br>Clave<br><input type="password" name="clave" value="" size="8" />' . 'Usuario<br><input type="text" name="usuario" value="" size="8" /><br><br>Clave<br><input type="password" name="clave" value="" size="8" />'.
'<br><br><button type="submit" name="iniciar" class="btn btn-primary">Iniciar <span class="glyphicon glyphicon-log-in"></span></button></form>'); '<br><br><button type="submit" name="iniciar" class="btn btn-primary">Iniciar <span class="glyphicon glyphicon-log-in"></span></button></form>');
define('MENSAJE_DEMO', 'Puede Iniciar sesi&oacute;n con<br>usuario <i><b>demo</b></i><br>contrase&ntilde;a <i>demo</i><br>'); define('MENSAJE_DEMO', 'Puede Iniciar sesi&oacute;n con<br>usuario <i><b>demo</b></i><br>contrase&ntilde;a <i>demo</i><br>');
define('USUARIO_INCORRECTO', '<label class="bg-danger">Usuario y clave incorrectos!</label><br><br>'); define('USUARIO_INCORRECTO', '<label class="bg-danger">Usuario y clave incorrectos!</label><br><br>');
@@ -40,7 +38,7 @@ define('CREDITOS_CABECERA', '<div class="modal fade" tabindex="-1" id="creditos"
<h1>Inventario2</h1> <h1>Inventario2</h1>
<p> Aplicación para controlar el inventario de un centro educativo.</p> <p> Aplicación para controlar el inventario de un centro educativo.</p>
<p>En la aplicación se hace uso de los siguientes módulos y/o bibliotecas</p>'); <p>En la aplicación se hace uso de los siguientes módulos y/o bibliotecas</p>');
define('CREDITOS_PIE', ' <p><h5>Copyright &copy; 2008-2014 Ricardo Montañana Gómez</h5> define('CREDITOS_PIE', ' <p><h5>Copyright &copy; 2008-2014 Ricardo Montañana Gómez</h5>
<h5><small>Esta aplicación se distribuye con licencia <a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0.html">GPLv3 </a></small></h5></p> <h5><small>Esta aplicación se distribuye con licencia <a target="_blank" href="http://www.gnu.org/licenses/gpl-3.0.html">GPLv3 </a></small></h5></p>
</div> </div>
@@ -50,18 +48,17 @@ define('CREDITOS_PIE', ' <p><h5>Copyright &copy; 2008-2014 Ricard
</div>'); </div>');
// Esta clase aportará el contenido a la plantilla // Esta clase aportará el contenido a la plantilla
class AportaContenido { class AportaContenido
{
/** /**
* * @var bool Aporta información sobre si el usuario está registrado o no.
* @var boolean Aporta información sobre si el usuario está registrado o no.
*/ */
private $registrado; private $registrado;
/** /**
* @var string Nombre del usuario * @var string Nombre del usuario
*/ */
private $usuario = NULL; private $usuario = null;
/** /**
* @var Menu Menú de la página. * @var Menu Menú de la página.
@@ -79,7 +76,7 @@ class AportaContenido {
private $opcionActual; private $opcionActual;
/** /**
* @var boolean Usuario y clave incorrectos? * @var bool Usuario y clave incorrectos?
*/ */
private $usuario_inc = false; private $usuario_inc = false;
@@ -89,19 +86,20 @@ class AportaContenido {
private $perfil; private $perfil;
/** /**
*
* @var array Datos pasados en la URL * @var array Datos pasados en la URL
*/ */
private $datosURL = array(); private $datosURL = [];
// 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. * Constructor de la clase.
* @param BaseDatos $baseDatos Manejador de la base de datos *
* @param boolean $registrado usuario registrado si/no * @param BaseDatos $baseDatos Manejador de la base de datos
* @param String $usuario Nombre del usuario * @param bool $registrado usuario registrado si/no
* @param array $perfil Permisos de acceso del usuario * @param string $usuario Nombre del usuario
* @param String $opcion Opción elegida por el usuario * @param array $perfil Permisos de acceso del usuario
* @param string $opcion Opción elegida por el usuario
*/ */
public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion) public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion)
{ {
@@ -112,52 +110,56 @@ class AportaContenido {
$this->perfil = $perfil; $this->perfil = $perfil;
$this->opcionActual = $opcion; $this->opcionActual = $opcion;
} }
/** /**
* Devuelve una tabla HTML con el contenido de las bibliotecas/módulos utilizadas en la aplicación * 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 *
* @return string
*/ */
public function creaTablaAcercaDe() public function creaTablaAcercaDe()
{ {
$poner = $this->perfil['Config']; $poner = $this->perfil['Config'];
$tabla = '<table class="table table-condensed">'; $tabla = '<table class="table table-condensed">';
$tabla .='<thead><tr><th>Biblioteca/Módulo</th>'.($poner?'<th>Versión</th>':'').'<th>Licencia</th></tr></thead>'; $tabla .= '<thead><tr><th>Biblioteca/Módulo</th>'.($poner ? '<th>Versión</th>' : '').'<th>Licencia</th></tr></thead>';
$tabla .='<tbody>'; $tabla .= '<tbody>';
$tabla .='<tr><td><a href="http://jquery.com/" target="_blank">jquery</a></td>'.($poner?'<td>2.1.0</td>':'').'<td><a target="_blank" href="https://jquery.org/license/">MIT</a></td>'; $tabla .= '<tr><td><a href="http://jquery.com/" target="_blank">jquery</a></td>'.($poner ? '<td>2.1.0</td>' : '').'<td><a target="_blank" href="https://jquery.org/license/">MIT</a></td>';
$tabla .='<tr><td><a href="http://getbootstrap.com/" target="_blank">Twitter Bootstrap</a></td>'.($poner?'<td>3.1.1</td>':'').'<td><a target="_blank" href="https://github.com/twbs/bootstrap/blob/master/LICENSE">MIT</a></td>'; $tabla .= '<tr><td><a href="http://getbootstrap.com/" target="_blank">Twitter Bootstrap</a></td>'.($poner ? '<td>3.1.1</td>' : '').'<td><a target="_blank" href="https://github.com/twbs/bootstrap/blob/master/LICENSE">MIT</a></td>';
$tabla .='<tr><td><a href="http://www.fpdf.org/" target="_blank">FPDF</a></td>'.($poner?'<td>1.7</td>':'').'<td>Libre</td>'; $tabla .= '<tr><td><a href="http://www.fpdf.org/" target="_blank">FPDF</a></td>'.($poner ? '<td>1.7</td>' : '').'<td>Libre</td>';
$tabla .='<tr><td><a href="http://phpqrcode.sourceforge.net/" target="_blank">PHP QR Code Enconder</a></td>'.($poner?'<td>1.1.4</td>':'').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>'; $tabla .= '<tr><td><a href="http://phpqrcode.sourceforge.net/" target="_blank">PHP QR Code Enconder</a></td>'.($poner ? '<td>1.1.4</td>' : '').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .='<tr><td><a href="http://stefangabos.ro/php-libraries/zebra-image/" target="_blank">Zebra_Image</a></td>'.($poner?'<td>2.2.3</td>':'').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>'; $tabla .= '<tr><td><a href="http://stefangabos.ro/php-libraries/zebra-image/" target="_blank">Zebra_Image</a></td>'.($poner ? '<td>2.2.3</td>' : '').'<td><a target="_blank" href="http://www.gnu.org/licenses/lgpl-3.0.txt">LGPL</a></td>';
$tabla .='<tr><td><a href="http://jasny.github.io/bootstrap/" target="_blank">Jasny Bootstrap</a></td>'.($poner?'<td>3.1.0</td>':'').'<td><a target="_blank" href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a></td>'; $tabla .= '<tr><td><a href="http://jasny.github.io/bootstrap/" target="_blank">Jasny Bootstrap</a></td>'.($poner ? '<td>3.1.0</td>' : '').'<td><a target="_blank" href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a></td>';
$tabla .='<tr><td><a href="http://1000hz.github.io/bootstrap-validator/" target="_blank">Bootstrap Validator</a></td>'.($poner?'<td>0.2.1</td>':'').'<td><a target="_blank" href="https://github.com/1000hz/bootstrap-validator/blob/master/LICENSE">MIT</a></td>'; $tabla .= '<tr><td><a href="http://1000hz.github.io/bootstrap-validator/" target="_blank">Bootstrap Validator</a></td>'.($poner ? '<td>0.2.1</td>' : '').'<td><a target="_blank" href="https://github.com/1000hz/bootstrap-validator/blob/master/LICENSE">MIT</a></td>';
$tabla .='<tr><td><a href="https://github.com/tkrotoff/jquery-simplecolorpicker" target="_blank">jquery-simplecolorpicker</a></td>'.($poner?'<td>0.3.0</td>':'').'<td><a target="_blank" href="https://github.com/tkrotoff/jquery-simplecolorpicker/blob/master/LICENSE.txt">MIT</a></td>'; $tabla .= '<tr><td><a href="https://github.com/tkrotoff/jquery-simplecolorpicker" target="_blank">jquery-simplecolorpicker</a></td>'.($poner ? '<td>0.3.0</td>' : '').'<td><a target="_blank" href="https://github.com/tkrotoff/jquery-simplecolorpicker/blob/master/LICENSE.txt">MIT</a></td>';
$tabla .='<tr><td><a href="http://eonasdan.github.io/bootstrap-datetimepicker/" target="_blank">Bootstrap datetimepicker</a></td>'.($poner?'<td>2.1.32</td>':'').'<td><a target="_blank" href="https://github.com/Eonasdan/bootstrap-datetimepicker/blob/master/src/js/bootstrap-datetimepicker.js">MIT</a></td>'; $tabla .= '<tr><td><a href="http://eonasdan.github.io/bootstrap-datetimepicker/" target="_blank">Bootstrap datetimepicker</a></td>'.($poner ? '<td>2.1.32</td>' : '').'<td><a target="_blank" href="https://github.com/Eonasdan/bootstrap-datetimepicker/blob/master/src/js/bootstrap-datetimepicker.js">MIT</a></td>';
$tabla .='<tr><td><a href="http://silviomoreto.github.io/bootstrap-select/" target="_blank">Bootstrap-select</a></td>'.($poner?'<td>1.5.4</td>':'').'<td><a target="_blank" href="https://github.com/silviomoreto/bootstrap-select">MIT</a></td>'; $tabla .= '<tr><td><a href="http://silviomoreto.github.io/bootstrap-select/" target="_blank">Bootstrap-select</a></td>'.($poner ? '<td>1.5.4</td>' : '').'<td><a target="_blank" href="https://github.com/silviomoreto/bootstrap-select">MIT</a></td>';
$tabla .='<tr><td><a href="https://github.com/vitalets/x-editable" target="_blank">X-editable</a></td>'.($poner?'<td>1.5.1</td>':'').'<td><a target="_blank" href="https://github.com/vitalets/x-editable/blob/master/LICENSE-MIT">MIT</a></td>'; $tabla .= '<tr><td><a href="https://github.com/vitalets/x-editable" target="_blank">X-editable</a></td>'.($poner ? '<td>1.5.1</td>' : '').'<td><a target="_blank" href="https://github.com/vitalets/x-editable/blob/master/LICENSE-MIT">MIT</a></td>';
$tabla .='<tr><td><a href="http://momentjs.com/" target="_blank">Moment.js</a></td>'.($poner?'<td>2.5.1</td>':'').'<td><a target="_blank" href="https://github.com/moment/moment/blob/develop/LICENSE">MIT</a></td>'; $tabla .= '<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 .= '</tbody>';
$tabla .='</table>'; $tabla .= '</table>';
return $tabla; return $tabla;
} }
/** /**
* Devuelve la fecha actual * Devuelve la fecha actual.
*
* @param string $formato formato de devolución de la fecha * @param string $formato formato de devolución de la fecha
* @param string $idioma idioma para formatear la fecha, p.ej. es_ES * @param string $idioma idioma para formatear la fecha, p.ej. es_ES
*
* @return string * @return string
*/ */
public function fechaActual($formato = '', $idioma = 'es_ES') public function fechaActual($formato = '', $idioma = 'es_ES')
{ {
if ($formato == '') if ($formato == '') {
$formato = "%d-%b-%y"; $formato = '%d-%b-%y';
}
setlocale(LC_TIME, $idioma); setlocale(LC_TIME, $idioma);
return strftime($formato); return strftime($formato);
} }
/** /**
*
* @return string Mensaje el usuario debe registrarse. * @return string Mensaje el usuario debe registrarse.
*/ */
private function mensajeRegistro() private function mensajeRegistro()
@@ -167,78 +169,87 @@ class AportaContenido {
// Procesaremos todas las invocaciones a métodos en // Procesaremos todas las invocaciones a métodos en
// la función __call() // la función __call()
/** /**
* Procesa las peticiones de contenido de la plantilla. * Procesa las peticiones de contenido de la plantilla.
* @param string $metodo Método a ejecutar *
* @param string $metodo Método a ejecutar
* @param string $parametros Parámetros del método * @param string $parametros Parámetros del método
*
* @return string Contenido devuelto por el método * @return string Contenido devuelto por el método
*/ */
public function __call($metodo, $parametros) public function __call($metodo, $parametros)
{ {
switch ($metodo) { // Dependiendo del método invocado switch ($metodo) { // Dependiendo del método invocado
case 'usuario': case 'usuario':
if ($this->registrado) if ($this->registrado) {
return "Usuario=$this->usuario"; return "Usuario=$this->usuario";
else } else {
return ''; return '';
}
case 'fecha': case 'fecha':
$script = '<script type="text/javascript"> $script = '<script type="text/javascript">
$(function () { $(function () {
$(' . "'#fechaCabecera'" . ").datetimepicker({ $('."'#fechaCabecera'".").datetimepicker({
pick12HourFormat: false, pick12HourFormat: false,
language: 'es', language: 'es',
pickTime: false pickTime: false
}); });
}); });
</script>"; </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>'; $etiqueta = '<label for="fechaCabecera" onClick="$('."'#fechaCabecera'".").data('DateTimePicker').show();".'">'.$this->fechaActual().'</label>';
return $etiqueta . $campo . $script;
case 'aplicacion': return $etiqueta.$campo.$script;
$nombre = explode(" ", PROGRAMA); case 'aplicacion':
$nombre = explode(' ', PROGRAMA);
$nombre = $nombre[2]; $nombre = $nombre[2];
return $nombre . " v" . VERSION;
return $nombre.' v'.VERSION;
case 'menu': // el menú case 'menu': // el menú
if ($this->registrado) { if ($this->registrado) {
return $this->miMenu->insertaMenu(); return $this->miMenu->insertaMenu();
} else { } else {
$salida = FORMULARIO_ACCESO; $salida = FORMULARIO_ACCESO;
if ($this->usuario_inc) { if ($this->usuario_inc) {
$salida.=USUARIO_INCORRECTO; $salida .= USUARIO_INCORRECTO;
} }
//$salida.=MENSAJE_DEMO; //$salida.=MENSAJE_DEMO;
return $salida; return $salida;
} }
case 'opcion': case 'opcion':
if (strstr($this->opcionActual, "&")) { if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode("&", $this->opcionActual); list($opcion, $parametro) = explode('&', $this->opcionActual);
} else { } else {
$opcion = $this->opcionActual; $parametro = ""; $opcion = $this->opcionActual;
$parametro = '';
} }
switch ($opcion) { switch ($opcion) {
case 'bienvenido': case 'bienvenido':
return "Men&uacute; Principal"; return 'Men&uacute; Principal';
case 'principal': case 'principal':
return "Pantalla Inicial"; return 'Pantalla Inicial';
case 'articulos': $opcion = "art&iacute;culos"; case 'articulos': $opcion = 'art&iacute;culos';
case 'elementos': case 'elementos':
case 'ubicaciones': case 'ubicaciones':
case 'usuarios': case 'usuarios':
case 'test': case 'test':
return "Mantenimiento " . ucfirst($opcion); return 'Mantenimiento '.ucfirst($opcion);
case 'configuracion': case 'configuracion':
return 'Configuraci&oacute;n y Preferencias'; 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 'descuadres':return 'Informe de descuadres';
case 'importacion': return 'Importaci&oacute;n de datos'; case 'importacion': return 'Importaci&oacute;n de datos';
case 'copiaseg': return 'Copia de seguridad de datos'; case 'copiaseg': return 'Copia de seguridad de datos';
} }
return ''; return '';
case 'control': 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>'; return '<a href="index.php?cerrarSesion">Cerrar Sesi&oacute;n <span class="glyphicon glyphicon-log-out"></span></a>';
else } else {
return ''; return '';
}
// Para incluir el contenido central de la página // Para incluir el contenido central de la página
case 'contenido': case 'contenido':
// tendremos en cuenta cuál es la opción actual // tendremos en cuenta cuál es la opción actual
@@ -248,52 +259,56 @@ class AportaContenido {
// if (!$this->registrado) { // if (!$this->registrado) {
// return $this->mensajeRegistro(); // return $this->mensajeRegistro();
// } // }
if (strstr($this->opcionActual, "&")) { if (strstr($this->opcionActual, '&')) {
list($opcion, $parametro) = explode("&", $this->opcionActual); list($opcion, $parametro) = explode('&', $this->opcionActual);
} else { } else {
$opcion = $this->opcionActual; $parametro = ""; $opcion = $this->opcionActual;
$parametro = '';
} }
switch ($opcion) { switch ($opcion) {
case 'bienvenido': case 'bienvenido':
$mensaje = '<div class="alert alert-success">'; $mensaje = '<div class="alert alert-success">';
$mensaje .= 'Bienvenid@ ' . $this->usuario . '</div>'; $mensaje .= 'Bienvenid@ '.$this->usuario.'</div>';
case 'principal': // contenido inicial case 'principal': // contenido inicial
$mensaje = ""; $mensaje = '';
$creditos = "$('#creditos').modal({keyboard: false});"; $creditos = "$('#creditos').modal({keyboard: false});";
$centro = '<div class="well well-sm">' . CENTRO . '</div>'; $centro = '<div class="well well-sm">'.CENTRO.'</div>';
$tabla = $this->creaTablaAcercaDe(); $tabla = $this->creaTablaAcercaDe();
$rama_texto = trim(substr(file_get_contents('.git/HEAD'), 16)); $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>':''); $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; return $mensaje.'<br><br><center><img src="img/qrlogo.png" alt="'.PROGRAMA.'" onClick="'.$creditos.'" >'.
'<br><br><label onClick="'.$creditos.'">'.$centro.'</label>'.$rama.'</center>'.CREDITOS_CABECERA.$tabla.CREDITOS_PIE;
case 'articulos': case 'articulos':
case 'ubicaciones': case 'ubicaciones':
case 'test': case 'test':
case 'elementos': case 'elementos':
$this->cargaDatosURL(); $this->cargaDatosURL();
if ($this->datosURL['opc'] == "informe") { if ($this->datosURL['opc'] == 'informe') {
if ($this->perfil['Informe']) { if ($this->perfil['Informe']) {
$this->procesaURL(); $this->procesaURL();
$fichero = 'xml/informe' . ucfirst($opcion) . '.xml'; $fichero = 'xml/informe'.ucfirst($opcion).'.xml';
$salida = TMP.'/informe' . ucfirst($opcion) . '.xml'; $salida = TMP.'/informe'.ucfirst($opcion).'.xml';
//Establece los posibles parámetros del listado. //Establece los posibles parámetros del listado.
$orden = $this->datosURL['orden']; $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']) : ''; $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 = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla = str_replace("{filtro}", $filtro, $plantilla); $plantilla = str_replace('{filtro}', $filtro, $plantilla);
$plantilla = str_replace("{orden}", $orden . $sentido, $plantilla); $plantilla = str_replace('{orden}', $orden.$sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
$informe = new InformePDF($this->bdd, $salida, $this->registrado); $informe = new InformePDF($this->bdd, $salida, $this->registrado);
$informe->crea($salida); $informe->crea($salida);
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
} else { } else {
return $this->mensajePermisos("Informes"); return $this->mensajePermisos('Informes');
} }
} }
if ($this->perfil['Consulta']) { if ($this->perfil['Consulta']) {
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion); $ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta(); return $ele->ejecuta();
} else { } else {
return $this->mensajePermisos(ucfirst($opcion)); return $this->mensajePermisos(ucfirst($opcion));
@@ -301,28 +316,30 @@ class AportaContenido {
case 'usuarios': case 'usuarios':
if ($this->perfil['Usuarios']) { if ($this->perfil['Usuarios']) {
$this->cargaDatosURL(); $this->cargaDatosURL();
if ($this->datosURL['opc'] == "informe") { if ($this->datosURL['opc'] == 'informe') {
if (!$this->pefil['Informe']) { if (!$this->pefil['Informe']) {
$this->procesaURL(); $this->procesaURL();
$fichero = 'xml/informe' . ucfirst($opcion) . '.xml'; $fichero = 'xml/informe'.ucfirst($opcion).'.xml';
$salida = TMP.'/informe' . ucfirst($opcion) . '.xml'; $salida = TMP.'/informe'.ucfirst($opcion).'.xml';
//Establece los posibles parámetros del listado. //Establece los posibles parámetros del listado.
$orden = $this->datosURL['orden']; $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']) : ''; $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 = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla '.$fichero);
$plantilla = str_replace("{filtro}", $filtro, $plantilla); $plantilla = str_replace('{filtro}', $filtro, $plantilla);
$plantilla = str_replace("{orden}", $orden . $sentido, $plantilla); $plantilla = str_replace('{orden}', $orden.$sentido, $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
$informe = new InformePDF($this->bdd, $salida, $this->registrado); $informe = new InformePDF($this->bdd, $salida, $this->registrado);
$informe->crea($salida); $informe->crea($salida);
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
} else { } else {
return $this->mensajePermisos("Informes"); return $this->mensajePermisos('Informes');
} }
} }
$ele = new Mantenimiento($this->bdd, $this->perfil, $opcion); $ele = new Mantenimiento($this->bdd, $this->perfil, $opcion);
return $ele->ejecuta(); return $ele->ejecuta();
} else { } else {
return $this->mensajePermisos('Usuarios'); return $this->mensajePermisos('Usuarios');
@@ -330,6 +347,7 @@ class AportaContenido {
case 'configuracion': case 'configuracion':
if ($this->perfil['Config']) { if ($this->perfil['Config']) {
$conf = new Configuracion(); $conf = new Configuracion();
return $conf->ejecuta(); return $conf->ejecuta();
} else { } else {
return $this->mensajePermisos('Configuraci&oacute;n'); return $this->mensajePermisos('Configuraci&oacute;n');
@@ -337,6 +355,7 @@ class AportaContenido {
case 'informeInventario': case 'informeInventario':
if ($this->perfil['Informe']) { if ($this->perfil['Informe']) {
$info = new InformeInventario($this->bdd); $info = new InformeInventario($this->bdd);
return $info->ejecuta(); return $info->ejecuta();
} else { } else {
return $this->mensajePermisos('Informes'); return $this->mensajePermisos('Informes');
@@ -344,36 +363,39 @@ class AportaContenido {
case 'importacion': case 'importacion':
if ($this->perfil['Modificacion'] && $this->perfil['Borrado']) { if ($this->perfil['Modificacion'] && $this->perfil['Borrado']) {
$import = new Importacion($this->bdd, $this->registrado); $import = new Importacion($this->bdd, $this->registrado);
return $import->ejecuta(); return $import->ejecuta();
} else { } 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': case 'copiaseg':
if ($this->perfil['Config']) { if ($this->perfil['Config']) {
$copia = new CopiaSeguridad(); $copia = new CopiaSeguridad();
if (isset($_GET['confirmado']) && $_GET['confirmado'] == "1") { if (isset($_GET['confirmado']) && $_GET['confirmado'] == '1') {
if (!$copia->creaCopia()) { if (!$copia->creaCopia()) {
$tipo = "danger"; $tipo = 'danger';
$cabecera = "ERROR"; $cabecera = 'ERROR';
} else { } else {
$tipo = "info"; $tipo = 'info';
$cabecera = "INFORMACIÓN"; $cabecera = 'INFORMACIÓN';
} }
return $this->panel($cabecera, $copia->mensaje(), $tipo); return $this->panel($cabecera, $copia->mensaje(), $tipo);
} else { } else {
return $copia->dialogo(); return $copia->dialogo();
} }
} else { } else {
return $this->mensajePermisos("Copias de seguridad"); return $this->mensajePermisos('Copias de seguridad');
} }
} // Fin del contenido } // Fin del contenido
case 'usuario_incorrecto': case 'usuario_incorrecto':
$this->usuario_inc = true; $this->usuario_inc = true;
return; return;
case 'registro': // Si está registrado mostrar bienvenida case 'registro': // Si está registrado mostrar bienvenida
// si no, un enlace // si no, un enlace
if ($this->bEstaRegistrado) { if ($this->bEstaRegistrado) {
return "Bienvenid@ <b>$this->sUsuario</b><hr />" . return "Bienvenid@ <b>$this->sUsuario</b><hr />".
'<a href="index.php?cerrarSesion">Cerrar sesi&oacute;n</a>'; '<a href="index.php?cerrarSesion">Cerrar sesi&oacute;n</a>';
} else { } else {
return ''; return '';
@@ -394,35 +416,36 @@ class AportaContenido {
} }
/** /**
*
* @param string $tipo * @param string $tipo
*
* @return string * @return string
*/ */
public function mensajePermisos($tipo) 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) private function devuelveInforme($informe)
{ {
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; $letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf"; $nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf';
$informe->guardaArchivo($nombre); $informe->guardaArchivo($nombre);
return '<div class="container"> return '<div class="container">
<!--<a href="' . $nombre . '" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>--> <!--<a href="'.$nombre.'" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="' . $nombre . '" type="application/pdf" width="100%" height="700" style="float:left;"> <object data="'.$nombre.'" type="application/pdf" width="100%" height="700" style="float:left;">
</object> </object>
</div>'; </div>';
} }
public function panel($cabecera, $mensaje, $tipo) public function panel($cabecera, $mensaje, $tipo)
{ {
$panel = '<div class="panel panel-' . $tipo . '"><div class="panel-heading">'; $panel = '<div class="panel panel-'.$tipo.'"><div class="panel-heading">';
$panel .= '<h3 class="panel-title">' . $cabecera . '</h3></div>'; $panel .= '<h3 class="panel-title">'.$cabecera.'</h3></div>';
$panel .= '<div class="panel-body">'; $panel .= '<div class="panel-body">';
$panel .= $mensaje; $panel .= $mensaje;
$panel .= '</div>'; $panel .= '</div>';
return $panel; return $panel;
} }
} }
?>

View File

@@ -1,6 +1,5 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -16,59 +15,60 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
class Configuracion { class Configuracion
private $configuracion = "inc/configuracion.inc"; {
private $confNueva = "inc/configuracion.new"; private $configuracion = 'inc/configuracion.inc';
private $confAnterior = "inc/configuracion.ant"; private $confNueva = 'inc/configuracion.new';
private $confAnterior = 'inc/configuracion.ant';
private $datosConf; private $datosConf;
//Campos del fichero de configuración que se van a editar. //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; private $campos;
public function __construct() public function __construct()
{ {
$this->campos = implode(",", $this->lista); $this->campos = implode(',', $this->lista);
} }
//Hecho público para poder efectuar los tests correspondientes. //Hecho público para poder efectuar los tests correspondientes.
public function obtieneFichero() public function obtieneFichero()
{ {
return file_get_contents($this->configuracion, FILE_TEXT); return file_get_contents($this->configuracion, FILE_TEXT);
} }
public function obtieneLista() public function obtieneLista()
{ {
return $this->lista; return $this->lista;
} }
public function obtieneDatos($linea, &$clave, &$valor) public function obtieneDatos($linea, &$clave, &$valor)
{ {
$filtro = str_replace("'", "", $linea); $filtro = str_replace("'", '', $linea);
list($clave, $valor) = explode(",", $filtro); list($clave, $valor) = explode(',', $filtro);
list($resto, $campo) = explode("(", $clave); list($resto, $campo) = explode('(', $clave);
list($valor, $resto) = explode(")", $valor); list($valor, $resto) = explode(')', $valor);
list($resto, $clave) = explode("(", $clave); list($resto, $clave) = explode('(', $clave);
$valor = trim($valor); $valor = trim($valor);
} }
private function creaTitulo($titulo, $ayuda) private function creaTitulo($titulo, $ayuda)
{ {
return '<td style="vertical-align:middle"><a class="dato" href="#" data-placement="right" data-content="'.$ayuda.'">'.$titulo.'</a></td>'; 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(); $fichero = $this->obtieneFichero();
$datos = explode("\n", $fichero); $datos = explode("\n", $fichero);
$grabar = isset($_POST['SERVIDOR']); $grabar = isset($_POST['SERVIDOR']);
if ($grabar) { if ($grabar) {
$fsalida = @fopen($this->confNueva, "wb"); $fsalida = @fopen($this->confNueva, 'wb');
} }
foreach ($datos as $linea) { foreach ($datos as $linea) {
if (stripos($linea, "DEFINE") !== false) { if (stripos($linea, 'DEFINE') !== false) {
//Comprueba que tenga una definición correcta //Comprueba que tenga una definición correcta
$this->obtieneDatos($linea, $clave, $valor); $this->obtieneDatos($linea, $clave, $valor);
$this->datosConf[$clave] = $valor; $this->datosConf[$clave] = $valor;
if ($grabar && stripos($this->campos, $clave) !== false) { if ($grabar && stripos($this->campos, $clave) !== false) {
$linea = str_replace($valor, $_POST[$clave], $linea); $linea = str_replace($valor, $_POST[$clave], $linea);
@@ -78,96 +78,98 @@ class Configuracion {
//$salida .= "Post=" . var_export($_POST, true); //$salida .= "Post=" . var_export($_POST, true);
} }
if ($grabar) { if ($grabar) {
$registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n"; $registro = substr($linea, 0, 2) == '?>' ? $linea : $linea."\n";
fwrite($fsalida, $registro); fwrite($fsalida, $registro);
} }
} }
$salida = $this->formulario(); $salida = $this->formulario();
if ($grabar) { if ($grabar) {
$salida.='<div class="alert alert-success">Configuraci&oacute;n guardada correctamente</div>'; $salida .= '<div class="alert alert-success">Configuraci&oacute;n guardada correctamente</div>';
fclose($fsalida); fclose($fsalida);
//unlink($this->confAnterior); //unlink($this->confAnterior);
rename($this->configuracion, $this->confAnterior); rename($this->configuracion, $this->confAnterior);
rename($this->confNueva, $this->configuracion); rename($this->confNueva, $this->configuracion);
unlink($this->confAnterior); unlink($this->confAnterior);
} }
return $salida; return $salida;
} }
private function formulario() { 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", $coloresLateral = ['Original' => '#C4FAEC', 'Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db',
"Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1"); 'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Morado' => '#6633FF',
$coloresFondo = array("Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db", 'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1'];
"Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Rojo" => "#ff887c", $coloresFondo = ['Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db',
"Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1", "Original" => '#F3FEC8'); 'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Rojo' => '#ff887c',
$personal = $this->datosConf['ESTILO'] == "personal" ? 'selected' : ' '; 'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1', 'Original' => '#F3FEC8'];
$bluecurve = $this->datosConf['ESTILO'] == "bluecurve" ? 'selected' : ' '; $personal = $this->datosConf['ESTILO'] == 'personal' ? 'selected' : ' ';
$cristal = $this->datosConf['ESTILO'] == "cristal" ? 'selected' : ' '; $bluecurve = $this->datosConf['ESTILO'] == 'bluecurve' ? 'selected' : ' ';
$bootst = $this->datosConf['ESTILO'] == "bootstrap" ? 'selected' : ' '; $cristal = $this->datosConf['ESTILO'] == 'cristal' ? 'selected' : ' ';
$normal = $this->datosConf['PLANTILLA'] == "normal" ? 'selected' : ' '; $bootst = $this->datosConf['ESTILO'] == 'bootstrap' ? 'selected' : ' ';
$bootstrap = $this->datosConf['PLANTILLA'] == "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 = '<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=1 class="tablaDatos"><tbody>';
$salida.='<p align="center"><table border=2 class="table table-hover"><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 .= '<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('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('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('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 value="normal" '.$normal.'>normal</option>';
$salida.='<option ' . $bootstrap . '>bootstrap</option></select></td></tr>'; $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 value="personal" '.$personal.'>personal</option>';
$salida.='<option ' . $bluecurve . '>bluecurve</option>'; $salida .= '<option '.$bluecurve.'>bluecurve</option>';
$salida.='<option ' . $bootst . '>bootstrap</option>'; $salida .= '<option '.$bootst.'>bootstrap</option>';
$salida.='<option ' . $cristal . '>cristal</option></select></td></tr>'; $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) { foreach ($coloresLateral as $color => $codigo) {
$selec = ""; $selec = '';
if (trim($this->datosConf['COLORLAT']) == $codigo) { if (trim($this->datosConf['COLORLAT']) == $codigo) {
$selec = "selected"; $selec = 'selected';
} }
$salida.='<option value="' . $codigo . '" ' . $selec . ' >' . $color . '</option>'; $salida .= '<option value="'.$codigo.'" '.$selec.' >'.$color.'</option>';
} }
$salida.='</select></td></tr>'; $salida .= '</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) { foreach ($coloresFondo as $color => $codigo) {
$selec = ""; $selec = '';
if (trim($this->datosConf['COLORFON']) == $codigo) { if (trim($this->datosConf['COLORFON']) == $codigo) {
$selec = "selected"; $selec = 'selected';
} }
$salida.='<option value="' . $codigo . '" ' . $selec . ' >' . $color . '</option>'; $salida .= '<option value="'.$codigo.'" '.$selec.' >'.$color.'</option>';
} }
$salida.='</select></td></tr>'; $salida .= '</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 .= '<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('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('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', '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('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('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('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('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('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> $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> <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>'; <button type="submit" class="btn btn-primary" name="aceptar"><span class="glyphicon glyphicon-ok"></span> Aceptar</td></tr></p>';
$salida.='</form></div></center>'; $salida .= '</form></div></center>';
$salida.="<script> $salida .= "<script>
$(document).ready(function() { $(document).ready(function() {
$('select[name=" . '"COLORFON"' . "]').on('change', function() { $('select[name=".'"COLORFON"'."]').on('change', function() {
$(document.body).css('background-color', $('select[name=" . '"COLORFON"' . "]').val()); $(document.body).css('background-color', $('select[name=".'"COLORFON"'."]').val());
$('.main').css('background-color', $('select[name=" . '"COLORFON"' . "]').val()); $('.main').css('background-color', $('select[name=".'"COLORFON"'."]').val());
}); });
$('select[name=" . '"COLORLAT"' . "]').on('change', function() { $('select[name=".'"COLORLAT"'."]').on('change', function() {
$('.sidebar').css('background-color', $('select[name=" . '"COLORLAT"' . "]').val()); $('.sidebar').css('background-color', $('select[name=".'"COLORLAT"'."]').val());
}); });
$('select[name=" . '"COLORLAT"' . "]').simplecolorpicker({theme: 'glyphicons'}); $('select[name=".'"COLORLAT"'."]').simplecolorpicker({theme: 'glyphicons'});
$('select[name=" . '"COLORFON"' . "]').simplecolorpicker({theme: 'glyphicons'}); $('select[name=".'"COLORFON"'."]').simplecolorpicker({theme: 'glyphicons'});
$('.dato').popover({trigger: 'hover'}); $('.dato').popover({trigger: 'hover'});
}); });
</script>"; </script>";
return $salida; return $salida;
} }
} }
?>

View File

@@ -1,6 +1,5 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2014, Ricardo Montañana Gómez * @copyright Copyright (c) 2014, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -8,21 +7,21 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
class CopiaSeguridad { class CopiaSeguridad
{
private $mensaje; private $mensaje;
private $baseDatos; private $baseDatos;
private $imagenes; private $imagenes;
public function creaCopia() public function creaCopia()
{ {
if (!$this->copiaBaseDatos()) { if (!$this->copiaBaseDatos()) {
@@ -34,95 +33,106 @@ class CopiaSeguridad {
if (!$this->empaqueta()) { if (!$this->empaqueta()) {
return false; return false;
} }
return true; return true;
} }
public function dialogo() public function dialogo()
{ {
$dialogo = '<div class="container col-5"><div class="jumbotron"> $dialogo = '<div class="container col-5"><div class="jumbotron">
<h1>Copia de Seguridad</h1> <h1>Copia de Seguridad</h1>
<p>¿Desea realizar una copia de seguridad de todos los datos de la Base de Datos y de todas las Imágenes?</p> <p>¿Desea realizar una copia de seguridad de todos los datos de la Base de Datos y de todas las Imágenes?</p>
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href=' . "'index.php'" . '"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a> <p><a class="btn btn-primary btn-lg" role="button" onClick="location.href='."'index.php'".'"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href=' . "'index.php?copiaseg&confirmado=1'" . '"> <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> <span class="glyphicon glyphicon-cloud-download"></span> Continuar</a></p>
</div></div>'; </div></div>';
return $dialogo; return $dialogo;
} }
private function copiaBaseDatos()
private function copiaBaseDatos()
{ {
$archivo_sql = TMP."/baseDatos" . BASEDATOS . ".sql"; $archivo_sql = TMP.'/baseDatos'.BASEDATOS.'.sql';
$baseDatosComprimida = $archivo_sql . ".gz"; $baseDatosComprimida = $archivo_sql.'.gz';
$this->baseDatos = $baseDatosComprimida; $this->baseDatos = $baseDatosComprimida;
if (file_exists($baseDatosComprimida)) { if (file_exists($baseDatosComprimida)) {
unlink($baseDatosComprimida); unlink($baseDatosComprimida);
} }
$comando = escapeshellcmd(MYSQLDUMP . ' -h ' . SERVIDOR . ' -P ' . PUERTO . ' -u ' . USUARIO . ' --password=' . CLAVE . ' --result-file=' . $archivo_sql . ' ' . BASEDATOS); $comando = escapeshellcmd(MYSQLDUMP.' -h '.SERVIDOR.' -P '.PUERTO.' -u '.USUARIO.' --password='.CLAVE.' --result-file='.$archivo_sql.' '.BASEDATOS);
$comando2 = escapeshellcmd(GZIP . ' -9f ' . $archivo_sql); $comando2 = escapeshellcmd(GZIP.' -9f '.$archivo_sql);
exec($comando); exec($comando);
exec($comando2); exec($comando2);
if (filesize($baseDatosComprimida) < 1024) { if (filesize($baseDatosComprimida) < 1024) {
//No se ha realizado la copia de seguridad //No se ha realizado la copia de seguridad
$mensaje = "La copia de seguridad no se ha realizado correctamente.<br><br>"; $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 .= '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 .= 'y que los datos de acceso a la base de datos sean correctos.<br>';
$mensaje .= "mysqldump=[" . MYSQLDUMP . "]<br>"; $mensaje .= 'mysqldump=['.MYSQLDUMP.']<br>';
$mensaje .= "gzip=[" . GZIP . "]"; $mensaje .= 'gzip=['.GZIP.']';
$this->mensaje = $mensaje; $this->mensaje = $mensaje;
$this->error = true; $this->error = true;
return false; return false;
} }
return true; return true;
} }
private function copiaImagenes() private function copiaImagenes()
{ {
$copiaImagenes = TMP."/Imagenes.tbz"; $copiaImagenes = TMP.'/Imagenes.tbz';
$this->imagenes = $copiaImagenes; $this->imagenes = $copiaImagenes;
if (file_exists($copiaImagenes)) { if (file_exists($copiaImagenes)) {
unlink($copiaImagenes); unlink($copiaImagenes);
} }
$comando = escapeshellcmd('tar cf ' . $copiaImagenes . ' ' . IMAGEDATA); $comando = escapeshellcmd('tar cf '.$copiaImagenes.' '.IMAGEDATA);
exec($comando); exec($comando);
if (filesize($copiaImagenes) == 0) { if (filesize($copiaImagenes) == 0) {
$this->error = true; $this->error = true;
$mensaje = "No se ha podido comprimir el directorio de las imágenes " . IMAGEDATA . "<br>"; $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 .= 'Compruebe que la ruta de acceso al programa tar en configuraci&oacute;n est&aacute; correctamente establecida';
$this->mensaje = $mensaje; $this->mensaje = $mensaje;
return false; return false;
} }
return true; return true;
} }
private function empaqueta() private function empaqueta()
{ {
// Empaqueta los dos archivos en el que va a devolver // 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)) { if (file_exists($nombreCopia)) {
unlink($nombreCopia); unlink($nombreCopia);
} }
$comando = escapeshellcmd('tar cf ' . $nombreCopia . ' ' . $this->baseDatos . ' ' . $this->imagenes); $comando = escapeshellcmd('tar cf '.$nombreCopia.' '.$this->baseDatos.' '.$this->imagenes);
exec($comando); exec($comando);
if (filesize($nombreCopia) ==0 || !file_exists($nombreCopia)) { if (filesize($nombreCopia) == 0 || !file_exists($nombreCopia)) {
$this->error = true; $this->error = true;
$mensaje = "No se ha creado el paquete con los archivos de imágenes en [<b>" . $this->imagenes . "</b>] y <br>"; $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 .= ' 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 .= 'Compruebe que los datos de configuración están correctamente establecidos <br>';
$mensaje .= "El comando de copia fue [" . $comando . "]<br>"; $mensaje .= 'El comando de copia fue ['.$comando.']<br>';
$mensaje .= "gzip=[" . GZIP . "]"; $mensaje .= 'gzip=['.GZIP.']';
$this->mensaje = $mensaje; $this->mensaje = $mensaje;
return false; return false;
} }
$this->error = false; $this->error = false;
unlink ($this->baseDatos); unlink($this->baseDatos);
unlink ($this->imagenes); unlink($this->imagenes);
$mensaje = 'Copia de seguridad realizada con &eacute;xito.<br><br>Pulse sobre el siguiente enlace para descargar:<br><br>'; $mensaje = 'Copia de seguridad realizada con &eacute;xito.<br><br>Pulse sobre el siguiente enlace para descargar:<br><br>';
$mensaje .= '<a href="' . $nombreCopia . '">Descargar Copia de Seguridad de Datos</a><br><br>'; $mensaje .= '<a href="'.$nombreCopia.'">Descargar Copia de Seguridad de Datos</a><br><br>';
$mensaje .= 'El paquete de copia contiene un archivo con la copia de la información de la base de datos y un archivo que contiene el directorio de las fotografías e imágenes asociadas a los datos'; $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; $this->mensaje = $mensaje;
return true; return true;
} }
public function mensaje ()
public function mensaje()
{ {
return $this->mensaje; return $this->mensaje;
} }
} }
?>

159
Csv.php
View File

@@ -1,7 +1,6 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -9,28 +8,26 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * 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; private $nombre;
/** /**
* @var FILE manejador del fichero * @var FILE manejador del fichero
*/ */
private $fichero = NULL; private $fichero = null;
/** /**
* @var xml conulta asociada a este fichero * @var xml conulta asociada a este fichero
@@ -43,7 +40,6 @@ class Csv {
private $bdd; private $bdd;
/** /**
*
* @var int Número de registros en el fichero csv * @var int Número de registros en el fichero csv
*/ */
private $numRegistros; private $numRegistros;
@@ -59,8 +55,7 @@ class Csv {
private $datosFichero; private $datosFichero;
/** /**
* Indices a los campos correspondientes * Indices a los campos correspondientes.
*
*/ */
private $idElemento; private $idElemento;
private $idArticulo; private $idArticulo;
@@ -71,9 +66,10 @@ class Csv {
private $nSerie; 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. * Constructor de la clase.
*
* @param BaseDatos $baseDatos Manejador de la base de datos * @param BaseDatos $baseDatos Manejador de la base de datos
*/ */
public function __construct($baseDatos) public function __construct($baseDatos)
@@ -82,22 +78,22 @@ class Csv {
} }
/** /**
* Crea un fichero csv con el nombre especificado * Crea un fichero csv con el nombre especificado.
* @param String $fichero Nombre del fichero *
* @param string $fichero Nombre del fichero
*/ */
public function crea($fichero) public function crea($fichero)
{ {
$this->nombre = $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 * @param array $datos escribe la línea en el archivo
*/ */
public function escribeLinea($datos) 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() public function __destruct()
@@ -107,18 +103,17 @@ class Csv {
public function cierra() 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) 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 // 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) { foreach ($consulta->Pagina->Cuerpo->Col as $campo) {
$campos[] = $campo['Titulo']; $campos[] = $campo['Titulo'];
} }
@@ -126,7 +121,7 @@ class Csv {
// Escribe los datos de los campos // Escribe los datos de los campos
$this->bdd->ejecuta($consulta->Datos->Consulta); $this->bdd->ejecuta($consulta->Datos->Consulta);
while ($fila = $this->bdd->procesaResultado()) { while ($fila = $this->bdd->procesaResultado()) {
$campos = array(); $campos = [];
foreach ($consulta->Pagina->Cuerpo->Col as $campo) { foreach ($consulta->Pagina->Cuerpo->Col as $campo) {
$campos[] = $fila[(string) $campo['Nombre']]; $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) public function cargaCSV($ficheroCSV)
{ {
$this->nombre = $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); list($archivo, $idCabecera, $cabecera) = fgetcsv($this->fichero);
while ($linea = fgetcsv($this->fichero)) { while ($linea = fgetcsv($this->fichero)) {
$datosFichero[] = $linea; $datosFichero[] = $linea;
@@ -153,70 +147,69 @@ class Csv {
} }
/** /**
* Muestra un resumen de los datos del fichero csv cargado por pantalla * Muestra un resumen de los datos del fichero csv cargado por pantalla.
*
*/ */
public function resumen() public function resumen()
{ {
//$mensaje .= //$mensaje .=
$mensaje = "<center><h1>Archivo [inventario" . $this->cabecera[0] . "]</h1>"; $mensaje = '<center><h1>Archivo [inventario'.$this->cabecera[0].']</h1>';
$mensaje .= "<h2>id=[" . $this->cabecera[1] . "] Descripci&oacute;n=[" . $this->cabecera[2] . "]</h2><br>"; $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>'; $mensaje .= '<table border=1 class="table table-striped table-bordered table-condensed table-hover"><theader>';
foreach ($this->datosFichero[0] as $campo) { foreach ($this->datosFichero[0] as $campo) {
$dato = $campo; $dato = $campo;
$mensaje .= "<th><b>$dato</b></th>"; $mensaje .= "<th><b>$dato</b></th>";
} }
$mensaje .= "<th><b>Acci&oacute;n</b></th>"; $mensaje .= '<th><b>Acci&oacute;n</b></th>';
$mensaje .="</theader><tbody>"; $mensaje .= '</theader><tbody>';
$this->cargaIndices($this->datosFichero[0]); $this->cargaIndices($this->datosFichero[0]);
//echo "$mensaje contar Datosfichero=[".count($datosFichero)."]"; //echo "$mensaje contar Datosfichero=[".count($datosFichero)."]";
for ($i = 1; $i < count($this->datosFichero); $i++) { for ($i = 1; $i < count($this->datosFichero); $i++) {
$mensaje .= "<tr>"; $mensaje .= '<tr>';
$primero = true; $primero = true;
foreach ($this->datosFichero[$i] as $dato) { foreach ($this->datosFichero[$i] as $dato) {
if ($primero) { if ($primero) {
$primero = false; $primero = false;
switch ($dato) { switch ($dato) {
case 'S': $estado = "-Baja-"; case 'S': $estado = '-Baja-';
$color = "danger"; $color = 'danger';
break; break;
case 'Alta': $estado = "-Alta-"; case 'Alta': $estado = '-Alta-';
$color = "primary"; $color = 'primary';
break; break;
case "N" : $estado = $this->compruebaCantidades($i); case 'N': $estado = $this->compruebaCantidades($i);
if ($estado != 0) { if ($estado != 0) {
$color = "warning"; $color = 'warning';
if ($estado > 0) { if ($estado > 0) {
$estado = "+" . $estado; $estado = '+'.$estado;
} }
} else { } else {
$estado = "igual"; $estado = 'igual';
$color = "info"; $color = 'info';
} }
break; break;
default: throw new Exception("El archivo csv tiene un formato incorrecto.<br>Bajas=[$dato]"); 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 .= '<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 .= $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"> $mensaje .= '<form method="post" name="Aceptar" action="index.php?importacion&opc=ejecutar">
<button type="button" name="Cancelar" value="Cancelar" onClick="location.href=' . "'index.php'" . '" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Cancelar</button> <button type="button" name="Cancelar" value="Cancelar" onClick="location.href='."'index.php'".'" class="btn btn-danger"><span class="glyphicon glyphicon-remove"></span> Cancelar</button>
<button type="submit" name="Aceptar" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button> <button type="submit" name="Aceptar" class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button>
<input type="hidden" name="ficheroCSV" value="' . $this->nombre . '"> <input type="hidden" name="ficheroCSV" value="'.$this->nombre.'">
</form></center>'; </form></center>';
return $mensaje; return $mensaje;
} }
/** /**
* * @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no
* @param $array línea de datos del fichero csv para comprobar las cantidades si se han modificado o no *
* @return string * @return string
*/ */
private function compruebaCantidades($i) private function compruebaCantidades($i)
@@ -225,61 +218,62 @@ class Csv {
return $this->datosFichero[$i][$this->cantidadReal] - $this->datosFichero[$i][$this->cantidad]; 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 = '<div class="panel panel-'.$tipo.'"><div class="panel-heading">';
$mensaje .= '<h3 class="panel-title">' . $cabecera . '</h3></div>'; $mensaje .= '<h3 class="panel-title">'.$cabecera.'</h3></div>';
$mensaje .= '<div class="panel-body">'; $mensaje .= '<div class="panel-body">';
$mensaje .= $info; $mensaje .= $info;
$mensaje .= '</div>'; $mensaje .= '</div>';
$mensaje .= '</div>'; $mensaje .= '</div>';
return $mensaje; return $mensaje;
} }
private function escribeLog($comando) private function escribeLog($comando)
{ {
$fp = fopen($this->nombre . ".log", "a"); $fp = fopen($this->nombre.'.log', 'a');
$linea = strftime("%Y/%m/%d") . "|" . $this->nombre . "|" . $comando; $linea = strftime('%Y/%m/%d').'|'.$this->nombre.'|'.$comando;
fputs($fp, $linea . "\n"); fwrite($fp, $linea."\n");
fclose($fp); fclose($fp);
} }
private function bajaElemento($i) private function bajaElemento($i)
{ {
$id = $this->datosFichero[$i][$this->idElemento]; $id = $this->datosFichero[$i][$this->idElemento];
$comando = 'delete from Elementos where id="' . $id . '";'; $comando = 'delete from Elementos where id="'.$id.'";';
$this->escribeLog($comando); $this->escribeLog($comando);
if (!$this->bdd->ejecuta($comando)) { if (!$this->bdd->ejecuta($comando)) {
throw new Exception("Baja-" . $this->bdd->mensajeError, $this->bdd->error); throw new Exception('Baja-'.$this->bdd->mensajeError, $this->bdd->error);
} }
} }
private function modificaElemento($i) private function modificaElemento($i)
{ {
$id = $this->datosFichero[$i][$this->idElemento]; $id = $this->datosFichero[$i][$this->idElemento];
$comando = 'update Elementos set Cantidad=' . $this->datosFichero[$i][$this->cantidadReal] . ' where id="' . $id . '";'; $comando = 'update Elementos set Cantidad='.$this->datosFichero[$i][$this->cantidadReal].' where id="'.$id.'";';
$this->escribeLog($comando); $this->escribeLog($comando);
if (!$this->bdd->ejecuta($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) private function altaElemento($i)
{ {
if ($this->cabecera[0] == "Articulo") { if ($this->cabecera[0] == 'Articulo') {
$idUbicacion = $this->datosFichero[$i][$this->idUbicacion]; $idUbicacion = $this->datosFichero[$i][$this->idUbicacion];
$idArticulo = $this->cabecera[1]; $idArticulo = $this->cabecera[1];
$comando = 'select id from Ubicaciones where Descripcion="' . $this->datosFichero[$i][$this->desUbicacion] . '";'; $comando = 'select id from Ubicaciones where Descripcion="'.$this->datosFichero[$i][$this->desUbicacion].'";';
} else { } else {
$idUbicacion = $this->cabecera[1]; $idUbicacion = $this->cabecera[1];
$idArticulo = $this->datosFichero[$i][$this->idArticulo]; $idArticulo = $this->datosFichero[$i][$this->idArticulo];
} }
$idArt = $datosFichero[$i]; $idArt = $datosFichero[$i];
$comando = 'insert into Elementos () values (null,' . $idArticulo . ',' . $idUbicacion . ',"' . $this->datosFichero[$i][$this->nSerie]; $comando = 'insert into Elementos () values (null,'.$idArticulo.','.$idUbicacion.',"'.$this->datosFichero[$i][$this->nSerie];
$comando .= '",' . $this->datosFichero[$i][$this->cantidadReal] . ',"' . $this->datosFichero[$i][$this->fechaCompra] . '");'; $comando .= '",'.$this->datosFichero[$i][$this->cantidadReal].',"'.$this->datosFichero[$i][$this->fechaCompra].'");';
$this->escribeLog($comando); $this->escribeLog($comando);
if (!$this->bdd->ejecuta($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++) { for ($i = 0; $i < count($campos); $i++) {
switch ($campos[$i]) { switch ($campos[$i]) {
case "Cant. Real": $this->cantidadReal = $i; case 'Cant. Real': $this->cantidadReal = $i;
break; break;
case "Fecha C.": $this->fechaCompra = $i; case 'Fecha C.': $this->fechaCompra = $i;
break; break;
case "idUbic": $this->idUbicacion = $i; case 'idUbic': $this->idUbicacion = $i;
break; break;
case "idArt": $this->idArticulo = $i; case 'idArt': $this->idArticulo = $i;
break; break;
case "idElem": $this->idElemento = $i; case 'idElem': $this->idElemento = $i;
break; break;
case "Cantidad": $this->cantidad = $i; case 'Cantidad': $this->cantidad = $i;
break; break;
case "N Serie": $this->nSerie = $i; case 'N Serie': $this->nSerie = $i;
break; 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() public function ejecutaFichero()
{ {
@@ -333,15 +327,17 @@ class Csv {
$acciones++; $acciones++;
} }
break; 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."; $mensaje = "Se han procesado correctamente $acciones acciones en la Base de Datos.";
$this->bdd->confirmaTransaccion(); $this->bdd->confirmaTransaccion();
return $this->panelMensaje($mensaje, "success", "Informaci&oacute;n");
return $this->panelMensaje($mensaje, 'success', 'Informaci&oacute;n');
} catch (Exception $e) { } catch (Exception $e) {
$this->bdd->abortaTransaccion(); $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); return $this->panelMensaje($mensaje);
} }
} }
@@ -352,13 +348,10 @@ class Csv {
for ($i = 1; $i < 80; $i++) { for ($i = 1; $i < 80; $i++) {
//sleep(1); //sleep(1);
$progreso = $i; $progreso = $i;
echo '<script>actProgreso(' . $progreso . ');</script>'; echo '<script>actProgreso('.$progreso.');</script>';
//echo str_repeat(' ',1024*64); //echo str_repeat(' ',1024*64);
flush(); flush();
//echo '$(".bar").css("width", "'.$progreso.'");'; //echo '$(".bar").css("width", "'.$progreso.'");';
} }
} }
} }
?>

View File

@@ -1,23 +1,21 @@
<?php <?php
/** /**
* @package Inventario * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt
* @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario.
* This file is part of Inventario. * Inventario is free software: you can redistribute it and/or modify
* Inventario is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by
* it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or
* the Free Software Foundation, either version 3 of the License, or * (at your option) any later version.
* (at your option) any later version. *
* * Inventario is distributed in the hope that it will be useful,
* Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.
* GNU General Public License for more details. *
* * You should have received a copy of the GNU General Public License
* You should have received a copy of the GNU General Public License * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. */
*
*/
// //
// Esta clase procesará una página sustituyendo // Esta clase procesará una página sustituyendo
// las marcas {} por el contenido que proceda. // las marcas {} por el contenido que proceda.
@@ -27,46 +25,49 @@
// y una referencia al objeto cuyos métodos deberán // y una referencia al objeto cuyos métodos deberán
// aportar los contenidos. // aportar los contenidos.
// //
class Distribucion { class Distribucion
// Variable para conservar la plantilla {
private $plantilla; // Variable para conservar la plantilla
// Matriz que contendrá los nombres de elementos private $plantilla;
private $elementos; // Matriz que contendrá los nombres de elementos
// Referencia al objeto cuyos métodos serán private $elementos;
// invocados para aportar el contenido // Referencia al objeto cuyos métodos serán
private $objeto; // invocados para aportar el contenido
// Constructor de la clase private $objeto;
public function __construct($archivo, $objeto)
{ // Constructor de la clase
// Recuperamos el contenido del archivo public function __construct($archivo, $objeto)
$this->plantilla=file_get_contents($archivo) {
// Recuperamos el contenido del archivo
$this->plantilla = file_get_contents($archivo)
or die('Fallo en la apertura de la plantilla '.$archivo); or die('Fallo en la apertura de la plantilla '.$archivo);
// y guardamos la referencia al objeto // y guardamos la referencia al objeto
$this->objeto=$objeto; $this->objeto = $objeto;
// Extraemos todas las marcas de contenido // Extraemos todas las marcas de contenido
preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla,$el, PREG_PATTERN_ORDER); preg_match_all('/\{[A-Za-z]+\}/', $this->plantilla, $el, PREG_PATTERN_ORDER);
// Nos quedamos con la matriz de resultados // Nos quedamos con la matriz de resultados
$this->elementos=$el[0]; $this->elementos = $el[0];
} }
// Este método es el encargado de procesar la plantilla
public function procesaPlantilla() // Este método es el encargado de procesar la plantilla
{ public function procesaPlantilla()
// Tomamos la plantilla en una variable local, para {
// así no modificar el contenido original // Tomamos la plantilla en una variable local, para
$pagina=$this->plantilla; // así no modificar el contenido original
// Recorremos la matriz de marcas de contenido $pagina = $this->plantilla;
foreach($this->elementos as $el) { // Recorremos la matriz de marcas de contenido
// Eliminamos los delimitadores { y } foreach ($this->elementos as $el) {
$el=substr($el,1,strlen($el)-2); // Eliminamos los delimitadores { y }
// invocamos a la función del objeto $el = substr($el, 1, strlen($el) - 2);
$resultado=$this->objeto->$el(); // invocamos a la función del objeto
// e introducimos su contenido en lugar de la marca $resultado = $this->objeto->$el();
$pagina=str_replace('{'.$el.'}',$resultado,$pagina); // e introducimos su contenido en lugar de la marca
} $pagina = str_replace('{'.$el.'}', $resultado, $pagina);
/** }
* @todo Tratar de activar la compresión. /*
*/ * @todo Tratar de activar la compresión.
// Si es posible comprimir */
// Si es posible comprimir
// if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) { // if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) {
// // introducimos la cabecera que indica que el contenido está comprimido // // introducimos la cabecera que indica que el contenido está comprimido
// header('Content-Encoding: gzip'); // header('Content-Encoding: gzip');
@@ -74,6 +75,5 @@ class Distribucion {
// return gzencode($pagina, 9); // return gzencode($pagina, 9);
// } // }
return $pagina; // enviamos sin comprimir return $pagina; // enviamos sin comprimir
} }
} }
?>

View File

@@ -1,12 +1,13 @@
<?php <?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> * @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0 * @version 1.0
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana * @copyright Copyright (c) 2008, Ricardo Montañana
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -14,22 +15,20 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
require_once 'phpqrcode.php'; require_once 'phpqrcode.php';
class EtiquetasPDF { class EtiquetasPDF
{
/** /**
*
* @var basedatos Controlador de la base de datos * @var basedatos Controlador de la base de datos
*/ */
private $bdd; private $bdd;
@@ -39,19 +38,21 @@ class EtiquetasPDF {
private $nombreFichero; 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 basedatos $bdd manejador de la base de datos
* @param boolean $registrado usuario registrado si/no * @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF * @return ficheroPDF
* todo: cambiar este comentario * todo: cambiar este comentario
*/ */
public function __construct($bdd, $definicion, $registrado) public function __construct($bdd, $definicion, $registrado)
{ {
if (!$registrado) { if (!$registrado) {
return 'Debe registrarse para acceder a este apartado'; return 'Debe registrarse para acceder a este apartado';
} }
$this->nombreFichero = TMP."/informeEtiquetas.pdf"; $this->nombreFichero = TMP.'/informeEtiquetas.pdf';
// Recuperamos la definición del informe // Recuperamos la definición del informe
$this->def = simplexml_load_file($definicion); $this->def = simplexml_load_file($definicion);
$this->bdd = $bdd; $this->bdd = $bdd;
@@ -61,7 +62,7 @@ class EtiquetasPDF {
$this->pdf->setAutoPageBreak(false); $this->pdf->setAutoPageBreak(false);
//echo $def->Titulo.$def->Cabecera; //echo $def->Titulo.$def->Cabecera;
$this->pdf->setAuthor(AUTOR, true); $this->pdf->setAuthor(AUTOR, true);
$creador = CENTRO . " " . PROGRAMA . VERSION; $creador = CENTRO.' '.PROGRAMA.VERSION;
$this->pdf->setCreator(html_entity_decode($creador), true); $this->pdf->setCreator(html_entity_decode($creador), true);
$this->pdf->setSubject($this->def->Titulo, true); $this->pdf->setSubject($this->def->Titulo, true);
//$this->pdf->setAutoPageBreak(true, 10); //$this->pdf->setAutoPageBreak(true, 10);
@@ -78,12 +79,13 @@ class EtiquetasPDF {
$this->pdf->AddPage(); $this->pdf->AddPage();
$tamLinea = 5; $tamLinea = 5;
$fila = -1; $fila = -1;
$primero = true; $i = 0; $primero = true;
$url = explode("/", $_SERVER['SCRIPT_NAME']); $i = 0;
$url = explode('/', $_SERVER['SCRIPT_NAME']);
$aplicacion = $url[1]; $aplicacion = $url[1];
$protocolo = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443 ? "https://" : "http://"; $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="; $enlace = $protocolo.$_SERVER['SERVER_NAME'].'/'.$aplicacion.'/index.php?elementos&opc=editar&id=';
while($tupla = $this->bdd->procesaResultado()) { while ($tupla = $this->bdd->procesaResultado()) {
for ($j = 0; $j < $tupla['cantidad']; $j++) { for ($j = 0; $j < $tupla['cantidad']; $j++) {
//Hay que generar tantas etiquetas como ponga la cantidad de cada elemento //Hay que generar tantas etiquetas como ponga la cantidad de cada elemento
if ($i % 2) { if ($i % 2) {
@@ -104,31 +106,31 @@ class EtiquetasPDF {
$primero = false; $primero = false;
} }
$py = 6 + 41 * $fila; $py = 6 + 41 * $fila;
$enlace2=$enlace.$tupla['idEl']; $enlace2 = $enlace.$tupla['idEl'];
$fichero = TMP."/etiq".rand(1000,9999).".png"; $fichero = TMP.'/etiq'.rand(1000, 9999).'.png';
QRcode::png($enlace2, $fichero); QRcode::png($enlace2, $fichero);
$this->pdf->image($fichero, $etiq2, $py, 30, 30); $this->pdf->image($fichero, $etiq2, $py, 30, 30);
unlink($fichero); unlink($fichero);
$this->pdf->setxy($etiq1, $py); $this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['articulo'])); $this->pdf->Cell(30, 10, utf8_decode($tupla['articulo']));
$py+=$tamLinea; $py += $tamLinea;
$this->pdf->setxy($etiq1, $py); $this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['marca'])); $this->pdf->Cell(30, 10, utf8_decode($tupla['marca']));
$py+=$tamLinea; $py += $tamLinea;
$this->pdf->setxy($etiq1, $py); $this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['modelo'])); $this->pdf->Cell(30, 10, utf8_decode($tupla['modelo']));
$py+=$tamLinea; $py += $tamLinea;
$this->pdf->setxy($etiq1, $py); $this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['numserie'])); $this->pdf->Cell(30, 10, utf8_decode($tupla['numserie']));
$py+=$tamLinea; $py += $tamLinea;
$this->pdf->setxy($etiq1, $py); $this->pdf->setxy($etiq1, $py);
$this->pdf->Cell(30, 10, $tupla['fechaCompra']); $this->pdf->Cell(30, 10, $tupla['fechaCompra']);
$py+=$tamLinea-1; $py += $tamLinea - 1;
$this->pdf->setxy($etiq2, $py); $this->pdf->setxy($etiq2, $py);
$this->pdf->Cell(30, 10, utf8_decode($tupla['ubicacion'])); $this->pdf->Cell(30, 10, utf8_decode($tupla['ubicacion']));
$py+=$tamLinea-1; $py += $tamLinea - 1;
$this->pdf->setxy($etiq2, $py); $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); $this->pdf->Cell(30, 10, $cadena);
$i++; $i++;
} }
@@ -149,15 +151,16 @@ class EtiquetasPDF {
public function getCabecera() public function getCabecera()
{ {
$cabecera = "Content-type: application/pdf"; $cabecera = 'Content-type: application/pdf';
$cabecera = $cabecera . "Content-length: " . strlen($this->docu); $cabecera = $cabecera.'Content-length: '.strlen($this->docu);
$cabecera = $cabecera . "Content-Disposition: inline; filename=" . $this->nombreFichero; $cabecera = $cabecera.'Content-Disposition: inline; filename='.$this->nombreFichero;
return $cabecera; return $cabecera;
} }
public function guardaArchivo($nombre) public function guardaArchivo($nombre)
{ {
$fichero = fopen($nombre, "w"); $fichero = fopen($nombre, 'w');
fwrite($fichero, $this->getCabecera()); fwrite($fichero, $this->getCabecera());
fwrite($fichero, $this->getContenido(), strlen($this->getContenido())); fwrite($fichero, $this->getContenido(), strlen($this->getContenido()));
$this->nombreFichero = $nombre; $this->nombreFichero = $nombre;
@@ -166,10 +169,10 @@ class EtiquetasPDF {
public function enviaCabecera() public function enviaCabecera()
{ {
header("Content-type: application/pdf"); header('Content-type: application/pdf');
$longitud = strlen($this->docu); $longitud = strlen($this->docu);
header("Content-length: $longitud"); header("Content-length: $longitud");
header("Content-Disposition: inline; filename=" . $this->nombreFichero); header('Content-Disposition: inline; filename='.$this->nombreFichero);
} }
public function imprimeInforme() public function imprimeInforme()
@@ -178,5 +181,3 @@ class EtiquetasPDF {
echo $this->docu; echo $this->docu;
} }
} }
?>

3615
FPDF.php

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,5 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2014, Ricardo Montañana Gómez * @copyright Copyright (c) 2014, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -16,29 +15,29 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
//Para comprimir las imágenes //Para comprimir las imágenes
require_once('Zebra_Image.php'); require_once 'Zebra_Image.php';
define("HAYQUEGRABAR", 1); define('HAYQUEGRABAR', 1);
define("HAYQUEBORRAR", 2); define('HAYQUEBORRAR', 2);
define("NOHACERNADA", 3); define('NOHACERNADA', 3);
class Imagen { class Imagen
{
private $archivoSubido; private $archivoSubido;
public $archivoComprimido; public $archivoComprimido;
private $extension; private $extension;
private $dirData; private $dirData;
public $archivoCopiado; public $archivoCopiado;
public function __construct() public function __construct()
{ {
$this->dirData = IMAGEDATA; $this->dirData = IMAGEDATA;
} }
public function determinaAccion($campo) 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 return HAYQUEBORRAR; //Hay que borrar el archivo de imagen
} elseif (isset($_FILES[$campo]['error']) && $_FILES[$campo]['error'] == 0) { } elseif (isset($_FILES[$campo]['error']) && $_FILES[$campo]['error'] == 0) {
return HAYQUEGRABAR; //Hay que guardar el archivo de imagen enviado return HAYQUEGRABAR; //Hay que guardar el archivo de imagen enviado
@@ -46,7 +45,7 @@ class Imagen {
return NOHACERNADA; //No hay que hacer nada return NOHACERNADA; //No hay que hacer nada
} }
} }
public function procesaEnvio($campo, &$mensaje) public function procesaEnvio($campo, &$mensaje)
{ {
try { try {
@@ -77,11 +76,11 @@ class Imagen {
$finfo = new finfo(FILEINFO_MIME_TYPE); $finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search( if (false === $ext = array_search(
$finfo->file($_FILES[$campo]['tmp_name']), $finfo->file($_FILES[$campo]['tmp_name']),
array( [
'jpg' => 'image/jpeg', 'jpg' => 'image/jpeg',
'png' => 'image/png', 'png' => 'image/png',
'gif' => 'image/gif', 'gif' => 'image/gif',
), ],
true true
)) { )) {
throw new RuntimeException('Formato de imagen inválido, no es {jpg, png, gif}'); throw new RuntimeException('Formato de imagen inválido, no es {jpg, png, gif}');
@@ -98,47 +97,51 @@ class Imagen {
return true; return true;
} catch (RuntimeException $e) { } catch (RuntimeException $e) {
$mensaje = $e->getMessage(); $mensaje = $e->getMessage();
return false; return false;
} }
} }
public static function borraImagenId($tabla, $id) public static function borraImagenId($tabla, $id)
{ {
$extensiones = array ("png", "gif", "jpg"); $extensiones = ['png', 'gif', 'jpg'];
foreach ($extensiones as $extension) { foreach ($extensiones as $extension) {
$archivo = IMAGEDATA . "/" . $tabla . "_" . $id . "." . $extension; $archivo = IMAGEDATA.'/'.$tabla.'_'.$id.'.'.$extension;
if (file_exists($archivo)) { if (file_exists($archivo)) {
unlink ($archivo); unlink($archivo);
} }
} }
} }
public function copiaImagenId($valorImagen, $tabla, $id, &$mensaje) public function copiaImagenId($valorImagen, $tabla, $id, &$mensaje)
{ {
$extension = strrchr($valorImagen, "."); $extension = strrchr($valorImagen, '.');
$nombre = $this->dirData . "/" . $tabla . "_" . $id . $extension; $nombre = $this->dirData.'/'.$tabla.'_'.$id.$extension;
if (!@copy($valorImagen, $nombre)) { if (!@copy($valorImagen, $nombre)) {
$errors= error_get_last(); $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; return false;
} }
$this->archivoCopiado = $nombre; $this->archivoCopiado = $nombre;
return true; return true;
} }
public function mueveImagenId($tabla, $id, &$mensaje) public function mueveImagenId($tabla, $id, &$mensaje)
{ {
if (!$this->comprimeArchivo($tabla . "_" . $id, $mensaje)) { if (!$this->comprimeArchivo($tabla.'_'.$id, $mensaje)) {
return false; return false;
} else { } else {
return true; return true;
} }
} }
private function comprimeArchivo($id, &$mensaje) private function comprimeArchivo($id, &$mensaje)
{ {
$zebra = new Zebra_Image(); $zebra = new Zebra_Image();
$zebra->source_path = $this->archivoSubido; $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->target_path = $this->archivoComprimido;
$zebra->jpeg_quality = 100; $zebra->jpeg_quality = 100;
@@ -156,28 +159,28 @@ class Imagen {
switch ($zebra->error) { switch ($zebra->error) {
case 1: $mensaje = 'El fichero origen no se ha encontrado!'; case 1: $mensaje = 'El fichero origen no se ha encontrado!';
break; break;
case 2: $mensaje = 'No se puede leer el archivo origen ' . $this->archivoSubido; case 2: $mensaje = 'No se puede leer el archivo origen '.$this->archivoSubido;
break; break;
case 3: $mensaje = 'No se pudo escribir el archivo destino ' . $this->archivoComprimido; case 3: $mensaje = 'No se pudo escribir el archivo destino '.$this->archivoComprimido;
break; break;
case 4: $mensaje = 'Formato de fichero origen no soportado ' . $this->archivoSubido; case 4: $mensaje = 'Formato de fichero origen no soportado '.$this->archivoSubido;
break; break;
case 5: $mensaje = 'Formato de fichero destino no soportado ' . $this->archivoComprimido; case 5: $mensaje = 'Formato de fichero destino no soportado '.$this->archivoComprimido;
break; break;
case 6: $mensaje = 'La versión de la biblioteca GD no soporta el formato de destino ' . $this->archivoComprimido; case 6: $mensaje = 'La versión de la biblioteca GD no soporta el formato de destino '.$this->archivoComprimido;
break; break;
case 7: $mensaje = 'La biblioteca GD no está instalada'; case 7: $mensaje = 'La biblioteca GD no está instalada';
break; break;
case 8: $mensaje = 'el comando "chmod" está deshabilitado por configuración'; case 8: $mensaje = 'el comando "chmod" está deshabilitado por configuración';
break; break;
} }
return false; return false;
} else { } else {
//Borra el archivo subido //Borra el archivo subido
unlink($this->archivoSubido); unlink($this->archivoSubido);
return true; return true;
} }
} }
} }
?>

View File

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

View File

@@ -1,7 +1,6 @@
<?php <?php
/** /**
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -17,10 +16,9 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
class InformeInventario { class InformeInventario
{
private $bdd; private $bdd;
public function __construct($baseDatos) public function __construct($baseDatos)
@@ -48,67 +46,71 @@ class InformeInventario {
$informe = new InformePDF($this->bdd, $enlace, true); $informe = new InformePDF($this->bdd, $enlace, true);
$informe->crea($enlace); $informe->crea($enlace);
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
} }
private function devuelveInforme($informe) private function devuelveInforme($informe)
{ {
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; $letras = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$nombre = TMP."/informe" . substr(str_shuffle($letras), 0, 10) . ".pdf"; $nombre = TMP.'/informe'.substr(str_shuffle($letras), 0, 10).'.pdf';
$informe->guardaArchivo($nombre); $informe->guardaArchivo($nombre);
return '<div class="container"> return '<div class="container">
<!--<a href="' . $nombre . '" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>--> <!--<a href="'.$nombre.'" target="_blank"><span class="glyphicon glyphicon-cloud-download" style="font-size:1.5em;"></span>Descargar Informe</a>-->
<object data="' . $nombre . '" type="application/pdf" width="100%" height="700" style="float:left;"> <object data="'.$nombre.'" type="application/pdf" width="100%" height="700" style="float:left;">
</object> </object>
</div>'; </div>';
} }
private function listarUbicacion() private function listarUbicacion()
{ {
$salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla'; $salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla';
switch ($salidaInforme) { switch ($salidaInforme) {
case "pantalla": case 'pantalla':
$fichero = "xml/inventarioUbicacion.xml"; $fichero = 'xml/inventarioUbicacion.xml';
$salida = TMP."/inventarioUbicacion.xml"; $salida = TMP.'/inventarioUbicacion.xml';
break; break;
case "csv": case 'csv':
$fichero = "xml/inventarioUbicacionCSV.xml"; $fichero = 'xml/inventarioUbicacionCSV.xml';
$salida = TMP."/inventarioUbicacionCSV.xml"; $salida = TMP.'/inventarioUbicacionCSV.xml';
break; break;
case "etiquetas": case 'etiquetas':
$fichero = "xml/inventarioUbicacionEtiquetas.xml"; $fichero = 'xml/inventarioUbicacionEtiquetas.xml';
$salida = TMP."/inventarioUbicacionEtiquetas.xml"; $salida = TMP.'/inventarioUbicacionEtiquetas.xml';
break; break;
} }
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); $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 . "';"; $comando = "select * from Ubicaciones where id='".$id."';";
$resultado = $this->bdd->ejecuta($comando); $resultado = $this->bdd->ejecuta($comando);
if (!$resultado) { if (!$resultado) {
return $this->bdd->mensajeError($comando); return $this->bdd->mensajeError($comando);
} }
$fila = $this->bdd->procesaResultado(); $fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $id, $plantilla); $plantilla = str_replace('{id}', $id, $plantilla);
$plantilla = str_replace("{Descripcion}", $fila['Descripcion'], $plantilla); $plantilla = str_replace('{Descripcion}', $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
switch ($salidaInforme) { switch ($salidaInforme) {
case "pantalla": case 'pantalla':
$informe = new InformePDF($this->bdd, $salida, true); $informe = new InformePDF($this->bdd, $salida, true);
$informe->crea($salida); $informe->crea($salida);
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
case "csv": case 'csv':
//Genera una hoja de cálculo en formato 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 = new Csv($this->bdd);
$hoja->crea($nombre); $hoja->crea($nombre);
$hoja->ejecutaConsulta($salida); $hoja->ejecutaConsulta($salida);
echo '<script type="text/javascript"> window.open( "' . $nombre . '" ) </script>'; echo '<script type="text/javascript"> window.open( "'.$nombre.'" ) </script>';
break; break;
case "etiquetas": case 'etiquetas':
$etiquetas = new EtiquetasPDF($this->bdd, $salida, true); $etiquetas = new EtiquetasPDF($this->bdd, $salida, true);
$etiquetas->crea($salida); $etiquetas->crea($salida);
$etiquetas->cierraPDF(); $etiquetas->cierraPDF();
return $this->devuelveInforme($etiquetas); return $this->devuelveInforme($etiquetas);
} }
} }
@@ -117,50 +119,52 @@ class InformeInventario {
{ {
$salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla'; $salidaInforme = isset($_POST['salida']) ? $_POST['salida'] : 'pantalla';
switch ($salidaInforme) { switch ($salidaInforme) {
case "pantalla": case 'pantalla':
$fichero = "xml/inventarioArticulo.xml"; $fichero = 'xml/inventarioArticulo.xml';
$salida = TMP."/inventarioArticulo.xml"; $salida = TMP.'/inventarioArticulo.xml';
break; break;
case "csv": case 'csv':
$fichero = "xml/inventarioArticuloCSV.xml"; $fichero = 'xml/inventarioArticuloCSV.xml';
$salida = TMP."/inventarioArticuloCSV.xml"; $salida = TMP.'/inventarioArticuloCSV.xml';
break; break;
case "etiquetas": case 'etiquetas':
$fichero = "xml/inventarioArticuloEtiquetas.xml"; $fichero = 'xml/inventarioArticuloEtiquetas.xml';
$salida = TMP."/inventarioArticuloEtiquetas.xml"; $salida = TMP.'/inventarioArticuloEtiquetas.xml';
break; break;
} }
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); $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 . "';"; $comando = "select * from Articulos where id='".$id."';";
$resultado = $this->bdd->ejecuta($comando); $resultado = $this->bdd->ejecuta($comando);
if (!$resultado) { if (!$resultado) {
return $this->bdd->mensajeError($comando); return $this->bdd->mensajeError($comando);
} }
$fila = $this->bdd->procesaResultado(); $fila = $this->bdd->procesaResultado();
$plantilla = str_replace("{id}", $id, $plantilla); $plantilla = str_replace('{id}', $id, $plantilla);
$plantilla = str_replace("{Descripcion}", $fila['descripcion'], $plantilla); $plantilla = str_replace('{Descripcion}', $fila['descripcion'], $plantilla);
$plantilla = str_replace("{Marca}", $fila['marca'], $plantilla); $plantilla = str_replace('{Marca}', $fila['marca'], $plantilla);
$plantilla = str_replace("{Modelo}", $fila['modelo'], $plantilla); $plantilla = str_replace('{Modelo}', $fila['modelo'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
switch ($salidaInforme) { switch ($salidaInforme) {
case "pantalla": case 'pantalla':
$informe = new InformePDF($this->bdd, $salida, true); $informe = new InformePDF($this->bdd, $salida, true);
$informe->crea($salida); $informe->crea($salida);
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
case "csv": case 'csv':
//Genera una hoja de cálculo en formato 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 = new Csv($this->bdd);
$hoja->crea($nombre); $hoja->crea($nombre);
$hoja->ejecutaConsulta($salida); $hoja->ejecutaConsulta($salida);
echo '<script type="text/javascript"> window.open( "' . $nombre . '" ) </script>'; echo '<script type="text/javascript"> window.open( "'.$nombre.'" ) </script>';
break; break;
case "etiquetas": case 'etiquetas':
$etiquetas = new EtiquetasPDF($this->bdd, $salida, true); $etiquetas = new EtiquetasPDF($this->bdd, $salida, true);
$etiquetas->crea($salida); $etiquetas->crea($salida);
$etiquetas->cierraPDF(); $etiquetas->cierraPDF();
return $this->devuelveInforme($etiquetas); return $this->devuelveInforme($etiquetas);
} }
} }
@@ -168,63 +172,68 @@ class InformeInventario {
private function listaUbicaciones() private function listaUbicaciones()
{ {
$salida = "<select class=\"selectpicker show-tick\" name=\"id\" data-live-search=\"true\" data-width=\"auto\">\n"; $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); $resultado = $this->bdd->ejecuta($comando);
if (!$resultado) { if (!$resultado) {
return $this->bdd->mensajeError($comando); return $this->bdd->mensajeError($comando);
} }
while ($fila = $this->bdd->procesaResultado()) { while ($fila = $this->bdd->procesaResultado()) {
$salida.="<option value=" . $fila['id'] . ">" . $fila['Descripcion'] . "</option><br>\n"; $salida .= '<option value='.$fila['id'].'>'.$fila['Descripcion']."</option><br>\n";
} }
$salida.="</select>\n"; $salida .= "</select>\n";
return $salida; return $salida;
} }
private function listaArticulos() private function listaArticulos()
{ {
$salida = "<select class=\"selectpicker show-tick\" name=\"id\" data-live-search=\"true\" data-width=\"auto\">\n"; $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); $resultado = $this->bdd->ejecuta($comando);
if (!$resultado) { if (!$resultado) {
return $this->bdd->mensajeError($comando); return $this->bdd->mensajeError($comando);
} }
while ($fila = $this->bdd->procesaResultado()) { while ($fila = $this->bdd->procesaResultado()) {
$salida.="<option value=" . $fila['id'] . ">" . $fila['descripcion'] . "-" . $fila['marca'] . "-" . $fila['modelo'] . "</option><br>\n"; $salida .= '<option value='.$fila['id'].'>'.$fila['descripcion'].'-'.$fila['marca'].'-'.$fila['modelo']."</option><br>\n";
} }
$salida.="</select>\n"; $salida .= "</select>\n";
return $salida; return $salida;
} }
private function formulario($accion, $etiqueta, $lista) private function formulario($accion, $etiqueta, $lista)
{ {
$salida = '<div class="col-sm-6 col-md-6"><form name="informeInventario.form" method="post" action="' . $accion . '">' . "\n"; $salida = '<div class="col-sm-6 col-md-6"><form name="informeInventario.form" method="post" action="'.$accion.'">'."\n";
$salida.="<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige $etiqueta</b></legend>\n"; $salida .= "<fieldset style=\"width: 96%;\"><p><legend style=\"color: red;\"><b>Elige $etiqueta</b></legend>\n";
$salida.="<br><br><label>$etiqueta </label>"; $salida .= "<br><br><label>$etiqueta </label>";
$salida.=$lista; $salida .= $lista;
$salida.="<br><br> $salida .= "<br><br>
<label for='salida'>Salida del informe por:</label>"; <label for='salida'>Salida del informe por:</label>";
$salida.='<div class="radio"><label><input type="radio" name="salida" value="pantalla" checked><span class="glyphicon glyphicon-list-alt"></span> Pantalla</label></div>'; $salida .= '<div class="radio"><label><input type="radio" name="salida" value="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="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 .= '<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 .= '<p align="center"><button type=submit class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span> Aceptar</button></p><br></div>'."\n";
$salida.="<script>$('.selectpicker').selectpicker();</script>"; $salida .= "<script>$('.selectpicker').selectpicker();</script>";
return $salida; return $salida;
} }
private function formularioUbicacion() private function formularioUbicacion()
{ {
//Genera un formulario con las ubicaciones disponibles. //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()); return $this->formulario($accion, 'Ubicaci&oacute;n', $this->listaUbicaciones());
} }
private function formularioArticulo() private function formularioArticulo()
{ {
$accion = "index.php?informeInventario&opc=listarArticulo"; $accion = 'index.php?informeInventario&opc=listarArticulo';
return $this->formulario($accion, 'Art&iacute;culo', $this->listaArticulos()); return $this->formulario($accion, 'Art&iacute;culo', $this->listaArticulos());
} }
private function inventarioTotal() private function inventarioTotal()
{ {
return $this->dialogo(); return $this->dialogo();
@@ -235,18 +244,19 @@ class InformeInventario {
$dialogo = '<div class="container col-5"><div class="jumbotron"> $dialogo = '<div class="container col-5"><div class="jumbotron">
<h1>Inventario Total</h1> <h1>Inventario Total</h1>
<p>¿Desea obtener el inventario de todo el centro?</p> <p>¿Desea obtener el inventario de todo el centro?</p>
<p><a class="btn btn-primary btn-lg" role="button" onClick="location.href=' . "'index.php'" . '"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a> <p><a class="btn btn-primary btn-lg" role="button" onClick="location.href='."'index.php'".'"><span class="glyphicon glyphicon-arrow-left"></span> Volver</a>
<a class="btn btn-success btn-lg" role="button" onClick="location.href=' . "'index.php?informeInventario&opc=listarTotal'" . '"> <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> <span class="glyphicon glyphicon-list-alt"></span> Continuar</a></p>
</div></div>'; </div></div>';
return $dialogo; return $dialogo;
} }
private function listarTotal() private function listarTotal()
{ {
$fichero = "xml/inventarioUbicacion.xml"; $fichero = 'xml/inventarioUbicacion.xml';
$salida = TMP."/inventarioUbicacion.xml"; $salida = TMP.'/inventarioUbicacion.xml';
$comando = "select * from Ubicaciones ;"; $comando = 'select * from Ubicaciones ;';
$resultado = $this->bdd->ejecuta($comando); $resultado = $this->bdd->ejecuta($comando);
if (!$resultado) { if (!$resultado) {
return $this->bdd->mensajeError($comando); return $this->bdd->mensajeError($comando);
@@ -255,10 +265,10 @@ class InformeInventario {
$bdatos = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); $bdatos = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
$primero = true; $primero = true;
while ($fila = $this->bdd->procesaResultado()) { while ($fila = $this->bdd->procesaResultado()) {
$plantilla = file_get_contents($fichero) or die('Fallo en la apertura de la plantilla ' . $fichero); $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('{id}', $fila['id'], $plantilla);
$plantilla = str_replace("{Descripcion}", $fila['Descripcion'], $plantilla); $plantilla = str_replace('{Descripcion}', $fila['Descripcion'], $plantilla);
file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla ' . $salida); file_put_contents($salida, $plantilla) or die('Fallo en la escritura de la plantilla '.$salida);
if ($primero) { if ($primero) {
$primero = false; $primero = false;
$informe = new InformePDF($bdatos, $salida, true); $informe = new InformePDF($bdatos, $salida, true);
@@ -266,9 +276,7 @@ class InformeInventario {
$informe->crea($salida); $informe->crea($salida);
} }
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
} }
} }
?>

View File

@@ -1,12 +1,13 @@
<?php <?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> * @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0 * @version 1.0
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana * @copyright Copyright (c) 2008, Ricardo Montañana
* @package Inventario
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -14,20 +15,18 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
class InformePDF { class InformePDF
{
/** /**
*
* @var basedatos Controlador de la base de datos * @var basedatos Controlador de la base de datos
*/ */
private $bdd; private $bdd;
@@ -36,14 +35,17 @@ class InformePDF {
private $def; 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 basedatos $bdd manejador de la base de datos
* @param boolean $registrado usuario registrado si/no * @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no
*
* @return ficheroPDF * @return ficheroPDF
* todo: cambiar este comentario * todo: cambiar este comentario
*/ */
public function __construct($bdd, $definicion, $registrado) { public function __construct($bdd, $definicion, $registrado)
{
if (!$registrado) { if (!$registrado) {
return 'Debe registrarse para acceder a este apartado'; return 'Debe registrarse para acceder a este apartado';
} }
@@ -53,15 +55,16 @@ class InformePDF {
$this->pdf = new Pdf_mysql_table($this->bdd->obtieneManejador(), (string) $this->def->Pagina['Orientacion'], (string) $this->def->Pagina['Formato'], (string) utf8_decode($this->def->Titulo['Texto']), (string) $this->def->Pagina->Cabecera); $this->pdf = new Pdf_mysql_table($this->bdd->obtieneManejador(), (string) $this->def->Pagina['Orientacion'], (string) $this->def->Pagina['Formato'], (string) utf8_decode($this->def->Titulo['Texto']), (string) $this->def->Pagina->Cabecera);
//echo $def->Titulo.$def->Cabecera; //echo $def->Titulo.$def->Cabecera;
$this->pdf->Open(); $this->pdf->Open();
$this->pdf->setAuthor(AUTOR,true); $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->setCreator(html_entity_decode($creador), true);
$this->pdf->setSubject($this->def->Titulo,true); $this->pdf->setSubject($this->def->Titulo, true);
$this->pdf->setAutoPageBreak(true, 10); $this->pdf->setAutoPageBreak(true, 10);
} }
public function crea($definicion) { public function crea($definicion)
{
//print_r($def);echo $bdd;die(); //print_r($def);echo $bdd;die();
// Iniciamos la creación del documento // Iniciamos la creación del documento
$this->def = simplexml_load_file($definicion); $this->def = simplexml_load_file($definicion);
@@ -74,50 +77,55 @@ class InformePDF {
foreach ($this->def->Pagina->Cuerpo->Col as $columna) { 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']); $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), $prop = ['HeaderColor' => [255, 150, 100],
'color1' => array(210, 245, 255), 'color1' => [210, 245, 255],
'color2' => array(255, 255, 210), 'color2' => [255, 255, 210],
'padding' => 2); 'padding' => 2];
$this->pdf->Table($this->def->Datos->Consulta, $prop); $this->pdf->Table($this->def->Datos->Consulta, $prop);
} }
public function cierraPDF() { public function cierraPDF()
{
$this->pdf->Close(); $this->pdf->Close();
$this->docu = $this->pdf->Output('', 'S'); $this->docu = $this->pdf->Output('', 'S');
} }
public function getContenido() { public function getContenido()
{
return $this->docu; return $this->docu;
} }
public function getCabecera() { public function getCabecera()
$cabecera = "Content-type: application/pdf"; {
$cabecera = $cabecera . "Content-length: " . strlen($this->docu); $cabecera = 'Content-type: application/pdf';
$cabecera = $cabecera . "Content-Disposition: inline; filename=".TMP."/Informe.pdf"; $cabecera = $cabecera.'Content-length: '.strlen($this->docu);
$cabecera = $cabecera.'Content-Disposition: inline; filename='.TMP.'/Informe.pdf';
return $cabecera; return $cabecera;
} }
public function guardaArchivo($nombre) { public function guardaArchivo($nombre)
if (!isset($nombre)) {
$nombre = TMP . "/Informe.pdf"; if (!isset($nombre)) {
$fichero = fopen($nombre, "w"); $nombre = TMP.'/Informe.pdf';
}
$fichero = fopen($nombre, 'w');
fwrite($fichero, $this->getCabecera()); fwrite($fichero, $this->getCabecera());
fwrite($fichero, $this->getContenido(), strlen($this->getContenido())); fwrite($fichero, $this->getContenido(), strlen($this->getContenido()));
fclose($fichero); fclose($fichero);
} }
public function enviaCabecera() { public function enviaCabecera()
header("Content-type: application/pdf"); {
header('Content-type: application/pdf');
$longitud = strlen($this->docu); $longitud = strlen($this->docu);
header("Content-length: $longitud"); 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(); $this->enviaCabecera();
echo $this->docu; echo $this->docu;
} }
} }
?>

View File

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

View File

@@ -2,9 +2,11 @@
/** /**
* Clase Inventario que controla la ejecución principal del programa. * Clase Inventario que controla la ejecución principal del programa.
*
* @author Ricardo Montañana Gómez <rmontanana@gmail.com> * @author Ricardo Montañana Gómez <rmontanana@gmail.com>
*
* @version 1.0 * @version 1.0
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -12,23 +14,22 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
// Clase del objeto principal de la aplicación // Clase del objeto principal de la aplicación
class Inventario { class Inventario
{
// Declaración de miembros // Declaración de miembros
private $bdd; // Enlace con el SGBD private $bdd; // Enlace con el SGBD
private $registrado; // Usuario registrado s/n 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 $clave; //contraseña del usuario
private $opcActual; // Opción elegida por el usuario private $opcActual; // Opción elegida por el usuario
private $perfil; //Permisos del usuario. private $perfil; //Permisos del usuario.
@@ -36,13 +37,15 @@ class Inventario {
private $plant; private $plant;
// Constructor // Constructor
public function __construct() { public function __construct()
{
// Analizamos la cadena de solicitud para saber // Analizamos la cadena de solicitud para saber
// qué opción es la actual // qué opción es la actual
$this->opcActual = $_SERVER['QUERY_STRING'] == '' ? 'principal' : $_SERVER['QUERY_STRING']; $this->opcActual = $_SERVER['QUERY_STRING'] == '' ? 'principal' : $_SERVER['QUERY_STRING'];
//Si el programa no está instalado, llama al instalador. //Si el programa no está instalado, llama al instalador.
if (INSTALADO == "no") { if (INSTALADO == 'no') {
header('location: Instalar.php'); header('location: Instalar.php');
return; return;
} }
// Iniciamos una sesión // Iniciamos una sesión
@@ -50,25 +53,25 @@ class Inventario {
//Conexión con la base de datos. //Conexión con la base de datos.
$this->bdd = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS); $this->bdd = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($this->bdd->error()) { if ($this->bdd->error()) {
echo '<h1>Fallo al conectar con el servidor MySQL.</h1>'; 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; $this->estado = false;
return; return;
} else { } else {
$this->estado = true; $this->estado = true;
} }
//Selecciona la plantilla a utilizar //Selecciona la plantilla a utilizar
$this->plant='plant/'; $this->plant = 'plant/';
$this->plant.=PLANTILLA; $this->plant .= PLANTILLA;
$this->plant.='.html'; $this->plant .= '.html';
// Comprobamos si el usuario ya está registrado en esta sesión // Comprobamos si el usuario ya está registrado en esta sesión
$this->registrado = isset($_SESSION['Registrado']); $this->registrado = isset($_SESSION['Registrado']);
if ($this->registrado) {// si está... if ($this->registrado) {// si está...
// recuperamos el nombre del usuario // recuperamos el nombre del usuario
$this->usuario = $_SESSION['Usuario']; $this->usuario = $_SESSION['Usuario'];
$this->perfil = $_SESSION['Perfil']; $this->perfil = $_SESSION['Perfil'];
// en caso contrario comprobamos si tiene la cookie que le identifica como usuario // en caso contrario comprobamos si tiene la cookie que le identifica como usuario
} elseif (isset($_COOKIE['InventarioId'])) { } elseif (isset($_COOKIE['InventarioId'])) {
// y usamos el Id para recuperar el nombre de la base de ddtos // y usamos el Id para recuperar el nombre de la base de ddtos
$this->recuperaNombreConId($_COOKIE['InventarioId']); $this->recuperaNombreConId($_COOKIE['InventarioId']);
@@ -77,14 +80,16 @@ class Inventario {
} }
} }
public function estado() { public function estado()
{
return $this->estado; return $this->estado;
} }
// Esta función pondrá en marcha la aplicación ocupándose // Esta función pondrá en marcha la aplicación ocupándose
// de las acciones que no generan contenido, esto es // de las acciones que no generan contenido, esto es
// iniciar sesión, cerrarla, etc. // iniciar sesión, cerrarla, etc.
public function Ejecuta() { public function Ejecuta()
{
// Dependiendo de la opción a procesar // Dependiendo de la opción a procesar
switch ($this->opcActual) { switch ($this->opcActual) {
// El usuario quiere cerrar la sesión actual // El usuario quiere cerrar la sesión actual
@@ -118,7 +123,7 @@ class Inventario {
header('location:index.php?usuario_incorrecto'); header('location:index.php?usuario_incorrecto');
exit; exit;
case 'usuario_incorrecto': case 'usuario_incorrecto':
$this->opcActual = "principal"; $this->opcActual = 'principal';
$contenido = $this->creaContenido(); $contenido = $this->creaContenido();
$contenido->usuario_incorrecto(); $contenido->usuario_incorrecto();
$salida = new Distribucion($this->plant, $contenido); $salida = new Distribucion($this->plant, $contenido);
@@ -132,18 +137,20 @@ class Inventario {
$salida = new Distribucion($this->plant, $this->creaContenido()); $salida = new Distribucion($this->plant, $this->creaContenido());
echo $salida->procesaPlantilla(); echo $salida->procesaPlantilla();
break; break;
} }
} }
private function creaContenido() { private function creaContenido()
{
return new AportaContenido($this->bdd, $this->registrado, $this->usuario, $this->perfil, $this->opcActual); return new AportaContenido($this->bdd, $this->registrado, $this->usuario, $this->perfil, $this->opcActual);
} }
// Esta función comprueba si el usuario está o no registrado, // Esta función comprueba si el usuario está o no registrado,
// devolviendo su IdSesion en caso afirmativo o false // devolviendo su IdSesion en caso afirmativo o false
// en caso contrario // en caso contrario
private function usuarioRegistrado() { private function usuarioRegistrado()
{
$this->usuario = $_POST['usuario']; $this->usuario = $_POST['usuario'];
$this->clave = $_POST['clave']; $this->clave = $_POST['clave'];
// ejecuta la consulta para buscar el usuario // ejecuta la consulta para buscar el usuario
@@ -167,10 +174,11 @@ class Inventario {
return false; return false;
} }
private function creaPerfil($fila) { private function creaPerfil($fila)
return array("Consulta" => $fila['consulta'], "Modificacion" => $fila['modificacion'], {
"Alta" => $fila['alta'], "Borrado" => $fila['borrado'], "Informe" => $fila['informe'], return ['Consulta' => $fila['consulta'], 'Modificacion' => $fila['modificacion'],
"Usuarios" => $fila['usuarios'], "Config" => $fila['config']); 'Alta' => $fila['alta'], 'Borrado' => $fila['borrado'], 'Informe' => $fila['informe'],
'Usuarios' => $fila['usuarios'], 'Config' => $fila['config']];
} }
// Esta función intenta recuperar el nombre del usuario // Esta función intenta recuperar el nombre del usuario
@@ -178,7 +186,8 @@ class Inventario {
// dejando las variables Registrado y Usuario con // dejando las variables Registrado y Usuario con
// los valores apropiados // los valores apropiados
// @param String Identificador de sesión del usuario actual // @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 // para ejecutar la consulta para buscar el Id de sesión
$res = $this->bdd->ejecuta("SELECT * FROM Usuarios WHERE idSesion='$idSesion'"); $res = $this->bdd->ejecuta("SELECT * FROM Usuarios WHERE idSesion='$idSesion'");
// Si no hemos encontrado el ID // Si no hemos encontrado el ID
@@ -204,5 +213,3 @@ class Inventario {
} }
} }
} }
?>

File diff suppressed because it is too large Load Diff

View File

@@ -1,54 +1,57 @@
<?php <?php
/** /**
* @package Inventario * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @license http://www.gnu.org/licenses/gpl-3.0.txt
* @license http://www.gnu.org/licenses/gpl-3.0.txt * This file is part of Inventario.
* This file is part of Inventario. * Inventario is free software: you can redistribute it and/or modify
* Inventario is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by
* it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or
* the Free Software Foundation, either version 3 of the License, or * (at your option) any later version.
* (at your option) any later version. *
* * Inventario is distributed in the hope that it will be useful,
* Inventario is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details.
* GNU General Public License for more details. *
* * You should have received a copy of the GNU General Public License
* You should have received a copy of the GNU General Public License * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. */
*
*/
// //
// Esta clase generará el menú de la aplicación. // Esta clase generará el menú de la aplicación.
class Menu { class Menu
{
private $opciones; private $opciones;
public function __construct($fichero) public function __construct($fichero)
{ {
$contenido=@file_get_contents($fichero) or $contenido = @file_get_contents($fichero) or
die("<h1>No puedo generar el menú. No puedo acceder al fichero $fichero</h1>"); die("<h1>No puedo generar el menú. No puedo acceder al fichero $fichero</h1>");
// Obtenemos la lista de pares Opción|Enlace // Obtenemos la lista de pares Opción|Enlace
$elementos=explode("\n", $contenido); $elementos = explode("\n", $contenido);
foreach($elementos as $elemento) { foreach ($elementos as $elemento) {
list($tipo, $opcion, $enlace, $destino, $titulo)=explode('|', $elemento); list($tipo, $opcion, $enlace, $destino, $titulo) = explode('|', $elemento);
// Los guardamos en la matriz de opciones // Los guardamos en la matriz de opciones
if ($tipo) if ($tipo) {
$this->opciones[]=$tipo.",".$opcion.",".$enlace.",".$destino.",".$titulo; $this->opciones[] = $tipo.','.$opcion.','.$enlace.','.$destino.','.$titulo;
}
} }
} }
public function insertaMenu() public function insertaMenu()
{ {
$salida=""; $salida = '';
reset($this->opciones); reset($this->opciones);
foreach($this->opciones as $opcion) { foreach ($this->opciones as $opcion) {
list($tipo,$opcion,$enlace,$destino,$titulo)=explode(",",$opcion); list($tipo, $opcion, $enlace, $destino, $titulo) = explode(',', $opcion);
if ($tipo==2) if ($tipo == 2) {
$salida.='<li class="active"><a href="'.$enlace.'" target="'.$destino.'" title="'.$titulo.'">'.$opcion.'</a><br /></li>'; $salida .= '<li class="active"><a href="'.$enlace.'" target="'.$destino.'" title="'.$titulo.'">'.$opcion.'</a><br /></li>';
else } else {
$salida.= $salida .=
//'<span class="label label-default">'.$opcion.'</span><br>'; //'<span class="label label-default">'.$opcion.'</span><br>';
'<label class="">'.$opcion.'</label><br/>'; '<label class="">'.$opcion.'</label><br/>';
}
} }
return $salida; return $salida;
} }
} }
?>

View File

@@ -9,236 +9,259 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
class Pdf_mysql_table extends FPDF class Pdf_mysql_table extends FPDF
{ {
/** /**
* Modificado por Ricardo Montañana 05/2008 para añadir la posibilidad de cálculo de totales * 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 *
* @var float[] Vector de totales de las columnas que lo necesiten
*/ */
private $ProcessingTable=false,$aCols=array(),$TableX,$HeaderColor; private $ProcessingTable = false;
private $RowColors,$ColorIndex; private $aCols = [];
private $bdd,$titulo,$cabecera; private $TableX;
private $totales=array(),$procesandoTotales=false; private $HeaderColor;
/** private $RowColors;
* private $ColorIndex;
* @param mixed $bdd Controlador de la base de datos private $bdd;
* @param string $orientacion Orientación de la página P/L private $titulo;
* @param string $formato Tamaño de la página p. ej. A4 private $cabecera;
* @param string $titulo Título del informe private $totales = [];
* @param string $cabecera Texto para la cabecera private $procesandoTotales = false;
*/
public function __construct($bdd,$orientacion,$formato,$titulo='',$cabecera='') /**
* @param mixed $bdd Controlador de la base de datos
* @param string $orientacion Orientación de la página P/L
* @param string $formato Tamaño de la página p. ej. A4
* @param string $titulo Título del informe
* @param string $cabecera Texto para la cabecera
*/
public function __construct($bdd, $orientacion, $formato, $titulo = '', $cabecera = '')
{ {
$this->bdd=$bdd; $this->bdd = $bdd;
$this->titulo=$titulo; $this->titulo = $titulo;
$this->cabecera=$cabecera; $this->cabecera = $cabecera;
parent::__construct($orientacion,'mm',$formato); parent::__construct($orientacion, 'mm', $formato);
} }
public function setTitulo($titulo) public function setTitulo($titulo)
{ {
$this->titulo=$titulo; $this->titulo = $titulo;
}
public function iniciaTotales()
{
$this->totales = array();
}
function Header()
{
//Modficada por Ricardo Montañana
//Titulo
$fecha=strftime("%d-%b-%Y %H:%M");
$this->SetFont('Arial','',8);
$this->Cell(0,4,html_entity_decode(CENTRO . " " . PROGRAMA . " v" . VERSION,ENT_COMPAT | ENT_HTML401,'ISO-8859-1'),0,1,'L');
$this->SetFont('Arial','',18);
$this->Cell(0,6,utf8_decode($this->titulo),0,1,'C');
$this->SetFont('Arial','',8);
$this->Cell(0,3,$fecha,0,1,'R');
$this->Cell(0,5,utf8_decode($this->cabecera),0,1,'C');
$this->Ln(10);
//Print the table header if necessary
if($this->ProcessingTable)
$this->TableHeader();
//Ensure table header is output
parent::Header();
}
public function Footer()
{
$this->SetFont('Arial','',8);
$this->setY($this->h-10);
$this->Cell(0,6,'-'.$this->PageNo().'-',0,1,'C');
parent::Footer();
} }
function TableHeader() public function iniciaTotales()
{ {
$this->SetFont('Arial','B',12); $this->totales = [];
}
public function Header()
{
//Modficada por Ricardo Montañana
//Titulo
$fecha = strftime('%d-%b-%Y %H:%M');
$this->SetFont('Arial', '', 8);
$this->Cell(0, 4, html_entity_decode(CENTRO.' '.PROGRAMA.' v'.VERSION, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'), 0, 1, 'L');
$this->SetFont('Arial', '', 18);
$this->Cell(0, 6, utf8_decode($this->titulo), 0, 1, 'C');
$this->SetFont('Arial', '', 8);
$this->Cell(0, 3, $fecha, 0, 1, 'R');
$this->Cell(0, 5, utf8_decode($this->cabecera), 0, 1, 'C');
$this->Ln(10);
//Print the table header if necessary
if ($this->ProcessingTable) {
$this->TableHeader();
}
//Ensure table header is output
parent::Header();
}
public function Footer()
{
$this->SetFont('Arial', '', 8);
$this->setY($this->h - 10);
$this->Cell(0, 6, '-'.$this->PageNo().'-', 0, 1, 'C');
parent::Footer();
}
public function TableHeader()
{
$this->SetFont('Arial', 'B', 12);
$this->SetX($this->TableX); $this->SetX($this->TableX);
$fill=!empty($this->HeaderColor); $fill = !empty($this->HeaderColor);
if($fill) if ($fill) {
$this->SetFillColor($this->HeaderColor[0],$this->HeaderColor[1],$this->HeaderColor[2]); $this->SetFillColor($this->HeaderColor[0], $this->HeaderColor[1], $this->HeaderColor[2]);
foreach($this->aCols as $col) }
$this->Cell($col['w'],6,utf8_decode($col['c']),1,0,'C',$fill); foreach ($this->aCols as $col) {
$this->Cell($col['w'], 6, utf8_decode($col['c']), 1, 0, 'C', $fill);
}
$this->Ln(); $this->Ln();
} }
function Row($data) public function Row($data)
{ {
$this->SetX($this->TableX); $this->SetX($this->TableX);
$ci=$this->ColorIndex; $ci = $this->ColorIndex;
$fill=!empty($this->RowColors[$ci]); $fill = !empty($this->RowColors[$ci]);
if($fill) if ($fill) {
$this->SetFillColor($this->RowColors[$ci][0],$this->RowColors[$ci][1],$this->RowColors[$ci][2]); $this->SetFillColor($this->RowColors[$ci][0], $this->RowColors[$ci][1], $this->RowColors[$ci][2]);
foreach($this->aCols as $col) { }
foreach ($this->aCols as $col) {
switch ($col['a']) { switch ($col['a']) {
case 'D':$alin='R';break; case 'D':$alin = 'R'; break;
case 'I':$alin='L';break; case 'I':$alin = 'L'; break;
case 'C':$alin='C';break; case 'C':$alin = 'C'; break;
default:$alin='L';break; default:$alin = 'L'; break;
} }
if ($this->procesandoTotales) { if ($this->procesandoTotales) {
$this->SetFont('Arial','B',12); $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($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[$col['f']]),1,0,$alin,$fill);
//$this->Cell($col['w'],5,utf8_decode($data['proveedor']),1,0,$alin,$fill); //$this->Cell($col['w'],5,utf8_decode($data['proveedor']),1,0,$alin,$fill);
//$this->Write(5,"nombre=".$col['f'].",titulo=".$col['c'].",ancho=".$col['w'].",alin=".$col['a']); //$this->Write(5,"nombre=".$col['f'].",titulo=".$col['c'].",ancho=".$col['w'].",alin=".$col['a']);
//$this->Write(5,$data[$col['f']].$col['f']); //$this->Write(5,$data[$col['f']].$col['f']);
//print_r($data); //print_r($data);
//print_r($this->aCols); //print_r($this->aCols);
if ($col['t']=='S' && !$this->procesandoTotales) { 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']]; $this->totales[$col['f']] += $data[$col['f']];
else } else {
$this->totales[$col['f']] = $data[$col['f']]; $this->totales[$col['f']] = $data[$col['f']];
}
} }
} }
$this->Ln(); $this->Ln();
$this->ColorIndex=1-$ci; $this->ColorIndex = 1 - $ci;
} }
function CalcWidths($width,$align) public function CalcWidths($width, $align)
{ {
//Compute the widths of the columns //Compute the widths of the columns
$TableWidth=0; $TableWidth = 0;
foreach($this->aCols as $i=>$col) foreach ($this->aCols as $i=>$col) {
{ $w = $col['w'];
$w=$col['w']; if ($w == -1) {
if($w==-1) $w = $width / count($this->aCols);
$w=$width/count($this->aCols); } elseif (substr($w, -1) == '%') {
elseif(substr($w,-1)=='%') $w = $w / 100 * $width;
$w=$w/100*$width; }
$this->aCols[$i]['w']=$w; $this->aCols[$i]['w'] = $w;
$TableWidth+=$w; $TableWidth += $w;
} }
//Compute the abscissa of the table //Compute the abscissa of the table
if($align=='C') if ($align == 'C') {
$this->TableX=max(($this->w-$TableWidth)/2,0); $this->TableX = max(($this->w - $TableWidth) / 2, 0);
elseif($align=='R') } elseif ($align == 'R') {
$this->TableX=max($this->w-$this->rMargin-$TableWidth,0); $this->TableX = max($this->w - $this->rMargin - $TableWidth, 0);
else } else {
$this->TableX=$this->lMargin; $this->TableX = $this->lMargin;
}
} }
function AddCol($field=-1,$width=-1,$caption='',$align='I',$total='N') public function AddCol($field = -1, $width = -1, $caption = '', $align = 'I', $total = 'N')
{ {
//Add a column to the table //Add a column to the table
if($field==-1) if ($field == -1) {
$field=count($this->aCols); $field = count($this->aCols);
$this->aCols[]=array('f'=>$field,'c'=>$caption,'w'=>$width,'a'=>$align,'t'=>$total); }
$this->aCols[] = ['f'=>$field, 'c'=>$caption, 'w'=>$width, 'a'=>$align, 't'=>$total];
} }
function Table($query,$prop=array()) public function Table($query, $prop = [])
{ {
//Issue query //Issue query
$res=$this->bdd->query($query) or die('Error: '.$this->bdd->error."<BR>Query: $query"); $res = $this->bdd->query($query) or die('Error: '.$this->bdd->error."<BR>Query: $query");
//Add all columns if none was specified //Add all columns if none was specified
if(count($this->aCols)==0) if (count($this->aCols) == 0) {
{ $nb = $res->field_count;
$nb=$res->field_count; for ($i = 0; $i < $nb; $i++) {
for($i=0;$i<$nb;$i++)
$this->AddCol(); $this->AddCol();
}
} }
//Retrieve column names when not specified //Retrieve column names when not specified
$i=0; $i = 0;
foreach($this->aCols as $i=>$col) foreach ($this->aCols as $i=>$col) {
{ if ($col['c'] == '') {
if($col['c']=='') if (is_string($col['f'])) {
{ $this->aCols[$i]['c'] = ucfirst($col['f']);
if(is_string($col['f'])) } else {
$this->aCols[$i]['c']=ucfirst($col['f']); $this->aCols[$i]['c'] = ucfirst($res->field_seek($i));
else }
$this->aCols[$i]['c']=ucfirst($res->field_seek($i));
} }
$i++; $i++;
} }
//Handle properties //Handle properties
if(!isset($prop['width'])) if (!isset($prop['width'])) {
$prop['width']=0; $prop['width'] = 0;
if($prop['width']==0) }
$prop['width']=$this->w-$this->lMargin-$this->rMargin; if ($prop['width'] == 0) {
if(!isset($prop['align'])) $prop['width'] = $this->w - $this->lMargin - $this->rMargin;
$prop['align']='C'; }
if(!isset($prop['padding'])) if (!isset($prop['align'])) {
$prop['padding']=$this->cMargin; $prop['align'] = 'C';
$cMargin=$this->cMargin; }
$this->cMargin=$prop['padding']; if (!isset($prop['padding'])) {
if(!isset($prop['HeaderColor'])) $prop['padding'] = $this->cMargin;
$prop['HeaderColor']=array(); }
$this->HeaderColor=$prop['HeaderColor']; $cMargin = $this->cMargin;
if(!isset($prop['color1'])) $this->cMargin = $prop['padding'];
$prop['color1']=array(); if (!isset($prop['HeaderColor'])) {
if(!isset($prop['color2'])) $prop['HeaderColor'] = [];
$prop['color2']=array(); }
$this->RowColors=array($prop['color1'],$prop['color2']); $this->HeaderColor = $prop['HeaderColor'];
if (!isset($prop['color1'])) {
$prop['color1'] = [];
}
if (!isset($prop['color2'])) {
$prop['color2'] = [];
}
$this->RowColors = [$prop['color1'], $prop['color2']];
//Compute column widths //Compute column widths
$this->CalcWidths($prop['width'],$prop['align']); $this->CalcWidths($prop['width'], $prop['align']);
//Print header //Print header
$this->TableHeader(); $this->TableHeader();
//Print rows //Print rows
$this->SetFont('Arial','',11); $this->SetFont('Arial', '', 11);
$this->ColorIndex=0; $this->ColorIndex = 0;
$this->ProcessingTable=true; $this->ProcessingTable = true;
$this->procesandoTotales=false; $this->procesandoTotales = false;
while($row=$res->fetch_assoc()) { while ($row = $res->fetch_assoc()) {
$this->Row($row); $this->Row($row);
} }
$this->procesandoTotales=true; $this->procesandoTotales = true;
// Procesa los totales // Procesa los totales
if ($this->procesaTotales()) { if ($this->procesaTotales()) {
$this->Row($this->totales); $this->Row($this->totales);
} }
$this->ProcessingTable=false; $this->ProcessingTable = false;
$this->cMargin=$cMargin; $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 * @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() private function procesaTotales()
{ {
foreach($this->aCols as $col) { foreach ($this->aCols as $col) {
if ($col['t']=='S') { if ($col['t'] == 'S') {
return true; return true;
} }
} }
return false; return false;
} }
} }
?>

View File

@@ -15,7 +15,7 @@ Utiliza:
[Manual de Usuario](http://rmontanana.gitbooks.io/inventario2/) [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) [Estadísticas del proyecto](https://www.ohloh.net/p/inventario2)

240
Sql.php
View File

@@ -1,82 +1,89 @@
<?php <?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 * @author Ricardo Montañana <rmontanana@gmail.com>
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @version 1.0
* @license http://www.gnu.org/licenses/gpl-3.0.txt *
* This file is part of Inventario. * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* Inventario is free software: you can redistribute it and/or modify * @license http://www.gnu.org/licenses/gpl-3.0.txt
* it under the terms of the GNU General Public License as published by * This file is part of Inventario.
* the Free Software Foundation, either version 3 of the License, or * Inventario is free software: you can redistribute it and/or modify
* (at your option) any later version. * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* Inventario is distributed in the hope that it will be useful, * (at your option) any later version.
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Inventario is distributed in the hope that it will be useful,
* GNU General Public License for more details. * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* You should have received a copy of the GNU General Public License * GNU General Public License for more details.
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. *
* * 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. * @var mixed Manejador de la base de datos.
*/ */
private $bdd=NULL; private $bdd = null;
/** /**
* @var string Mensaje del último mensaje de error generado * @var string Mensaje del último mensaje de error generado
*/ */
private $mensajeError=''; private $mensajeError = '';
/** /**
* @var boolean Almacena el estado de error o no de la última acción. * @var bool Almacena el estado de error o no de la última acción.
*/ */
private $error=false; private $error = false;
/** /**
* @var boolean Estado de la conexión con la base de datos. * @var bool Estado de la conexión con la base de datos.
*/ */
private $estado=false; private $estado = false;
/** /**
* @var mixed Objeto que alberga la última consulta ejecutada. * @var mixed Objeto que alberga la última consulta ejecutada.
*/ */
private $peticion=NULL; private $peticion = null;
/** /**
* @var integer Número de tuplas afectadas en la última consulta. * @var int Número de tuplas afectadas en la última consulta.
*/ */
private $numero=0; private $numero = 0;
/** /**
* @var string vector de cadenas con los resultados de la petición. * @var string vector de cadenas con los resultados de la petición.
*/ */
private $datos=array(); private $datos = [];
/** /**
* Id del último registro insertado * Id del último registro insertado.
* @var integer mysql_ *
* @var int mysql_
*/ */
private $id; private $id;
/** /**
* Crea un objeto Sql y conecta con la Base de Datos. * Crea un objeto Sql y conecta con la Base de Datos.
*
* @param string $servidor * @param string $servidor
* @param string $usuario * @param string $usuario
* @param string $baseDatos * @param string $baseDatos
*/ */
public function __construct($servidor,$usuario,$clave,$baseDatos) public function __construct($servidor, $usuario, $clave, $baseDatos)
{ {
$this->bdd = @new mysqli($servidor,$usuario,$clave,$baseDatos); $this->bdd = @new mysqli($servidor, $usuario, $clave, $baseDatos);
if (mysqli_connect_errno()) { if (mysqli_connect_errno()) {
$this->mensajeError='<h1>Fallo al conectar con el servidor MySQL.</h1>'; $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->error = true;
$this->estado=false; $this->estado = false;
} else { } else {
$this->mensajeError=''; $this->mensajeError = '';
$this->error=false; $this->error = false;
$this->estado=true; $this->estado = true;
} }
$this->peticion=NULL; $this->peticion = null;
return $this; return $this;
} }
public function __destruct() public function __destruct()
{ {
//Libera la memoria de una posible consulta. //Libera la memoria de una posible consulta.
@@ -88,103 +95,132 @@ class Sql {
$this->bdd->close(); $this->bdd->close();
} }
} }
public function filtra($cadena)
public function filtra($cadena)
{ {
return $this->bdd->real_escape_string($cadena); return $this->bdd->real_escape_string($cadena);
} }
public function ejecuta($comando) public function ejecuta($comando)
{ {
if (!$this->estado) { if (!$this->estado) {
$this->error=true; $this->error = true;
$this->mensajeError='No est&aacute; conectado'; $this->mensajeError = 'No est&aacute; conectado';
return false; return false;
} }
if (!$this->peticion=$this->bdd->query($comando)) { if (!$this->peticion = $this->bdd->query($comando)) {
$this->error=true; $this->error = true;
$this->mensajeError='No pudo ejecutar la petici&oacute;n: '.$comando; $this->mensajeError = 'No pudo ejecutar la petici&oacute;n: '.$comando;
return false; return false;
} }
$this->numero=$this->bdd->affected_rows; $this->numero = $this->bdd->affected_rows;
$this->id=$this->bdd->insert_id; $this->id = $this->bdd->insert_id;
$this->error=false; $this->error = false;
$this->mensajeError=''; $this->mensajeError = '';
return true; return true;
} }
public function procesaResultado() public function procesaResultado()
{ {
if (!$this->estado) { if (!$this->estado) {
$this->error=true; $this->error = true;
$this->mensajeError='No está conectado a una base de datos'; $this->mensajeError = 'No está conectado a una base de datos';
return NULL;
return;
} }
if (!$this->peticion) { if (!$this->peticion) {
$this->error=true; $this->error = true;
$this->mensajeError='No hay un resultado disponible'; $this->mensajeError = 'No hay un resultado disponible';
return NULL;
return;
} }
$datos=$this->peticion->fetch_assoc(); $datos = $this->peticion->fetch_assoc();
$this->error=false; $this->error = false;
$this->mensajeError=''; $this->mensajeError = '';
return ($datos);
return $datos;
} }
public function camposResultado()
public function camposResultado()
{ {
if (!$this->estado) { if (!$this->estado) {
$this->error=true; $this->error = true;
$this->mensajeError='No está conectado a una base de datos'; $this->mensajeError = 'No está conectado a una base de datos';
return NULL;
return;
} }
if (!$this->peticion) { if (!$this->peticion) {
$this->error=true; $this->error = true;
$this->mensajeError='No hay un resultado disponible'; $this->mensajeError = 'No hay un resultado disponible';
return NULL;
return;
} }
$datos=$this->peticion->fetch_field(); $datos = $this->peticion->fetch_field();
$this->error=false; $this->error = false;
$this->mensajeError=''; $this->mensajeError = '';
return ($datos);
return $datos;
} }
/**
/**
* Devuelve el número de tuplas afectadas en la última petición. * 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; return $this->numero;
} }
/** /**
* Devuelve el número de tuplas total si se ha hecho una consulta select * Devuelve el número de tuplas total si se ha hecho una consulta select
* con SELECT SQL_CALC_FOUND_ROWS * ... * con SELECT SQL_CALC_FOUND_ROWS * ...
* @return integer Número de tuplas. *
* @return int Número de tuplas.
*/ */
public function numeroTotalTuplas() public function numeroTotalTuplas()
{ {
$comando = "select found_rows();"; $comando = 'select found_rows();';
if (!$peticion=$this->bdd->query($comando)) { if (!$peticion = $this->bdd->query($comando)) {
$this->error=true; $this->error = true;
$this->mensajeError='No pudo ejecutar la petici&oacute;n: '.$comando; $this->mensajeError = 'No pudo ejecutar la petici&oacute;n: '.$comando;
return false; return false;
} }
$numero = $peticion->fetch_row(); $numero = $peticion->fetch_row();
return $numero[0] ;
return $numero[0];
} }
/** /**
* Devuelve la condición de error de la última petición * Devuelve la condición de error de la última petición.
* @return boolean condición de error. *
* @return bool condición de error.
*/ */
public function error() { public function error()
{
return $this->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> * @return <type>
*/ */
public function mensajeError() { public function mensajeError()
{
return $this->mensajeError.$this->bdd->error; return $this->mensajeError.$this->bdd->error;
} }
/** /**
* Devuelve la estructura de campos de una tabla. * Devuelve la estructura de campos de una tabla.
*
* @param string $tabla Nombre de la tabla. * @param string $tabla Nombre de la tabla.
*
* @return string vector asociativo con la descripción de la tabla [campo]->valor * @return string vector asociativo con la descripción de la tabla [campo]->valor
*/ */
public function estructura($tabla) public function estructura($tabla)
@@ -192,40 +228,46 @@ class Sql {
if ($this->peticion) { if ($this->peticion) {
$this->peticion->free_result(); $this->peticion->free_result();
} }
$comando="show full columns from $tabla"; $comando = "show full columns from $tabla";
if (!$this->ejecuta($comando)) { if (!$this->ejecuta($comando)) {
return false; return false;
} }
while ($dato=$this->procesaResultado()) { while ($dato = $this->procesaResultado()) {
$salida[]=$dato; $salida[] = $dato;
} }
return $salida; return $salida;
} }
public function ultimoId() public function ultimoId()
{ {
return $this->id; return $this->id;
} }
public function obtieneManejador() public function obtieneManejador()
{ {
return $this->bdd; return $this->bdd;
} }
public function comienzaTransaccion() public function comienzaTransaccion()
{ {
return $this->bdd->autocommit(false); return $this->bdd->autocommit(false);
} }
public function abortaTransaccion() public function abortaTransaccion()
{ {
$codigo = $this->bdd->rollback(); $codigo = $this->bdd->rollback();
$this->bdd->autocommit(true); $this->bdd->autocommit(true);
return $codigo;
return $codigo;
} }
public function confirmaTransaccion() public function confirmaTransaccion()
{ {
$codigo = $this->bdd->commit(); $codigo = $this->bdd->commit();
$this->bdd->autocommit(true); $this->bdd->autocommit(true);
$this->peticion = null; $this->peticion = null;
return $codigo; return $codigo;
} }
} }
?>

View File

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

View File

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

View File

@@ -1,9 +1,11 @@
<?php <?php
/** /**
* Genera una instancia de la aplicación y la ejecuta. * Genera una instancia de la aplicación y la ejecuta.
*
* @author Ricardo Montañana <rmontanana@gmail.com> * @author Ricardo Montañana <rmontanana@gmail.com>
*
* @version 1.0 * @version 1.0
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -11,23 +13,23 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
//Se incluyen los módulos necesarios //Se incluyen los módulos necesarios
function __autoload($class_name) { function __autoload($class_name)
require_once $class_name . '.php'; {
require_once $class_name.'.php';
} }
include('inc/configuracion.inc'); include 'inc/configuracion.inc';
$aplicacion=new Inventario(); $aplicacion = new Inventario();
if ($aplicacion->estado()) if ($aplicacion->estado()) {
$aplicacion->Ejecuta(); $aplicacion->Ejecuta();
?> }

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* Migra los datos de la versión anterior de Inventario a la actual. * Migra los datos de la versión anterior de Inventario a la actual.
* @package Inventario *
* @copyright Copyright (c) 2008, Ricardo Montañana Gómez * @copyright Copyright (c) 2008, Ricardo Montañana Gómez
* @license http://www.gnu.org/licenses/gpl-3.0.txt * @license http://www.gnu.org/licenses/gpl-3.0.txt
* This file is part of Inventario. * This file is part of Inventario.
@@ -9,81 +9,84 @@
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version. * (at your option) any later version.
* *
* Inventario is distributed in the hope that it will be useful, * Inventario is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with Inventario. If not, see <http://www.gnu.org/licenses/>. * along with Inventario. If not, see <http://www.gnu.org/licenses/>.
*
*/ */
$host="localhost"; $host = 'localhost';
$baseAnt="Inventario"; $baseAnt = 'Inventario';
$baseNueva="Inventario2"; $baseNueva = 'Inventario2';
$usuario="test"; $usuario = 'test';
$claveUsuario="tset"; $claveUsuario = 'tset';
$probar=false; $probar = false;
// No se debería modificar nada después de este comentario // No se debería modificar nada después de este comentario
function creaUbicacion($bd1,$bd2,$clave) function creaUbicacion($bd1, $bd2, $clave)
{ {
global $probar; global $probar;
$comando="select nombre from Ubicaciones where codigo=".$clave.";"; $comando = 'select nombre from Ubicaciones where codigo='.$clave.';';
$resultado=$bd1->query($comando); $resultado = $bd1->query($comando);
if ($bd1->affected_rows==0) { if ($bd1->affected_rows == 0) {
echo $comando; echo $comando;
die("No encontró la ubicación ".$clave); die('No encontró la ubicación '.$clave);
} }
$dato=$resultado->fetch_assoc(); $dato = $resultado->fetch_assoc();
$valor=$dato['nombre']; $valor = $dato['nombre'];
$comando="insert into Ubicaciones values (NULL,'".$valor."');"; $comando = "insert into Ubicaciones values (NULL,'".$valor."');";
if ($probar) { if ($probar) {
echo $comando; echo $comando;
return 1; return 1;
} else { } else {
$test=$bd2->query($comando); $test = $bd2->query($comando);
if (!$test) { if (!$test) {
die("**No pudo insertar ubicacion.".$comando); die('**No pudo insertar ubicacion.'.$comando);
} }
return $bd2->insert_id; return $bd2->insert_id;
} }
} }
function creaArticulo($bd1,$bd2,$clave) function creaArticulo($bd1, $bd2, $clave)
{ {
global $probar; global $probar;
$comando="select * from Articulos where codigo='".$clave."';"; $comando = "select * from Articulos where codigo='".$clave."';";
$resultado=$bd1->query($comando); $resultado = $bd1->query($comando);
if ($bd1->affected_rows==0) { if ($bd1->affected_rows == 0) {
echo $comando; echo $comando;
die("No encontró el artículo ".$clave); die('No encontró el artículo '.$clave);
} }
$dato=$resultado->fetch_assoc(); $dato = $resultado->fetch_assoc();
$valor1=$dato['descripcion']; $valor1 = $dato['descripcion'];
$valor2=$dato['marca']; $valor2 = $dato['marca'];
$valor3=$dato['modelo']; $valor3 = $dato['modelo'];
$valor4=$dato['cantidad']; $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) { if ($probar) {
echo $comando; echo $comando;
return 1; return 1;
} else { } else {
$test=$bd2->query($comando); $test = $bd2->query($comando);
if (!$test) { if (!$test) {
die("**No pudo insertar artículo.".$comando); die('**No pudo insertar artículo.'.$comando);
} }
return $bd2->insert_id; return $bd2->insert_id;
} }
} }
function generaSesion() function generaSesion()
{ {
$long=10; $long = 10;
$cadena=""; $cadena = '';
for ($i=0;$i<$long;$i++) { for ($i = 0; $i < $long; $i++) {
$cadena.=chr(rand(40,126)); $cadena .= chr(rand(40, 126));
} }
return $cadena; return $cadena;
} }
/* /*
@@ -91,64 +94,64 @@ function generaSesion()
* Comienzo del programa principal. * Comienzo del programa principal.
* *
*/ */
$bd1=new mysqli($host,$usuario,$claveUsuario,$baseAnt); $bd1 = new mysqli($host, $usuario, $claveUsuario, $baseAnt);
if(mysqli_connect_errno()) { 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); $bd2 = new mysqli($host, $usuario, $claveUsuario, $baseNueva);
if(mysqli_connect_errno()) { 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); $bd2->autocommit(false);
$datos=$bd1->query("select * from Elementos;"); $datos = $bd1->query('select * from Elementos;');
if (!$datos) { if (!$datos) {
die("**No encontró datos en la tabla de elementos."); die('**No encontró datos en la tabla de elementos.');
} }
$numRegistros=$bd1->affected_rows; $numRegistros = $bd1->affected_rows;
$contador=0; $contador = 0;
$ubicaciones=array(); $ubicaciones = [];
$articulos=array(); $articulos = [];
echo "++Comenzando proceso de actualización de Elementos con ".$numRegistros." registros por procesar.<br>\n"; echo '++Comenzando proceso de actualización de Elementos con '.$numRegistros." registros por procesar.<br>\n";
while($fila=$datos->fetch_assoc()) { while ($fila = $datos->fetch_assoc()) {
$contador++; $contador++;
echo "Procesando registro ".$contador." de ".$numRegistros."<br>\n"; echo 'Procesando registro '.$contador.' de '.$numRegistros."<br>\n";
if (!isset($ubicaciones[$fila['codUbicacion']])) { if (!isset($ubicaciones[$fila['codUbicacion']])) {
$ubicaciones[$fila['codUbicacion']]=creaUbicacion($bd1,$bd2,$fila['codUbicacion']); $ubicaciones[$fila['codUbicacion']] = creaUbicacion($bd1, $bd2, $fila['codUbicacion']);
} }
if (!isset($articulos[$fila['codArticulo']])) { if (!isset($articulos[$fila['codArticulo']])) {
$articulos[$fila['codArticulo']]=creaArticulo($bd1,$bd2,$fila['codArticulo']); $articulos[$fila['codArticulo']] = creaArticulo($bd1, $bd2, $fila['codArticulo']);
} }
$comando="insert into Elementos values (NULL,".$articulos[$fila['codArticulo']].",".$ubicaciones[$fila['codUbicacion']]; $comando = 'insert into Elementos values (NULL,'.$articulos[$fila['codArticulo']].','.$ubicaciones[$fila['codUbicacion']];
$comando.=",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');"; $comando .= ",'".$fila['numserie']."',".$fila['cantidad'].",'".$fila['fechaCompra']."');";
if ($probar) { if ($probar) {
echo $comando."<br>"; echo $comando.'<br>';
} else { } else {
$res=$bd2->query($comando); $res = $bd2->query($comando);
if (!$res) { 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 //Traspasa los usuarios
$datos=$bd1->query("select * from Usuarios;"); $datos = $bd1->query('select * from Usuarios;');
if (!$datos) { if (!$datos) {
die("**No encontró datos en la tabla de Usuarios."); die('**No encontró datos en la tabla de Usuarios.');
} }
$numRegistros=$bd1->affected_rows; $numRegistros = $bd1->affected_rows;
$contador=0; $contador = 0;
while ($fila=$datos->fetch_assoc()) { while ($fila = $datos->fetch_assoc()) {
$contador++; $contador++;
echo "Procesando registro ".$contador." de ".$numRegistros."<br>\n"; echo 'Procesando registro '.$contador.' de '.$numRegistros."<br>\n";
$sesion=generaSesion(); $sesion = generaSesion();
$comando="insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion; $comando = "insert into Usuarios values (NULL,'".$fila['usuario']."','".$fila['usuario']."','".$sesion;
$comando.="',".$fila['altas'].",".$fila['modificaciones'].",".$fila['bajas'].",".$fila['consultas'].","; $comando .= "',".$fila['altas'].','.$fila['modificaciones'].','.$fila['bajas'].','.$fila['consultas'].',';
$comando.=$fila['informes'].",".$fila['usuarios'].",1);"; $comando .= $fila['informes'].','.$fila['usuarios'].',1);';
if ($probar) { if ($probar) {
echo $comando."<br>"; echo $comando.'<br>';
} else { } else {
$res=$bd2->query($comando); $res = $bd2->query($comando);
if (!$res) { 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(); $bd2->commit();
$bd1->close(); $bd1->close();
$bd2->close(); $bd2->close();
?>