<?php
/*
* Alliances Manager (Gestionador de Alianzas) - Travian
* Copyright (C) 2008-12 Viva Mayer, Francisco Mesías <hide@address.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ModeloGrupo extends ModeloBase
{
private $id_grupo;
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function resumen()
{
$a_retornar = array();
// Usuarios sin grupo
$sql = "SELECT count(`nombre`) FROM `".$this->config->get('PREFIX')."usuario` WHERE `grupo` IS NULL and `estado`='Activo'";
$result = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$aux = mysql_fetch_row($result);
$a_retornar[] = array (
'id'=>0,
'nombre'=> self::$texto->get('gd_nombre'),
'x1'=> 'NULL',
'y1'=> 'NULL',
'x2'=> 'NULL',
'y2'=> 'NULL',
'descripcion'=> self::$texto->get('gd_descripcion'),
'cant'=> $aux[0]
);
mysql_free_result($result);
// Usuarios con grupos
$sql = "SELECT
g.`id` ,
g.`nombre` ,
g.`x1` ,
g.`y1` ,
g.`x2` ,
g.`y2` ,
g.`descripcion` ,
( SELECT
count( `grupo` )
FROM `".$this->config->get('PREFIX')."usuario` AS u
WHERE g.`id` = u.`grupo`
) AS cant
FROM `".$this->config->get('PREFIX')."grupo` AS g
GROUP BY g.`id`
ORDER BY g.`id` ASC";
$result = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ($aux = mysql_fetch_assoc($result))
$a_retornar[] = $aux;
mysql_free_result($result);
return $a_retornar;
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
/* *********************************************************************************
* Función interna de la clase que chequea que ninguno de los vertices del grupo
* esté definido dentro de otro grupo. Devuelve TRUE si resulta así, y FALSE si
* todo está OK.
*********************************************************************************/
private function check($xsup, $ysup, $xinf, $yinf)
{
$sql = "SELECT `id`, `x1`, `y1`, `x2`, `y2` FROM `".$this->config->get('PREFIX')."grupo` WHERE `id`!=0";
if (!empty($this->id_grupo)) $sql .= " and `id`!=".$this->id_grupo;
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $grup = mysql_fetch_assoc($resultado) )
{
// definimos los vertices del grupo
$p1 = $xsup; $p2 = $ysup; // P _______ Q
$q1 = $xinf; $q2 = $ysup; // | |
$r1 = $xsup; $r2 = $yinf; // |_______|
$s1 = $xinf; $s2 = $yinf; // R S
$x = ( ($grup['x1']<=$p1) and ($p1<=$grup['x2']) );
$y = ( ($grup['y1']>=$p2) and ($p2>=$grup['y2']) );
if ( $x and $y ) { mysql_free_result($resultado); return true; }
$x = ( ($grup['x1']<=$q1) and ($q1<=$grup['x2']) );
$y = ( ($grup['y1']>=$q2) and ($q2>=$grup['y2']) );
if ( $x and $y ) { mysql_free_result($resultado); return true; }
$x = ( ($grup['x1']<=$r1) and ($r1<=$grup['x2']) );
$y = ( ($grup['y1']>=$r2) and ($r2>=$grup['y2']) );
if ( $x and $y ) { mysql_free_result($resultado); return true; }
$x = ( ($grup['x1']<=$s1) and ($s1<=$grup['x2']) );
$y = ( ($grup['y1']>=$s2) and ($s2>=$grup['y2']) );
if ( $x and $y ) { mysql_free_result($resultado); return true; }
}
mysql_free_result($resultado);
return false;
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function nuevo()
{
$descripcion = $_POST['desc'];
$nombre = $_POST['name'];
$xvsi = (int) $_POST['x1'];
$yvsi = (int) $_POST['y1'];
$xvid = (int) $_POST['x2'];
$yvid = (int) $_POST['y2'];
$super = $this->check($xvsi, $yvsi, $xvid, $yvid);
if ($super) { return 'EAG01'; }
elseif ( ($xvsi < -400) or ($yvsi > 400) or ($xvid > 400) or ($yvid < -400) )
{ return 'EAG02'; }
else {
$sql = "INSERT INTO `".$this->config->get('PREFIX')."grupo` (`id`,`nombre`,`descripcion`,`x1`,`y1`,`x2`,`y2`) VALUES (NULL,\"".$nombre."\",\"".$descripcion."\",".$xvsi.",".$yvsi.",".$xvid.",".$yvid.")";
mysql_query($sql, $this->db) or die(mysql_error($this->db));
header("Location: index.php?ctrl=Grupo&mod=resumen");
}
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function get_data($id)
{
$sql = "SELECT `nombre`, `x1`, `y1`, `x2`, `y2`, `descripcion`, `id` FROM `".$this->config->get('PREFIX')."grupo` WHERE `id`=".$id;
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
return mysql_fetch_assoc($resultado);
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function editar()
{
$this->id_grupo = $id = $_POST['id'];
$descripcion = $_POST['desc'];
$nombre = $_POST['name'];
$xvsi = (int) $_POST['x1'];
$yvsi = (int) $_POST['y1'];
$xvid = (int) $_POST['x2'];
$yvid = (int) $_POST['y2'];
$super = $this->check($xvsi, $yvsi, $xvid, $yvid);
if ($super) { return 'EAG01'; }
elseif ( ($xvsi < -400) or ($yvsi > 400) or ($xvid > 400) or ($yvid < -400) )
{ return 'EAG02'; }
else {
$sql = "UPDATE `".$this->config->get('PREFIX')."grupo`
SET
`nombre` = \"".$nombre."\",
`descripcion` = \"".$descripcion."\",
`x1` = ".$xvsi.",
`y1` = ".$yvsi.",
`x2` = ".$xvid.",
`y2` = ".$yvid."
WHERE `id`=".$id;
mysql_query($sql, $this->db) or die(mysql_error($this->db));
header("Location: index.php?ctrl=Grupo&mod=resumen");
}
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function eliminar()
{
if ( isset($_GET['g']) )
{
if ($_GET['g']==0) return 'EBG04';
else {
$id = (int) $_GET['g'];
$msj = self::$texto->get('MBG01');
$sql = "DELETE FROM `".$this->config->get('PREFIX')."grupo` WHERE `id`= ".$id;
mysql_query($sql, $this->db) or die(mysql_error($this->db));
header("Location: index.php?ctrl=Grupo&mod=resumen");
}
} else { return 'EBG03'; }
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function ver_detalle(&$datos, &$miembros, &$grupos)
{
$a_detallar = (int) $_GET['g'];
if ($a_detallar != 0)
{
$datos = $this->get_data($a_detallar);
$sql = "SELECT
`nombre`
FROM `".$this->config->get('PREFIX')."usuario`
WHERE `grupo`=".$a_detallar."
ORDER BY `nombre`";
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ($jugador = mysql_fetch_assoc($resultado))
{
$sql = "SELECT `x`, `y`
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre`='".$jugador['nombre']."'";
$aldeas = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$cont_tot = 0; $cont_en = 0;
while ($una_aldea = mysql_fetch_row($aldeas))
{
$x = ( ($datos['x1']<=$una_aldea[0]) and ($una_aldea[0]<=$datos['x2']) );
$y = ( ($datos['y1']>=$una_aldea[1]) and ($una_aldea[1]>=$datos['y2']) );
if ( $x and $y ) { $cont_tot++ ; $cont_en++; }
else $cont_tot++;
}
$miembros[] = array( $jugador['nombre'], $cont_tot, $cont_en );
mysql_free_result($aldeas);
}
} else
{
$datos = array (
'id'=>0,
'nombre'=> self::$texto->get('gd_nombre'),
'x1'=> 'X',
'y1'=> 'X',
'x2'=> 'X',
'y2'=> 'X',
'descripcion'=> self::$texto->get('gd_descripcion')
);
$sql = "SELECT `nombre` FROM `".$this->config->get('PREFIX')."usuario` WHERE `grupo` IS NULL AND `estado`='Activo'";
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ($jugador = mysql_fetch_assoc($resultado))
{
$sql = "SELECT count(`usuario_nombre`) AS cant
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre`='".$jugador['nombre']."'";
$result = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$lala = mysql_fetch_assoc($result);
mysql_free_result($result);
$miembros[] = array( $jugador['nombre'], $lala['cant'], $lala['cant'] );
}
}
mysql_free_result($resultado);
// datos de los grupos para la opción de mover de grupo uno o más miembros
$sql = "SELECT `id`, `nombre` FROM `".$this->config->get('PREFIX')."grupo` WHERE `id`<>".$a_detallar;
$resultado = mysql_query($sql) or die(mysql_error());
if ($a_detallar != 0) $grupos[] = array('id'=>0,'nombre'=>self::$texto->get('gd_nombre'));
while ( $algo = mysql_fetch_assoc($resultado) )
{
$grupos[] = array('id'=>$algo['id'],'nombre'=>$algo['nombre']);
}
}
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
public function procesar()
{
$sql = "SELECT `id`, `x1`, `y1`, `x2`, `y2` FROM `".$this->config->get('PREFIX')."grupo`";
$grupos = mysql_query($sql, $this->db) or die(mysql_error($this->db));
// Por ahora tomaremos arbitrariamente la pertenencia al grupo según la aldea principal
// más adelante se habilitará la selección por parte del usuario.
$sql = "SELECT `usuario_nombre`, `x`, `y` FROM `".$this->config->get('PREFIX')."aldea` WHERE `es_principal`=1";
$sql_usuarios = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$usuarios = array();
while ($jugador = mysql_fetch_assoc($sql_usuarios)) // Pasamos el resultado a una variable
$usuarios[] = $jugador; // normal para trabajar mejor
mysql_free_result($sql_usuarios);
if (!empty($usuarios) and $grupos)
{
while ($un_grupo = mysql_fetch_assoc($grupos))
{
$cont = 0; $tot_usuarios = count($usuarios);
while ($cont < $tot_usuarios)
{
$x = ( ($un_grupo['x1']<=$usuarios[$cont]['x']) and ($usuarios[$cont]['x']<=$un_grupo['x2']) );
$y = ( ($un_grupo['y1']>=$usuarios[$cont]['y']) and ($usuarios[$cont]['y']>=$un_grupo['y2']) );
if ( $x and $y )
{
$sql = "UPDATE `".$this->config->get('PREFIX')."usuario` SET `grupo` = '".$un_grupo['id']."' WHERE nombre='".$usuarios[$cont]['usuario_nombre']."'";
mysql_query($sql, $this->db) or die(mysql_error($this->db));
unset($usuarios[$cont]); // Eliminamos este usuario de la matriz
}
$cont++;
}
// Re-indexamos la matriz
$usuarios = array_values($usuarios);
}
// Ahora se actualiza el campo grupo de aquellos a los que no se le encontró uno
$cont = 0; $tot_usuarios = count($usuarios);
while ($cont < $tot_usuarios)
{
$sql = "UPDATE `".$this->config->get('PREFIX')."usuario` SET `grupo` = NULL WHERE nombre='".$usuarios[$cont]['usuario_nombre']."'";
mysql_query($sql, $this->db) or die(mysql_error($this->db));
$cont++;
}
}
header("Location: index.php?ctrl=Grupo&mod=resumen");
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
// modificamos grupo
public function modificar_grupo()
{
if ( isset ( $_POST['check'] ) )
{
//concatenamos los seleccionados
$usuarios = $_POST['check'];
$grupo = ((int) $_POST['mover']) ? (int) $_POST['mover'] : "NULL" ;
$concat = "";
$cant = count($usuarios);
if ($cant > 0 )
{
foreach($usuarios as $key => $user)
{
$concat .= "\"".$user."\"";
if (($key+1)!=$cant)
$concat .= ", ";
}
$sql = "UPDATE `".$this->config->get('PREFIX')."usuario`
SET
`grupo` = ".$grupo."
WHERE `nombre` IN (".$concat.")";
mysql_query($sql, $this->db) or die (mysql_error($this->db));
header("Location: ?ctrl=Grupo&mod=detalles&g=".$_POST['volver']);
} else $resultado = "E_seleccion";
} else //si no se sellecciono ninguna fila devolvemos un error
$resultado = "E_seleccion";
return $resultado;
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
public function campanieros (&$NG, &$DEVOLVER)
{
$DEVOLVER = array();
if (!$_SESSION['ver_grupo'])
{
$sql = "SELECT `nombre`, `raza`
FROM `".$this->config->get('PREFIX')."usuario`
WHERE `grupo` = ".$_SESSION['grupo'];
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $row = mysql_fetch_row($resultado) )
$DEVOLVER[] = array('player'=> $row[0], 'raza'=>$row[1]);
}
else
{
$dia_act = date('d');
$mes_act = date('m');
$anio_act = date('Y');
$patron = '/([0-9]*)-([0-9]*)-([0-9]*)/';
// $fecha[1] --> AÑO - $fecha[2] --> MES - $fecha[3] --> DÍA
$sql = "SELECT `nombre`, `raza`, `last_change_tropa` FROM `".$this->config->get('PREFIX')."usuario` WHERE `grupo` = ".$_SESSION['grupo'];
$jugadores = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$cont = 0;
while ( $player = mysql_fetch_assoc($jugadores) )
{
if ($player['last_change_tropa'] != '0000-00-00')
{
preg_match($patron, $player['last_change_tropa'], $fecha);
$update = dias_entre($dia_act, $mes_act, $anio_act,
$fecha[3], $fecha[2], $fecha[1]);
} else $update = self::$texto->get('nunca');
$DEVOLVER[$cont] = array(
'player'=> $player['nombre'],
'raza'=> $player['raza'],
'actualizacion'=> $update,
't0'=> 0, 't1'=> 0, 't2'=> 0, 't3'=> 0, 't4'=> 0,
't5'=> 0, 't6'=> 0, 't7'=> 0, 't8'=> 0, 't9'=> 0
);
$sql = "SELECT
`idtropa`,
`cantidad`
FROM `".$this->config->get('PREFIX')."tropas_aldea`
WHERE (`ox` , `oy`) IN (
SELECT `x` , `y`
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre` = '".$player['nombre']."' )";
$sql_en = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $aux = mysql_fetch_assoc($sql_en) )
{
$it = $aux['idtropa'] - (int) ($aux['idtropa']/10) * 10;
$DEVOLVER[$cont]['t'.$it] += $aux['cantidad'];
}
$sql = "SELECT
`idtropa`,
`cantidad`
FROM `".$this->config->get('PREFIX')."refuerzos`
WHERE (`ox` , `oy`) IN (
SELECT `x` , `y`
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre` = '".$player['nombre']."' )";
$sql_ref = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $aux = mysql_fetch_assoc($sql_ref) )
{
$it = $aux['idtropa'] - (int) ($aux['idtropa']/10) * 10;
$DEVOLVER[$cont]['t'.$it] += $aux['cantidad'];
}
mysql_free_result( $sql_en ); mysql_free_result( $sql_ref );
$cont++;
}
}
$sql = "SELECT `nombre` FROM `".$this->config->get('PREFIX')."grupo` WHERE `id` = ".$_SESSION['grupo'];
$result = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$NG = mysql_fetch_row($result);
}
} // Fin clase
?>