.
*
*/
//Se incluyen los módulos necesarios
function __autoload($class_name) {
require_once $class_name . '.php';
}
require_once 'inc/configuracion.inc';
define('NUMPASOS', 3);
//Para el Paso 1
define('MINBYTES', 4096000); // post_max_size y max_upload van con esto
define('CADENAMINBYTES', '4M');
define('CONFIGURACION', 'inc/configuracion.inc');
define('CONFIGTMP', 'tmp/config.tmp');
define('TMP', './tmp');
define('INC', './inc');
$instalar = new Instalar();
if ($instalar->error) {
echo $instalar->panelError();
return;
}
echo $instalar->ejecuta();
class Instalar {
private $contenido;
private $plant;
public $error;
public $error_msj;
public function __construct()
{
//Selecciona la plantilla a utilizar
$this->plant='plant/';
$this->plant.=PLANTILLA;
$this->plant.='.html';
$this->error = false;
$this->eror_msj = '';
if (INSTALADO != 'no') {
$this->error = true;
$this->error_msj = 'El programa ya está instalado';
}
/*if ($this->existenDatos()) {
$this->error = true;
$this->error_msj = "El indicador de instalación tiene 'no' pero la base de datos " . BASEDATOS . " contiene la tabla Articulos.";
}*/
}
private function existenDatos()
{
//Comprueba si existe la tabla Articulos
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($sql->error())
return false;
$sql->ejecuta('select * from Articulos;');
if ($sql->error())
return false;
return true;
}
public function ejecuta()
{
$paso = isset($_GET['paso']) ? $_GET['paso'] : 0;
$paso = $paso > NUMPASOS ? '0' : $paso;
$i=0;
//Si quiere ir a un determinado paso se asegura que estén completos los anteriores
for ($i = 0; $i < $paso; $i++) {
$funcion = "validaPaso" . $i;
if (!$this->$funcion()) {
break;
}
}
$funcion = "paso" . $i;
$this->contenido = $this->$funcion();
$salida = new Distribucion($this->plant, $this);
return $salida->procesaPlantilla();
}
// Cuestiones relacionadas con el servidor
private function paso0()
{
$info = '
';
return $info;
}
private function retornaBoton($error, $paso, $javascript = true)
{
$anadido = $javascript ? 'onclick="location.href=' . "'" . $paso . "'". '"' : '';
if (!$error) {
return '';
} else {
return '';
}
}
private function botonVolver($enlace)
{
$boton = '';
return $boton;
}
private function retornaLabel($error, $mensaje, $tipo = "danger")
{
if ($error) {
$nombre1 = $tipo; $nombre2 = "remove";
} else {
$nombre1 = "success"; $nombre2 = "ok";
}
$mensaje = '';
$mensaje .='';
return $mensaje;
}
private function retornaBytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// El modificador 'G' está disponble desde PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
private function validaPaso0()
{
$validar = true;
$postMax = ini_get('post_max_size');
$uploadMax = ini_get('upload_max_filesize');
$mysql = extension_loaded('mysqli');
$escConfig = is_writable(CONFIGURACION);
$escInc = is_writable(INC);
$escTMP = is_writable(TMP);
$escIMG = is_writable(IMAGEDATA);
if ($this->retornaBytes($postMax) < MINBYTES)
$validar = false;
if ($this->retornaBytes($uploadMax) < MINBYTES)
$validar = false;
if (!$mysql)
$validar = false;
if (!$escConfig)
$validar = false;
if (!$escTMP)
$validar = false;
if (!$escIMG)
$validar = false;
if (!$escInc)
$validar = false;
return $validar;
}
private function actualizaConfiguracion($grabar, $campos, &$datos)
{
$conf = new Configuracion();
$fichero = $conf->obtieneFichero();
$datosFichero = explode("\n", $fichero);
if ($grabar) {
$fsalida = @fopen(CONFIGTMP, "wb");
}
foreach ($datosFichero as $linea) {
if (stripos($linea, "DEFINE") !== false) {
$conf->obtieneDatos($linea, $clave, $valor);
if (stripos($campos, $clave) !== false) {
if ($grabar) {
$linea = str_replace($valor, $datos[$clave], $linea);
$valor = $datos[$clave];
}
}
$datos[$clave] = $valor;
}
$registro = substr($linea, 0, 2) == "?>" ? $linea : $linea . "\n";
if ($grabar) {
fwrite($fsalida, $registro);
}
}
if ($grabar) {
fclose($fsalida);
unlink(CONFIGURACION);
rename(CONFIGTMP, CONFIGURACION);
}
}
// Cuestiones de la base de datos
private function paso1()
{
$grabar = isset($_POST['SERVIDOR']);
$campos = 'SERVIDOR,PUERTO,BASEDATOS,USUARIO,CLAVE';
//Lee y si hace falta actualiza los datos del formulario en el fichero de configuración
if ($grabar) {
foreach ($_POST as $clave => $valor) {
$datos[$clave] = $valor;
}
} else {
$datos = array();
}
$this->actualizaConfiguracion($grabar, $campos, $datos);
if ($grabar && $this->validaPaso1()) {
//Pasa al paso siguiente
return $this->paso2();
}
$info = '';
$panel = $this->panelMensaje($info, 'primary', 'PASO 2: Configuración de la Base de Datos.');
return $panel;
}
private function validaPaso1()
{
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, '');
if ($sql->error())
return false;
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
if ($sql->error()) {
return false;
}
$comando = 'create table test2 (id int(10));';
$sql->ejecuta($comando);
if ($sql->error()) {
return false;
}
$comando = 'drop table test2;';
$sql->ejecuta($comando);
if ($sql->error()) {
return false;
}
return true;
}
// Usuario administrador
private function paso2()
{
if (isset($_POST['usuario'])) {
//ha enviado el formulario.
//Crea la base de datos
$borra_database = "DROP DATABASE " . BASEDATOS . " ;";
$database = "CREATE DATABASE " . BASEDATOS . " DEFAULT CHARACTER SET utf8;";
$articulos = "CREATE TABLE `Articulos` (
`id` smallint(6) NOT NULL auto_increment COMMENT 'ordenable,link/Articulo',
`descripcion` varchar(60) NOT NULL COMMENT 'ordenable,ajax/text',
`marca` varchar(20) default NULL COMMENT 'ordenable,ajax/text',
`modelo` varchar(20) default NULL COMMENT 'ordenable,ajax/text',
`cantidad` int(11) default NULL COMMENT 'ordenable,ajax/number',
`imagen` varchar(45) default NULL COMMENT 'imagen',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=769 DEFAULT CHARSET=utf8;
";
$ubicaciones = "CREATE TABLE `Ubicaciones` (
`id` smallint(5) unsigned NOT NULL auto_increment COMMENT 'ordenable,link/Ubicacion',
`Descripcion` varchar(50) NOT NULL COMMENT 'ordenable,ajax/text',
`imagen` varchar(45) DEFAULT NULL COMMENT 'imagen',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=179 DEFAULT CHARSET=utf8;
";
$elementos = "CREATE TABLE `Elementos` (
`id` int(10) unsigned NOT NULL auto_increment COMMENT 'ordenable',
`id_Articulo` smallint(6) NOT NULL COMMENT 'foreign(Articulos;id),ordenable',
`id_Ubicacion` smallint(5) unsigned NOT NULL COMMENT 'foreign(Ubicaciones;id),ordenable',
`numserie` varchar(30) default NULL COMMENT 'ordenable,ajax/text',
`cantidad` int(10) unsigned default NULL COMMENT 'ordenable,ajax/number',
`fechaCompra` date NOT NULL COMMENT 'ordenable,ajax/combodate',
`imagen` varchar(45) default NULL COMMENT 'imagen',
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `id_Articulo` (`id_Articulo`),
KEY `id_Ubicacion` (`id_Ubicacion`),
CONSTRAINT `Elementos_ibfk_1` FOREIGN KEY (`id_Articulo`) REFERENCES `Articulos` (`id`) ON DELETE CASCADE,
CONSTRAINT `Elementos_ibfk_2` FOREIGN KEY (`id_Ubicacion`) REFERENCES `Ubicaciones` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1789 DEFAULT CHARSET=utf8;
";
$usuarios = "CREATE TABLE `Usuarios` (
`id` int(10) unsigned NOT NULL auto_increment COMMENT 'ordenable',
`nombre` varchar(16) NOT NULL default '' COMMENT 'ajax/text',
`clave` varchar(32) NOT NULL default '' COMMENT 'ajax/text',
`idSesion` varchar(20) NOT NULL default '' COMMENT 'ajax/text',
`alta` tinyint(1) NOT NULL default '0',
`modificacion` tinyint(1) NOT NULL default '0',
`borrado` tinyint(1) NOT NULL default '0',
`consulta` tinyint(1) NOT NULL default '1',
`informe` tinyint(1) NOT NULL default '1',
`usuarios` tinyint(1) NOT NULL default '0',
`config` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `nombre` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
";
$letras = "abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$sesion = substr(str_shuffle($letras), 0, 8);
$usuario = $_POST['usuario'];
$clave = $_POST['clave'];
$administrador = "insert into Usuarios values (null,'$usuario','$clave','$sesion','1','1','1','1','1','1','1');";
@mysqli_query($borra_database);
@mysqli_query($database);
$sql = new Sql(SERVIDOR, USUARIO, CLAVE, BASEDATOS);
$sql->ejecuta($ubicaciones);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
}
$sql->ejecuta($articulos);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
}
$sql->ejecuta($elementos);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
}
$sql->ejecuta($usuarios);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
}
$sql->ejecuta($administrador);
if ($sql->error()) {
return $this->panelMensaje($sql->mensajeError(), "danger", "ERROR");
}
$campos="INSTALADO";
$datos['INSTALADO'] = "sí";
$this->actualizaConfiguracion(true, $campos, $datos);
return $this->resumen();
}
$info = '
';
$panel = $this->panelMensaje($info, 'primary', 'PASO 3: Creación de la base de datos y el usuario administrador.');
return $panel;
}
private function validaPaso2()
{
//La validación de este paso se hace con la del formulario en javascript
return true;
}
public function panelMensaje($info, $tipo = "info", $cabecera = "¡Atención!") {
$mensaje = '
';
$mensaje .= '
' . $cabecera . '
';
$mensaje .= '
';
$mensaje .= $info;
$mensaje .= '
';
$mensaje .= '
';
return $mensaje;
}
public function contenido()
{
return $this->contenido;
}
public function menu()
{
return '';
}
public function opcion()
{
return 'INSTALACIÓN';
}
public function control()
{
return '';
}
public function aplicacion()
{
return PROGRAMA . ' v' . VERSION;
}
public function usuario()
{
return '';
}
public function fecha()
{
$idioma = 'es_ES';
$formato = "%d-%b-%y";
setlocale(LC_TIME, $idioma);
return strftime($formato);
}
public function cabecera()
{
return '
Inventario
';
}
public function panelError()
{
$mensaje = $this->cabecera();
$mensaje .= $this->panelMensaje($this->error_msj, "danger", "¡ERROR!");
$mensaje .= "";
return $mensaje;
}
private function resumen()
{
$info = '
';
$info .= '
Paso 1
';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de PHP");
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la aplicación");
$info .= '
Paso 2
';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Configuración de la base de datos");
$info .= '
Paso 3
';
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación de Base de datos");
$info .= $this->retornaElemento($this->retornaLabel(false, ""), "Creación del usuario administrador");
$info .= '