2 Commits

Author SHA1 Message Date
6829495ca9 *Corregido que no aparecía el mensaje de bienvenida al hacer login en la aplicación 2014-10-23 19:28:38 +02:00
12ff042c1d Merge branch 'release/1.17' into develop
* release/1.17:
  Eliminados los mensajes de aviso de php en todos los archivos php, actualizada la versión y el changelog
2014-07-29 21:41:51 +02:00
39 changed files with 5038 additions and 5298 deletions

View File

@@ -1,5 +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.
@@ -15,6 +16,7 @@
* *
* 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';
@@ -23,8 +25,7 @@ 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;
@@ -33,61 +34,55 @@ class Ajax
$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(['success' => $exito, 'msj' => $texto]); return json_encode(array("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 = []; $filas = array();
while($r = $this->sql->procesaResultado()) { while($r = $this->sql->procesaResultado()) {
$filas[] = [$r['id'] => $r['descripcion']]; $filas[] = array($r['id'] => $r['descripcion']);
} }
$resp = json_encode($filas); $resp = json_encode($filas);
return $this->respuesta($resp); return $this->respuesta($resp);
} }
} }
} }
?>

View File

@@ -1,5 +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.
@@ -15,6 +16,7 @@
* *
* 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>' .
@@ -48,17 +50,18 @@ 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.
@@ -76,7 +79,7 @@ class AportaContenido
private $opcionActual; private $opcionActual;
/** /**
* @var bool Usuario y clave incorrectos? * @var boolean Usuario y clave incorrectos?
*/ */
private $usuario_inc = false; private $usuario_inc = false;
@@ -86,20 +89,19 @@ class AportaContenido
private $perfil; private $perfil;
/** /**
*
* @var array Datos pasados en la URL * @var array Datos pasados en la URL
*/ */
private $datosURL = []; private $datosURL = array();
// 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
* @param bool $registrado usuario registrado si/no * @param boolean $registrado usuario registrado si/no
* @param string $usuario Nombre del usuario * @param String $usuario Nombre del usuario
* @param array $perfil Permisos de acceso del usuario * @param array $perfil Permisos de acceso del usuario
* @param string $opcion Opción elegida por el usuario * @param String $opcion Opción elegida por el usuario
*/ */
public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion) public function __construct($baseDatos, $registrado, $usuario, $perfil, $opcion)
{ {
@@ -113,12 +115,12 @@ class AportaContenido
/** /**
* 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>';
@@ -137,29 +139,25 @@ class AportaContenido
$tabla .='<tr><td><a href="http://momentjs.com/" target="_blank">Moment.js</a></td>'.($poner?'<td>2.5.1</td>':'').'<td><a target="_blank" href="https://github.com/moment/moment/blob/develop/LICENSE">MIT</a></td>'; $tabla .='<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()
@@ -169,24 +167,20 @@ 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 () {
@@ -197,15 +191,13 @@ class AportaContenido
}); });
}); });
</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; return $etiqueta . $campo . $script;
case 'aplicacion': case 'aplicacion':
$nombre = explode(' ', PROGRAMA); $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();
@@ -218,38 +210,35 @@ class AportaContenido
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; $opcion = $this->opcionActual; $parametro = "";
$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
@@ -259,24 +248,24 @@ 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; $opcion = $this->opcionActual; $parametro = "";
$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 = ''; if (!isset($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 . '" >' . 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; '<br><br><label onClick="' . $creditos . '">' . $centro . '</label>' . $rama . '</center>' . CREDITOS_CABECERA . $tabla . CREDITOS_PIE;
case 'articulos': case 'articulos':
@@ -284,31 +273,29 @@ class AportaContenido
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));
@@ -316,30 +303,28 @@ 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');
@@ -347,7 +332,6 @@ 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');
@@ -355,7 +339,6 @@ 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');
@@ -363,34 +346,31 @@ 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
@@ -416,21 +396,20 @@ 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;">
@@ -445,7 +424,7 @@ class AportaContenido
$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,5 +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.
@@ -15,20 +16,20 @@
* *
* 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 $configuracion = 'inc/configuracion.inc'; private $confNueva = "inc/configuracion.new";
private $confNueva = 'inc/configuracion.new'; private $confAnterior = "inc/configuracion.ant";
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 = ['SERVIDOR', 'PUERTO', 'BASEDATOS', 'BASEDATOSTEST', 'USUARIO', 'CLAVE', 'CENTRO', 'NUMFILAS', 'ESTILO', 'PLANTILLA', 'COLORLAT', 'COLORFON', 'MYSQLDUMP', 'GZIP', 'TMP']; private $lista = array('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.
@@ -44,11 +45,11 @@ class Configuracion
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);
} }
@@ -57,16 +58,15 @@ class Configuracion
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;
@@ -78,7 +78,7 @@ 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);
} }
} }
@@ -91,66 +91,64 @@ class Configuracion
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",
$coloresLateral = ['Original' => '#C4FAEC', 'Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db', "Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Morado" => "#6633FF",
'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Morado' => '#6633FF', "Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1");
'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1', ]; $coloresFondo = array("Verde" => "#7bd148", "Azul marino" => "#5484ed", "Azul" => "#a4bdfc", "Turquesa" => "#46d6db",
$coloresFondo = ['Verde' => '#7bd148', 'Azul marino' => '#5484ed', 'Azul' => '#a4bdfc', 'Turquesa' => '#46d6db', "Verde claro" => "#7ae7bf", "Verde oscuro" => "#51b749", "Amarillo" => "#fbd75b", "Naranja" => "#ffb878", "Rojo" => "#ff887c",
'Verde claro' => '#7ae7bf', 'Verde oscuro' => '#51b749', 'Amarillo' => '#fbd75b', 'Naranja' => '#ffb878', 'Rojo' => '#ff887c', "Rojo oscuro" => "#dc2127", "P&uacute;rpura" => "#dbadff", "Gris" => "#e1e1e1", "Original" => '#F3FEC8');
'Rojo oscuro' => '#dc2127', 'P&uacute;rpura' => '#dbadff', 'Gris' => '#e1e1e1', 'Original' => '#F3FEC8', ]; $personal = $this->datosConf['ESTILO'] == "personal" ? 'selected' : ' ';
$personal = $this->datosConf['ESTILO'] == 'personal' ? 'selected' : ' '; $bluecurve = $this->datosConf['ESTILO'] == "bluecurve" ? 'selected' : ' ';
$bluecurve = $this->datosConf['ESTILO'] == 'bluecurve' ? 'selected' : ' '; $cristal = $this->datosConf['ESTILO'] == "cristal" ? 'selected' : ' ';
$cristal = $this->datosConf['ESTILO'] == 'cristal' ? 'selected' : ' '; $bootst = $this->datosConf['ESTILO'] == "bootstrap" ? 'selected' : ' ';
$bootst = $this->datosConf['ESTILO'] == 'bootstrap' ? 'selected' : ' '; $normal = $this->datosConf['PLANTILLA'] == "normal" ? 'selected' : ' ';
$normal = $this->datosConf['PLANTILLA'] == 'normal' ? 'selected' : ' '; $bootstrap = $this->datosConf['PLANTILLA'] == "bootstrap" ? '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>';
@@ -169,7 +167,7 @@ class Configuracion
$('.dato').popover({trigger: 'hover'}); $('.dato').popover({trigger: 'hover'});
}); });
</script>"; </script>";
return $salida; return $salida;
} }
} }
?>

View File

@@ -1,5 +1,6 @@
<?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.
@@ -15,9 +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 CopiaSeguridad class CopiaSeguridad {
{
private $mensaje; private $mensaje;
private $baseDatos; private $baseDatos;
private $imagenes; private $imagenes;
@@ -33,10 +34,8 @@ 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">
@@ -46,14 +45,12 @@ class CopiaSeguridad
<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);
@@ -64,23 +61,20 @@ class CopiaSeguridad
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);
@@ -90,20 +84,17 @@ class CopiaSeguridad
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);
} }
@@ -111,13 +102,12 @@ class CopiaSeguridad
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;
@@ -127,12 +117,12 @@ class CopiaSeguridad
$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;
} }
} }
?>

129
Csv.php
View File

@@ -1,6 +1,7 @@
<?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,18 +17,20 @@
* *
* 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
@@ -40,6 +43,7 @@ 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;
@@ -55,7 +59,8 @@ class Csv
private $datosFichero; private $datosFichero;
/** /**
* Indices a los campos correspondientes. * Indices a los campos correspondientes
*
*/ */
private $idElemento; private $idElemento;
private $idArticulo; private $idArticulo;
@@ -66,10 +71,9 @@ 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)
@@ -78,22 +82,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()
@@ -103,17 +107,18 @@ 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([$consulta->Pagina->Cabecera, $consulta->Titulo['id'], $consulta->Titulo['Texto']]); $this->escribeLinea(array($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'];
} }
@@ -121,7 +126,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 = []; $campos = array();
foreach ($consulta->Pagina->Cuerpo->Col as $campo) { foreach ($consulta->Pagina->Cuerpo->Col as $campo) {
$campos[] = $fila[(string) $campo['Nombre']]; $campos[] = $fila[(string) $campo['Nombre']];
} }
@@ -130,12 +135,13 @@ 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;
@@ -147,55 +153,56 @@ 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">
@@ -208,8 +215,8 @@ class Csv
} }
/** /**
* @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)
@@ -218,7 +225,7 @@ 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>';
@@ -226,15 +233,14 @@ class Csv
$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;
fwrite($fp, $linea."\n"); fputs($fp, $linea . "\n");
fclose($fp); fclose($fp);
} }
@@ -244,7 +250,7 @@ class Csv
$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);
} }
} }
@@ -254,13 +260,13 @@ class Csv
$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] . '";';
@@ -273,7 +279,7 @@ class Csv
$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);
} }
} }
@@ -281,19 +287,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;
} }
} }
@@ -302,7 +308,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()
{ {
@@ -327,17 +333,15 @@ 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);
} }
} }
@@ -354,4 +358,7 @@ class Csv
//echo '$(".bar").css("width", "'.$progreso.'");'; //echo '$(".bar").css("width", "'.$progreso.'");';
} }
} }
} }
?>

View File

@@ -1,5 +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.
@@ -15,6 +16,7 @@
* *
* 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
@@ -25,8 +27,7 @@
// 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 // Variable para conservar la plantilla
private $plantilla; private $plantilla;
// Matriz que contendrá los nombres de elementos // Matriz que contendrá los nombres de elementos
@@ -34,7 +35,6 @@ class Distribucion
// Referencia al objeto cuyos métodos serán // Referencia al objeto cuyos métodos serán
// invocados para aportar el contenido // invocados para aportar el contenido
private $objeto; private $objeto;
// Constructor de la clase // Constructor de la clase
public function __construct($archivo, $objeto) public function __construct($archivo, $objeto)
{ {
@@ -48,7 +48,6 @@ class Distribucion
// 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 // Este método es el encargado de procesar la plantilla
public function procesaPlantilla() public function procesaPlantilla()
{ {
@@ -64,7 +63,7 @@ class Distribucion
// e introducimos su contenido en lugar de la marca // e introducimos su contenido en lugar de la marca
$pagina=str_replace('{'.$el.'}',$resultado,$pagina); $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
@@ -77,3 +76,4 @@ class Distribucion
return $pagina; // enviamos sin comprimir return $pagina; // enviamos sin comprimir
} }
} }
?>

View File

@@ -1,13 +1,12 @@
<?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.
@@ -23,12 +22,14 @@
* *
* 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;
@@ -38,12 +39,10 @@ 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 basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML * @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no * @param boolean $registrado usuario registrado si/no
*
* @return ficheroPDF * @return ficheroPDF
* todo: cambiar este comentario * todo: cambiar este comentario
*/ */
@@ -52,7 +51,7 @@ class EtiquetasPDF
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;
@@ -62,7 +61,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);
@@ -79,12 +78,11 @@ class EtiquetasPDF
$this->pdf->AddPage(); $this->pdf->AddPage();
$tamLinea = 5; $tamLinea = 5;
$fila = -1; $fila = -1;
$primero = true; $primero = true; $i = 0;
$i = 0; $url = explode("/", $_SERVER['SCRIPT_NAME']);
$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
@@ -107,7 +105,7 @@ class EtiquetasPDF
} }
$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);
@@ -130,7 +128,7 @@ class EtiquetasPDF
$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++;
} }
@@ -151,16 +149,15 @@ 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;
@@ -169,10 +166,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()
@@ -181,3 +178,5 @@ class EtiquetasPDF
echo $this->docu; echo $this->docu;
} }
} }
?>

1189
FPDF.php

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,6 @@
<?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.
@@ -15,15 +16,15 @@
* *
* 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;
@@ -37,7 +38,7 @@ class Imagen
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
@@ -76,11 +77,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}');
@@ -97,40 +98,36 @@ 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 = ['png', 'gif', 'jpg']; $extensiones = array ("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;
@@ -141,7 +138,7 @@ class Imagen
{ {
$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;
@@ -174,13 +171,13 @@ class Imagen
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,6 +1,7 @@
<?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,21 +17,20 @@
* *
* 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,23 @@ 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";
$accion = 'index.php?importacion&opc=importar'; $salida = "";
$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";
@@ -93,16 +90,14 @@ 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,6 +1,7 @@
<?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,9 +17,10 @@
* *
* 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)
@@ -46,16 +48,14 @@ 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;">
@@ -67,50 +67,48 @@ 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/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);
} }
} }
@@ -119,52 +117,50 @@ 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);
} }
} }
@@ -172,32 +168,30 @@ 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;
} }
@@ -212,25 +206,22 @@ class InformeInventario
$salida.='<div class="radio"><label><input type="radio" name="salida" value="pantalla" checked><span class="glyphicon glyphicon-list-alt"></span> Pantalla</label></div>'; $salida.='<div class="radio"><label><input type="radio" name="salida" value="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());
} }
@@ -248,15 +239,14 @@ class InformeInventario
<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);
@@ -266,8 +256,8 @@ class InformeInventario
$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;
@@ -276,7 +266,9 @@ class InformeInventario
$informe->crea($salida); $informe->crea($salida);
} }
$informe->cierraPDF(); $informe->cierraPDF();
return $this->devuelveInforme($informe); return $this->devuelveInforme($informe);
} }
} }
?>

View File

@@ -1,13 +1,12 @@
<?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.
@@ -23,10 +22,12 @@
* *
* 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;
@@ -35,17 +36,14 @@ 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 basedatos $bdd manejador de la base de datos
* @param string $definicion fichero con la definición del informe en XML * @param string $definicion fichero con la definición del informe en XML
* @param bool $registrado usuario registrado si/no * @param boolean $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';
} }
@@ -56,14 +54,13 @@ class InformePDF
//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
@@ -77,55 +74,50 @@ 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 = ['HeaderColor' => [255, 150, 100], $prop = array('HeaderColor' => array(255, 150, 100),
'color1' => [210, 245, 255], 'color1' => array(210, 245, 255),
'color2' => [255, 255, 210], 'color2' => array(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 = 'Content-type: application/pdf'; $cabecera = $cabecera . "Content-length: " . strlen($this->docu);
$cabecera = $cabecera.'Content-length: '.strlen($this->docu); $cabecera = $cabecera . "Content-Disposition: inline; filename=".TMP."/Informe.pdf";
$cabecera = $cabecera.'Content-Disposition: inline; filename='.TMP.'/Informe.pdf';
return $cabecera; return $cabecera;
} }
public function guardaArchivo($nombre) public function guardaArchivo($nombre) {
{ if (!isset($nombre))
if (!isset($nombre)) { $nombre = TMP . "/Informe.pdf";
$nombre = TMP.'/Informe.pdf'; $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()));
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,10 +18,10 @@
* *
* 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';
} }
@@ -37,13 +37,11 @@ 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;
@@ -71,14 +69,11 @@ class Instalar
{ {
//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;
} }
@@ -89,15 +84,14 @@ class Instalar
$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();
} }
@@ -108,9 +102,9 @@ 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');
@@ -124,49 +118,46 @@ class Instalar
$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) ? 'Sí' : 'No'; $valor = is_writable(IMAGEDATA) ? "" : "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) ? 'Sí' : 'No'; $valor = is_writable(TMP) ? "" : "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) ? 'Sí' : 'No'; $valor = is_writable(INC) ? "" : "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) ? 'Sí' : 'No'; $valor = is_writable(CONFIGURACION) ? "" : "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;
} }
@@ -183,24 +174,20 @@ class Instalar
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; $nombre1 = $tipo; $nombre2 = "remove";
$nombre2 = 'remove';
} else { } else {
$nombre1 = 'success'; $nombre1 = "success"; $nombre2 = "ok";
$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;
} }
@@ -217,7 +204,6 @@ class Instalar
case 'k': case 'k':
$val *= 1024; $val *= 1024;
} }
return $val; return $val;
} }
@@ -231,28 +217,20 @@ 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;
} }
@@ -262,10 +240,10 @@ class Instalar
$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) {
@@ -275,7 +253,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);
} }
@@ -298,7 +276,7 @@ class Instalar
$datos[$clave] = $valor; $datos[$clave] = $valor;
} }
} else { } else {
$datos = []; $datos = array();
} }
$this->actualizaConfiguracion($grabar, $campos, $datos); $this->actualizaConfiguracion($grabar, $campos, $datos);
if ($grabar && $this->validaPaso1()) { if ($grabar && $this->validaPaso1()) {
@@ -315,20 +293,18 @@ class Instalar
$info .= '<li class="list-group-item">Usuario <input type="text" name="USUARIO" class="form-control" placeholder="Usuario" value="'. $datos['USUARIO'] .'"></li>'; $info .= '<li class="list-group-item">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;
@@ -343,7 +319,6 @@ class Instalar
if ($sql->error()) { if ($sql->error()) {
return false; return false;
} }
return true; return true;
} }
@@ -353,8 +328,8 @@ class Instalar
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',
@@ -404,7 +379,7 @@ 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'];
@@ -415,28 +390,27 @@ class Instalar
$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'] = 'sí'; $datos['INSTALADO'] = "";
$this->actualizaConfiguracion(true, $campos, $datos); $this->actualizaConfiguracion(true, $campos, $datos);
return $this->resumen(); return $this->resumen();
} }
@@ -461,14 +435,13 @@ 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;
} }
@@ -478,15 +451,13 @@ class Instalar
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 = '<div class="panel panel-' . $tipo . ' col-sm-6"><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;
} }
@@ -523,12 +494,10 @@ class Instalar
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>
@@ -562,9 +531,8 @@ class Instalar
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;
} }
@@ -572,17 +540,19 @@ class Instalar
{ {
$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,11 +2,9 @@
/** /**
* 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.
@@ -22,14 +20,15 @@
* *
* 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.
@@ -37,15 +36,13 @@ 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
@@ -53,10 +50,10 @@ 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 'Servidor [ '.SERVIDOR.' ] base de datos ['.BASEDATOS.']';
$this->estado = false;
echo '<h1>Fallo al conectar con el servidor MySQL.</h1>';
echo "Servidor [ " . SERVIDOR . " ] base de datos [" . BASEDATOS . "]";
$this->estado = false;
return; return;
} else { } else {
$this->estado = true; $this->estado = true;
@@ -80,16 +77,14 @@ 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
@@ -123,7 +118,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);
@@ -141,16 +136,14 @@ class Inventario
} }
} }
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
@@ -174,11 +167,10 @@ class Inventario
return false; return false;
} }
private function creaPerfil($fila) private function creaPerfil($fila) {
{ return array("Consulta" => $fila['consulta'], "Modificacion" => $fila['modificacion'],
return ['Consulta' => $fila['consulta'], 'Modificacion' => $fila['modificacion'], "Alta" => $fila['alta'], "Borrado" => $fila['borrado'], "Informe" => $fila['informe'],
'Alta' => $fila['alta'], 'Borrado' => $fila['borrado'], 'Informe' => $fila['informe'], "Usuarios" => $fila['usuarios'], "Config" => $fila['config']);
'Usuarios' => $fila['usuarios'], 'Config' => $fila['config'], ];
} }
// Esta función intenta recuperar el nombre del usuario // Esta función intenta recuperar el nombre del usuario
@@ -186,8 +178,7 @@ 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
@@ -213,3 +204,5 @@ class Inventario
} }
} }
} }
?>

View File

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

View File

@@ -1,5 +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.
@@ -15,13 +16,12 @@
* *
* 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
@@ -31,27 +31,24 @@ class Menu
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

@@ -17,33 +17,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/>.
*
*/ */
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; private $ProcessingTable=false,$aCols=array(),$TableX,$HeaderColor;
private $aCols = []; private $RowColors,$ColorIndex;
private $TableX; private $bdd,$titulo,$cabecera;
private $HeaderColor; private $totales=array(),$procesandoTotales=false;
private $RowColors;
private $ColorIndex;
private $bdd;
private $titulo;
private $cabecera;
private $totales = [];
private $procesandoTotales = false;
/** /**
*
* @param mixed $bdd Controlador de la base de datos * @param mixed $bdd Controlador de la base de datos
* @param string $orientacion Orientación de la página P/L * @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 $formato Tamaño de la página p. ej. A4
* @param string $titulo Título del informe * @param string $titulo Título del informe
* @param string $cabecera Texto para la cabecera * @param string $cabecera Texto para la cabecera
*/ */
public function __construct($bdd,$orientacion,$formato,$titulo='',$cabecera='') public function __construct($bdd,$orientacion,$formato,$titulo='',$cabecera='')
{ {
$this->bdd=$bdd; $this->bdd=$bdd;
@@ -51,24 +47,21 @@ class Pdf_mysql_table extends FPDF
$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() public function iniciaTotales()
{ {
$this->totales = []; $this->totales = array();
} }
function Header()
public function Header()
{ {
//Modficada por Ricardo Montañana //Modficada por Ricardo Montañana
//Titulo //Titulo
$fecha = strftime('%d-%b-%Y %H:%M'); $fecha=strftime("%d-%b-%Y %H:%M");
$this->SetFont('Arial','',8); $this->SetFont('Arial','',8);
$this->Cell(0, 4, html_entity_decode(CENTRO.' '.PROGRAMA.' v'.VERSION, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1'), 0, 1, 'L'); $this->Cell(0,4,html_entity_decode(CENTRO . " " . PROGRAMA . " v" . VERSION,ENT_COMPAT | ENT_HTML401,'ISO-8859-1'),0,1,'L');
$this->SetFont('Arial','',18); $this->SetFont('Arial','',18);
$this->Cell(0,6,utf8_decode($this->titulo),0,1,'C'); $this->Cell(0,6,utf8_decode($this->titulo),0,1,'C');
$this->SetFont('Arial','',8); $this->SetFont('Arial','',8);
@@ -76,13 +69,11 @@ class Pdf_mysql_table extends FPDF
$this->Cell(0,5,utf8_decode($this->cabecera),0,1,'C'); $this->Cell(0,5,utf8_decode($this->cabecera),0,1,'C');
$this->Ln(10); $this->Ln(10);
//Print the table header if necessary //Print the table header if necessary
if ($this->ProcessingTable) { if($this->ProcessingTable)
$this->TableHeader(); $this->TableHeader();
}
//Ensure table header is output //Ensure table header is output
parent::Header(); parent::Header();
} }
public function Footer() public function Footer()
{ {
$this->SetFont('Arial','',8); $this->SetFont('Arial','',8);
@@ -91,28 +82,25 @@ class Pdf_mysql_table extends FPDF
parent::Footer(); parent::Footer();
} }
public function TableHeader() function TableHeader()
{ {
$this->SetFont('Arial','B',12); $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)
foreach ($this->aCols as $col) {
$this->Cell($col['w'],6,utf8_decode($col['c']),1,0,'C',$fill); $this->Cell($col['w'],6,utf8_decode($col['c']),1,0,'C',$fill);
}
$this->Ln(); $this->Ln();
} }
public function Row($data) 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;
@@ -123,7 +111,7 @@ class Pdf_mysql_table extends FPDF
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);
@@ -132,99 +120,91 @@ class Pdf_mysql_table extends FPDF
//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;
} }
public function CalcWidths($width, $align) 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;
} }
}
public function AddCol($field = -1, $width = -1, $caption = '', $align = 'I', $total = 'N') 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];
} }
public function Table($query, $prop = []) function Table($query,$prop=array())
{ {
//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 (is_string($col['f'])) { if($col['c']=='')
{
if(is_string($col['f']))
$this->aCols[$i]['c']=ucfirst($col['f']); $this->aCols[$i]['c']=ucfirst($col['f']);
} else { else
$this->aCols[$i]['c']=ucfirst($res->field_seek($i)); $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)
if ($prop['width'] == 0) {
$prop['width']=$this->w-$this->lMargin-$this->rMargin; $prop['width']=$this->w-$this->lMargin-$this->rMargin;
} if(!isset($prop['align']))
if (!isset($prop['align'])) {
$prop['align']='C'; $prop['align']='C';
} if(!isset($prop['padding']))
if (!isset($prop['padding'])) {
$prop['padding']=$this->cMargin; $prop['padding']=$this->cMargin;
}
$cMargin=$this->cMargin; $cMargin=$this->cMargin;
$this->cMargin=$prop['padding']; $this->cMargin=$prop['padding'];
if (!isset($prop['HeaderColor'])) { if(!isset($prop['HeaderColor']))
$prop['HeaderColor'] = []; $prop['HeaderColor']=array();
}
$this->HeaderColor=$prop['HeaderColor']; $this->HeaderColor=$prop['HeaderColor'];
if (!isset($prop['color1'])) { if(!isset($prop['color1']))
$prop['color1'] = []; $prop['color1']=array();
} if(!isset($prop['color2']))
if (!isset($prop['color2'])) { $prop['color2']=array();
$prop['color2'] = []; $this->RowColors=array($prop['color1'],$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
@@ -244,15 +224,12 @@ class Pdf_mysql_table extends FPDF
} }
$this->ProcessingTable=false; $this->ProcessingTable=false;
$this->cMargin=$cMargin; $this->cMargin=$cMargin;
$this->aCols = []; $this->aCols=array();
} }
/** /**
* 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()
{ {
@@ -261,7 +238,7 @@ class Pdf_mysql_table extends FPDF
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](https://inventario.rmontanana.es) [Instalación de ejemplo](http://inventario2.rmontanana.es)
[Estadísticas del proyecto](https://www.ohloh.net/p/inventario2) [Estadísticas del proyecto](https://www.ohloh.net/p/inventario2)

104
Sql.php
View File

@@ -1,11 +1,9 @@
<?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> * @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.
@@ -21,47 +19,44 @@
* *
* 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 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 bool Almacena el estado de error o no de la última acción. * @var boolean Almacena el estado de error o no de la última acción.
*/ */
private $error=false; private $error=false;
/** /**
* @var bool Estado de la conexión con la base de datos. * @var boolean 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 int Número de tuplas afectadas en la última consulta. * @var integer 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 = []; private $datos=array();
/** /**
* 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
@@ -71,7 +66,7 @@ class Sql
$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 {
@@ -79,11 +74,9 @@ class Sql
$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.
@@ -95,132 +88,103 @@ 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)
@@ -235,39 +199,33 @@ class Sql
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 int * @var integer
*/ */
public $chmod_value; var $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 bool * @var boolean
*/ */
public $enlarge_smaller_images; var $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 int * @var integer
*/ */
public $error; var $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 int * @var integer
*/ */
public $jpeg_quality; var $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 int * @var integer
*/ */
public $png_compression; var $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 bool * @var boolean
*/ */
public $preserve_aspect_ratio; var $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 bool * @var boolean
*/ */
public $preserve_time; var $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 bool * @var boolean
*/ */
public $sharpen_images; var $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
*/ */
public $source_path; var $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
*/ */
public $target_path; var $target_path;
/** /**
* Constructor of the class. * Constructor of the class.
@@ -193,7 +193,7 @@ class Zebra_Image
* *
* @return void * @return void
*/ */
public function Zebra_Image() function Zebra_Image()
{ {
// set default values for properties // set default values for properties
@@ -210,6 +210,7 @@ class Zebra_Image
$this->sharpen_images = false; $this->sharpen_images = false;
$this->source_path = $this->target_path = ''; $this->source_path = $this->target_path = '';
} }
/** /**
@@ -291,17 +292,21 @@ 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
@@ -309,7 +314,7 @@ class Zebra_Image
* *
* @since 2.2.2 * @since 2.2.2
* *
* @return bool Returns TRUE on success or FALSE on error. * @return boolean 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.
@@ -321,11 +326,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.
*/ */
public function apply_filter($filter, $arg1 = '', $arg2 = '', $arg3 = '', $arg4 = '') 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()) {
@@ -353,23 +358,19 @@ 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([$target_identifier, constant('IMG_FILTER_'.strtoupper($arguments[0]))], array_slice($arguments, 1)))) { if (!@call_user_func_array('imagefilter', array_merge(array($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 { } else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
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))) {
@@ -378,26 +379,24 @@ class Zebra_Image
$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([$target_identifier, constant('IMG_FILTER_'.strtoupper($filter))], array_slice($arguments, 1)))) { if (!@call_user_func_array('imagefilter', array_merge(array($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 { } else trigger_error('Filter "' . strtoupper($arguments[0]) . '" is not available', E_USER_WARNING);
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;
} }
/** /**
@@ -422,18 +421,21 @@ class Zebra_Image
* $img->crop(0, 0, 100, 100); * $img->crop(0, 0, 100, 100);
* </code> * </code>
* *
* @param int $start_x x coordinate to start cropping from * @param integer $start_x x coordinate to start cropping from
* @param int $start_y y coordinate to start cropping from *
* @param int $end_x x coordinate where to end the cropping * @param integer $start_y y coordinate to start cropping from
* @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 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.
*/ */
public function crop($start_x, $start_y, $end_x, $end_y) function crop($start_x, $start_y, $end_x, $end_y)
{ {
// this method might be also called internally // this method might be also called internally
@@ -451,9 +453,7 @@ 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 { } else $result = $this->_create_from_source();
$result = $this->_create_from_source();
}
// if image resource was successfully created // if image resource was successfully created
if ($result !== false) { if ($result !== false) {
@@ -479,17 +479,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;
} }
/** /**
* 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
@@ -512,17 +514,19 @@ class Zebra_Image
* *
* @since 2.1 * @since 2.1
* *
* @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.
*/ */
public function flip_both() 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
@@ -543,17 +547,19 @@ class Zebra_Image
* $img->flip_horizontal(); * $img->flip_horizontal();
* </code> * </code>
* *
* @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.
*/ */
public function flip_horizontal() 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
@@ -574,13 +580,15 @@ class Zebra_Image
* $img->flip_vertical(); * $img->flip_vertical();
* </code> * </code>
* *
* @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.
*/ */
public function flip_vertical() function flip_vertical()
{ {
return $this->_flip('vertical'); return $this->_flip('vertical');
} }
/** /**
@@ -608,7 +616,7 @@ class Zebra_Image
* $img->resize(150, 150, ZEBRA_IMAGE_CROP_CENTER); * $img->resize(150, 150, ZEBRA_IMAGE_CROP_CENTER);
* </code> * </code>
* *
* @param int $width The width to resize the image to. * @param integer $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
@@ -630,7 +638,8 @@ 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
@@ -652,6 +661,7 @@ 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.
* *
@@ -688,6 +698,7 @@ 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.
* *
@@ -697,12 +708,12 @@ class Zebra_Image
* *
* Default is #FFFFFF. * Default is #FFFFFF.
* *
* @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 what went * If FALSE is returned, check the {@link error} property to see what went
* wrong * wrong
*/ */
public function resize($width = 0, $height = 0, $method = ZEBRA_IMAGE_CROP_CENTER, $background_color = '#FFFFFF') 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
@@ -711,9 +722,7 @@ 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) { if ($width == 0 || $height == 0) $auto_preserve_aspect_ratio = true;
$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)) {
@@ -766,6 +775,7 @@ 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
@@ -796,6 +806,7 @@ 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
@@ -806,6 +817,7 @@ 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
@@ -1029,20 +1041,21 @@ 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 { } else return $this->_write_image($this->source_identifier);
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;
} }
/** /**
@@ -1067,9 +1080,10 @@ class Zebra_Image
* $img->rotate(45); * $img->rotate(45);
* </code> * </code>
* *
* @param float $angle Angle by which to rotate the image clockwise. * @param double $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.
* *
@@ -1079,12 +1093,12 @@ class Zebra_Image
* *
* Default is -1. * Default is -1.
* *
* @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 * If FALSE is returned, check the {@link error} property to see the error
* code. * code.
*/ */
public function rotate($angle, $background_color = -1) function rotate($angle, $background_color = -1)
{ {
// if image resource was successfully created // if image resource was successfully created
@@ -1105,6 +1119,7 @@ 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
@@ -1157,23 +1172,28 @@ 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
*/ */
public function _create_from_source() function _create_from_source()
{ {
// perform some error checking first // perform some error checking first
@@ -1235,14 +1255,13 @@ 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;
@@ -1275,18 +1294,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) { if ($this->preserve_time) $this->source_image_time = filemtime($this->source_path);
$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;
} }
/** /**
@@ -1295,48 +1314,50 @@ 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
*/ */
public function _hex2rgb($color, $default_on_error = '#FFFFFF') 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) { if (preg_match('/^#?([a-f]|[0-9]){3}(([a-f]|[0-9]){3})?$/i', $color) == 0) $color = $default_on_error;
$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++) { for ($i = 0; $i < 3; $i++) $tmp .= str_repeat($color[$i], 2);
$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 [ return array(
'r' => 0xFF & ($int >> 0x10), 'r' => 0xFF & ($int >> 0x10),
'g' => 0xFF & ($int >> 0x8), 'g' => 0xFF & ($int >> 0x8),
'b' => 0xFF & $int, 'b' => 0xFF & $int
);
];
} }
/** /**
@@ -1344,11 +1365,13 @@ class Zebra_Image
* *
* @since 2.1 * @since 2.1
* *
* @return bool Returns TRUE on success or FALSE on error. * @access private
*
* @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.
*/ */
public function _flip($orientation) function _flip($orientation)
{ {
// if image resource was successfully created // if image resource was successfully created
@@ -1421,19 +1444,23 @@ 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 int $width Width of the new image. * @param integer $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
@@ -1442,8 +1469,10 @@ 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
*/ */
public function _prepare_image($width, $height, $background_color = '#FFFFFF') function _prepare_image($width, $height, $background_color = '#FFFFFF')
{ {
// create a blank image // create a blank image
@@ -1485,9 +1514,7 @@ 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) { if ($background_color == -1) $background_color = '#FFFFFF';
$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);
@@ -1497,10 +1524,12 @@ 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;
} }
/** /**
@@ -1512,8 +1541,10 @@ class Zebra_Image
* versions!</i> * versions!</i>
* *
* @param $identifier identifier An image identifier * @param $identifier identifier An image identifier
*
* @access private
*/ */
public function _sharpen_image($image) 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
@@ -1521,11 +1552,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 = [ $matrix = array(
[-1.2, -1, -1.2], array(-1.2, -1, -1.2),
[-1, 20, -1], array(-1, 20, -1),
[-1.2, -1, -1.2], array(-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));
@@ -1535,10 +1566,12 @@ 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;
} }
/** /**
@@ -1546,11 +1579,13 @@ class Zebra_Image
* *
* @param $identifier identifier An image identifier * @param $identifier identifier An image identifier
* *
* @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.
*
* @access private
*/ */
public function _write_image($identifier) function _write_image($identifier)
{ {
// sharpen image if it's required // sharpen image if it's required
@@ -1579,6 +1614,7 @@ class Zebra_Image
$this->error = 3; $this->error = 3;
return false; return false;
} }
break; break;
@@ -1602,6 +1638,7 @@ class Zebra_Image
$this->error = 3; $this->error = 3;
return false; return false;
} }
break; break;
@@ -1627,6 +1664,7 @@ class Zebra_Image
$this->error = 3; $this->error = 3;
return false; return false;
} }
break; break;
@@ -1651,18 +1689,19 @@ 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 { } else $this->error = 8;
$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,8 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Courier'; $name = 'Courier';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
$cw[chr($i)] = 600; $cw[chr($i)] = 600;
} ?>

View File

@@ -1,9 +1,8 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Courier-Bold'; $name = 'Courier-Bold';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
$cw[chr($i)] = 600; $cw[chr($i)] = 600;
} ?>

View File

@@ -1,9 +1,8 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Courier-BoldOblique'; $name = 'Courier-BoldOblique';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
$cw[chr($i)] = 600; $cw[chr($i)] = 600;
} ?>

View File

@@ -1,9 +1,8 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Courier-Oblique'; $name = 'Courier-Oblique';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
$cw[chr($i)] = 600; $cw[chr($i)] = 600;
} ?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Helvetica'; $name = 'Helvetica';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278,
chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584,
','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667,
chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556,
chr(242)=> 556, chr(243)=>556, chr(244)=>556, chr(245)=>556, chr(246)=>556, chr(247)=>584, chr(248)=>611, chr(249)=>556, chr(250)=>556, chr(251)=>556, chr(252)=>556, chr(253)=>500, chr(254)=>556, chr(255)=>500, ]; chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Helvetica-Bold'; $name = 'Helvetica-Bold';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278,
chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584,
','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722,
chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611,
chr(242)=> 611, chr(243)=>611, chr(244)=>611, chr(245)=>611, chr(246)=>611, chr(247)=>584, chr(248)=>611, chr(249)=>611, chr(250)=>611, chr(251)=>611, chr(252)=>611, chr(253)=>556, chr(254)=>611, chr(255)=>556, ]; chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Helvetica-BoldOblique'; $name = 'Helvetica-BoldOblique';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278,
chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584,
','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722,
chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611,
chr(242)=> 611, chr(243)=>611, chr(244)=>611, chr(245)=>611, chr(246)=>611, chr(247)=>584, chr(248)=>611, chr(249)=>611, chr(250)=>611, chr(251)=>611, chr(252)=>611, chr(253)=>556, chr(254)=>611, chr(255)=>556, ]; chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Helvetica-Oblique'; $name = 'Helvetica-Oblique';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(0)=>278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278,
chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584,
','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667,
chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556,
chr(242)=> 556, chr(243)=>556, chr(244)=>556, chr(245)=>556, chr(246)=>556, chr(247)=>584, chr(248)=>611, chr(249)=>556, chr(250)=>556, chr(251)=>556, chr(252)=>556, chr(253)=>500, chr(254)=>556, chr(255)=>500, ]; chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500);
?>

View File

@@ -12,24 +12,24 @@ function ReadMap($enc)
//Read a map file //Read a map file
$file=dirname(__FILE__).'/'.strtolower($enc).'.map'; $file=dirname(__FILE__).'/'.strtolower($enc).'.map';
$a=file($file); $a=file($file);
if (empty($a)) { if(empty($a))
die('<b>Error:</b> encoding not found: '.$enc); die('<b>Error:</b> encoding not found: '.$enc);
} $cc2gn=array();
$cc2gn = []; foreach($a as $l)
foreach ($a as $l) { {
if ($l[0] == '!') { if($l[0]=='!')
{
$e=preg_split('/[ \\t]+/',rtrim($l)); $e=preg_split('/[ \\t]+/',rtrim($l));
$cc=hexdec(substr($e[0],1)); $cc=hexdec(substr($e[0],1));
$gn=$e[2]; $gn=$e[2];
$cc2gn[$cc]=$gn; $cc2gn[$cc]=$gn;
} }
} }
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
if (!isset($cc2gn[$i])) { {
if(!isset($cc2gn[$i]))
$cc2gn[$i]='.notdef'; $cc2gn[$i]='.notdef';
} }
}
return $cc2gn; return $cc2gn;
} }
@@ -37,100 +37,100 @@ function ReadAFM($file, &$map)
{ {
//Read a font metric file //Read a font metric file
$a=file($file); $a=file($file);
if (empty($a)) { if(empty($a))
die('File not found'); die('File not found');
} $widths=array();
$widths = []; $fm=array();
$fm = []; $fix=array('Edot'=>'Edotaccent','edot'=>'edotaccent','Idot'=>'Idotaccent','Zdot'=>'Zdotaccent','zdot'=>'zdotaccent',
$fix = ['Edot' => 'Edotaccent', 'edot'=>'edotaccent', 'Idot'=>'Idotaccent', 'Zdot'=>'Zdotaccent', 'zdot'=>'zdotaccent',
'Odblacute'=>'Ohungarumlaut','odblacute'=>'ohungarumlaut','Udblacute'=>'Uhungarumlaut','udblacute'=>'uhungarumlaut', 'Odblacute'=>'Ohungarumlaut','odblacute'=>'ohungarumlaut','Udblacute'=>'Uhungarumlaut','udblacute'=>'uhungarumlaut',
'Gcedilla'=>'Gcommaaccent','gcedilla'=>'gcommaaccent','Kcedilla'=>'Kcommaaccent','kcedilla'=>'kcommaaccent', 'Gcedilla'=>'Gcommaaccent','gcedilla'=>'gcommaaccent','Kcedilla'=>'Kcommaaccent','kcedilla'=>'kcommaaccent',
'Lcedilla'=>'Lcommaaccent','lcedilla'=>'lcommaaccent','Ncedilla'=>'Ncommaaccent','ncedilla'=>'ncommaaccent', 'Lcedilla'=>'Lcommaaccent','lcedilla'=>'lcommaaccent','Ncedilla'=>'Ncommaaccent','ncedilla'=>'ncommaaccent',
'Rcedilla'=>'Rcommaaccent','rcedilla'=>'rcommaaccent','Scedilla'=>'Scommaaccent','scedilla'=>'scommaaccent', 'Rcedilla'=>'Rcommaaccent','rcedilla'=>'rcommaaccent','Scedilla'=>'Scommaaccent','scedilla'=>'scommaaccent',
'Tcedilla'=>'Tcommaaccent','tcedilla'=>'tcommaaccent','Dslash'=>'Dcroat','dslash'=>'dcroat','Dmacron'=>'Dcroat','dmacron'=>'dcroat', 'Tcedilla'=>'Tcommaaccent','tcedilla'=>'tcommaaccent','Dslash'=>'Dcroat','dslash'=>'dcroat','Dmacron'=>'Dcroat','dmacron'=>'dcroat',
'combininggraveaccent'=>'gravecomb','combininghookabove'=>'hookabovecomb','combiningtildeaccent'=>'tildecomb', 'combininggraveaccent'=>'gravecomb','combininghookabove'=>'hookabovecomb','combiningtildeaccent'=>'tildecomb',
'combiningacuteaccent'=> 'acutecomb', 'combiningdotbelow'=>'dotbelowcomb', 'dongsign'=>'dong', ]; 'combiningacuteaccent'=>'acutecomb','combiningdotbelow'=>'dotbelowcomb','dongsign'=>'dong');
foreach ($a as $l) { foreach($a as $l)
{
$e=explode(' ',rtrim($l)); $e=explode(' ',rtrim($l));
if (count($e) < 2) { if(count($e)<2)
continue; continue;
}
$code=$e[0]; $code=$e[0];
$param=$e[1]; $param=$e[1];
if ($code == 'C') { if($code=='C')
{
//Character metrics //Character metrics
$cc=(int)$e[1]; $cc=(int)$e[1];
$w=$e[4]; $w=$e[4];
$gn=$e[7]; $gn=$e[7];
if (substr($gn, -4) == '20AC') { if(substr($gn,-4)=='20AC')
$gn='Euro'; $gn='Euro';
} if(isset($fix[$gn]))
if (isset($fix[$gn])) { {
//Fix incorrect glyph name //Fix incorrect glyph name
foreach ($map as $c=>$n) { foreach($map as $c=>$n)
if ($n == $fix[$gn]) { {
if($n==$fix[$gn])
$map[$c]=$gn; $map[$c]=$gn;
} }
} }
} if(empty($map))
if (empty($map)) { {
//Symbolic font: use built-in encoding //Symbolic font: use built-in encoding
$widths[$cc]=$w; $widths[$cc]=$w;
} else { }
else
{
$widths[$gn]=$w; $widths[$gn]=$w;
if ($gn == 'X') { if($gn=='X')
$fm['CapXHeight']=$e[13]; $fm['CapXHeight']=$e[13];
} }
} if($gn=='.notdef')
if ($gn == '.notdef') {
$fm['MissingWidth']=$w; $fm['MissingWidth']=$w;
} }
} elseif ($code == 'FontName') { elseif($code=='FontName')
$fm['FontName']=$param; $fm['FontName']=$param;
} elseif ($code == 'Weight') { elseif($code=='Weight')
$fm['Weight']=$param; $fm['Weight']=$param;
} elseif ($code == 'ItalicAngle') { elseif($code=='ItalicAngle')
$fm['ItalicAngle'] = (float) $param; $fm['ItalicAngle']=(double)$param;
} elseif ($code == 'Ascender') { elseif($code=='Ascender')
$fm['Ascender']=(int)$param; $fm['Ascender']=(int)$param;
} elseif ($code == 'Descender') { elseif($code=='Descender')
$fm['Descender']=(int)$param; $fm['Descender']=(int)$param;
} elseif ($code == 'UnderlineThickness') { elseif($code=='UnderlineThickness')
$fm['UnderlineThickness']=(int)$param; $fm['UnderlineThickness']=(int)$param;
} elseif ($code == 'UnderlinePosition') { elseif($code=='UnderlinePosition')
$fm['UnderlinePosition']=(int)$param; $fm['UnderlinePosition']=(int)$param;
} elseif ($code == 'IsFixedPitch') { elseif($code=='IsFixedPitch')
$fm['IsFixedPitch']=($param=='true'); $fm['IsFixedPitch']=($param=='true');
} elseif ($code == 'FontBBox') { elseif($code=='FontBBox')
$fm['FontBBox'] = [$e[1], $e[2], $e[3], $e[4]]; $fm['FontBBox']=array($e[1],$e[2],$e[3],$e[4]);
} elseif ($code == 'CapHeight') { elseif($code=='CapHeight')
$fm['CapHeight']=(int)$param; $fm['CapHeight']=(int)$param;
} elseif ($code == 'StdVW') { elseif($code=='StdVW')
$fm['StdVW']=(int)$param; $fm['StdVW']=(int)$param;
} }
} if(!isset($fm['FontName']))
if (!isset($fm['FontName'])) {
die('FontName not found'); die('FontName not found');
} if(!empty($map))
if (!empty($map)) { {
if (!isset($widths['.notdef'])) { if(!isset($widths['.notdef']))
$widths['.notdef']=600; $widths['.notdef']=600;
} if(!isset($widths['Delta']) && isset($widths['increment']))
if (!isset($widths['Delta']) && isset($widths['increment'])) {
$widths['Delta']=$widths['increment']; $widths['Delta']=$widths['increment'];
}
//Order widths according to map //Order widths according to map
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
if (!isset($widths[$map[$i]])) { {
if(!isset($widths[$map[$i]]))
{
echo '<b>Warning:</b> character '.$map[$i].' is missing<br>'; echo '<b>Warning:</b> character '.$map[$i].' is missing<br>';
$widths[$i]=$widths['.notdef']; $widths[$i]=$widths['.notdef'];
} else { }
else
$widths[$i]=$widths[$map[$i]]; $widths[$i]=$widths[$map[$i]];
} }
} }
}
$fm['Widths']=$widths; $fm['Widths']=$widths;
return $fm; return $fm;
} }
@@ -143,54 +143,45 @@ function MakeFontDescriptor($fm, $symbolic)
$desc=(isset($fm['Descender']) ? $fm['Descender'] : -200); $desc=(isset($fm['Descender']) ? $fm['Descender'] : -200);
$fd.=",'Descent'=>".$desc; $fd.=",'Descent'=>".$desc;
//CapHeight //CapHeight
if (isset($fm['CapHeight'])) { if(isset($fm['CapHeight']))
$ch=$fm['CapHeight']; $ch=$fm['CapHeight'];
} elseif (isset($fm['CapXHeight'])) { elseif(isset($fm['CapXHeight']))
$ch=$fm['CapXHeight']; $ch=$fm['CapXHeight'];
} else { else
$ch=$asc; $ch=$asc;
}
$fd.=",'CapHeight'=>".$ch; $fd.=",'CapHeight'=>".$ch;
//Flags //Flags
$flags=0; $flags=0;
if (isset($fm['IsFixedPitch']) && $fm['IsFixedPitch']) { if(isset($fm['IsFixedPitch']) && $fm['IsFixedPitch'])
$flags+=1<<0; $flags+=1<<0;
} if($symbolic)
if ($symbolic) {
$flags+=1<<2; $flags+=1<<2;
} if(!$symbolic)
if (!$symbolic) {
$flags+=1<<5; $flags+=1<<5;
} if(isset($fm['ItalicAngle']) && $fm['ItalicAngle']!=0)
if (isset($fm['ItalicAngle']) && $fm['ItalicAngle'] != 0) {
$flags+=1<<6; $flags+=1<<6;
}
$fd.=",'Flags'=>".$flags; $fd.=",'Flags'=>".$flags;
//FontBBox //FontBBox
if (isset($fm['FontBBox'])) { if(isset($fm['FontBBox']))
$fbb=$fm['FontBBox']; $fbb=$fm['FontBBox'];
} else { else
$fbb = [0, $desc - 100, 1000, $asc + 100]; $fbb=array(0,$desc-100,1000,$asc+100);
}
$fd.=",'FontBBox'=>'[".$fbb[0].' '.$fbb[1].' '.$fbb[2].' '.$fbb[3]."]'"; $fd.=",'FontBBox'=>'[".$fbb[0].' '.$fbb[1].' '.$fbb[2].' '.$fbb[3]."]'";
//ItalicAngle //ItalicAngle
$ia=(isset($fm['ItalicAngle']) ? $fm['ItalicAngle'] : 0); $ia=(isset($fm['ItalicAngle']) ? $fm['ItalicAngle'] : 0);
$fd.=",'ItalicAngle'=>".$ia; $fd.=",'ItalicAngle'=>".$ia;
//StemV //StemV
if (isset($fm['StdVW'])) { if(isset($fm['StdVW']))
$stemv=$fm['StdVW']; $stemv=$fm['StdVW'];
} elseif (isset($fm['Weight']) && preg_match('/bold|black/i', $fm['Weight'])) { elseif(isset($fm['Weight']) && preg_match('/bold|black/i',$fm['Weight']))
$stemv=120; $stemv=120;
} else { else
$stemv=70; $stemv=70;
}
$fd.=",'StemV'=>".$stemv; $fd.=",'StemV'=>".$stemv;
//MissingWidth //MissingWidth
if (isset($fm['MissingWidth'])) { if(isset($fm['MissingWidth']))
$fd.=",'MissingWidth'=>".$fm['MissingWidth']; $fd.=",'MissingWidth'=>".$fm['MissingWidth'];
}
$fd.=')'; $fd.=')';
return $fd; return $fd;
} }
@@ -199,26 +190,23 @@ function MakeWidthArray($fm)
//Make character width array //Make character width array
$s="array(\n\t"; $s="array(\n\t";
$cw=$fm['Widths']; $cw=$fm['Widths'];
for ($i = 0; $i <= 255; $i++) { for($i=0;$i<=255;$i++)
if (chr($i) == "'") { {
if(chr($i)=="'")
$s.="'\\''"; $s.="'\\''";
} elseif (chr($i) == '\\') { elseif(chr($i)=="\\")
$s.="'\\\\'"; $s.="'\\\\'";
} elseif ($i >= 32 && $i <= 126) { elseif($i>=32 && $i<=126)
$s.="'".chr($i)."'"; $s.="'".chr($i)."'";
} else { else
$s.="chr($i)"; $s.="chr($i)";
}
$s.='=>'.$fm['Widths'][$i]; $s.='=>'.$fm['Widths'][$i];
if ($i < 255) { if($i<255)
$s.=','; $s.=',';
} if(($i+1)%22==0)
if (($i + 1) % 22 == 0) {
$s.="\n\t"; $s.="\n\t";
} }
}
$s.=')'; $s.=')';
return $s; return $s;
} }
@@ -228,25 +216,24 @@ function MakeFontEncoding($map)
$ref=ReadMap('cp1252'); $ref=ReadMap('cp1252');
$s=''; $s='';
$last=0; $last=0;
for ($i = 32; $i <= 255; $i++) { for($i=32;$i<=255;$i++)
if ($map[$i] != $ref[$i]) { {
if ($i != $last + 1) { if($map[$i]!=$ref[$i])
{
if($i!=$last+1)
$s.=$i.' '; $s.=$i.' ';
}
$last=$i; $last=$i;
$s.='/'.$map[$i].' '; $s.='/'.$map[$i].' ';
} }
} }
return rtrim($s); return rtrim($s);
} }
function SaveToFile($file, $s, $mode) function SaveToFile($file, $s, $mode)
{ {
$f=fopen($file,'w'.$mode); $f=fopen($file,'w'.$mode);
if (!$f) { if(!$f)
die('Can\'t write to file '.$file); die('Can\'t write to file '.$file);
}
fwrite($f,$s,strlen($s)); fwrite($f,$s,strlen($s));
fclose($f); fclose($f);
} }
@@ -254,14 +241,12 @@ function SaveToFile($file, $s, $mode)
function ReadShort($f) function ReadShort($f)
{ {
$a=unpack('n1n',fread($f,2)); $a=unpack('n1n',fread($f,2));
return $a['n']; return $a['n'];
} }
function ReadLong($f) function ReadLong($f)
{ {
$a=unpack('N1N',fread($f,4)); $a=unpack('N1N',fread($f,4));
return $a['N']; return $a['N'];
} }
@@ -269,25 +254,26 @@ function CheckTTF($file)
{ {
//Check if font license allows embedding //Check if font license allows embedding
$f=fopen($file,'rb'); $f=fopen($file,'rb');
if (!$f) { if(!$f)
die('<b>Error:</b> Can\'t open '.$file); die('<b>Error:</b> Can\'t open '.$file);
}
//Extract number of tables //Extract number of tables
fseek($f,4,SEEK_CUR); fseek($f,4,SEEK_CUR);
$nb=ReadShort($f); $nb=ReadShort($f);
fseek($f,6,SEEK_CUR); fseek($f,6,SEEK_CUR);
//Seek OS/2 table //Seek OS/2 table
$found=false; $found=false;
for ($i = 0; $i < $nb; $i++) { for($i=0;$i<$nb;$i++)
if (fread($f, 4) == 'OS/2') { {
if(fread($f,4)=='OS/2')
{
$found=true; $found=true;
break; break;
} }
fseek($f,12,SEEK_CUR); fseek($f,12,SEEK_CUR);
} }
if (!$found) { if(!$found)
{
fclose($f); fclose($f);
return; return;
} }
fseek($f,4,SEEK_CUR); fseek($f,4,SEEK_CUR);
@@ -300,10 +286,9 @@ function CheckTTF($file)
$pp=($fsType & 0x04)!=0; $pp=($fsType & 0x04)!=0;
$e=($fsType & 0x08)!=0; $e=($fsType & 0x08)!=0;
fclose($f); fclose($f);
if ($rl && !$pp && !$e) { if($rl && !$pp && !$e)
echo '<b>Warning:</b> font license does not allow embedding'; echo '<b>Warning:</b> font license does not allow embedding';
} }
}
/******************************************************************************* /*******************************************************************************
* fontfile: path to TTF file (or empty string if not to be embedded) * * fontfile: path to TTF file (or empty string if not to be embedded) *
@@ -312,57 +297,53 @@ function CheckTTF($file)
* patch: optional patch for encoding * * patch: optional patch for encoding *
* type: font type if fontfile is empty * * type: font type if fontfile is empty *
*******************************************************************************/ *******************************************************************************/
function MakeFont($fontfile, $afmfile, $enc = 'cp1252', $patch = [], $type = 'TrueType') function MakeFont($fontfile, $afmfile, $enc='cp1252', $patch=array(), $type='TrueType')
{ {
//Generate a font definition file //Generate a font definition file
if (get_magic_quotes_runtime()) { if(get_magic_quotes_runtime())
@set_magic_quotes_runtime(0); @set_magic_quotes_runtime(0);
}
ini_set('auto_detect_line_endings','1'); ini_set('auto_detect_line_endings','1');
if ($enc) { if($enc)
{
$map=ReadMap($enc); $map=ReadMap($enc);
foreach ($patch as $cc=>$gn) { foreach($patch as $cc=>$gn)
$map[$cc]=$gn; $map[$cc]=$gn;
} }
} else { else
$map = []; $map=array();
} if(!file_exists($afmfile))
if (!file_exists($afmfile)) {
die('<b>Error:</b> AFM file not found: '.$afmfile); die('<b>Error:</b> AFM file not found: '.$afmfile);
}
$fm=ReadAFM($afmfile,$map); $fm=ReadAFM($afmfile,$map);
if ($enc) { if($enc)
$diff=MakeFontEncoding($map); $diff=MakeFontEncoding($map);
} else { else
$diff=''; $diff='';
}
$fd=MakeFontDescriptor($fm,empty($map)); $fd=MakeFontDescriptor($fm,empty($map));
//Find font type //Find font type
if ($fontfile) { if($fontfile)
{
$ext=strtolower(substr($fontfile,-3)); $ext=strtolower(substr($fontfile,-3));
if ($ext == 'ttf') { if($ext=='ttf')
$type='TrueType'; $type='TrueType';
} elseif ($ext == 'pfb') { elseif($ext=='pfb')
$type='Type1'; $type='Type1';
} else { else
die('<b>Error:</b> unrecognized font file extension: '.$ext); die('<b>Error:</b> unrecognized font file extension: '.$ext);
} }
} else { else
if ($type != 'TrueType' && $type != 'Type1') { {
if($type!='TrueType' && $type!='Type1')
die('<b>Error:</b> incorrect font type: '.$type); die('<b>Error:</b> incorrect font type: '.$type);
} }
}
//Start generation //Start generation
$s='<?php'."\n"; $s='<?php'."\n";
$s.='$type=\''.$type."';\n"; $s.='$type=\''.$type."';\n";
$s.='$name=\''.$fm['FontName']."';\n"; $s.='$name=\''.$fm['FontName']."';\n";
$s.='$desc='.$fd.";\n"; $s.='$desc='.$fd.";\n";
if (!isset($fm['UnderlinePosition'])) { if(!isset($fm['UnderlinePosition']))
$fm['UnderlinePosition']=-100; $fm['UnderlinePosition']=-100;
} if(!isset($fm['UnderlineThickness']))
if (!isset($fm['UnderlineThickness'])) {
$fm['UnderlineThickness']=50; $fm['UnderlineThickness']=50;
}
$s.='$up='.$fm['UnderlinePosition'].";\n"; $s.='$up='.$fm['UnderlinePosition'].";\n";
$s.='$ut='.$fm['UnderlineThickness'].";\n"; $s.='$ut='.$fm['UnderlineThickness'].";\n";
$w=MakeWidthArray($fm); $w=MakeWidthArray($fm);
@@ -370,59 +351,64 @@ function MakeFont($fontfile, $afmfile, $enc = 'cp1252', $patch = [], $type = 'Tr
$s.='$enc=\''.$enc."';\n"; $s.='$enc=\''.$enc."';\n";
$s.='$diff=\''.$diff."';\n"; $s.='$diff=\''.$diff."';\n";
$basename=substr(basename($afmfile),0,-4); $basename=substr(basename($afmfile),0,-4);
if ($fontfile) { if($fontfile)
{
//Embedded font //Embedded font
if (!file_exists($fontfile)) { if(!file_exists($fontfile))
die('<b>Error:</b> font file not found: '.$fontfile); die('<b>Error:</b> font file not found: '.$fontfile);
} if($type=='TrueType')
if ($type == 'TrueType') {
CheckTTF($fontfile); CheckTTF($fontfile);
}
$f=fopen($fontfile,'rb'); $f=fopen($fontfile,'rb');
if (!$f) { if(!$f)
die('<b>Error:</b> Can\'t open '.$fontfile); die('<b>Error:</b> Can\'t open '.$fontfile);
}
$file=fread($f,filesize($fontfile)); $file=fread($f,filesize($fontfile));
fclose($f); fclose($f);
if ($type == 'Type1') { if($type=='Type1')
{
//Find first two sections and discard third one //Find first two sections and discard third one
$header=(ord($file[0])==128); $header=(ord($file[0])==128);
if ($header) { if($header)
{
//Strip first binary header //Strip first binary header
$file=substr($file,6); $file=substr($file,6);
} }
$pos=strpos($file,'eexec'); $pos=strpos($file,'eexec');
if (!$pos) { if(!$pos)
die('<b>Error:</b> font file does not seem to be valid Type1'); die('<b>Error:</b> font file does not seem to be valid Type1');
}
$size1=$pos+6; $size1=$pos+6;
if ($header && ord($file[$size1]) == 128) { if($header && ord($file[$size1])==128)
{
//Strip second binary header //Strip second binary header
$file=substr($file,0,$size1).substr($file,$size1+6); $file=substr($file,0,$size1).substr($file,$size1+6);
} }
$pos=strpos($file,'00000000'); $pos=strpos($file,'00000000');
if (!$pos) { if(!$pos)
die('<b>Error:</b> font file does not seem to be valid Type1'); die('<b>Error:</b> font file does not seem to be valid Type1');
}
$size2=$pos-$size1; $size2=$pos-$size1;
$file=substr($file,0,$size1+$size2); $file=substr($file,0,$size1+$size2);
} }
if (function_exists('gzcompress')) { if(function_exists('gzcompress'))
{
$cmp=$basename.'.z'; $cmp=$basename.'.z';
SaveToFile($cmp,gzcompress($file),'b'); SaveToFile($cmp,gzcompress($file),'b');
$s.='$file=\''.$cmp."';\n"; $s.='$file=\''.$cmp."';\n";
echo 'Font file compressed ('.$cmp.')<br>'; echo 'Font file compressed ('.$cmp.')<br>';
} else { }
else
{
$s.='$file=\''.basename($fontfile)."';\n"; $s.='$file=\''.basename($fontfile)."';\n";
echo '<b>Notice:</b> font file could not be compressed (zlib extension not available)<br>'; echo '<b>Notice:</b> font file could not be compressed (zlib extension not available)<br>';
} }
if ($type == 'Type1') { if($type=='Type1')
{
$s.='$size1='.$size1.";\n"; $s.='$size1='.$size1.";\n";
$s.='$size2='.$size2.";\n"; $s.='$size2='.$size2.";\n";
} else { }
else
$s.='$originalsize='.filesize($fontfile).";\n"; $s.='$originalsize='.filesize($fontfile).";\n";
} }
} else { else
{
//Not embedded font //Not embedded font
$s.='$file='."'';\n"; $s.='$file='."'';\n";
} }
@@ -430,3 +416,4 @@ function MakeFont($fontfile, $afmfile, $enc = 'cp1252', $patch = [], $type = 'Tr
SaveToFile($basename.'.php',$s,'t'); SaveToFile($basename.'.php',$s,'t');
echo 'Font definition file generated ('.$basename.'.php'.')<br>'; echo 'Font definition file generated ('.$basename.'.php'.')<br>';
} }
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Symbol'; $name = 'Symbol';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250,
chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>713,'#'=>500,'$'=>549,'%'=>833,'&'=>778,'\''=>439,'('=>333,')'=>333,'*'=>500,'+'=>549, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>713,'#'=>500,'$'=>549,'%'=>833,'&'=>778,'\''=>439,'('=>333,')'=>333,'*'=>500,'+'=>549,
','=>250,'-'=>549,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>549,'='=>549,'>'=>549,'?'=>444,'@'=>549,'A'=>722, ','=>250,'-'=>549,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>549,'='=>549,'>'=>549,'?'=>444,'@'=>549,'A'=>722,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>549,chr(178)=>411,chr(179)=>549,chr(180)=>549,chr(181)=>713,chr(182)=>494,chr(183)=>460,chr(184)=>549,chr(185)=>549,chr(186)=>549,chr(187)=>549,chr(188)=>1000,chr(189)=>603,chr(190)=>1000,chr(191)=>658,chr(192)=>823,chr(193)=>686,chr(194)=>795,chr(195)=>987,chr(196)=>768,chr(197)=>768, chr(176)=>400,chr(177)=>549,chr(178)=>411,chr(179)=>549,chr(180)=>549,chr(181)=>713,chr(182)=>494,chr(183)=>460,chr(184)=>549,chr(185)=>549,chr(186)=>549,chr(187)=>549,chr(188)=>1000,chr(189)=>603,chr(190)=>1000,chr(191)=>658,chr(192)=>823,chr(193)=>686,chr(194)=>795,chr(195)=>987,chr(196)=>768,chr(197)=>768,
chr(198)=>823,chr(199)=>768,chr(200)=>768,chr(201)=>713,chr(202)=>713,chr(203)=>713,chr(204)=>713,chr(205)=>713,chr(206)=>713,chr(207)=>713,chr(208)=>768,chr(209)=>713,chr(210)=>790,chr(211)=>790,chr(212)=>890,chr(213)=>823,chr(214)=>549,chr(215)=>250,chr(216)=>713,chr(217)=>603,chr(218)=>603,chr(219)=>1042, chr(198)=>823,chr(199)=>768,chr(200)=>768,chr(201)=>713,chr(202)=>713,chr(203)=>713,chr(204)=>713,chr(205)=>713,chr(206)=>713,chr(207)=>713,chr(208)=>768,chr(209)=>713,chr(210)=>790,chr(211)=>790,chr(212)=>890,chr(213)=>823,chr(214)=>549,chr(215)=>250,chr(216)=>713,chr(217)=>603,chr(218)=>603,chr(219)=>1042,
chr(220)=>987,chr(221)=>603,chr(222)=>987,chr(223)=>603,chr(224)=>494,chr(225)=>329,chr(226)=>790,chr(227)=>790,chr(228)=>786,chr(229)=>713,chr(230)=>384,chr(231)=>384,chr(232)=>384,chr(233)=>384,chr(234)=>384,chr(235)=>384,chr(236)=>494,chr(237)=>494,chr(238)=>494,chr(239)=>494,chr(240)=>0,chr(241)=>329, chr(220)=>987,chr(221)=>603,chr(222)=>987,chr(223)=>603,chr(224)=>494,chr(225)=>329,chr(226)=>790,chr(227)=>790,chr(228)=>786,chr(229)=>713,chr(230)=>384,chr(231)=>384,chr(232)=>384,chr(233)=>384,chr(234)=>384,chr(235)=>384,chr(236)=>494,chr(237)=>494,chr(238)=>494,chr(239)=>494,chr(240)=>0,chr(241)=>329,
chr(242)=> 274, chr(243)=>686, chr(244)=>686, chr(245)=>686, chr(246)=>384, chr(247)=>384, chr(248)=>384, chr(249)=>384, chr(250)=>384, chr(251)=>384, chr(252)=>494, chr(253)=>494, chr(254)=>494, chr(255)=>0, ]; chr(242)=>274,chr(243)=>686,chr(244)=>686,chr(245)=>686,chr(246)=>384,chr(247)=>384,chr(248)=>384,chr(249)=>384,chr(250)=>384,chr(251)=>384,chr(252)=>494,chr(253)=>494,chr(254)=>494,chr(255)=>0);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Times-Roman'; $name = 'Times-Roman';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250,
chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>408,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>180,'('=>333,')'=>333,'*'=>500,'+'=>564, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>408,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>180,'('=>333,')'=>333,'*'=>500,'+'=>564,
','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>564,'='=>564,'>'=>564,'?'=>444,'@'=>921,'A'=>722, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>564,'='=>564,'>'=>564,'?'=>444,'@'=>921,'A'=>722,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>564,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>453,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>444,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(176)=>400,chr(177)=>564,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>453,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>444,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722,
chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>564,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>564,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>722,chr(222)=>556,chr(223)=>500,chr(224)=>444,chr(225)=>444,chr(226)=>444,chr(227)=>444,chr(228)=>444,chr(229)=>444,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, chr(220)=>722,chr(221)=>722,chr(222)=>556,chr(223)=>500,chr(224)=>444,chr(225)=>444,chr(226)=>444,chr(227)=>444,chr(228)=>444,chr(229)=>444,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500,
chr(242)=> 500, chr(243)=>500, chr(244)=>500, chr(245)=>500, chr(246)=>500, chr(247)=>564, chr(248)=>500, chr(249)=>500, chr(250)=>500, chr(251)=>500, chr(252)=>500, chr(253)=>500, chr(254)=>500, chr(255)=>500, ]; chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>564,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>500,chr(254)=>500,chr(255)=>500);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Times-Bold'; $name = 'Times-Bold';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250,
chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>555,'#'=>500,'$'=>500,'%'=>1000,'&'=>833,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>555,'#'=>500,'$'=>500,'%'=>1000,'&'=>833,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570,
','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>930,'A'=>722, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>930,'A'=>722,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>556,chr(182)=>540,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>330,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>556,chr(182)=>540,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>330,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722,
chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>570,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>570,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>722,chr(222)=>611,chr(223)=>556,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, chr(220)=>722,chr(221)=>722,chr(222)=>611,chr(223)=>556,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556,
chr(242)=> 500, chr(243)=>500, chr(244)=>500, chr(245)=>500, chr(246)=>500, chr(247)=>570, chr(248)=>500, chr(249)=>556, chr(250)=>556, chr(251)=>556, chr(252)=>556, chr(253)=>500, chr(254)=>556, chr(255)=>500, ]; chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Times-BoldItalic'; $name = 'Times-BoldItalic';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250,
chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>389,'"'=>555,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>389,'"'=>555,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570,
','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>832,'A'=>667, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>832,'A'=>667,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>576,chr(182)=>500,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>300,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>576,chr(182)=>500,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>300,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667,
chr(198)=>944,chr(199)=>667,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>570,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>944,chr(199)=>667,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>570,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>611,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, chr(220)=>722,chr(221)=>611,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556,
chr(242)=> 500, chr(243)=>500, chr(244)=>500, chr(245)=>500, chr(246)=>500, chr(247)=>570, chr(248)=>500, chr(249)=>556, chr(250)=>556, chr(251)=>556, chr(252)=>556, chr(253)=>444, chr(254)=>500, chr(255)=>444, ]; chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>444,chr(254)=>500,chr(255)=>444);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'Times-Italic'; $name = 'Times-Italic';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(0)=>250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250,
chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>420,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>214,'('=>333,')'=>333,'*'=>500,'+'=>675, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>420,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>214,'('=>333,')'=>333,'*'=>500,'+'=>675,
','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>675,'='=>675,'>'=>675,'?'=>500,'@'=>920,'A'=>611, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>675,'='=>675,'>'=>675,'?'=>500,'@'=>920,'A'=>611,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>400,chr(177)=>675,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>523,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>611,chr(193)=>611,chr(194)=>611,chr(195)=>611,chr(196)=>611,chr(197)=>611, chr(176)=>400,chr(177)=>675,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>523,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>611,chr(193)=>611,chr(194)=>611,chr(195)=>611,chr(196)=>611,chr(197)=>611,
chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>667,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>675,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>667,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>675,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722,
chr(220)=>722,chr(221)=>556,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, chr(220)=>722,chr(221)=>556,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500,
chr(242)=> 500, chr(243)=>500, chr(244)=>500, chr(245)=>500, chr(246)=>500, chr(247)=>675, chr(248)=>500, chr(249)=>500, chr(250)=>500, chr(251)=>500, chr(252)=>500, chr(253)=>444, chr(254)=>500, chr(255)=>444, ]; chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>675,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>444,chr(254)=>500,chr(255)=>444);
?>

View File

@@ -1,10 +1,9 @@
<?php <?php
$type = 'Core'; $type = 'Core';
$name = 'ZapfDingbats'; $name = 'ZapfDingbats';
$up = -100; $up = -100;
$ut = 50; $ut = 50;
$cw = [ $cw = array(
chr(0)=>0,chr(1)=>0,chr(2)=>0,chr(3)=>0,chr(4)=>0,chr(5)=>0,chr(6)=>0,chr(7)=>0,chr(8)=>0,chr(9)=>0,chr(10)=>0,chr(11)=>0,chr(12)=>0,chr(13)=>0,chr(14)=>0,chr(15)=>0,chr(16)=>0,chr(17)=>0,chr(18)=>0,chr(19)=>0,chr(20)=>0,chr(21)=>0, chr(0)=>0,chr(1)=>0,chr(2)=>0,chr(3)=>0,chr(4)=>0,chr(5)=>0,chr(6)=>0,chr(7)=>0,chr(8)=>0,chr(9)=>0,chr(10)=>0,chr(11)=>0,chr(12)=>0,chr(13)=>0,chr(14)=>0,chr(15)=>0,chr(16)=>0,chr(17)=>0,chr(18)=>0,chr(19)=>0,chr(20)=>0,chr(21)=>0,
chr(22)=>0,chr(23)=>0,chr(24)=>0,chr(25)=>0,chr(26)=>0,chr(27)=>0,chr(28)=>0,chr(29)=>0,chr(30)=>0,chr(31)=>0,' '=>278,'!'=>974,'"'=>961,'#'=>974,'$'=>980,'%'=>719,'&'=>789,'\''=>790,'('=>791,')'=>690,'*'=>960,'+'=>939, chr(22)=>0,chr(23)=>0,chr(24)=>0,chr(25)=>0,chr(26)=>0,chr(27)=>0,chr(28)=>0,chr(29)=>0,chr(30)=>0,chr(31)=>0,' '=>278,'!'=>974,'"'=>961,'#'=>974,'$'=>980,'%'=>719,'&'=>789,'\''=>790,'('=>791,')'=>690,'*'=>960,'+'=>939,
','=>549,'-'=>855,'.'=>911,'/'=>933,'0'=>911,'1'=>945,'2'=>974,'3'=>755,'4'=>846,'5'=>762,'6'=>761,'7'=>571,'8'=>677,'9'=>763,':'=>760,';'=>759,'<'=>754,'='=>494,'>'=>552,'?'=>537,'@'=>577,'A'=>692, ','=>549,'-'=>855,'.'=>911,'/'=>933,'0'=>911,'1'=>945,'2'=>974,'3'=>755,'4'=>846,'5'=>762,'6'=>761,'7'=>571,'8'=>677,'9'=>763,':'=>760,';'=>759,'<'=>754,'='=>494,'>'=>552,'?'=>537,'@'=>577,'A'=>692,
@@ -16,4 +15,5 @@ $cw = [
chr(176)=>788,chr(177)=>788,chr(178)=>788,chr(179)=>788,chr(180)=>788,chr(181)=>788,chr(182)=>788,chr(183)=>788,chr(184)=>788,chr(185)=>788,chr(186)=>788,chr(187)=>788,chr(188)=>788,chr(189)=>788,chr(190)=>788,chr(191)=>788,chr(192)=>788,chr(193)=>788,chr(194)=>788,chr(195)=>788,chr(196)=>788,chr(197)=>788, chr(176)=>788,chr(177)=>788,chr(178)=>788,chr(179)=>788,chr(180)=>788,chr(181)=>788,chr(182)=>788,chr(183)=>788,chr(184)=>788,chr(185)=>788,chr(186)=>788,chr(187)=>788,chr(188)=>788,chr(189)=>788,chr(190)=>788,chr(191)=>788,chr(192)=>788,chr(193)=>788,chr(194)=>788,chr(195)=>788,chr(196)=>788,chr(197)=>788,
chr(198)=>788,chr(199)=>788,chr(200)=>788,chr(201)=>788,chr(202)=>788,chr(203)=>788,chr(204)=>788,chr(205)=>788,chr(206)=>788,chr(207)=>788,chr(208)=>788,chr(209)=>788,chr(210)=>788,chr(211)=>788,chr(212)=>894,chr(213)=>838,chr(214)=>1016,chr(215)=>458,chr(216)=>748,chr(217)=>924,chr(218)=>748,chr(219)=>918, chr(198)=>788,chr(199)=>788,chr(200)=>788,chr(201)=>788,chr(202)=>788,chr(203)=>788,chr(204)=>788,chr(205)=>788,chr(206)=>788,chr(207)=>788,chr(208)=>788,chr(209)=>788,chr(210)=>788,chr(211)=>788,chr(212)=>894,chr(213)=>838,chr(214)=>1016,chr(215)=>458,chr(216)=>748,chr(217)=>924,chr(218)=>748,chr(219)=>918,
chr(220)=>927,chr(221)=>928,chr(222)=>928,chr(223)=>834,chr(224)=>873,chr(225)=>828,chr(226)=>924,chr(227)=>924,chr(228)=>917,chr(229)=>930,chr(230)=>931,chr(231)=>463,chr(232)=>883,chr(233)=>836,chr(234)=>836,chr(235)=>867,chr(236)=>867,chr(237)=>696,chr(238)=>696,chr(239)=>874,chr(240)=>0,chr(241)=>874, chr(220)=>927,chr(221)=>928,chr(222)=>928,chr(223)=>834,chr(224)=>873,chr(225)=>828,chr(226)=>924,chr(227)=>924,chr(228)=>917,chr(229)=>930,chr(230)=>931,chr(231)=>463,chr(232)=>883,chr(233)=>836,chr(234)=>836,chr(235)=>867,chr(236)=>867,chr(237)=>696,chr(238)=>696,chr(239)=>874,chr(240)=>0,chr(241)=>874,
chr(242)=> 760, chr(243)=>946, chr(244)=>771, chr(245)=>865, chr(246)=>771, chr(247)=>888, chr(248)=>967, chr(249)=>888, chr(250)=>831, chr(251)=>873, chr(252)=>927, chr(253)=>970, chr(254)=>918, chr(255)=>0, ]; chr(242)=>760,chr(243)=>946,chr(244)=>771,chr(245)=>865,chr(246)=>771,chr(247)=>888,chr(248)=>967,chr(249)=>888,chr(250)=>831,chr(251)=>873,chr(252)=>927,chr(253)=>970,chr(254)=>918,chr(255)=>0);
?>

View File

@@ -1,11 +1,9 @@
<?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.
@@ -21,15 +19,15 @@
* *
* 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.
@@ -17,37 +17,37 @@
* *
* 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;
} }
} }
@@ -58,35 +58,32 @@ function creaArticulo($bd1, $bd2, $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;
} }
/* /*
@@ -96,62 +93,62 @@ function generaSesion()
*/ */
$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 = []; $ubicaciones=array();
$articulos = []; $articulos=array();
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);
} }
} }
} }
@@ -159,3 +156,4 @@ echo "++Fin del proceso.<br>\n";
$bd2->commit(); $bd2->commit();
$bd1->close(); $bd1->close();
$bd2->close(); $bd2->close();
?>