Version 1.12

This commit is contained in:
nemunaire 2009-11-01 12:00:00 +01:00
commit de31cd3e9a
1373 changed files with 156282 additions and 45238 deletions

View file

@ -0,0 +1,16 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'accueil';
$titre = 'Accueil administration';
$bdd = new BDD();
$mail = $bdd->unique_query("SELECT COUNT(id) AS nombre FROM $table_ope_mail WHERE statut = 0;");
$pilori = $bdd->unique_query("SELECT COUNT(id) AS nombre FROM $table_user WHERE mv > 1;");
$news = $bdd->query("SELECT * FROM $table_ope_news ORDER BY id ASC LIMIT 3;");
$bdd->deconnexion();
$template->assign('nbMail', $mail['nombre']);
$template->assign('nbPilori', $pilori['nombre']);
$template->assign('news', $news);
?>

View file

@ -0,0 +1,52 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'print';
$titre = 'Vérification alliance';
$template->assign('linkpage', 'valliances');
if (!empty($_GET['id']) && !empty($_GET['key']) && $_GET['key'] != 'id') {
$pagea = 'print_key';
$id_plan = $_GET['id'];
$key = $_GET['key'];
$chapeau->connexion();
$chapeau->escape($id_plan);
$chapeau->escape($key);
$reqA = $chapeau->unique_query("SELECT * FROM $table_alliances WHERE id = '$id_plan';");
$req = $chapeau->unique_query("DESCRIBE $table_alliances $key;");
$chapeau->deconnexion();
$template->assign('tableau', $reqA);
$template->assign('type', explode('(', $req['Type']));
$template->assign('idPlan', $id_plan);
$template->assign('key', $_GET['key']);
}
elseif (!empty($_GET['id'])) {
$id_plan = $_GET['id'];
if (isset($_POST['key']) && isset($_POST['mod'])) {
$key = $_POST['key'];
$mod = $_POST['mod'];
$chapeau->connexion();
$chapeau->escape($mod);
$chapeau->escape($id_plan);
$chapeau->query("UPDATE $table_alliances SET $key = '$mod' WHERE id = '$id_plan';");
$chapeau->deconnexion();
}
$chapeau->connexion();
$req = $chapeau->unique_query("SELECT * FROM $table_alliances WHERE id = '$id_plan';");
$chapeau->deconnexion();
$template->assign('tableau', $req);
$template->assign('idPlan', $id_plan);
}
elseif (!empty($_GET['name'])) {
$name = $_GET['name'];
$chapeau->connexion();
$chapeau->escape($name);
$req = $chapeau->unique_query("SELECT * FROM $table_alliances WHERE nom = '$name';");
$chapeau->deconnexion();
header('Location: admin.php?p=valliances&id='.$req['id']);
exit;
}
else {
$pagea = 'print_choixU';
}
?>

View file

@ -0,0 +1,74 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'bandeau';
$titre = 'Bandeau d\'information';
//Ajout d'une information
if (!empty($_GET['i']) && $_GET['i'] == 'add' && !empty($_POST['texte']) && isset($_POST['color']))
{
$texte = gpc('texte', 'post');
$color = gpc('color', 'post');
$bdd = new BDD();
$bdd->escape($texte);
$bdd->escape($color);
$bdd->query("INSERT INTO $table_infoshead (texte, color) VALUES ('$texte', '$color');");
$bdd->deconnexion();
header('Location: admin.php?p=bandeau');
exit;
}
//Modification
elseif (!empty($_GET['i']))
{
$id = intval(gpc('i'));
if (!empty($_POST['texte']) && isset($_POST['color']))
{
$texte = gpc('texte', 'post');
$color = gpc('color', 'post');
$bdd = new BDD();
$bdd->escape($texte);
$bdd->escape($color);
$bdd->query("UPDATE $table_infoshead SET texte = '$texte', color = '$color' WHERE id = '$id';");
$bdd->deconnexion();
header('Location: admin.php?p=bandeau');
exit;
}
$bdd = new BDD();
$req = $bdd->unique_query("SELECT * FROM $table_infoshead WHERE id = '$id';");
$reqTT = $bdd->query("SELECT * FROM $table_infoshead ORDER BY id ASC;");
$bdd->deconnexion();
$template->assign('mod', $req);
$template->assign('tableau', $reqTT);
$template->assign('id', $id);
}
//Demande de suppression
elseif (!empty($_GET['d']))
{
$id = intval(gpc('d'));
$bdd = new BDD();
$bdd->query("DELETE FROM $table_infoshead WHERE id = $id;");
$bdd->deconnexion();
header('Location: admin.php?p=bandeau');
exit;
}
//Demande de mise à jour du cache
elseif (isset($_GET['actuCache']))
{
Cache::del('headerNB');
header('Location: admin.php?p=bandeau');
exit;
}
else
{
//Récupération des lignes du bandeau
$bdd = new BDD();
$req = $bdd->query("SELECT * FROM $table_infoshead ORDER BY id ASC;");
$bdd->deconnexion();
$template->assign('tableau', $req);
$template->assign('id', "add");
}
?>

View file

@ -0,0 +1,73 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'demarrage';
$titre = 'Page de démarrage';
if (!empty($_GET['i']) && $_GET['i'] == 'add' && !empty($_POST['contenu']) && isset($_POST['titre']))
{
$titre = gpc('titre', 'post');
$contenu = gpc('contenu', 'post');
$time = time();
$bdd = new BDD();
$bdd ->escape($titre);
$bdd ->escape($contenu);
$bdd ->query("INSERT INTO $table_messages_demarrage (titre, contenu, time) VALUES ('$titre', '$contenu', $time);");
$bdd ->deconnexion();
header('Location: admin.php?p=demarrage');
exit;
}
elseif (!empty($_GET['i']))
{
$id = intval(gpc('i'));
if (!empty($_POST['contenu']) && isset($_POST['titre']))
{
$titre = gpc('titre', 'post');
$texte = gpc('contenu', 'post');
$time = time();
$reset = gpc('reset', 'post');
$bdd = new BDD();
$bdd->escape($titre);
$bdd->escape($texte);
if (!empty($reset))
$bdd->query("UPDATE $table_messages_demarrage SET contenu = '$texte', titre = '$titre', time = $time WHERE id = $id;");
else
$bdd->query("UPDATE $table_messages_demarrage SET contenu = '$texte', titre = '$titre' WHERE id = $id;");
$bdd->deconnexion();
header('Location: admin.php?p=demarrage');
exit;
}
$bdd = new BDD();
$template->assign('mod', $bdd->unique_query("SELECT * FROM $table_messages_demarrage WHERE id = '$id';"));
$template->assign('tableau', $bdd->query("SELECT * FROM $table_messages_demarrage;"));
$bdd->deconnexion();
$template->assign('id', $id);
}
//Suppression d'un message
elseif (!empty($_GET['d']))
{
$id = intval(gpc('d'));
$bdd = new BDD();
$bdd->query("DELETE FROM $table_messages_demarrage WHERE id = '$id';");
$bdd->deconnexion();
header('Location: admin.php?p=demarrage');
exit;
}
//Demande de mise à jour du cache
elseif (isset($_GET['actuCache']))
{
Cache::del('headerNB');
header('Location: admin.php?p=demarrage');
exit;
}
else
{
$bdd = new BDD();
$template->assign('tableau', $bdd->query("SELECT * FROM $table_messages_demarrage;"));
$bdd->deconnexion();
$template->assign('id', 'add');
}
?>

View file

@ -0,0 +1,21 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'vflotte';
$titre = 'Vérification flottes';
//Vérification des flottes
if (!isset($_GET['ceil'])) $_GET['ceil'] = 5000;
$chapeau->connexion();
$req = mysql_query("SELECT * FROM `$table_flottes` ORDER BY `start_time` DESC");
$tableau = array();
while($resultat = mysql_fetch_array($req)) {
$user_source = infoPlan($resultat['end_galaxie'], $resultat['end_ss'], $resultat['end_position'], 'id_user');
if ($resultat['contenu_metal'] + $resultat['contenu_cristal'] + $resultat['contenu_hydrogene'] >= $_GET['ceil']) $color = 'FF0000';
elseif ($user_source != $resultat['id_user']) $color = 'DFBF00';
else $color = false;
$tableau[] = array(trouvNom($user_source), trouvNom($resultat['id_user']), infoPlan($resultat['start_galaxie'], $resultat['start_ss'], $resultat['start_position'], 'nom_planete'), '['.$resultat['start_galaxie'].':'.$resultat['start_ss'].':'.$resultat['start_position'].']', infoPlan($resultat['end_galaxie'], $resultat['end_ss'], $resultat['end_position'], 'nom_planete'), '['.$resultat['end_galaxie'].':'.$resultat['end_ss'].':'.$resultat['end_position'].']', $resultat['start_time'], '<acronym title="!!!Détail vaisseaux">'.$resultat['nb_vais'].'</acronym>', $resultat['vitesse'], $resultat['contenu_metal'], $resultat['contenu_cristal'], $resultat['contenu_hydrogene'], $color);
}
$template->assign('flottes', $tableau);
?>

View file

@ -0,0 +1,17 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Création d\'inscription';
$pagea = 'inscription';
if (!empty($_POST['HB_pseudo']) && !empty($_POST['race']))
{
if ($_POST['HB_conf'] == $_POST['HB_mdp'] && !empty($_POST['HB_mdp']))
{
$res = $_POST;
$cds = sha1($res['HB_pseudo'].'$'.$res['race'].'£'.$res['HB_mdp'].'#'.$res['HB_mail'].'ß'.time().'Ó'.$_SERVER['HTTP_USER_AGENT'].'♀☻'.$_SERVER['REMOTE_ADDR'].$res['HB_placement']);
erreur('URL : ?p=njoueur&nom='.$res['HB_pseudo'].'&race='.$res['race'].'&mdp='.$res['HB_mdp'].'&mail='.$res['HB_mail'].'&ti='.time().'&placement='.$res['HB_placement'].'&cds='.$cds.'<br /><br />L\'inscription doit avoir lieu par vous même en raison des procédures de sécurités !', "white");
}
else
erreur('Mot de passe incorrect !');
}
?>

View file

@ -0,0 +1,36 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'vip';
$titre = 'Vérification IP';
$timelimit = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d"), date("Y"))); //2008-06-17 18:15:00
$chapeau->connexion();
$page = gpc('v');
if (empty($page) || !is_numeric($page)) $page = 0;
$act = gpc('act');
if ($act == 'multiok') $chapeau->query("UPDATE $table_user SET multi = '1' WHERE id = ".$_GET['util'].";");
if (isset($_GET['ip'])) $req = mysql_query("SELECT R.id, R.id_util, R.time, R.ip, U.pseudo, U.mv, U.multi FROM $table_registre_identification R INNER JOIN $table_user U ON R.id_util = U.id WHERE ip = '".$_GET['ip']."' ORDER BY ip ASC;");
elseif (isset($_GET['util']) && isset($_GET['comp'])) $req = mysql_query("SELECT R.id, R.id_util, R.time, R.ip, U.pseudo, U.mv, U.multi FROM $table_registre_identification R INNER JOIN $table_user U ON R.id_util = U.id WHERE id_util = ".$_GET['util']." OR id_util = ".$_GET['comp']." ORDER BY ip ASC;");
elseif (isset($_GET['util'])) $req = mysql_query("SELECT R.id, R.id_util, R.time, R.ip, U.pseudo, U.mv, U.multi FROM $table_registre_identification R INNER JOIN $table_user U ON R.id_util = U.id WHERE id_util = '".$_GET['util']."' ORDER BY ip ASC;");
elseif (isset($_GET['tri'])) $req = mysql_query("SELECT R.id, R.id_util, R.time, R.ip, U.pseudo, U.mv, U.multi FROM $table_registre_identification R INNER JOIN $table_user U ON R.id_util = U.id ORDER BY ".$_GET['tri']." ASC;");
else $req = mysql_query("SELECT R.id, R.id_util, R.time, R.ip, U.pseudo, U.mv, U.multi FROM $table_registre_identification R INNER JOIN $table_user U ON R.id_util = U.id WHERE R.time > '$timelimit 00:00:00' ORDER BY R.ip ASC LIMIT ".($page*75).",75;");
//SELECT last_ip,COUNT(*) FROM user GROUP BY last_ip HAVING COUNT(*)>1
$nbpage = $chapeau->unique_query("SELECT COUNT(id) AS nb FROM $table_registre_identification WHERE time > '$timelimit 00:00:00';");
$chapeau->deconnexion();
$anc = array('ip' => 0, 'id_util' => 0);
$tableau = array();
while($resultat = mysql_fetch_array($req)) {
if ($resultat['mv'] == 3) $color = 'DFBF00';
elseif ($resultat['multi'] == 1 && $anc['ip'] == $resultat['ip'] && $anc['id_util'] != $resultat['id_util']) $color = 'EE66EE';
elseif ($anc['ip'] == $resultat['ip'] && $anc['id_util'] != $resultat['id_util']) $color = 'FF0000';
else $color = false;
$tableau[] = array($resultat['ip'], 'absent pour plus de rapidité'/*gethostbyaddr($resultat['ip'])*/, $resultat['id_util'], $resultat['pseudo'], $resultat['time'], $resultat['mv'], $color);
$anc = $resultat;
}
$template->assign('ips', $tableau);
$template->assign('numpage', $page);
$template->assign('nbpage', floor($nbpage['nb']/75));
?>

View file

@ -0,0 +1,52 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'print';
$titre = 'Vérification joueur';
$template->assign('linkpage', 'vjoueurs');
if (!empty($_GET['id']) && !empty($_GET['key']) && $_GET['key'] != 'id') {
$pagea = 'print_key';
$id_plan = $_GET['id'];
$key = $_GET['key'];
$chapeau->connexion();
$chapeau->escape($id_plan);
$chapeau->escape($key);
$reqJ = $chapeau->unique_query("SELECT * FROM $table_user WHERE id = '$id_plan';");
$req = $chapeau->unique_query("DESCRIBE $table_user $key;");
$chapeau->deconnexion();
$template->assign('tableau', $reqJ);
$template->assign('type', explode('(', $req['Type']));
$template->assign('idPlan', $id_plan);
$template->assign('key', $_GET['key']);
}
elseif (!empty($_GET['id'])) {
$id_plan = $_GET['id'];
if (isset($_POST['key']) && isset($_POST['mod'])) {
$key = $_POST['key'];
$mod = $_POST['mod'];
$chapeau->connexion();
$chapeau->escape($mod);
$chapeau->escape($id_plan);
$chapeau->query("UPDATE $table_user SET $key = '$mod' WHERE id = '$id_plan';");
$chapeau->deconnexion();
}
$chapeau->connexion();
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE id = '$id_plan';");
$chapeau->deconnexion();
$template->assign('tableau', $req);
$template->assign('idPlan', $id_plan);
}
elseif (!empty($_GET['name'])) {
$name = $_GET['name'];
$chapeau->connexion();
$chapeau->escape($name);
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE pseudo = '$name';");
$chapeau->deconnexion();
header('Location: admin.php?p=vjoueurs&id='.$req['id']);
exit;
}
else {
$pagea = 'print_choixU';
}
?>

View file

@ -0,0 +1,49 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'mail_liste';
$titre = 'Demandes et problèmes de la galaxie';
$template->assign('linkpage', 'courrier');
if (!empty($_GET['w']) || !empty($_GET['x'])) {
if (!empty($_GET['w'])) $id = $_GET['w'];
else $id = $_GET['x'];
$bdd = new BDD();
$bdd->escape($id);
$req = $bdd->unique_query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user WHERE $table_ope_mail.id = '$id';");
if ($req['statut'] >= 6) $bdd->query("UPDATE $table_ope_mail SET statut = '0' WHERE id = '$id';");
else $bdd->query("UPDATE $table_ope_mail SET statut = statut + 1 WHERE id = '$id';");
$bdd->deconnexion();
if (isset($_GET['x'])) header('Location: admin.php?p=courrier&v='.$id);
else header('Location: admin.php?p=courrier');
exit;
}
elseif (!empty($_GET['v'])) {
$id = $_GET['v'];
$bdd = new BDD();
$bdd->escape($id);
$req = $bdd->unique_query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user WHERE $table_ope_mail.id = '$id';");
$bdd->deconnexion();
$template->assign('req', $req);
$template->assign('id', $id);
$pagea = 'mail_view';
}
elseif (!empty($_GET['d']) && $sess->level >= 5) {
$id = $_GET['d'];
$bdd = new BDD();
$bdd->escape($id);
$bdd->query("DELETE FROM $table_ope_mail WHERE id = '$id';");
$bdd->deconnexion();
header('Location: admin.php?p=courrier');
exit;
}
else {
$bdd = new BDD();
$req = $bdd->query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user ORDER BY $table_ope_mail.time DESC;");
$bdd->deconnexion();
$template->assign('mails', $req);
}
?>

View file

@ -0,0 +1,65 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'print';
$titre = 'Vérification planète';
$template->assign('linkpage', 'vplanetes');
if (!empty($_GET['id']) && !empty($_GET['key']) && $_GET['key'] == 'hash_planete') {
$id_plan = $_GET['id'];
$chapeau->connexion();
$chapeau->query("UPDATE $table_planete SET hash_planete = SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)) WHERE id = $id_plan;");
$req = $chapeau->unique_query("SELECT * FROM $table_planete WHERE id = $id_plan;");
$chapeau->deconnexion();
$template->assign('tableau', $req);
$template->assign('idPlan', $id_plan);
}
elseif (!empty($_GET['id']) && !empty($_GET['key']) && $_GET['key'] != 'id') {
$pagea = 'print_key';
$id_plan = $_GET['id'];
$key = $_GET['key'];
$chapeau->connexion();
$chapeau->escape($id_plan);
$chapeau->escape($key);
$reqp = $chapeau->unique_query("SELECT * FROM $table_planete WHERE id = '$id_plan';");
$req = $chapeau->unique_query("DESCRIBE $table_planete $key;");
$chapeau->deconnexion();
$template->assign('tableau', $reqp);
$template->assign('type', explode('(', $req['Type']));
$template->assign('idPlan', $id_plan);
$template->assign('key', $_GET['key']);
}
elseif (!empty($_GET['id'])) {
$id_plan = $_GET['id'];
if (isset($_POST['key']) && isset($_POST['mod']) && $_POST['key'] != 'id') {
$key = $_POST['key'];
$mod = $_POST['mod'];
$chapeau->connexion();
$chapeau->escape($mod);
$chapeau->query("UPDATE $table_planete SET $key = '$mod' WHERE id = $id_plan;");
$chapeau->deconnexion();
}
$chapeau->connexion();
$req = $chapeau->unique_query("SELECT * FROM $table_planete WHERE id = $id_plan;");
$chapeau->deconnexion();
$template->assign('tableau', $req);
$template->assign('idPlan', $id_plan);
}
elseif (isset($_GET['amas']) && isset($_GET['ss']) && !empty($_GET['pos'])) {
$amas = $_GET['amas'];
$ss = $_GET['ss'];
$pos = $_GET['pos'];
$chapeau->connexion();
$chapeau->escape($amas);
$chapeau->escape($ss);
$chapeau->escape($pos);
$req = $chapeau->unique_query("SELECT * FROM $table_planete WHERE galaxie = '$amas' AND ss = '$ss' AND position = '$pos';");
$chapeau->deconnexion();
header('Location: admin.php?p=vplanetes&id='.$req['id']);
exit;
}
else {
$pagea = 'print_choixP';
}
?>

View file

@ -0,0 +1,42 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Prise de contrôle d\'un joueur';
$pagea = 'erreur';
$template->assign('linkpage', 'cjoueurs');
if ($SESS->level >= 5 && !empty($_GET['id'])) {
$name = gpc('id');
$bdd = new BDD();
$bdd->escape($name);
$req = $bdd->unique_query("SELECT id, pseudo, auth_level FROM $table_user WHERE id = '$name';");
$bdd->deconnexion();
if ($req['auth_level'] >= $SESS->level) {
$template->assign('message', 'Vous ne pouvez pas prendre le contrôle de cet utilisateur !');
}
else {
$bdd->reconnexion();
$reqPl = $bdd->unique_query("SELECT id, nom_planete FROM $table_planete WHERE id_user = '".$req['id']."' LIMIT 1;");
$bdd->deconnexion();
if (empty($SESS->values['souscontrole'])) $SESS->values['souscontrole'] = array($SESS->values['id'], $SESS->values['idPlan']);
$SESS->values['id'] = $req['id'];
$SESS->values['idPlan'] = $reqPl['id'];
$SESS->put();
$template->assign('message', 'Vous contrôlez maintenant le joueur '.$req['pseudo'].'.<br />Planète '.$reqPl['nom_planete'].' sélectionnée !');
}
}
elseif (!empty($_GET['name'])) {
$name = gpc('name');
$bdd = new BDD();
$bdd->escape($name);
$req = $bdd->unique_query("SELECT id FROM $table_user WHERE pseudo = '$name';");
$bdd->deconnexion();
header('Location: admin.php?p=cjoueurs&id='.$req['id']);
exit;
}
else {
$pagea = 'print_choixU';
}
?>

View file

@ -0,0 +1,26 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'rapports';
$titre = 'Afficher les rapports d\'un joueur';
$template->assign('linkpage', 'vrapports');
if (!empty($_GET['name'])) {
$id_user = $_GET['name'];
$chapeau->connexion();
$req = $chapeau->query("SELECT * FROM $table_mail WHERE destinataire = '$id_user' AND expediteur = '' ORDER BY temps DESC;");
$chapeau->deconnexion();
$template->assign('tableau', $req);
$template->assign('idPlan', $id_user);
}
elseif (!empty($_GET['id'])) {
$chapeau->connexion();
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE id = '".mysql_real_escape_string($_GET['id'])."';");
$chapeau->deconnexion();
header('Location: admin.php?p=vrapports&name='.$req['pseudo']);
exit;
}
else {
$pagea = 'print_choixU';
}
?>

View file

@ -0,0 +1,42 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Sanction joueur';
$pagea = 'erreur';
$template->assign('linkpage', 'sjoueurs');
if (!empty($_GET['id']) && !empty($_GET['sanc']) && (!empty($_GET['raisonmv']) || $_GET['sanc'] < 0)) {
$raisonmv = $_GET['raisonmv'];
$id_plan = $_GET['id'];
$chapeau->connexion();
$chapeau->escape($raisonmv);
$chapeau->escape($id_plan);
if ($_GET['sanc'] == 'definitif' || $_GET['sanc'] == 'définitif' || $_GET['sanc'] == 'd') {
$chapeau->query("UPDATE $table_user SET mv = '3', raisonmv = '$raisonmv', operateurmv = '$id_user' WHERE id = '$id_plan';");
$chapeau->deconnexion();
$template->assign('message', 'Le joueur a été banni définitivement !');
}
else {
$sanc = $_GET['sanc'];
$time = time() + $_GET['sanc'] * 86400 - 259200;
$chapeau->query("UPDATE $table_user SET mv = '2', last_visite = '$time', raisonmv = '$raisonmv', operateurmv = '$id_user' WHERE id = '$id_plan';");
$chapeau->deconnexion();
$template->assign('message', 'Le joueur a été placé en mode vacances !');
}
}
elseif (!empty($_GET['name']) && !empty($_GET['sanc']) && isset($_GET['raisonmv'])) {
$name = $_GET['name'];
$chapeau->connexion();
$chapeau->escape($name);
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE pseudo = '$name';");
$chapeau->deconnexion();
header('Location: admin.php?p=sjoueurs&sanc='.$_GET['sanc'].'&raisonmv='.$_GET['raisonmv'].'&id='.$req['id']);
exit;
}
else {
$pagea = 'sanctionU_choix';
}
?>

View file

@ -0,0 +1,42 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = '!!! Supprimer joueur !!!';
$pagea = 'erreur';
$template->assign('linkpage', 'djoueurs');
if ($sess->level >= 5 && !empty($_GET['id'])) {
$id = $_GET['id'];
$chapeau->connexion();
$chapeau->escape($id);
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE id = '$id';");
$chapeau->deconnexion();
if ($req) {
$nom = trouvNom($id);
$chapeau->connexion();
$chapeau->escape($nom);
$chapeau->query("DELETE FROM $table_mail WHERE destinataire = '$nom';");
$chapeau->query("DELETE FROM $table_user WHERE id = '$id';");
$chapeau->query("DELETE FROM $table_flottes WHERE id_user = '$id';");
$chapeau->query("DELETE FROM $table_planete WHERE id_user = '$id';");
$chapeau->deconnexion();
$template->assign('message', 'Le joueur a été supprimé du jeu ainsi que toutes les données le concernant !');
}
else {
$chapeau->deconnexion();
$template->assign('message', 'Le joueur n\'a pas été trouvé !');
}
}
elseif (!empty($_GET['name'])) {
$name = $_GET['name'];
$chapeau->connexion();
$chapeau->escape($name);
$req = $chapeau->unique_query("SELECT * FROM $table_user WHERE pseudo = '$name';");
$chapeau->deconnexion();
header('Location: admin.php?p=djoueurs&id='.$req['id']);
exit;
}
else {
$pagea = 'print_choixU';
}
?>

View file

@ -0,0 +1,71 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$pagea = 'version';
$titre = 'Versions';
//Ajout d'une version
if (!empty($_GET['i']) && $_GET['i'] == 'add' && $SESS->level >= 7 && !empty($_POST['version']) && !empty($_POST['contenu']))
{
$version = gpc('version', 'post');
$contenu = gpc('contenu', 'post');
$temps = time();
$nom_user = trouvNom($SESS->values['id']);
$bdd = new BDD();
$bdd->escape($version);
$bdd->escape($contenu);
$bdd->escape($nom_user);
$bdd->query("INSERT INTO $table_version (version, contenu, temps, pseudo) VALUES ('$version', '$contenu', $temps, '$nom_user');");
$bdd->deconnexion();
header('Location: admin.php?p=version');
exit;
}
//Modification d'une version
elseif (!empty($_GET['i']))
{
$id = intval(gpc('i'));
if (!empty($_POST['version']) && !empty($_POST['contenu'])) {
$version = gpc('version', 'post');
$contenu = gpc('contenu', 'post');
$bdd = new BDD();
$bdd->escape($version);
$bdd->escape($contenu);
$bdd->query("UPDATE $table_version SET version = '$version', contenu = '$contenu' WHERE id = $id;");
$bdd->deconnexion();
header('Location: admin.php?p=version');
exit;
}
$bdd = new BDD();
$template->assign('mod', $bdd->unique_query("SELECT * FROM $table_version WHERE id = '$id';"));
$template->assign('tableau', $bdd->query("SELECT * FROM $table_version ORDER BY temps DESC;"));
$bdd->deconnexion();
$template->assign('id', $id);
}
//Suppression d'une version
elseif (!empty($_GET['d']) && $SESS->level >= 7)
{
$id = intval(gpc('d'));
$bdd = new BDD();
$bdd->query("DELETE FROM $table_version WHERE id = $id;");
$bdd->deconnexion();
header('Location: admin.php?p=version');
exit;
}
//Demande de mise à jour du cache
elseif (isset($_GET['actuCache']))
{
Cache::del('versionsDATA');
header('Location: admin.php?p=version');
exit;
}
else
{
$bdd = new BDD();
$template->assign('tableau', $bdd->query("SELECT * FROM $table_version ORDER BY temps DESC;"));
$bdd->deconnexion();
$template->assign('id', 'add');
}
?>

60
onyx2/include/common.php Normal file
View file

@ -0,0 +1,60 @@
<?php
if (empty($sess->values['connected']) && !defined("xCSRF"))
define("xCSRF", true);
require_once("function.php"); //Inclusion des fonctions principales
require_once("tables.php"); //Inclusion des noms des tables de base de données correspondant à l'architecture du serveur
//On prépare le gestionnaire de templates
$template = new Template();
$template->assign('date', strftime("%A %d %B %Y %H:%M"));
$template->assign('datehb', strftime("/%a %d %b %Y/%H%M %S"));
$template->assign('link', array_map("url", $VAR['link']));
$template->assign('url_serveur', $_SERVER['HTTP_HOST']);
$template->assign('url_images', $VAR['url_images']);
//On charge la session
$SESS = new Session();
//Extraction des données en cache
$header = Cache::read('headerNB');
if (empty($header))
{
$bdd = new BDD();
$nbcovie = $bdd->unique_query("SELECT COUNT(id) AS covenants FROM $table_user WHERE race = 'covenant';");
$nbhumain = $bdd->unique_query("SELECT COUNT(id) AS humains FROM $table_user WHERE race = 'humain';");
$enligne = $bdd->unique_query("SELECT COUNT(session) AS enligne FROM sessions WHERE active = true AND var != '0';");
$infos = $bdd->query("SELECT * FROM $table_infoshead ORDER BY id DESC;");
$msgdem = $bdd->unique_query("SELECT titre FROM $table_messages_demarrage ORDER BY id DESC LIMIT 1;");
$bdd->deconnexion();
Cache::set('headerNB', array('count' => array($nbcovie['covenants'], $nbhumain['humains'], "cette", $enligne['enligne']), 'infos' => $infos, 'messagedemarrage' => $msgdem['titre']));
unset($nbcovie, $nbhumain, $enligne, $infos, $msgdem, $bdd);
$header = Cache::read('headerNB');
}
$template->assign('header', $header);
$template->assign('version', $VAR['version']);
$template->assign('first_page', $VAR['first_page']);
$template->assign('LANG', $LANG);
define("VITESSE", $VAR['vitesse']);
//Evite les attaques CSRF
if (!empty($_SERVER['HTTP_REFERER']) && !ereg(time().'http://'.$_SERVER['HTTP_HOST'], time().$_SERVER['HTTP_REFERER']) && !defined('xCSRF'))
{
elog("Possibilité d'attaque CSRF\n".var_export($_REQUEST,TRUE), 2);
unset($_POST, $_GET);
$_GET = $_POST = array();
}
function limite($txt, $limit)
{
if (strlen($txt) > $limit)
return true;
else
return false;
}
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

16
onyx2/include/flottes.php Normal file
View file

@ -0,0 +1,16 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$bdd->reconnexion();
$flottes = $bdd->query("SELECT id FROM $table_flottes WHERE (id_user = ".$planete->id_user." OR end_planete = ".$planete->id.") AND (start_time + end_time) <= ".time()." AND last < ".(time()-10).";");
$bdd->deconnexion();
if ($flottes) {
foreach($flottes as $flotte) {
$flotte = new Flotte($flotte['id']);
$flotte->check_mission();
}
}
unset($flottes, $flotte);
?>

352
onyx2/include/function.php Normal file
View file

@ -0,0 +1,352 @@
<?php
function trouvNom($id_user)
{
global $table_user;
$base = new bdd();
$resultat = $base->unique_query("SELECT pseudo FROM $table_user WHERE id = $id_user;");
$base->deconnexion();
return $resultat['pseudo'];
}
function linkNom($id_user){
if (is_numeric($id_user)) $nom = trouvNom($id_user);
else $id_user = trouvId($id_user);
return '<a href="?p=util&amp;i='.$id_user.'">'.$nom.'</a>';
}
/*function trouvId($nom){
global $table_user;
$base = new bdd();
$base->connexion();
$resultat = $base->unique_query("SELECT id FROM $table_user WHERE pseudo = '$nom';");
$base->deconnexion();
return $resultat['id'];
}*/
/*function trouvInfo($id_user, $info){
global $table_user;
$base = new bdd();
$base->connexion();
$resultat = $base->unique_query("SELECT $info FROM $table_user WHERE id = $id_user;");
$base->deconnexion();
return $resultat[$info];
}*/
function affTemp($secondes){
$heures = intval($secondes/3600);
$minutes = intval($secondes/60-($heures*60));
if ($minutes < 10) $minutes = '0'.$minutes;
$seconde = $secondes-($heures*3600)-($minutes*60);
if ($seconde < 10) $seconde = '0'.$seconde;
return $heures.':'.$minutes.':'.$seconde;
}
function separerNombres($nombre) {
return number_format($nombre, 0, ',', ' ');
}
function sec($time) {
$output = '';
$tab = array ('jour' => '86400', 'heure' => '3600', 'minute' => '60', 'seconde' => '1');
foreach ($tab as $key => $value) {
$compteur = 0;
while ($time > ($value-1)) {
$time = $time - $value;
$compteur++;
}
if ($compteur != 0) {
$output .= $compteur.' '.$key;
if ($compteur > 1) $output .= 's';
if ($value != 1) $output .= ' ';
}
}
if (empty($output)) return 'Instantané';
else return $output;
}
function readDeblok($tableau, $queryPlanete){
global $batimentVAR, $technologiesVAR, $casernenVAR, $nomterrnVAR, $nomvaisnVAR;
if ($tableau == '0') return 'Débloqué';
else {
$return = '';
foreach ($tableau as $ligne){
if (!(array_search($ligne[1], $batimentVAR) === false)) {
$x = array_search($ligne[1], $batimentVAR);
$var = 'batiments';
}
elseif (!(array_search($ligne[1], $technologiesVAR) === false)) {
$x = array_search($ligne[1], $technologiesVAR);
$var = 'technologies';
}
elseif (!($x = array_search($ligne[1], $casernenVAR) === false)) {
$x = array_search($ligne[1], $casernenVAR);
$var = 'casernes';
}
elseif (!($x = array_search($ligne[1], $nomterrnVAR) === false)) {
$x = array_search($ligne[1], $nomterrnVAR);
$var = 'terrestres';
}
elseif (!($x = array_search($ligne[1], $nomvaisnVAR) === false)) {
$x = array_search($ligne[1], $nomvaisnVAR);
$var = 'vaisseaux';
}
else return '#Error';
if (isset($var) && $var == 'technologies') {
if (($queryPlanete->{$var}[$x] & $ligne[2]) != $ligne[2]) $return .= '<span class="lack">'.$ligne[0].' ('.$var.')</span><br />';
else $return .= $ligne[0].' ('.$var.')<br />';
}
elseif (isset($var) && $queryPlanete->{$var}[$x] < $ligne[2]) $return .= '<span class="lack">'.$ligne[0].' '.$ligne[2].' ('.$queryPlanete->{$var}[$x].') ('.$var.')</span><br />';
elseif (isset($var) && $queryPlanete->{$var}[$x] >= $ligne[2]) $return .= $ligne[0].' '.$ligne[2].' ('.$queryPlanete->{$var}[$x].') ('.$var.')<br />';
}
if (empty($return)) return 'Débloqué';
else return $return;
}
}
function requestDeblok($tableau, $queryPlanete){
global $batimentVAR, $technologiesVAR, $casernenVAR, $nomterrnVAR, $nomvaisnVAR;
if ($tableau == '0') return true;
else {
$return = true;
foreach ($tableau as $ligne){
if (!(array_search($ligne[1], $batimentVAR) === false)) {
$x = array_search($ligne[1], $batimentVAR);
$var = 'batiments';
}
elseif (!(array_search($ligne[1], $technologiesVAR) === false)) {
$x = array_search($ligne[1], $technologiesVAR);
$var = 'technologies';
}
elseif (!($x = array_search($ligne[1], $casernenVAR) === false)) {
$x = array_search($ligne[1], $casernenVAR);
$var = 'casernes';
}
elseif (!($x = array_search($ligne[1], $nomterrnVAR) === false)) {
$x = array_search($ligne[1], $nomterrnVAR);
$var = 'terrestres';
}
elseif (!($x = array_search($ligne[1], $nomvaisnVAR) === false)) {
$x = array_search($ligne[1], $nomvaisnVAR);
$var = 'vaisseaux';
}
else return false;
if (isset($var) && $var == 'technologies') {
if (($queryPlanete->{$var}[$x] & $ligne[2]) != $ligne[2]) $return = false;
}
elseif (isset($var) && $queryPlanete->{$var}[$x] < $ligne[2]) $return = false;
}
return $return;
}
}
function txtmission($mission){
if ($mission == 0) return 'Stationner';
elseif ($mission == 1) return 'Transporter';
elseif ($mission == 2) return 'Coloniser';
elseif ($mission == 3) return 'Attaquer';
elseif ($mission == 4) return 'Recycler';
elseif ($mission == 5) return 'Espionner';
elseif ($mission == 6) return 'Retour';
else return 'Erreur';
}
function txtTactique($tactique){
switch($tactique){
case 1: return '1'; break;
case 2: return '2'; break;
case 3: return '3'; break;
case 4: return '4'; break;
case 5: return '5'; break;
case 6: return '6'; break;
case 7: return '7'; break;
case 8: return '8'; break;
case 9: return '9'; break;
case 10: return '10'; break;
case 11: return '11'; break;
case 12: return '12'; break;
case 13: return '13'; break;
case 14: return '14'; break;
case 15: return '15'; break;
case 16: return '16'; break;
case 17: return '17'; break;
case 18: return '18'; break;
case 19: return '19'; break;
case 20: return '20'; break;
case 21: return '21'; break;
default: return 'autre'; break;
}
}
function tactique($tactique){
switch($tactique){
case 1: return array(1,0,12,false); break;
case 2: return array(2,88,12,false); break;
case 3: return array(3,75,25,false); break;
case 4: return array(4,63,37,false); break;
case 5: return array(5,50,50,false); break;
case 6: return array(6,37,63,false); break;
case 7: return array(7,25,75,false); break;
case 8: return array(8,12,88,false); break;
case 9: return array(9,12,88,true); break;
case 10: return array(10,25,75,true); break;
case 11: return array(11,37,63,true); break;
case 12: return array(12,50,50,true); break;
case 13: return array(13,63,37,true); break;
case 14: return array(14,75,25,true); break;
case 15: return array(15,75,26,true); break;
case 16: return array(16,75,27,true); break;
case 17: return array(17,75,28,true); break;
case 18: return array(18,75,29,true); break;
case 19: return array(19,75,30,true); break;
case 20: return array(20,75,31,true); break;
case 21: return array(21,75,32,true); break;
default: return array(1,0,10,false); break;
}
}
function pillage($metal, $cristal, $hydrogene, $vfm){
$Qm = $metal / $vfm;
$Qc = $cristal / $vfm;
$Qh = $hydrogene / $vfm;
$somme = $Qm + $Qc + $Qh;
if ($somme < 2) {
$Fm = $metal / 2;
$Fc = $cristal / 2;
$Fh = $hydrogene / 2;
}
else {
$Fm = $Qm / $somme * $vfm;
$Fc = $Qc / $somme * $vfm;
$Fh = $Qh / $somme * $vfm;
}
return array(floor($Fm), floor($Fc), floor($Fh));
}
function vais_tempsDeplacement($start_galaxie,$start_ss,$start_position,$end_galaxie,$end_ss,$end_position,$vitesse,$coefvitesse = 1,$preparation = 0,$chauffe = 0) {
if ($end_galaxie-$start_galaxie == 0 && $end_ss-$start_ss == 0 && $end_position-$start_position == 0) $temps = 0;
elseif ($end_galaxie-$start_galaxie == 0 && $end_ss-$start_ss == 0 && $chauffe == 0) $temps = $preparation+abs($end_position-$start_position)*$vitesse/12;
elseif ($end_galaxie-$start_galaxie == 0 && $chauffe == 0) $temps = $preparation+abs($end_ss-$start_ss)*$vitesse;
elseif ($chauffe == 0) $temps = $preparation+abs($end_galaxie-$start_galaxie)*$vitesse*300;
elseif ($end_galaxie-$start_galaxie == 0 && $end_ss-$start_ss == 0) $temps = $preparation+abs($end_position-$start_position)*($vitesse*2)/12+$preparation;
/*elseif ($end_galaxie-$start_galaxie == 0 && $end_ss-$start_ss <= $chauffe) $temps = abs($end_ss-$start_ss)*(($vitesse/$chauffe)*($chauffe-abs($end_ss-$start_ss))+$vitesse)+$preparation;
elseif ($end_galaxie-$start_galaxie == 0) $temps = $vitesse*abs($end_ss-$start_ss)+$vitesse*10+$preparation;*/
elseif ($end_galaxie-$start_galaxie == 0) $temps = (abs($end_ss-$start_ss)*(($vitesse/$chauffe)*((abs($chauffe-abs($end_ss-$start_ss))+($chauffe-abs($end_ss-$start_ss)))/2)+$vitesse))+(20-(abs($chauffe-abs($end_ss-$start_ss))+($chauffe-abs($end_ss-$start_ss)))/2)*54+$preparation;
else $temps = (($vitesse/$chauffe)*($chauffe-abs($end_galaxie-$start_galaxie))+$vitesse)*300+108+$preparation;
return $temps/$coefvitesse;
}
function vaisTempsdeplacement($start_amas, $start_ss, $start_pos, $end_amas,$end_ss, $end_pos, $vitessevaisseaux, $vitesseflotte=100) {
if($end_amas - $start_amas != 0) return (10+(35000/$vitesseFlotte*sqrt(abs($end_amas-$start_amas)*20000000/$vitesseVaisseaux)));
elseif($end_ss-$start_ss != 0) return (10+(35000/$vitesseFlotte*sqrt(2700000+abs($end_ss-$start_ss)*95000/$vitessevais)));
elseif($end_pos-$start_pos != 0) return (10+(35000/$vitesseFlotte*sqrt((abs($end_pos-$start_pos)*5000/$vitessevais))));
else return (10+(35000/$vitesseFlotte-sqrt(5000/$vitesseVais)));
}
function vais_conso($tempsDeplacement,$nbvais = 1){
return intval($tempsDeplacement*$nbvais/20);
}
function send_mail($admail, $sujet, $corps){
require_once(_FCORE."../game/Class/class.phpmailer.php");
$mail = new PHPmailer();
$mail->SetLanguage('fr', _FCORE."../game/Class/");
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->Host='s-fr.com';
$mail->From='no-reply@halo-battle.s-fr.com';
$mail->FromName='Halo-Battle';
$mail->SMTPAuth=true;
$mail->Username='no-reply@halo-battle.s-fr.com';
$mail->Password='hD3e2nXu';
$mail->AddAddress($admail);
$mail->AddReplyTo('no-reply@halo-battle.s-fr.com');
$mail->Subject = $sujet;
$mail->Body = $corps;
$return = $mail->Send();
$mail->SmtpClose();
return $return;
}
function send_mailHTML($admail, $sujet, $corps){
require_once(_FCORE."../game/Class/class.phpmailer.php");
$mail = new PHPmailer();
$mail->SetLanguage('fr', _FCORE."../game/Class/");
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->Host='s-fr.com';
$mail->From='no-reply@halo-battle.s-fr.com';
$mail->FromName='Halo-Battle';
$mail->SMTPAuth=true;
$mail->Username='no-reply@halo-battle.s-fr.com';
$mail->Password='hD3e2nXu';
$mail->AddAddress($admail);
$mail->AddReplyTo('no-reply@halo-battle.s-fr.com');
$mail->Subject = 'Halo-Battle :: '.$sujet;
$mail->Body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>Halo-Battle :: '.$sujet.'</title></head><body><p>'.$corps.'<br /><br />A bient&ocirc;t dans Halo-Battle,<br />Le staff</p></body></html>';
$return = $mail->Send();
$mail->SmtpClose();
return $return;
}
function erreur($message, $color = "red", $lien = "", $temps = 2500){
global $template, $page;
if (!empty($page))
$template->assign('page', $page);
$template->assign('message', $message);
//if (!empty($lien)) $template->assign('script','<script type="text/javascript">setTimeout(\'document.location.href="'.$lien.'";\', '.$temps.');</script>');
$template->assign('couleur',$color);
$template->display('game/erreur.tpl');
exit;
}
function send_mp($joueur, $titre, $message, $type = 0, $emetteur = 0){
global $table_mail, $bdd;
$temps = time();
if (!is_numeric($joueur)) $joueur = trouvId($joueur);
if (!is_numeric($emetteur)) $emetteur = trouvId($emetteur);
if (!empty($joueur)) {
$bdd->connexion();
$bdd->escape($joueur);
$bdd->escape($titre);
$bdd->escape($message);
$bdd->query("INSERT INTO $table_mail (destinataire, expediteur, type, sujet, contenu, temps) VALUES($joueur, $emetteur, $type, '$titre', '$message', '$temps');");
$bdd->deconnexion();
}
}
function nameLink($id, $type){
global $race;
require(_FCORE."../game/noms.php");
if ($type == "technologie") return '<a href="?p=description&amp;t=1">'.$technolo[$id].'</a>';
}
function mdp($nom, $mdp, $alea = false){
if (empty($alea)) {
$alea = random(1024);
return array(hash('whirlpool', cxor(strtoupper($nom).':'.$mdp.'♂♪',$alea)), $alea);
}
else return hash('whirlpool', cxor(strtoupper($nom).':'.$mdp.'♂♪',$alea));
}
function redirection($url){
header('Location: '.$url);
print '<meta http-equiv="refresh" content="0; url='.$url.'" />';
}
?>

View file

@ -0,0 +1,806 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

View file

@ -0,0 +1,139 @@
<?php
/***************************************************************************
* class.alliance.php
* --------------------
* begin : Vendredi 10 octobre 2008
* update : Samedi 11 octobre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Alliance extends Surface{
var $id,
$race,
$fondateur,
$sante,
$nom,
$tag,
$galaxie,
$ss,
$nom_asteroide,
$image_asteroide,
$debris_met,
$debris_cri,
$credits,
$metal,
$cristal,
$hydrogene;
/**
* Constructeur
* @param int $id id de l'alliance à importer
*
* @return void
* @access public
*/
function Alliance($id = 0){
if (!empty($id)) {
global $var___db, $config, $table_alliances;
global $alli_batimentVAR, $nomvaisnVAR;
$bdd = new bdd();
$bdd->connexion();
$bdd->escape($id);
$alli = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
if (!empty($alli)) {
$this->id = $alli["id"];
$this->race = $alli["race"];
$this->fondateur = $alli["fondateur"];
$this->sante = $alli["sante"];
$this->nom = $alli["nom"];
$this->tag = $alli["tag"];
$this->galaxie = $alli["galaxie"];
$this->ss = $alli["ss"];
$this->nom_asteroide = $alli["nom_asteroide"];
$this->image_asteroide = $alli["image_asteroide"];
$this->debris_met = $alli["debris_met"];
$this->debris_cri = $alli["debris_cri"];
$this->credits = $alli["credits"];
$this->metal = $alli["metal"];
$this->cristal = $alli["cristal"];
$this->hydrogene = $alli["hydrogene"];
foreach($alli_batimentVAR as $bat){
$this->batiments[] = $alli[$bat];
}
$this->file_bat = unserialize($alli["file_bat"]);
foreach($nomvaisnVAR as $vais){
$this->vaisseaux[] = $plan[$vais];
}
$this->file_vais = unserialize($alli["file_vais"]);
$this->actualiser();
}
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true){
//Actualisation des files d'attentes
if ($actuFile) {
$this->file_pret("alli_batiments");
$this->file_pret("vaisseaux");
}
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $var___db, $config, $table_alliances;
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
$bdd->connexion();
for($i = 0; $i < $nb; $i++){
if (!is_array($this->{$this->modif[$i]})) {
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]})) $out[] .= $this->modif[$i]." = ".$this->{$this->modif[$i]};
else $out[] .= $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else {
if (ereg('file', $this->modif[$i])) {
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] .= $this->modif[$i]." = '$prep'";
}
else {
if ($this->modif[$i] == "batiments") $calc = "batiment";
elseif ($this->modif[$i] == "alli_batiments") $calc = "alli_batiment";
elseif ($this->modif[$i] == "technologies") $calc = "technolo";
elseif ($this->modif[$i] == "casernes")$calc = "casernen";
elseif ($this->modif[$i] == "terrestres") $calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux") $calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat") $calc = "coeff";
if (!isset(${$calc.'VAR'})) global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++){
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] .= ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out)) $plan = $bdd->unique_query("UPDATE $table_alliances SET ".implode(', ', $out)." WHERE id = ".$this->id.";");
$bdd->deconnexion();
}
}
?>

View file

@ -0,0 +1,637 @@
<?php
include_once("game/Class/class.surface.php");
/***************************************************************************
* class.asteroide.php
* ---------------------
* begin : Jeudi 25 décembre 2008
* update : Dimanche 4 janvier 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Asteroide extends Surface
{
var $fondateur,
$sante,
$nom_alliance,
$tag,
$nom_asteroide,
$image_asteroide,
$credits_alliance;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function Asteroide($id = 0)
{
if (!empty($id)) {
global $table_alliances, $SESS;
global $alli_batimentVAR, $nomvaisnVAR;
$bdd = new bdd();
//On traite le cas où l'on envoie les coordonnées
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
die('Erreur #04 : Format de recherche d\'asteroide incorrect !');
if (!empty($plan))
{
$this->id = $plan["id"];
parent::User($SESS->values['id']); //On utilise le numéro d'utilisateur enregistré en session
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->image = $this->image_asteroide = $plan["image_asteroide"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
foreach($alli_batimentVAR as $bat)
$this->batiments[] = $plan[$bat];
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new File('alli_batiments');
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new File('vaisseaux');
}
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true, $first = false)
{
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_ready("batiments");
$this->file_readyTechno("technologies");
$this->file_ready("casernes");
$this->file_ready("terrestres");
$this->file_ready("vaisseaux");
}
//Calcul de la capacité de stockage maximale
if (!empty($timestamp_lastSilo))
{
$this->cap = pow(2, $this->batiments[10]-1) * 100000;
$capnouv = pow(2, $this->batiments[10]) * 100000;
}
else
$this->cap = pow(2, $this->batiments[10]) * 100000;
//Calcul du temps écoulé depuis la dernière mise à jour de la planète
$temps_ecoule = time() - $this->timestamp;
$ressources = $this->production($temps_ecoule);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->metal + $ressources[0] < $capnouv)
$this->metal += $ressources[0];
}
else
{
$this->alert_ressources[0] = true;
$this->metal = $this->cap;
}
}
if ($this->cristal + $ressources[1] < $this->cap)
$this->cristal += $ressources[1];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->cristal + $ressources[1] < $capnouv)
$this->cristal += $ressources[1];
}
else
{
$this->alert_ressources[1] = true;
$this->cristal = $this->cap;
}
}
if ($this->hydrogene + $ressources[2] < $this->cap)
$this->hydrogene += $ressources[2];
else
{
//Si les capacité de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->hydrogene + $ressources[2] < $capnouv)
$this->hydrogene += $ressources[2];
}
else
{
$this->alert_ressources[2] = true;
$this->hydrogene = $this->cap;
}
}
//Vérification de la date pour faire les actions journalières
if (date('zya') != date('zya', $this->timestamp))
{
//On évalue le moral
$this->evalMoral($first);
//Si la population est à 0, on ajoute des habitants
if ($this->population <= 0)
$this->population = 1000;
$popPlus = $this->population * 0.0153^max(1, floor((time()-$this->timestamp)/86400));
if ($this->politique == 2)
$popPlus *= 1.1; //Communisme : 10 % de population qui arrive en plus.
elseif ($this->politique == 3)
$popPlus *= 1.05; //Démocratie : 5 % de population qui arrive en plus.
if ($this->technologies[2] & 4)
$popPlus *= 1.15;
elseif ($this->technologies[2] & 2)
$popPlus *= 1.10;
elseif ($this->technologies[2] & 1)
$popPlus *= 1.05;
$this->population += $popPlus;
$this->credits += $this->population/100*exp(0.01)*25;
$this->modif[] = 'population';
}
$this->timestamp = time();
//Calcul du nombre de cases restantes
$this->casesRest = $this->cases;
foreach($this->batiments as $bat)
$this->casesRest -= $bat;
}
function setMoral($difference)
{
$this->moral += $difference;
//Ajustement du moral
if ($this->moral > 1)
$this->moral = 1;
elseif ($this->moral < 0)
$this->moral = 0;
if (!in_array("moral", $this->modif))
$this->modif[] = "moral";
}
function evalMoral($first = false)
{
//Cas de sous-production
if (($this->coeff_bat[0] + $this->coeff_bat[1] + $this->coeff_bat[2])/3 < 0.9)
{
if ($this->politique == 2)
$this->moral -= 0.10; //Communisme : démoralise 2x plus
else
$this->moral -= 0.05;
if (!in_array('moral', $this->modif))
$this->modif[] = 'moral';
}
//Surpopulation
//Surlogement
//Ajustement du moral en fonction de la politique
if ($this->politique == 1 && $this->moral > 0.7)
$this->moral = 0.7;
//On vérifie qu'on ne dépasse pas le maximum
if ($this->moral > 1)
$this->moral = 1;
if ($this->moral < 0)
$this->moral = 0;
//Isolement si besoin
if ($this->moral < 0.1)
{
//On vérifie qu'il ne s'agit pas de la planète mère
global $bdd, $table_planete;
$bdd->connexion();
$res = $bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = ".$this->id_user." ORDER BY id LIMIT 1;");
$bdd->deconnexion();
if ($res['id'] != $this->id)
{
if ($this->moral <= 0.01 || $this->moral <= 0.04)
{
if ($this->moral <= 0.01)
$rand = rand(0,4);
else
$rand = rand(0,20);
//Perte de la planète
if ($rand == 1)
{
$bdd->connexion();
$bdd->query("DELETE FROM $table_planete WHERE id = ".$this->id.";");
$bdd->deconnexion();
send_mp($this->id_user, 'Perte de contrôle de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a renversé votre gouvernement en tuant tous vos gouverneurs. Vous perdez donc définitivement le contrôle de cette planète.");
if (!$first)
{
$SESS->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révolté contre vous. Vous ne contrôlez plus cette planète.');
}
}
}
elseif ($this->moral <= 0.06 || $this->moral <= 0.1)
{
if ($this->moral <= 0.06)
$rand = rand(0,2);
else
$rand = rand(0,10);
//Perte de contrôle temporaire
if ($rand == 1)
{
$debut = time() - rand(0, 3600)*4;
$fin = $debut + 86400;
$this->isolement = array($debut, $fin);
if (!in_array('isolement', $this->modif)) $this->modif[] = 'isolement';
send_mp($this->id_user, 'Perte de contrôle temporaire de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a pris le contrôle de votre planète. Vous perdez le contrôle de cette planète le temps que vos gouverneurs reprennent le pouvoir.");
if (!$first)
{
$SESS->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révoltée contre vous. Vous perdez temporairement le contrôle de cette planète.');
}
}
}
}
}
}
/**
* Vérifie si la planète est isolée ou non
*
* @return boolean
* @access public
*/
function isolement()
{
return false;
}
/**
* Calcul les ressources produites en fonction de $temps_ecoule
* @param int $temps_ecoule Temps écoulé depuis la dernière actualisation
*
* @return array
* @access public
*/
function production($temps_ecoule, $retarray = false)
{
//Accélération de la production
$temps_ecoule *= VITESSE;
//Calcul de la consomation d'énergie
if ($this->batiments[0] > 0)
$energie_m = ceil(exp(0.28*$this->batiments[0])*10);
else
$energie_m = 0;
if ($this->batiments[1] > 0)
$energie_c = ceil(exp(0.28*$this->batiments[1])*10);
else
$energie_c = 0;
if ($this->batiments[2] > 0)
$energie_h = ceil(exp(0.2849*$this->batiments[2])*13);
else
$energie_h = 0;
if ($this->batiments[3] > 0)
$energie_s = ceil(exp(0.28*$this->batiments[3])*22);
else
$energie_s = 0;
if ($this->batiments[4] > 0)
$energie_f = ceil(exp(0.297*$this->batiments[4])*25);
else
$energie_f = 0;
//Calcul de la consomation d'énergie
$this->energieConso = $energie_m * $this->coeff_bat[0] + $energie_c * $this->coeff_bat[1] + $energie_h * $this->coeff_bat[2];
$nrjmx = $energie_m + $energie_c + $energie_h;
//Calcul de la production d'énergie
$this->energie = $energie_s * $this->coeff_bat[3] + $energie_f * $this->coeff_bat[4];
if ($this->energieConso == 0)
$coeff = 0;
else
$coeff = $this->energie / $this->energieConso;
if ($coeff < 0)
$coeff = 0;
elseif ($coeff > 1)
$coeff = 1;
$Ncoeff = array();
for($i = 0; $i < 3; $i++)
{
$Ncoeff[$i] = $coeff * $this->coeff_bat[$i];
if ($Ncoeff[$i] > 1)
$Ncoeff[$i] = 1;
if ($Ncoeff[$i] < $this->coeff_bat[$i] && $this->batiments[$i] != 0)
{
$this->coeff_bat[$i] = $Ncoeff[$i];
if (!in_array('coeff_bat', $this->modif))
$this->modif[] = 'coeff_bat';
}
}
//Calcul de la consomation d'hydrogène
if ($this->batiments[4] > 0)
$conso_h = ((ceil(pow(1.34,($this->batiments[4]-1))*9)/3600)*$temps_ecoule) * $this->coeff_bat[4];
else
$conso_h = 0;
//Calcul des production de ressources
if ($this->batiments[0] <= 0 || $this->batiments[3] <= 0)
$prod_met = 0.011 * $temps_ecoule;
else
$prod_met = ((ceil(pow(1.1, $this->batiments[0]) * 35 * $this->batiments[0]) / 3600) * $temps_ecoule) * $this->coeff_bat[0] * 1.5;
if ($this->batiments[1] <= 0 || $this->batiments[3] <= 0)
$prod_cri = 0.0055 * $temps_ecoule;
else
$prod_cri = ((ceil(pow(1.1, $this->batiments[1]) * 23 * $this->batiments[1]) / 3600) * $temps_ecoule) * $this->coeff_bat[1] * 1.5;
if ($this->batiments[2] <= 0)
$prod_hy = 0;
else
$prod_hy = ((ceil(pow(1.1, $this->batiments[2]) * 14 * ($this->batiments[2] + 0.7)) / 3600) * $temps_ecoule) * $this->coeff_bat[2] * 1.5;
//Augmentation de la production en fonction des technologies
if ($this->technologies[0] &4)
{
$prod_met *= 1.15;
$prod_cri *= 1.15;
$prod_hy *= 1.15;
}
elseif ($this->technologies[0] &2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
elseif ($this->technologies[0] &1)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
//Augmentation de la production en fonction du moral
if ($this->moral > 0.9)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
elseif ($this->moral > 0.75)
{
$prod_met *= 1.02;
$prod_cri *= 1.02;
$prod_hy *= 1.02;
}
elseif ($this->moral < 0.45)
{
$prod_met *= 0.97;
$prod_cri *= 0.97;
$prod_hy *= 0.97;
}
elseif ($this->moral < 0.25)
{
$prod_met *= 0.94;
$prod_cri *= 0.94;
$prod_hy *= 0.94;
}
//Augmentation de la production en fonction de la politique
if ($this->politique == 2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
//On enlève la consomation d'hydrogène
$prod_hy -= $conso_h;
if ($retarray)
return array(array(ceil($this->coeff_bat[0]*100), ceil($this->coeff_bat[1]*100), ceil($this->coeff_bat[2]*100), ceil($this->coeff_bat[3]*100), ceil($this->coeff_bat[4]*100)), array($prod_met, $prod_cri, $prod_hy + $conso_h, $energie_s*$this->coeff_bat[3], $energie_f*$this->coeff_bat[4]), array($energie_m*$this->coeff_bat[0], $energie_c*$this->coeff_bat[1], $energie_h*$this->coeff_bat[2], $conso_h, ($energie_s*$this->coeff_bat[3] + $energie_f*$this->coeff_bat[4])-($energie_m*$this->coeff_bat[0] + $energie_c*$this->coeff_bat[1] + $energie_h*$this->coeff_bat[2])));
else
return array($prod_met, $prod_cri, $prod_hy);
}
function creer($id_user)
{
//Définition des paramètres de l'utilisateur pour la planète
$this->id_user = $id_user;
//Génération du nombre de case et de l'image en fonction de la position dans le système
if ($this->position > MAX_PLANETE*0.75)
{
$this->cases = mt_rand(200,255);
$this->image = mt_rand(1,19);
}
elseif ($this->position > MAX_PLANETE/2)
{
$this->cases = mt_rand(250,300);
$this->image = mt_rand(1,19);
}
elseif ($this->position > MAX_PLANETE/4)
{
$this->cases = mt_rand(175,260);
$this->image = mt_rand(1,19);
}
else
{
$this->cases = mt_rand(150,220);
$this->image = mt_rand(1,19);
}
//Définition des principaux paramètres de la planète
$this->nom_planete = 'Planète colonisée';
$this->timestamp = time();
$this->metal = 1000;
$this->cristal = 700;
$this->hydrogene = 0;
$this->modif = array("id_user", "nom_planete", "galaxie", "ss", "position", "image", "cases", "timestamp", "metal", "cristal", "hydrogene");
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->id_user))
return;
if ($this->id_user == 1)
var_dump($this);
global $var___db, $config, $table_planete;
if (empty($this->id))
{
$out1 = array(); $out2 = array();
$bdd = new bdd();
foreach($this->modif as $modif)
{
if ($modif == "force")
continue;
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$out1[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out2[] = $this->{$modif};
else
$out2[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out1[] = $modif;
$out2[] = "'$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technolo";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
elseif ($modif == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$out1[] = ${$calc.'VAR'}[$j];
$out2[] = $value;
}
}
}
}
$bdd->query("INSERT INTO $table_planete (".implode(', ', $out1).", hash_planete) VALUES (".implode(', ', $out2).", SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)))");
$bdd->deconnexion();
}
else
{
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
for($i = 0; $i < $nb; $i++)
{
if ($this->modif[$i] == "force")
$out[] = "timestamp = timestamp";
elseif ($this->modif[$i] == 'technologies')
$this->modifUser[] = $this->modif[$i];
elseif (is_object($this->{$this->modif[$i]}))
{
$export = serialize($this->{$this->modif[$i]});
$bdd->escape($export);
$out[] = $this->modif[$i]." = '".$export."'";
}
elseif (!is_array($this->{$this->modif[$i]}))
{
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]}))
$out[] = $this->modif[$i]." = ".$this->{$this->modif[$i]};
else
$out[] = $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else
{
if (is_array($this->{$this->modif[$i]}) && $this->modif[$i] != "coeff_bat" && $this->modif[$i] != "vaisseaux" && $this->modif[$i] != "terrestres" && $this->modif[$i] != "casernes" && $this->modif[$i] != "technologies" && $this->modif[$i] != "batiments")
{
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] = $this->modif[$i]." = '$prep'";
}
else
{
if ($this->modif[$i] == "batiments")
$calc = "batiment";
elseif ($this->modif[$i] == "technologies")
$calc = "technolo";
elseif ($this->modif[$i] == "casernes")
$calc = "casernen";
elseif ($this->modif[$i] == "terrestres")
$calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux")
$calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++)
{
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] = ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_planete SET timestamp = ".time().", metal = ".$this->metal.", cristal = ".$this->cristal.", hydrogene = ".$this->hydrogene.", ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,190 @@
<?php
/**
* Classe Bourse par Pierre-Olivier MERCIER
* Dernière édition le 21 Juillet 2008
* Copyright Halo-Battle Tous droits réservés
*/
class Bourse{
var $bd;
var $id;
var $nom;
var $taxeA = 1.1;
var $taxeV = 1.5;
var $metal;
var $cristal;
var $actionsUser;
var $user;
/**
* Constructor
*
* @param String $nom Nom de l'action
* @param int $user ID du joueur à charger automatiquement
*
* @access protected
*/
function Bourse($nom = "", $user = 0){
global $var___db, $config;
$db = new bdd();
$db->connexion();
$this->bd = $db;
if (!empty($nom)) {
$this->loadAction($nom, "id");
if (!empty($user)) $this->loadUser($user);
}
}
function __destruct(){
$this->bd->deconnexion();
}
function loadAction($nom, $type = "nom"){
global $table_bourse;
$this->bd->escape($nom);
$act = $this->bd->unique_query("SELECT * FROM $table_bourse WHERE $type = '$nom';");
if ($act) {
$this->id = $act['id'];
$this->nom = $act['nom'];
$this->metal = $act['metal'];
$this->cristal = $act['cristal'];
}
else erreur('Impossible de trouver cette action !', "red", '?p=bourse');
}
function loadUser($user, $type = "id"){
global $table_user;
$this->bd->escape($user);
$act = $this->bd->unique_query("SELECT id, bourse FROM $table_user WHERE $type = '$user';");
$this->user = $act['id'];
$this->traitUser($act['bourse']);
}
function traitUser($start){
$end = array();
$start = explode(';', $start);
$cnt = count($start);
for($i = 0; $i < $cnt; $i++){
$tmp = explode(':', $start[$i]);
if (!empty($tmp[1])) $end[$tmp[0]] = explode(',', $tmp[1]);
else $end[$tmp[0]] = array();
}
$this->actionsUser = $end;
}
function prixAchat($nb){
return array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
}
function prixVente($nb){
if ($this->action() < $nb) $nb = $this->action();
return array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
}
function addAction($nb){
$ret = array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
$this->metal *= pow(1.1, $nb);
$this->cristal *= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
$this->actionsUser[$this->id][] = time();
}
$this->maj();
return $ret;
}
function delAction($nb){
if ($this->action() < $nb) $nb = $this->action();
$ret = array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
$this->metal /= pow(1.1, $nb);
$this->cristal /= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
unset($this->actionsUser[$this->id][$i]);
}
$this->maj();
return $ret;
}
function actionIn24Hours(){
$nb = 0;
if (isset($this->actionsUser[$this->id])) {
$cnt = count($this->actionsUser[$this->id]);
for($i = 0; $i < $cnt; $i++){
if ($this->actionsUser[$this->id][$i] > time() - 86400) $nb++;
}
}
return $nb;
}
function action(){
if (isset($this->actionsUser[$this->id])) return count($this->actionsUser[$this->id]);
else return 0;
}
function maj(){
$this->majBourse();
$this->majUser();
$this->fileSave();
}
function majBourse(){
global $table_bourse;
$this->bd->query("UPDATE $table_bourse SET nom = '".$this->nom."', metal = '".$this->metal."', cristal = '".$this->cristal."' WHERE id = ".$this->id.";");
}
function majUser(){
global $table_user;
$champ = '';
foreach($this->actionsUser as $key => $cell) {
if (count($cell) > 0) {
if (empty($champ)) $champ .= $key.':'.implode(',', $cell);
else $champ .= ';'.$key.':'.implode(',', $cell);
}
}
$this->bd->query("UPDATE $table_user SET bourse = '$champ' WHERE id = ".$this->user.";");
}
function delUser($id = ""){
if (!empty($id)) $this->loadUser($id);
$champ = '';
foreach($this->actionsUser as $key => $cell) {
$cnt = count($cell);
if ($cnt > 0) {
$this->loadAction($key, "id");
$this->delAction($cnt);
}
}
}
function fileSave(){
$fichier = fopen(_FCORE."../game/cache/bourse/".$this->id.".".strftime('%Y%m%d').".bourse",'a+');
fwrite($fichier, time().';'.$this->metal.';'.$this->cristal."\n");
fclose($fichier);
}
function newGroupe($nom, $metal, $cristal, $description = ""){
global $table_bourse;
$this->bd->query("INSERT INTO $table_bourse (nom, metal, cristal, description) VALUES('$nom', '$metal', '$cristal', '$description');");
}
function editGroupe($description){
//TODO toute cette fonction !!
}
}
?>

View file

@ -0,0 +1,505 @@
<?php
/***************************************************************************
* class.combat.php
* -------------------
* begin : Samedi 26 janvier 2008
* update : Mercredi 4 juin 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Combat {
var $refflotte = 0;
var $ATvais = array();
var $ENvais = array();
var $ENres = array('metal' => 0, 'cristal' => 0, 'hydrogene' => 0);
var $ENdef = array();
var $Ntour = 0;
var $ATtactique = 0;
var $ENtactique = 0;
var $timestamp = 0;
var $vaisContenu = 0;
var $vaisContenuM = 0;
var $vaisContenuC = 0;
var $vaisContenuH = 0;
var $pillage = array(0, 0, 0);
var $debriM = 0;
var $debriC = 0;
/**
* Constructeur
* @param array $flotteAT tableau SQL des vaisseaux envoyés par l'attaquant
* @param array $flotteEN tableau SQL de la planète du défenseur
* @param array $defEN tableau SQL de la planète du défenseur
*
* @return void
* @access public
*/
function Combat($flotteAT, $flotteEN, $defEN, $tableTechno = array(0, 0)) {
include(_FCORE."hb_game/vars.php");
//Génération des vaisseaux attaquants
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteAT['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteAT['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
}
$this->ATvais[] = array($i, $flotteAT['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Définition d'autres variables de la classe concernant la flotte
$this->refflotte = $flotteAT['id'];
$this->vaisContenu = $flotteAT['contenu_max'];
$this->vaisContenuM = $flotteAT['contenu_metal'];
$this->vaisContenuC = $flotteAT['contenu_cristal'];
$this->vaisContenuH = $flotteAT['contenu_hydrogene'];
$this->timestamp = $flotteAT['start_time'] + $flotteAT['end_time'];
//Génération des vaisseaux défenseurs
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteEN['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteEN['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
}
$this->ENvais[] = array($i, $flotteEN['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Génération des défenses défenseurs
for ($i=1 ; $i<=5 ; $i++) {
if ($defEN['def_'.$i] >= 1) {
//Création des groupes
$nbvais = $defEN['def_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
}
$this->ENdef[] = array($i, $defEN['def_'.$i], $nbgroupes, $groupe, $defense_initiative[$i-1]);
}
}
}
/**
* Change la tactique de l'attaquant
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueAT($tactique) {
$this->ATtactique = ceil($tactique);
}
/**
* Change la tactique du défenseur
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueEN($tactique) {
$this->ENtactique = ceil($tactique);
}
/**
* Régénére les boucliers
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant régénére le bouclier de l'attaquant si true, sinon régénrére celui du défenseur
* @param bool $retour si true, renvoie true ou false si !le pourcentage a été consommé ou non, si false, retrourne ne nombre de pourcentage restant
* @param int $blindage niveau de la technologie blindage du joueur
*
* @return float pourcentage non utilisé
* @access public
*/
function regenereBC($pourcentage, $attaquant, $retour = false, $blindage = 0) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
$count = count($this->ATvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ATvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ATvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] < $maxbc) {
$this->ATvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ATvais[$i][3][$j][1] - $maxbc)*$this->ATvais[$i][3][$j][0];
$this->ATvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $enplus/$norm;
}
else {
$count = count($this->ENvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] < $maxbc) {
$this->ENvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENvais[$i][3][$j][1] - $maxbc)*$this->ENvais[$i][3][$j][0];
$this->ENvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
//Défenses
$count = count($this->ENdef);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENdef[$i][0]-1;
$maxbc = $defense_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENdef[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] < $maxbc) {
$this->ENdef[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENdef[$i][3][$j][1] - $maxbc)*$this->ENdef[$i][3][$j][0];
$this->ENdef[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $return/2;
}
}
/**
* Calcul la puissance d'attaque disponible
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant calcul les points de l'attaquant si true, sinon calcul pour le défenseur
* @param int $armement niveau de la technologie armement du joueur
* @param bool $method true pour utiliser la mèthode classique, false pour utiliser la méthode d'Apocalypse Joe
*
* @return int points disponibles
* @access public
*/
function calcAttaque($pourcentage, $attaquant, $armement = 0, $method = false) {
include(_FCORE."hb_game/vars.php");
if ($method) {
if ($attaquant) {
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1];
}
return $puissance;
}
else {
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1];
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
else {
if ($attaquant) {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ENvais);
$countd = count($this->ENdef);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ENvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ENvais[$i][0]] = $this->ENvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ATvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ATvais[$i][0]-1][$this->ENvais[$i][0]-1] * $vaisEff[$this->ENvais[$i][0]];
}
for ($j=0 ; $j<$countd ; $j++) {
$bonus += 1/$countd;
}
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1] * $bonus;
}
return $puissance;
}
else {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ATvais);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ATvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ATvais[$i][0]] = $this->ATvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ENvais[$i][0]-1][$this->ATvais[$i][0]-1] * $vaisEff[$this->ATvais[$i][0]];
}
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1] * $bonus;
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENdef[$i][4] > $this->Ntour) continue;
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
}
/**
* Attaque les vaisseaux adverses
* @param int $points points d'attaque disponible pour l'attaque
* @param bool $attaquant attaque le défenseur si true, sinon attaque l'attaquant
*
* @return void
* @access public
*/
function attaquerVais($points, $attaquant) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ENvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENvais[$i][1];
$nbgroupes += $this->ENvais[$i][2];
}
$nb = count($this->ENdef);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENdef[$i][1];
$nbgroupes += $this->ENdef[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque contre les vaisseaux
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENvais)-1);
$l = rand(0, count($this->ENvais[$k][3])-1);
$this->ENvais[$k][3][$l][1] -= $ppv;
if ($this->ENvais[$k][3][$l][1] < 0) {
$this->ENvais[$k][3][$l][2] -= abs($this->ENvais[$k][3][$l][1]);
$this->ENvais[$k][3][$l][1] = 0;
if ($this->ENvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENvais[$k][3][$l][0] * $nomvais_md[$this->ENvais[$k][0]];
$this->debriC += $this->ENvais[$k][3][$l][0] * $nomvais_cd[$this->ENvais[$k][0]];
$this->ENvais[$k][1] -= $this->ENvais[$k][3][$l][0];
$this->ENvais[$k][2] --;
array_splice($this->ENvais[$k][3], $l, 1);
if (!count($this->ENvais[$k][3])) {
array_splice($this->ENvais, $k, 1);
}
}
}
}
//On lance l'attaque contre les défenses
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENdef)-1);
$l = rand(0, count($this->ENdef[$k][3])-1);
$this->ENdef[$k][3][$l][1] -= $ppv;
if ($this->ENdef[$k][3][$l][1] < 0) {
$this->ENdef[$k][3][$l][2] -= abs($this->ENdef[$k][3][$l][1]);
$this->ENdef[$k][3][$l][1] = 0;
if ($this->ENdef[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENdef[$k][3][$l][0] * $nomvais_md[$this->ENdef[$k][0]];
$this->debriC += $this->ENdef[$k][3][$l][0] * $nomvais_cd[$this->ENdef[$k][0]];
$this->ENdef[$k][1] -= $this->ENdef[$k][3][$l][0];
$this->ENdef[$k][2] --;
array_splice($this->ENdef[$k][3], $l, 1);
if (!count($this->ENdef[$k][3])) {
array_splice($this->ENdef, $k, 1);
}
}
}
}
}
return count($this->ENvais) + count($this->ENdef);
}
else {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ATvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ATvais[$i][1];
$nbgroupes += $this->ATvais[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ATvais)-1);
$l = rand(0, count($this->ATvais[$k][3])-1);
$this->ATvais[$k][3][$l][1] -= $ppv;
if ($this->ATvais[$k][3][$l][1] < 0) {
$this->ATvais[$k][3][$l][2] -= abs($this->ATvais[$k][3][$l][1]);
$this->ATvais[$k][3][$l][1] = 0;
if ($this->ATvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ATvais[$k][3][$l][0] * $nomvais_md[$this->ATvais[$k][0]];
$this->debriC += $this->ATvais[$k][3][$l][0] * $nomvais_cd[$this->ATvais[$k][0]];
$this->ATvais[$k][1] -= $this->ATvais[$k][3][$l][0];
$this->ATvais[$k][2] --;
array_splice($this->ATvais[$k][3], $l, 1);
if (!count($this->ATvais[$k][3])) {
array_splice($this->ATvais, $k, 1);
}
}
}
}
}
return count($this->ATvais);
}
}
function exportAT($pillage = false){
include(_FCORE."hb_game/vars.php");
$nb = count($this->ATvais);
$nbvais = 0; $vaisContenu = 0; $vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ATvais[$i][0]} += $this->ATvais[$i][1];
$nbvais += $this->ATvais[$i][1];
$this->vaisContenu += $nomvais_rs[$this->ATvais[$i][0]-1];
}
$sommeCont = $this->vaisContenuM + $this->vaisContenuC + $this->vaisContenuH;
if ($sommeCont > $this->vaisContenu) {
$retirer = $sommeCont/$this->vaisContenu;
$this->vaisContenuM = floor($this->vaisContenuM/$retirer);
$this->vaisContenuC = floor($this->vaisContenuC/$retirer);
$this->vaisContenuH = floor($this->vaisContenuH/$retirer);
}
if ($pillage) {
$ressplus = pillage($this->ENres['metal'], $this->ENres['cristal'], $this->ENres['hydrogene'], $this->vaisContenu - $this->vaisContenuM - $this->vaisContenuC - $this->vaisContenuH);
$this->vaisContenuM += $ressplus[0];
$this->vaisContenuC += $ressplus[1];
$this->vaisContenuH += $ressplus[2];
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
return 'nb_vais = \''.$nbvais.'\', contenu_max = \''.$this->vaisContenu.'\', contenu_metal = \''.$this->vaisContenuM.'\', contenu_cristal = \''.$this->vaisContenuC.'\', contenu_hydrogene = \''.$this->vaisContenuH.'\', vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\'';
}
function pillageSimul($metal, $cristal, $hydrogene){
$ressplus = pillage($metal, $cristal, $hydrogene, 999999);
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
function exportEN(){
$nb = count($this->ENvais);
$vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ENvais[$i][0]} += $this->ENvais[$i][1];
}
$nb = count($this->ENdef);
$def_1 = 0; $def_2 = 0; $def_3 = 0; $def_4 = 0; $def_5 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'def_'.$this->ENdef[$i][0]} += $this->ENdef[$i][1];
}
return 'vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\', def_1 = \''.$def_1.'\', def_2 = \''.$def_2.'\', def_3 = \''.$def_3.'\', def_4 = \''.$def_4.'\', def_5 = \''.$def_5.'\'';
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,128 @@
<?php
/***************************************************************************
* class.exceptionHB.php
* -----------------------
* begin : Lundi 9 février 2009
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class ExceptionHB extends Exception {
public function __construct($branche, $code = 0, $debug = true, $gerer = false) {
if ($gerer)
parent::__construct($branche, $code);
else
{
if (is_numeric($branche))
{
switch($branche)
{
case 1:
switch($code)
{
case 0:
$message = "La planète est pleine, vous ne pouvez plus construire de batiment dessus !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de batiments.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour construire ce bâtiment.";
break;
case 3:
$message = "Le bâtiment dont vous demandez la construction est actuellement en démolition. Annulez la démolition pour lui ajouter l'aggrandir.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour construire ce bâtiment !";
break;
case 5:
$message = "Impossible d'annuler la construction de ce bâtiment, il n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démolir ce batiment, il n'est pas encore construit !";
break;
case 7:
$message = "Le bâtiment dont vous demandez la démolition est actuellement en travaux. Annulez les travaux en cours pour pouvoir le démolir.";
break;
}
break;
case 2:
switch($code)
{
case 0:
$message = "Cette technologie est déjà en file d'attente, soyez patient !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de technologies.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour rechercher cette technologie.";
break;
case 3:
$message = "Vous possédez déjà cette technologie !";
break;
case 4:
$message = "Vous n'avez pas les crédits ou ressources nécessaires pour rechercher cette technologie !";
break;
case 5:
$message = "Impossible d'annuler la recherche de cette technologie, elle n'a pas été trouvée dans la file !";
break;
}
break;
case 3:
switch($code)
{
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus d'unités.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour entraîner ces unités.";
break;
case 3:
$message = "L'unité dont vous demandez l'entraînement est actuellement en démentellement. Annulez le démentellement pour l'entraîner de nouveau.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour entraîner cette unité !";
break;
case 5:
$message = "Impossible d'annuler l'entraînement de cette unité, elle n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démenteler autant d'unités !";
break;
case 7:
$message = "L'unité dont vous demandez le démentellement est actuellement en entraînement. Annulez l'entraînement en cours pour pouvoir la démenteller.";
break;
case 8:
$message = "Dépassement de capacité.<br />Vous ne pouvez pas demander la construction d'autant d'unités en même temps.";
break;
}
break;
}
}
else
$message = $branche;
if ($debug || empty($message))
$message = "Erreur #".intval($branche)."/".$code." :<br />".$message;
global $template, $page;
if (!empty($page))
$template->assign('page', $page);
$template->assign('message', $message);
$template->assign('couleur', 'red');
$template->display('game/erreur.tpl');
exit;
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,639 @@
<?php
include_once("game/Class/class.rapport.php");
/***************************************************************************
* class.flotte.php
* ------------------
* begin : Samedi 20 septembre 2008
* update : Samedi 20 septembre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Flotte
{
var $id_flotte = 0,
$nom,
$start_planete,
$start_time,
$end_planete,
$end_time,
$end_type,
$ret_planete,
$ret_time,
$nb_vais,
$vaisseaux = array(),
$tactique = 0,
$mission,
$vitesse,
$statut = 0,
$last,
$contenu = array(0,0,0),
$contenuMax = 0,
$modifFlotte = array();
/**
* Constructeur
* @param int $id id de la flotte à importer
* @param bool $verrou Booléen disant si la classe doit obtenir préalablement un verrou pour la flotte.
*
* @return void
* @access public
*/
function __construct($id = 0, $verrou = true)
{
if (!empty($id))
{
global $table_flottes;
global $nomvaisnVAR, $ressoVAR;
$id = intval($id);
$bdd = new BDD();
$flotte = $bdd->unique_query("SELECT * FROM $table_flottes WHERE id = $id;");
if ($verrou)
$bdd->query("UPDATE $table_flottes SET last = ".time()." WHERE id = $id;"); //Obtention d'un vérrou de 10 seconde sur la flotte
$bdd->deconnexion();
if (!empty($flotte))
{
$this->id_flotte = $flotte["id"];
$this->nom = $flotte["nom"];
$this->start_planete = $flotte["start_planete"];
$this->start_time = $flotte["start_time"];
$this->end_planete = $flotte["end_planete"];
$this->end_type = $flotte["end_type"];
$this->end_time = $flotte["end_time"];
$this->ret_planete = $flotte["ret_planete"];
$this->ret_time = $flotte["ret_time"];
$this->tactique = $flotte["tactique"];
$this->mission = $flotte["mission"];
$this->vitesse = $flotte["vitesse"];
$this->statut = $flotte["statut"];
$this->last = $flotte["last"];
$this->nb_vais = $flotte["nb_vais"];
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $flotte[$vais];
$this->contenu = array($flotte["contenu_metal"], $flotte["contenu_cristal"], $flotte["contenu_hydrogene"]);
$this->calculer();
}
}
}
function calculer()
{
global $nomvais_rs;
$this->nb_vais = 0;
//Calcul de la capacité maximale d'embarquement de la flotte
foreach($this->vaisseaux as $key => $vais)
{
$this->nb_vais += $vais;
$this->contenuMax += $nomvais_rs[$key] * $vais;
}
}
function load_planete()
{
if (is_numeric($this->start_planete) && !empty($this->start_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->start_planete)
$this->start_planete = $planete;
else
$this->start_planete = new Planete($this->start_planete);
}
if (is_numeric($this->end_planete) && !empty($this->end_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Planete($this->end_planete);
}
if (is_numeric($this->ret_planete) && !empty($this->ret_planete))
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if ($planete->id == $this->ret_planete)
$this->ret_planete = $planete;
else
$this->ret_planete = new Planete($this->ret_planete);
}
}
function calc_deplacement($start_galaxie, $start_systeme, $start_position, $end_galaxie, $end_systeme, $end_position, $vitesse, $returnArray = false, $returnConso = false)
{
//Si la planète de départ n'est pas chargée, on charge les planètes
if (is_numeric($this->start_planete))
$this->load_planete();
global $config, $nomvais_vitesseP, $nomvais_vitesseS, $nomvais_vitesseG, $nomvais_rs;
$this->vitesse = $vitesse;
//Calcul de la longueur du déplacement
$diff_galaxie = abs($start_galaxie - $end_galaxie);
$diff_systeme = abs($start_systeme - $end_systeme);
$diff_position = abs($start_position - $end_position);
$diff_centre_position_start = abs(ceil($config['nb_amas']/2) - $start_position);
$diff_centre_systeme_start = abs(ceil($config['nb_systeme']/2) - $start_systeme);
$diff_centre_position_end = abs(ceil($config['nb_amas']/2) - $end_position);
$diff_centre_systeme_end = abs(ceil($config['nb_systeme']/2) - $end_systeme);
//Calcul du temps de déplacement pour chaque vaisseau
$temps = array(); $conso = array(0, 0, 0);
foreach($this->vaisseaux as $key => $vais)
{
//S'il n'y a pas de vaisseaux de ce type, on ne calcul pas leur vitesse
if ($vais == 0)
continue;
//Calcul du temps de déplacement entre planètes
if ($start_systeme == $end_systeme && $start_galaxie == $end_galaxie)
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * $diff_position);
$temps[1][$key] = $temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre système
elseif ($start_galaxie == $end_galaxie)
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (20/$nomvais_vitesseS[$key]) * (2 + 1 * $diff_systeme);
$temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre galaxies
else
{
$temps[0][$key] = (10/$nomvais_vitesseP[$key]) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (20/$nomvais_vitesseS[$key]) * (2 + 1 * ($diff_centre_systeme_start + $diff_centre_systeme_end));
$temps[2][$key] = (50/$nomvais_vitesseG[$key]) * (2 + 1.5 * $diff_galaxie);
}
//Calcul du bonus pour le réacteur à combustion
$techR = $this->start_planete->technologies[1];
if ($techR & 56)
$bonus = 0.7;
elseif ($techR & 24)
$bonus = 0.8;
elseif ($techR & 8)
$bonus = 0.9;
else
$bonus = 1;
$temps[0][$key] *= $bonus * 1/$vitesse;
$conso[0] += $vais * $temps[0][$key] * $bonus / exp($vitesse/5);
//Calcul du bonus pour le réacteur à fusion
$techR = $this->start_planete->technologies[1];
if ($techR &448)
$bonus = 0.7;
elseif ($techR &192)
$bonus = 0.8;
elseif ($techR &64)
$bonus = 0.9;
else
$bonus = 1;
$temps[1][$key] *= $bonus * 1/$vitesse;
$conso[1] += $vais * $temps[1][$key] * $bonus / exp($vitesse/7.5);
//Calcul du bonus pour le réacteur à fusion de type II
$techR = $this->start_planete->technologies[1];
if ($techR &3584)
$bonus = 0.7;
elseif ($techR &1536)
$bonus = 0.8;
elseif ($techR &512)
$bonus = 0.9;
else
$bonus = 1;
$temps[2][$key] *= $bonus * 1/$vitesse;
$conso[2] += $vais * $temps[2][$key] * $bonus / exp($vitesse/10);
}
if (!isset($this->vaisseaux[4]))
$this->vaisseaux[4] = 0;
if (!isset($this->vaisseaux[5]))
$this->vaisseaux[5] = 0;
//Si les chasseurs peuvent rentrer dans les cales des vaisseaux, on les enlèves
if ($this->contenuMax - ($this->contenu[0] + $this->contenu[1] + $this->contenu[2]) - ($this->vaisseaux[4] * $nomvais_rs[4] + $this->vaisseaux[5] * $nomvais_rs[5]) >= ($this->vaisseaux[4] + $this->vaisseaux[5]) * 200)
$temps[2][4] = $temps[2][5] = $temps[1][4] = $temps[1][5] = $temps[0][4] = $temps[0][5] = 0;
//On calcul le temps de déplacement maximal
if ($returnArray)
return $temps;
elseif ($returnConso)
return array(max($temps[0]) + max($temps[1]) + max($temps[2]), ceil($conso[0]+$conso[1]+$conso[2]));
else
return (max($temps[0]) + max($temps[1]) + max($temps[2]));
}
function check_mission()
{
//On vérifie qu'un calcul ne soit pas déjà en cours
if ($this->last >= time() - 10)
return false;
elseif ($this->start_time + $this->end_time > time())
return false;
if ($this->statut == 0)
{
switch($this->mission)
{
case 0:
$this->stationner();
break;
case 1:
$this->transporter();
break;
case 2:
$this->coloniser();
break;
case 3:
$this->attaquer();
break;
case 4:
$this->recycler();
break;
case 5:
$this->espionner();
break;
}
}
if ($this->statut == 1 && ($this->ret_time > time() || $this->start_time + $this->end_time * 2 <= time()))
$this->retourner();
return true;
}
function stationner()
{
//On décharge les ressources éventuellement contenue
$this->decharger();
//On fait atterir les vaisseaux
foreach ($this->vaisseaux as $key => $vais)
$this->end_planete->vaisseaux[$key] += $vais;
if (!in_array("vaisseaux", $this->end_planete->modif))
$this->end_planete->modif[] = "vaisseaux";
$this->modifFlotte = "DELETE";
}
function transporter()
{
$max = $this->decharger();
//Envoie du MP de confirmation au joueur
$send = new Rapport(2, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$send->addInfo($this->end_planete, 0);
$send->addInfo($max, 1);
$send->sendTransport();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function coloniser()
{
//On vérifie que les coordonnées de la planètes sont bien enregistrée
if (empty($this->end_planete) || is_object($this->end_planete) || !preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $this->end_planete))
{
$this->load_planete();
file_log("Erreur de colonisation de la planète : ".$this->end_planete." pour le joueur : ".$this->start_planete->id_user, 2);
send_mp($this->start_planete->id_user, "Erreur de colonisation [F#01]", "Une erreur s'est produite lors de la tentative de colonisation de votre flotte, elle a fait demi-tour.");
$this->rappeler();
}
//On vérifie que la planète ne soit pas déjà colonisée
global $table_planete;
preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $this->end_planete, $position);
$bdd = new BDD();
$p = $bdd->query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
if ($p)
{
$this->load_planete();
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(false, 1);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
else
{
$this->load_planete();
//On crée la planète
$this->end_planete = new Planete(false);
$this->end_planete->galaxie = $position[1];
$this->end_planete->ss = $position[2];
$this->end_planete->position = $position[3];
$this->end_planete->creer($this->start_planete->id_user);
//Rembousement du carburant non utilisé (la colonisation prévois au départ un allé/retour)
$conso = $this->calc_deplacement($this->start_planete->galaxie, $this->start_planete->ss, $this->start_planete->position, $position[1], $position[2], $position[3], $this->vitesse, false, true);
$this->end_planete->hydrogene += $conso[1];
//On définit la limite de ressources pour permettre le déchargement de celles contenues dans les vaisseaux
$this->end_planete->cap = 100000;
//On enlève un vaisseau de colonisation de la liste
$this->vaisseaux[2]--;
//On fait atterir les vaisseaux et décharger les ressources
$this->decharger();
$this->atterir();
//On envoie un rapport
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(true, 1);
$rapport->send();
}
}
function recycler()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
$coeff = ($this->contenuMax - $this->contenu[0] - $this->contenu[1] - $this->contenu[2])/($this->end_planete->debris_met + $this->end_planete->debris_cri);
if ($coeff > 1)
$coeff = 1;
$a = floor($this->end_planete->debris_met * $coeff);
$b = floor($this->end_planete->debris_cri * $coeff);
$this->contenu[0] += $a;
$this->contenu[1] += $b;
if (!in_array('contenu', $this->modifFlotte))
$this->modifFlotte[] = 'contenu';
$this->end_planete->debris_met -= $a;
$this->end_planete->debris_cri -= $b;
if (!in_array('debris_met', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_met';
if (!in_array('debris_cri', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_cri';
//Send link
$rapport = new Rapport(4, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo(array($a, $b), 1);
$rapport->send();
$this->statut = 1;
if (!in_array('statut', $this->modifFlotte))
$this->modifFlotte[] = 'statut';
}
function espionner()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
//Extraction des niveaux technologique des deux adversaires
if (($this->start_planete->technologies[1]& 67108864) == 67108864)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 33554432) == 33554432)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 16777216) == 16777216)
$espionnage_A = 3;
else
$espionnage_A = 0;
if (($this->start_planete->technologies[1]& 536870912) == 536870912)
$contreespionnage_B = 3;
elseif (($this->start_planete->technologies[1]& 268435456) == 268435456)
$contreespionnage_B = 2;
elseif (($this->start_planete->technologies[1]& 134217728) == 134217728)
$contreespionnage_B = 1;
else
$contreespionnage_B = 0;
//Création du rapport
$rapport = new Rapport(5, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo($contreespionnage_B/$espionnage_A/10, 1);
$rapport->addInfo($espionnage_A+2-$contreespionnage_B+1, 2);
$rapport->addInfo($contreespionnage_B, 3);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function decharger($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
$max = array(0, 0, 0);
//Si on dépasse les capacités, on laisse les ressources en trop dans le cargo
if ($this->$plan->metal + $this->contenu[0] > $this->$plan->cap)
{
$max[0] = $this->$plan->cap - $this->$plan->metal;
if ($max[0] < 0) $max[0] = 0;
}
else
$max[0] = $this->contenu[0];
$this->$plan->metal += $max[0];
$this->contenu[0] -= $max[0];
if ($this->$plan->cristal + $this->contenu[1] > $this->$plan->cap)
{
$max[1] = $this->$plan->cap - $this->$plan->cristal;
if ($max[1] < 0) $max[1] = 0;
}
else
$max[1] = $this->contenu[1];
$this->$plan->cristal += $max[1];
$this->contenu[1] -= $max[1];
if ($this->$plan->hydrogene + $this->contenu[2] > $this->$plan->cap)
{
$max[2] = $this->$plan->cap - $this->$plan->hydrogene;
if ($max[2] < 0) $max[2] = 0;
}
else
$max[2] = $this->contenu[2];
$this->$plan->hydrogene += $max[2];
$this->contenu[2] -= $max[2];
$this->$plan->addModif("force");
$this->addModifFlotte("contenu");
return $max;
}
function atterir($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
if (isset($this->$plan->vaisseaux[0]))
{
foreach ($this->vaisseaux as $key => $vais)
$this->$plan->vaisseaux[$key] += $vais;
}
else
$this->$plan->vaisseaux = $this->vaisseaux;
$this->$plan->addModif("vaisseaux");
$this->modifFlotte = "DELETE";
}
function rappeler()
{
if ($this->start_time + $this->end_time >= time())
return false;
else
{
$this->end_time = time() - $this->start_time + 10;
$this->mission = 5;
if (!in_array('mission', $this->modifFlotte))
$this->modifFlotte[] = 'mission';
if (!in_array('end_time', $this->modifFlotte))
$this->modifFlotte[] = 'end_time';
return true;
}
}
function retourner()
{
//Si la planète de départ n'est pas chargée, on charge les planètes
if (is_numeric($this->start_planete))
$this->load_planete();
//Si on a demandé une planète particulière au retour
if (!empty($this->ret_time) && !empty($this->ret_planete) && !is_numeric($this->ret_planete))
{
$this->decharger("ret_planete");
$this->atterir("ret_planete");
}
//Si le retour se fait sur la planète source
else
{
$this->decharger("start_planete");
$this->atterir("start_planete");
}
$this->modifFlotte = "DELETE";
}
function addModifFlotte($modif)
{
if (!in_array($modif, $this->modifFlotte))
$this->modifFlotte[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
global $table_flottes;
if ($this->modifFlotte === "DELETE")
{
$bdd = new BDD();
$bdd->query("DELETE FROM $table_flottes WHERE id = ".$this->id_flotte.";");
$bdd->deconnexion();
}
else
{
if (empty($this->id_flotte))
{
if ($this->modifFlotte == "INSERT")
{
$out1 = ''; $out2 = '';
global $nomvaisnVAR;
foreach ($this->vaisseaux as $key => $vais)
{
$out1 .= ', '.$nomvaisnVAR[$key];
$out2 .= ', '.$vais;
}
$sql = "INSERT INTO $table_flottes (id_user, mission, start_time, start_planete, end_time, end_type, end_planete, vitesse, contenu_metal, contenu_cristal, contenu_hydrogene, tactique, nom, nb_vais$out1) VALUES ('".$this->start_planete->id_user."', '".$this->mission."', '".$this->start_time."', '".$this->start_planete->id."', '".$this->end_time."', '".$this->end_type."', '".$this->end_planete."', '".$this->vitesse."', '".$this->contenu[0]."', '".$this->contenu[1]."', '".$this->contenu[2]."', '".$this->tactique."', '".$this->nom."', ".$this->nb_vais."$out2);";
if (DEBUG) var_dump($sql);
$bdd = new BDD();
$bdd->query($sql);
$bdd->deconnexion();
}
}
elseif(isset($this->modifFlotte[0]))
{
$out = array();
$bdd = new BDD();
foreach($this->modifFlotte as $modif)
{
if (!is_array($this->{$modif}))
{
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] .= $modif." = ".$this->{$modif};
else
{
$bdd->escape($this->{$modif});
$out[] .= $modif." = '".$this->{$modif}."'";
}
}
else
{
if ($modif == "contenu")
$calc = "resso";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach(${$calc.'VAR'} as $key => $var)
{
$bdd->escape($this->{$modif}[$key]);
$out[] = ${$calc.'VAR'}[$key]." = ".$this->{$modif}[$key];
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_flottes SET ".implode(', ', $out).", last = 0 WHERE id = ".$this->id_flotte.";";
if (DEBUG) var_dump($sql);
$bdd->query($sql);
}
$bdd->deconnexion();
}
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,868 @@
<?php
//Gestion des dépendances, on importe les classes nécessaires à la classe en cours
include_once("game/Class/class.surface.php");
include_once("game/Class/class.file.php");
/***************************************************************************
* class.planete.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Planete extends Surface
{
private $timestamp_lastSilo,
$timestamp_lastMineM,
$timestamp_lastMineC,
$timestamp_lastMineH;
public $position,
$nom_planete,
$cases,
$casesRest,
$cap,
$population,
$population_max,
$moral,
$energie,
$energieConso,
$file_tech,
$file_cas,
$file_ter,
$coeff_bat = array(),
$casernes = array(),
$terrestres = array();
/**
* Constructeur
* @param mixed $id id de la planète à importer/coordonnées
* @param bool $first Bloquer l'affichage des messages d'erreurs
*
* @return void
* @access public
*/
function __construct($id, $first = false)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new bdd();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if ($id === false)
$bdd->deconnexion();
elseif (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
parent::User($plan["id_user"]);
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
if (!empty($plan["isolement"])) $this->isolement = unserialize($plan["isolement"]);
else $this->isolement = array();
$this->nom_planete = $plan["nom_planete"];
$this->image = $plan["image"];
$this->cases = $plan["cases"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
$this->population = $plan["population"];
$this->moral = $plan["moral"];
$this->timestamp = $plan["timestamp"];
//Chargement des variables de conversion
global $batimentVAR, $casernenVAR, $nomterrnVAR, $nomvaisnVAR;
$this->casesRest = $this->cases; //Calcul du nombre de cases en même temps
foreach($batimentVAR as $bat)
{
$this->batiments[] = $plan[$bat];
$this->casesRest -= $plan[$bat];
}
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new File('batiments');
$this->coeff_bat = array($plan["coeff_mine_m"], $plan["coeff_mine_c"], $plan["coeff_mine_h"], $plan["coeff_centrale_s"], $plan["coeff_centrale_f"]);
//On vérifie que les coefficient ne soient pas supérieurs à 1 ou inférieurs à 0
for($i = 0; $i < 5; $i++)
{
if ($this->coeff_bat[$i] > 1)
$this->coeff_bat[$i] = 1;
elseif ($this->coeff_bat[$i] < 0)
$this->coeff_bat[$i] = 0;
}
if (!empty($plan["file_tech"]))
$this->file_tech = unserialize($plan["file_tech"]);
else
$this->file_tech = new File('technologies');
foreach($casernenVAR as $cas)
$this->casernes[] = $plan[$cas];
if (!empty($plan["file_cas"]))
$this->file_cas = unserialize($plan["file_cas"]);
else
$this->file_cas = new File('casernes');
foreach($nomterrnVAR as $ter)
$this->terrestres[] = $plan[$ter];
if (!empty($plan["file_ter"]))
$this->file_ter = unserialize($plan["file_ter"]);
else
$this->file_ter = new File('terrestres');
foreach($nomvaisnVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new File('vaisseaux');
//Calcul de la population logée
$this->population_max = (pow($this->batiments[12],1.5)+pow($this->batiments[13],2.1))*1000+3000;
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true, $first = false)
{
//Détermination des capacités maximales
$this->cap = pow(2, $this->batiments[10]) * 100000;
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_bat->batiment_ready($this);
$this->file_tech->technologie_ready($this);
$this->file_cas->caserne_ready($this);
$this->file_ter->terrestre_ready($this);
$this->file_vais->vaisseaux_ready($this);
}
if (!empty($this->timestamp_lastSilo))
{
$this->cap = pow(2, $this->batiments[10]-1) * 100000;
$capnouv = pow(2, $this->batiments[10]) * 100000;
}
//Calcul du temps écoulé depuis la dernière mise à jour de la planète
$temps_ecoule = time() - $this->timestamp;
$ressources = $this->production($temps_ecoule);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
$this->metal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->metal + $ressources[0] < $capnouv)
$this->metal += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->metal = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->metal = $this->cap;
}
}
if ($this->cristal + $ressources[1] < $this->cap)
$this->cristal += $ressources[1];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->cristal + $ressources[0] < $this->cap)
$this->cristal += $ressources[0];
else
$this->cristal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->cristal + $ressources[0] < $capnouv)
$this->cristal += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->cristal = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->cristal = $this->cap;
}
}
if ($this->hydrogene + $ressources[2] < $this->cap)
$this->hydrogene += $ressources[2];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->hydrogene + $ressources[0] < $this->cap)
$this->hydrogene += $ressources[0];
else
$this->hydrogene = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->hydrogene + $ressources[0] < $capnouv)
$this->hydrogene += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->hydrogene = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->hydrogene = $this->cap;
}
}
//Vérification de la date pour faire les actions journalières
if (date('zya') != date('zya', $this->timestamp)) //Mise à jour trois fois par jour : 0h, 1h, 13h
//if (date('zy') != date('zy', $this->timestamp)) //Mise à jour une fois par jour : 0h
{
//On évalue le moral
$this->evalMoral($first);
//Si la population est à 0, on ajoute des habitants
if ($this->population <= 0)
$this->population = 1000;
$popPlus = $this->population * 0.0153^max(1, floor((time()-$this->timestamp)/86400));
if ($this->politique == 2)
$popPlus *= 1.1; //Communisme : 10 % de population qui arrive en plus.
elseif ($this->politique == 3)
$popPlus *= 1.05; //Démocratie : 5 % de population qui arrive en plus.
if ($this->technologies[2] & 4)
$popPlus *= 1.15;
elseif ($this->technologies[2] & 2)
$popPlus *= 1.10;
elseif ($this->technologies[2] & 1)
$popPlus *= 1.05;
$this->population += $popPlus;
$this->addCredits(($this->population/100*exp(0.01)*25) + ($this->population*0.01*$this->batiments[15])); //Première partie : production normale; seconde : batiment commercial
$this->addModif("population");
}
$this->timestamp = time();
}
function setMoral($difference)
{
$this->moral += $difference;
//Ajustement du moral
if ($this->moral > 1)
$this->moral = 1;
elseif ($this->moral < 0)
$this->moral = 0;
$this->addModif("moral");
}
function evalMoral($first = false)
{
$evolution = array();
//Cas de sous-production
if (($this->coeff_bat[0] + $this->coeff_bat[1] + $this->coeff_bat[2])/3 < 0.9)
{
if ($this->politique == 2)
$this->moral -= 0.10; //Communisme : démoralise 2x plus
else
$this->moral -= 0.05;
$this->addModif("moral");
}
//Surpopulation
//Surlogement
//Effets des batiments loisirs et commerces
$this->moral += 0.0025*$this->batiments[15] + 0.1*$this->batiments[16];
//Ajustement du moral en fonction de la politique
if ($this->politique == 1 && $this->moral > 0.7)
$this->moral = 0.7;
//On vérifie qu'on ne dépasse pas le maximum
if ($this->moral > 1)
$this->moral = 1;
if ($this->moral < 0)
$this->moral = 0;
//Isolement si besoin
if ($this->moral < 0.1)
{
//On vérifie qu'il ne s'agit pas de la planète mère
global $table_planete;
$bdd = new Bdd();
$bdd->reconnexion();
$res = $bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = ".$this->id_user." ORDER BY id LIMIT 1;");
$bdd->deconnexion();
if ($res['id'] != $this->id)
{
if ($this->moral <= 0.04)
{
if ($this->moral <= 0.01)
$rand = rand(0,4);
else
$rand = rand(0,20);
//Perte de la planète
if ($rand == 1)
{
$bdd->reconnexion();
$bdd->query("DELETE FROM $table_planete WHERE id = ".$this->id.";");
$bdd->deconnexion();
send_mp($this->id_user, 'Perte de contrôle de '.$this->nom_planete, "Suite à une démoralisation persistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a renversé votre gouvernement en tuant tous vos gouverneurs. Vous perdez donc définitivement le contrôle de cette planète.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révolté contre vous. Vous ne contrôlez plus cette planète.');
}
}
}
elseif ($this->moral <= 0.1)
{
if ($this->moral <= 0.06)
$rand = rand(0,2);
else
$rand = rand(0,10);
//Perte de contrôle temporaire
if ($rand == 1)
{
$debut = time() - rand(0, 3600)*4;
$fin = $debut + 86400;
$this->isolement = array($debut, $fin);
$this->addModif("isolement");
send_mp($this->id_user, 'Perte de contrôle temporaire de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a pris le contrôle de votre planète. Vous perdez le contrôle de cette planète le temps que vos gouverneurs reprennent le pouvoir.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révoltée contre vous. Vous perdez temporairement le contrôle de cette planète.');
}
}
}
}
}
}
function checkAndRetireRessources($metal, $cristal, $hydrogene, $credits)
{
if ($this->metal >= $metal && $this->cristal >= $cristal && $this->hydrogene >= $hydrogene && $this->credits >= $credits)
{
$this->metal -= $metal;
$this->cristal -= $cristal;
$this->hydrogene -= $hydrogene;
if (!empty($credits))
{
$this->credits -= $credits;
$this->addModifUser("credits");
}
return true;
}
else
return false;
}
function addRessources($metal, $cristal, $hydrogene)
{
$perte = 0;
$this->metal += $metal;
if ($this->metal > $this->cap)
{
$perte += $this->metal - $this->cap;
$this->metal = $this->cap;
}
$this->cristal += $cristal;
if ($this->cristal > $this->cap)
{
$perte += $this->cristal - $this->cap;
$this->cristal = $this->cap;
}
$this->hydrogene += $hydrogene;
if ($this->hydrogene > $this->cap)
{
$perte += $this->hydrogene - $this->cap;
$this->hydrogene = $this->cap;
}
return $perte;
}
/**
* Vérifie si la planète est isolée ou non
*
* @return boolean
* @access public
*/
function isolement()
{
$return = false;
global $queryPlanetes;
//Détermination du numéro de la planète par rapport aux autres, dans l'ordre de colonisation
$numP = 0;
foreach ($queryPlanetes as $key => $p)
{
if ($p['id'] == $this->id)
$numP = $key + 1;
}
if ($numP >= 11)
{
if (!isset($this->isolement[0]) || (time() > $this->isolement[0] && (!isset($this->isolement[1]) || (time() > $this->isolement[1] && date('dmY') != date('dmY', $this->isolement[0])))))
{
switch($numP)
{
case 11:
$tps = 2;
break;
case 12:
$tps = 4;
break;
case 13:
$tps = 6;
break;
case 14:
$tps = 8;
break;
case 15:
$tps = 12;
break;
case 16:
$tps = 16;
break;
case 17:
$tps = 20;
break;
default:
$tps = 24;
}
$debut = mktime(rand(0, 24-$tps), 0, 0, date('n'), date('j'), date('Y'));
$fin = $debut + $tps * 3600;
$this->isolement[0] = $debut;
if (time() > $this->isolement[0])
$this->isolement[1] = $fin;
$this->addModif("isolement");
}
if (isset($this->isolement[1]) && time() < $this->isolement[1])
$return = true;
}
elseif (!isset($this->isolement[0]))
{
$this->isolement = array(0,0);
$this->addModif("isolement");
}
return $return;
}
/**
* Calcul les ressources produites en fonction de $temps_ecoule
* @param int $temps_ecoule Temps écoulé depuis la dernière actualisation
*
* @return array
* @access public
*/
function production($temps_ecoule, $retarray = false)
{
//Accélération de la production
$temps_ecoule *= VITESSE;
//Calcul de la consomation d'énergie
if ($this->batiments[0] > 0)
$energie_m = ceil(exp(0.28*$this->batiments[0])*10);
else
$energie_m = 0;
if ($this->batiments[1] > 0)
$energie_c = ceil(exp(0.28*$this->batiments[1])*10);
else
$energie_c = 0;
if ($this->batiments[2] > 0)
$energie_h = ceil(exp(0.2849*$this->batiments[2])*13);
else
$energie_h = 0;
if ($this->batiments[3] > 0)
$energie_s = ceil(exp(0.28*$this->batiments[3])*22);
else
$energie_s = 0;
if ($this->batiments[4] > 0)
$energie_f = ceil(exp(0.297*$this->batiments[4])*25);
else
$energie_f = 0;
//Calcul de la consomation d'énergie
$this->energieConso = $energie_m * $this->coeff_bat[0] + $energie_c * $this->coeff_bat[1] + $energie_h * $this->coeff_bat[2];
$nrjmx = $energie_m + $energie_c + $energie_h;
//Calcul de la production d'énergie
$this->energie = $energie_s * $this->coeff_bat[3] + $energie_f * $this->coeff_bat[4];
if ($this->energieConso == 0)
$coeff = 0;
else
$coeff = $this->energie / $this->energieConso;
if ($coeff < 0)
$coeff = 0;
elseif ($coeff > 1)
$coeff = 1;
$Ncoeff = array();
for($i = 0; $i < 3; $i++)
{
$Ncoeff[$i] = $coeff * $this->coeff_bat[$i];
if ($Ncoeff[$i] > 1)
$Ncoeff[$i] = 1;
if ($Ncoeff[$i] < $this->coeff_bat[$i] && $this->batiments[$i] != 0)
{
$this->coeff_bat[$i] = $Ncoeff[$i];
$this->addModif("coeff_bat");
}
}
//Calcul de la consomation d'hydrogène
if ($this->batiments[4] > 0)
$conso_h = ((ceil(pow(1.34,($this->batiments[4]-1))*9)/3600)*$temps_ecoule) * $this->coeff_bat[4];
else
$conso_h = 0;
//Calcul des production de ressources
if ($this->batiments[0] <= 0 || $this->batiments[3] <= 0)
$prod_met = 0.011 * $temps_ecoule;
else
$prod_met = ((ceil(pow(1.1, $this->batiments[0]) * 52 * $this->batiments[0]) / 3600) * $temps_ecoule) * $this->coeff_bat[0];
if ($this->batiments[1] <= 0 || $this->batiments[3] <= 0)
$prod_cri = 0.0055 * $temps_ecoule;
else
$prod_cri = ((ceil(pow(1.1, $this->batiments[1]) * 34 * $this->batiments[1]) / 3600) * $temps_ecoule) * $this->coeff_bat[1];
if ($this->batiments[2] <= 0)
$prod_hy = 0;
else
$prod_hy = ((ceil(pow(1.1, $this->batiments[2]) * 21 * ($this->batiments[2] + 0.7)) / 3600) * $temps_ecoule) * $this->coeff_bat[2];
//Augmentation de la production en fonction des technologies
if ($this->technologies[0] &4)
{
$prod_met *= 1.15;
$prod_cri *= 1.15;
$prod_hy *= 1.15;
}
elseif ($this->technologies[0] &2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
elseif ($this->technologies[0] &1)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
//Rendement métal
if ($this->technologies[0] &64)
$prod_met *= 1.3;
elseif ($this->technologies[0] &32)
$prod_met *= 1.2;
elseif ($this->technologies[0] &16)
$prod_met *= 1.1;
//Rendemant cristal
if ($this->technologies[0] &512)
$prod_cri *= 1.3;
elseif ($this->technologies[0] &256)
$prod_cri *= 1.2;
elseif ($this->technologies[0] &128)
$prod_cri *= 1.1;
//Rendement hydrogène
if ($this->technologies[0] &4096)
$prod_hy *= 1.3;
elseif ($this->technologies[0] &2048)
$prod_hy *= 1.2;
elseif ($this->technologies[0] &1024)
$prod_hy *= 1.1;
//Augmentation de la production en fonction du moral
if ($this->moral > 0.9)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
elseif ($this->moral > 0.75)
{
$prod_met *= 1.02;
$prod_cri *= 1.02;
$prod_hy *= 1.02;
}
elseif ($this->moral < 0.45)
{
$prod_met *= 0.97;
$prod_cri *= 0.97;
$prod_hy *= 0.97;
}
elseif ($this->moral < 0.25)
{
$prod_met *= 0.94;
$prod_cri *= 0.94;
$prod_hy *= 0.94;
}
//Augmentation de la production en fonction de la politique
if ($this->politique == 2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
//On enlève la consomation d'hydrogène
$prod_hy -= $conso_h;
if ($retarray)
return array(array(ceil($this->coeff_bat[0]*100), ceil($this->coeff_bat[1]*100), ceil($this->coeff_bat[2]*100), ceil($this->coeff_bat[3]*100), ceil($this->coeff_bat[4]*100)), array($prod_met, $prod_cri, $prod_hy + $conso_h, $energie_s*$this->coeff_bat[3], $energie_f*$this->coeff_bat[4]), array($energie_m*$this->coeff_bat[0], $energie_c*$this->coeff_bat[1], $energie_h*$this->coeff_bat[2], $conso_h, ($energie_s*$this->coeff_bat[3] + $energie_f*$this->coeff_bat[4])-($energie_m*$this->coeff_bat[0] + $energie_c*$this->coeff_bat[1] + $energie_h*$this->coeff_bat[2])));
else
return array($prod_met, $prod_cri, $prod_hy);
}
function creer($id_user)
{
global $VAR;
//Définition des paramètres de l'utilisateur pour la planète
$this->id_user = $id_user;
//Génération du nombre de case et de l'image en fonction de la position dans le système
if ($this->position > $VAR['nb_planete']*0.75)
{
$this->cases = mt_rand(200,255);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/2)
{
$this->cases = mt_rand(250,300);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/4)
{
$this->cases = mt_rand(175,260);
$this->image = mt_rand(1,19);
}
else
{
$this->cases = mt_rand(150,220);
$this->image = mt_rand(1,19);
}
//Définition des principaux paramètres de la planète
$this->nom_planete = 'Planète colonisée';
$this->metal = 1000;
$this->cristal = 700;
$this->hydrogene = 0;
$this->modif = array("id_user", "nom_planete", "galaxie", "ss", "position", "image", "cases");
}
function addModif($modif)
{
if (!in_array($modif, $this->modif))
$this->modif[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->id_user))
return;
if ($this->id_user == 1)
var_dump($this);
global $var___db, $config, $table_planete;
if (empty($this->id))
{
$out1 = array(); $out2 = array();
$bdd = new bdd();
foreach($this->modif as $modif)
{
if ($modif == "force")
continue;
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$out1[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out2[] = $this->{$modif};
else
$out2[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out1[] = $modif;
$out2[] = "'$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technolo";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
elseif ($modif == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$out1[] = ${$calc.'VAR'}[$j];
$out2[] = $value;
}
}
}
}
$bdd->query("INSERT INTO $table_planete (".implode(', ', $out1).", hash_planete) VALUES (".implode(', ', $out2).", SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)))");
$bdd->deconnexion();
}
else
{
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
for($i = 0; $i < $nb; $i++)
{
if ($this->modif[$i] == "force")
$out[] = "timestamp = timestamp";
elseif ($this->modif[$i] == 'technologies')
$this->modifUser[] = $this->modif[$i];
elseif (is_object($this->{$this->modif[$i]}))
{
$export = serialize($this->{$this->modif[$i]});
$bdd->escape($export);
$out[] = $this->modif[$i]." = '".$export."'";
}
elseif (!is_array($this->{$this->modif[$i]}))
{
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]}))
$out[] = $this->modif[$i]." = ".$this->{$this->modif[$i]};
else
$out[] = $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else
{
if (is_array($this->{$this->modif[$i]}) && $this->modif[$i] != "coeff_bat" && $this->modif[$i] != "vaisseaux" && $this->modif[$i] != "terrestres" && $this->modif[$i] != "casernes" && $this->modif[$i] != "technologies" && $this->modif[$i] != "batiments")
{
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] = $this->modif[$i]." = '$prep'";
}
else
{
if ($this->modif[$i] == "batiments")
$calc = "batiment";
elseif ($this->modif[$i] == "technologies")
$calc = "technolo";
elseif ($this->modif[$i] == "casernes")
$calc = "casernen";
elseif ($this->modif[$i] == "terrestres")
$calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux")
$calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat")
$calc = "coeff";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++)
{
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] = ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_planete SET timestamp = ".time().", metal = ".$this->metal.", cristal = ".$this->cristal.", hydrogene = ".$this->hydrogene.", ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,796 @@
<?php
/*
* pop3.php
*
* @(#) $Header: /home/mlemos/cvsroot/pop3/pop3.php,v 1.23 2009/01/31 04:06:12 mlemos Exp $
*
*/
class pop3_class
{
var $hostname="localhost";
var $port=110;
var $tls=0;
var $quit_handshake=1;
var $error="";
var $authentication_mechanism="USER";
var $realm="";
var $workstation="";
var $join_continuation_header_lines=1;
/* Private variables - DO NOT ACCESS */
var $connection=0;
var $state="DISCONNECTED";
var $greeting="";
var $must_update=0;
var $debug=0;
var $html_debug=0;
var $next_token="";
var $message_buffer="";
var $connection_name = '';
/* Private methods - DO NOT CALL */
Function Tokenize($string,$separator="")
{
if(!strcmp($separator,""))
{
$separator=$string;
$string=$this->next_token;
}
for($character=0;$character<strlen($separator);$character++)
{
if(GetType($position=strpos($string,$separator[$character]))=="integer")
$found=(IsSet($found) ? min($found,$position) : $position);
}
if(IsSet($found))
{
$this->next_token=substr($string,$found+1);
return(substr($string,0,$found));
}
else
{
$this->next_token="";
return($string);
}
}
Function SetError($error)
{
return($this->error=$error);
}
Function OutputDebug($message)
{
$message.="\n";
if($this->html_debug)
$message=str_replace("\n","<br />\n",HtmlSpecialChars($message));
echo $message;
flush();
}
Function GetLine()
{
for($line="";;)
{
if(feof($this->connection))
return(0);
$line.=fgets($this->connection,100);
$length=strlen($line);
if($length>=2
&& substr($line,$length-2,2)=="\r\n")
{
$line=substr($line,0,$length-2);
if($this->debug)
$this->OutputDebug("S $line");
return($line);
}
}
}
Function PutLine($line)
{
if($this->debug)
$this->OutputDebug("C $line");
return(fputs($this->connection,"$line\r\n"));
}
Function OpenConnection()
{
if($this->tls)
{
$version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7");
$php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]);
if($php_version<4003000)
return("establishing TLS connections requires at least PHP version 4.3.0");
if(!function_exists("extension_loaded")
|| !extension_loaded("openssl"))
return("establishing TLS connections requires the OpenSSL extension enabled");
}
if($this->hostname=="")
return($this->SetError("2 it was not specified a valid hostname"));
if($this->debug)
$this->OutputDebug("Connecting to ".$this->hostname." ...");
if(($this->connection=@fsockopen(($this->tls ? "tls://" : "").$this->hostname, $this->port, $error, $error_message))==0)
{
switch($error)
{
case -3:
return($this->SetError("-3 socket could not be created"));
case -4:
return($this->SetError("-4 dns lookup on hostname \"$hostname\" failed"));
case -5:
return($this->SetError("-5 connection refused or timed out"));
case -6:
return($this->SetError("-6 fdopen() call failed"));
case -7:
return($this->SetError("-7 setvbuf() call failed"));
default:
return($this->SetError($error." could not connect to the host \"".$this->hostname."\": ".$error_message));
}
}
return("");
}
Function CloseConnection()
{
if($this->debug)
$this->OutputDebug("Closing connection.");
if($this->connection!=0)
{
fclose($this->connection);
$this->connection=0;
}
}
/* Public methods */
/* Open method - set the object variable $hostname to the POP3 server address. */
Function Open()
{
if($this->state!="DISCONNECTED")
return($this->SetError("1 a connection is already opened"));
if(($error=$this->OpenConnection())!="")
return($error);
$greeting=$this->GetLine();
if(GetType($greeting)!="string"
|| $this->Tokenize($greeting," ")!="+OK")
{
$this->CloseConnection();
return($this->SetError("3 POP3 server greeting was not found"));
}
$this->Tokenize("<");
$this->greeting = $this->Tokenize(">");
$this->must_update=0;
$this->state="AUTHORIZATION";
return("");
}
/* Close method - this method must be called at least if there are any
messages to be deleted */
Function Close()
{
if($this->state=="DISCONNECTED")
return($this->SetError("no connection was opened"));
while($this->state=='GETMESSAGE')
{
if(strlen($error=$this->GetMessage(8000, $message, $end_of_message)))
return($error);
}
if($this->must_update
|| $this->quit_handshake)
{
if($this->PutLine("QUIT")==0)
return($this->SetError("Could not send the QUIT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get quit command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not quit the connection: ".$this->Tokenize("\r\n")));
}
$this->CloseConnection();
$this->state="DISCONNECTED";
pop3_class::SetConnection(-1, $this->connection_name, $this);
return("");
}
/* Login method - pass the user name and password of POP account. Set
$apop to 1 or 0 wether you want to login using APOP method or not. */
Function Login($user,$password,$apop=0)
{
if($this->state!="AUTHORIZATION")
return($this->SetError("connection is not in AUTHORIZATION state"));
if($apop)
{
if(!strcmp($this->greeting,""))
return($this->SetError("Server does not seem to support APOP authentication"));
if($this->PutLine("APOP $user ".md5("<".$this->greeting.">".$password))==0)
return($this->SetError("Could not send the APOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get APOP login command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("APOP login failed: ".$this->Tokenize("\r\n")));
}
else
{
$authenticated=0;
if(strcmp($this->authentication_mechanism,"USER")
&& function_exists("class_exists")
&& class_exists("sasl_client_class"))
{
if(strlen($this->authentication_mechanism))
$mechanisms=array($this->authentication_mechanism);
else
{
$mechanisms=array();
if($this->PutLine("CAPA")==0)
return($this->SetError("Could not send the CAPA command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get CAPA command response"));
if(!strcmp($this->Tokenize($response," "),"+OK"))
{
for(;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the supported authentication methods"));
switch($this->Tokenize($response," "))
{
case ".":
break 2;
case "SASL":
for($method=1;strlen($mechanism=$this->Tokenize(" "));$method++)
$mechanisms[]=$mechanism;
break;
}
}
}
}
$sasl=new sasl_client_class;
$sasl->SetCredential("user",$user);
$sasl->SetCredential("password",$password);
if(strlen($this->realm))
$sasl->SetCredential("realm",$this->realm);
if(strlen($this->workstation))
$sasl->SetCredential("workstation",$this->workstation);
do
{
$status=$sasl->Start($mechanisms,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
break;
case SASL_NOMECH:
if(strlen($this->authentication_mechanism))
return($this->SetError("authenticated mechanism ".$this->authentication_mechanism." may not be used: ".$sasl->error));
break;
default:
return($this->SetError("Could not start the SASL authentication client: ".$sasl->error));
}
if(strlen($sasl->mechanism))
{
if($this->PutLine("AUTH ".$sasl->mechanism.(IsSet($message) ? " ".base64_encode($message) : ""))==0)
return("Could not send the AUTH command");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get AUTH command response");
switch($this->Tokenize($response," "))
{
case "+OK":
$response="";
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
for(;!$authenticated;)
{
do
{
$status=$sasl->Step($response,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
if($this->PutLine(base64_encode($message))==0)
return("Could not send message authentication step message");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get authentication step message response");
switch($this->Tokenize($response," "))
{
case "+OK":
$authenticated=1;
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
break;
default:
return($this->SetError("Could not process the SASL authentication step: ".$sasl->error));
}
}
}
}
if(!$authenticated)
{
if($this->PutLine("USER $user")==0)
return($this->SetError("Could not send the USER command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get user login entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("User error: ".$this->Tokenize("\r\n")));
if($this->PutLine("PASS $password")==0)
return($this->SetError("Could not send the PASS command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get login password entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Password error: ".$this->Tokenize("\r\n")));
}
}
$this->state="TRANSACTION";
return("");
}
/* Statistics method - pass references to variables to hold the number of
messages in the mail box and the size that they take in bytes. */
Function Statistics(&$messages,&$size)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("STAT")==0)
return($this->SetError("Could not send the STAT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get the statistics command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the statistics: ".$this->Tokenize("\r\n")));
$messages=$this->Tokenize(" ");
$size=$this->Tokenize(" ");
return("");
}
/* ListMessages method - the $message argument indicates the number of a
message to be listed. If you specify an empty string it will list all
messages in the mail box. The $unique_id flag indicates if you want
to list the each message unique identifier, otherwise it will
return the size of each message listed. If you list all messages the
result will be returned in an array. */
Function ListMessages($message,$unique_id)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($unique_id)
$list_command="UIDL";
else
$list_command="LIST";
if($this->PutLine("$list_command".($message ? " ".$message : ""))==0)
return($this->SetError("Could not send the $list_command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the message listing: ".$this->Tokenize("\r\n")));
if($message=="")
{
for($messages=array();;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list response"));
if($response==".")
break;
$message=intval($this->Tokenize($response," "));
if($unique_id)
$messages[$message]=$this->Tokenize(" ");
else
$messages[$message]=intval($this->Tokenize(" "));
}
return($messages);
}
else
{
$message=intval($this->Tokenize(" "));
$value=$this->Tokenize(" ");
return($unique_id ? $value : intval($value));
}
}
/* RetrieveMessage method - the $message argument indicates the number of
a message to be listed. Pass a reference variables that will hold the
arrays of the $header and $body lines. The $lines argument tells how
many lines of the message are to be retrieved. Pass a negative number
if you want to retrieve the whole message. */
Function RetrieveMessage($message,&$headers,&$body,$lines)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
for($headers=$body=array(),$line=0;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
case "":
break 2;
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
if($this->join_continuation_header_lines
&& $line>0
&& ($response[0]=="\t"
|| $response[0]==" "))
$headers[$line-1].=$response;
else
{
$headers[$line]=$response;
$line++;
}
}
for($line=0;;$line++)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
$body[$line]=$response;
}
return("");
}
/* OpenMessage method - the $message argument indicates the number of
a message to be opened. The $lines argument tells how many lines of
the message are to be retrieved. Pass a negative number if you want
to retrieve the whole message. */
Function OpenMessage($message, $lines=-1)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
$this->state="GETMESSAGE";
$this->message_buffer="";
return("");
}
/* GetMessage method - the $count argument indicates the number of bytes
to be read from an opened message. The $message returns by reference
the data read from the message. The $end_of_message argument returns
by reference a boolean value indicated whether it was reached the end
of the message. */
Function GetMessage($count, &$message, &$end_of_message)
{
if($this->state!="GETMESSAGE")
return($this->SetError("connection is not in GETMESSAGE state"));
$message="";
$end_of_message=0;
while($count>strlen($this->message_buffer)
&& !$end_of_message)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message headers"));
if(!strcmp($response,"."))
{
$end_of_message=1;
$this->state="TRANSACTION";
break;
}
else
{
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
$this->message_buffer.=$response."\r\n";
}
}
if($end_of_message
|| $count>=strlen($this->message_buffer))
{
$message=$this->message_buffer;
$this->message_buffer="";
}
else
{
$message=substr($this->message_buffer, 0, $count);
$this->message_buffer=substr($this->message_buffer, $count);
}
return("");
}
/* DeleteMessage method - the $message argument indicates the number of
a message to be marked as deleted. Messages will only be effectively
deleted upon a successful call to the Close method. */
Function DeleteMessage($message)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("DELE $message")==0)
return($this->SetError("Could not send the DELE command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message delete command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not delete the message: ".$this->Tokenize("\r\n")));
$this->must_update=1;
return("");
}
/* ResetDeletedMessages method - Reset the list of marked to be deleted
messages. No messages will be marked to be deleted upon a successful
call to this method. */
Function ResetDeletedMessages()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("RSET")==0)
return($this->SetError("Could not send the RSET command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get reset deleted messages command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not reset deleted messages: ".$this->Tokenize("\r\n")));
$this->must_update=0;
return("");
}
/* IssueNOOP method - Just pings the server to prevent it auto-close the
connection after an idle timeout (tipically 10 minutes). Not very
useful for most likely uses of this class. It's just here for
protocol support completeness. */
Function IssueNOOP()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("NOOP")==0)
return($this->SetError("Could not send the NOOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not NOOP command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not issue the NOOP command: ".$this->Tokenize("\r\n")));
return("");
}
Function &SetConnection($set, &$current_name, &$pop3)
{
static $connections = array();
if($set>0)
{
$current_name = strval(count($connections));
$connections[$current_name] = &$pop3;
}
elseif($set<0)
{
$connections[$current_name] = '';
$current_name = '';
}
elseif(IsSet($connections[$current_name])
&& GetType($connections[$current_name])!='string')
{
$connection = &$connections[$current_name];
return($connection);
}
return($pop3);
}
/* GetConnectionName method - Retrieve the name associated to an
established POP3 server connection to use as virtual host name for
use in POP3 stream wrapper URLs. */
Function GetConnectionName(&$connection_name)
{
if($this->state!="TRANSACTION")
return($this->SetError("cannot get the name of a POP3 connection that was not established and the user has logged in"));
if(strlen($this->connection_name) == 0)
pop3_class::SetConnection(1, $this->connection_name, $this);
$connection_name = $this->connection_name;
return('');
}
};
class pop3_stream
{
var $opened = 0;
var $report_errors = 1;
var $read = 0;
var $buffer = "";
var $end_of_message=1;
var $previous_connection = 0;
var $pop3;
Function SetError($error)
{
if($this->report_errors)
trigger_error($error);
return(FALSE);
}
Function ParsePath($path, &$url)
{
if(!$this->previous_connection)
{
if(IsSet($url["host"]))
$this->pop3->hostname=$url["host"];
if(IsSet($url["port"]))
$this->pop3->port=intval($url["port"]);
if(IsSet($url["scheme"])
&& !strcmp($url["scheme"],"pop3s"))
$this->pop3->tls=1;
if(!IsSet($url["user"]))
return($this->SetError("it was not specified a valid POP3 user"));
if(!IsSet($url["pass"]))
return($this->SetError("it was not specified a valid POP3 password"));
if(!IsSet($url["path"]))
return($this->SetError("it was not specified a valid mailbox path"));
}
if(IsSet($url["query"]))
{
parse_str($url["query"],$query);
if(IsSet($query["debug"]))
$this->pop3->debug = intval($query["debug"]);
if(IsSet($query["html_debug"]))
$this->pop3->html_debug = intval($query["html_debug"]);
if(!$this->previous_connection)
{
if(IsSet($query["tls"]))
$this->pop3->tls = intval($query["tls"]);
if(IsSet($query["realm"]))
$this->pop3->realm = UrlDecode($query["realm"]);
if(IsSet($query["workstation"]))
$this->pop3->workstation = UrlDecode($query["workstation"]);
if(IsSet($query["authentication_mechanism"]))
$this->pop3->realm = UrlDecode($query["authentication_mechanism"]);
}
if(IsSet($query["quit_handshake"]))
$this->pop3->quit_handshake = intval($query["quit_handshake"]);
}
return(TRUE);
}
Function stream_open($path, $mode, $options, &$opened_path)
{
$this->report_errors = (($options & STREAM_REPORT_ERRORS) !=0);
if(strcmp($mode, "r"))
return($this->SetError("the message can only be opened for reading"));
$url=parse_url($path);
$host = $url['host'];
$pop3 = &pop3_class::SetConnection(0, $host, $this->pop3);
if(IsSet($pop3))
{
$this->pop3 = &$pop3;
$this->previous_connection = 1;
}
else
$this->pop3=new pop3_class;
if(!$this->ParsePath($path, $url))
return(FALSE);
$message=substr($url["path"],1);
if(strcmp(intval($message), $message)
|| $message<=0)
return($this->SetError("it was not specified a valid message to retrieve"));
if(!$this->previous_connection)
{
if(strlen($error=$this->pop3->Open()))
return($this->SetError($error));
$this->opened = 1;
$apop = (IsSet($url["query"]["apop"]) ? intval($url["query"]["apop"]) : 0);
if(strlen($error=$this->pop3->Login(UrlDecode($url["user"]), UrlDecode($url["pass"]),$apop)))
{
$this->stream_close();
return($this->SetError($error));
}
}
if(strlen($error=$this->pop3->OpenMessage($message,-1)))
{
$this->stream_close();
return($this->SetError($error));
}
$this->end_of_message=FALSE;
if($options & STREAM_USE_PATH)
$opened_path=$path;
$this->read = 0;
$this->buffer = "";
return(TRUE);
}
Function stream_eof()
{
if($this->read==0)
return(FALSE);
return($this->end_of_message);
}
Function stream_read($count)
{
if($count<=0)
return($this->SetError("it was not specified a valid length of the message to read"));
if($this->end_of_message)
return("");
if(strlen($error=$this->pop3->GetMessage($count, $read, $this->end_of_message)))
return($this->SetError($error));
$this->read += strlen($read);
return($read);
}
Function stream_close()
{
while(!$this->end_of_message)
$this->stream_read(8000);
if($this->opened)
{
$this->pop3->Close();
$this->opened = 0;
}
}
};
?>

View file

@ -0,0 +1,359 @@
<?php
/**
* Class Rapport
*
* Génération et envoie de rapport de mission de flotte
*
*/
class Rapport{
var $table = 'mail';
var $type = 0;
var $var = array();
var $utilA = 0;
var $utilB = 0;
var $timestamp = 0;
/**
* Constructor
* @access protected
*/
function Rapport($type, $utilA, $utilB, $time)
{
global $table_mail;
$this->table = $table_mail;
$this->type = $type;
$this->utilA = $utilA;
$this->utilB = $utilB;
$this->timestamp = $time;
}
function addInfo($info, $id)
{
$this->var[$id] = $info;
}
function send()
{
if ($this->type == '3')
$this->sendCombat();
elseif ($this->type == '1')
$this->sendTransport();
elseif ($this->type == '2')
$this->sendColonisation();
elseif ($this->type == '4')
$this->sendRecyclage();
elseif ($this->type == '5')
$this->sendEspionnage();
elseif ($this->type == '6')
$this->sendAlliance();
elseif ($this->type == '7')
$this->sendAlliance2();
}
function sendEspionnage()
{
global $LANG;
$titreA = 'Rapport d\'espionnage de '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapportA = '<b>Espionnage de '.$this->var[0]->pseudo.' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
if ($this->var[2] < 1) $rapportA .= '<i>Nos sondes n\'ont pas pu récolter d\'informations sur cette planète.</i>';
else {
//Ressources
if ($this->var[2] > 1)
$rapportA .= '<table style="margin: auto;"><tr><th colspan="2">Ressources sur la planète :</th></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["metal"].' :</td><td>'.$this->var[0]->metal.'</td></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["cristal"].' :</td><td>'.$this->var[0]->cristal.'</td></tr><tr><td>'.$LANG[$this->var[0]->race]["ressources"]["noms"]["hydrogene"].' :</td><td>'.$this->var[0]->hydrogene.'</td></tr></table><br />';
//Bâtiments
if ($this->var[2] > 2)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Niveau</th><th>Bâtiment</th></tr>';
foreach ($this->var[0]->batiments as $key => $batiment)
{
$rapportA .= '<tr><td>'.rand($batiment * (1 - $this->var[1]), $batiment * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["batiments"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
//Flottes en orbite
if ($this->var[2] > 3)
{
}
//Flottes au sol
if ($this->var[2] > 5)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Nombre</th><th>Vaisseaux</th></tr>';
foreach ($this->var[0]->vaisseaux as $key => $vaisseau)
{
$rapportA .= '<tr><td>'.rand($vaisseau * (1 - $this->var[1]), $vaisseau * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["vaisseaux"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
//Défenses
if ($this->var[2] > 4)
{
$rapportA .= '<table style="margin: auto;"><tr><th>Nombre</th><th>Défenses</th></tr>';
foreach ($this->var[0]->terrestres as $key => $unite)
{
if (!Donnee::typeTerrestre($key)) $rapportA .= '<tr><td>'.rand($unite * (1 - $this->var[1]), $unite * (1 + $this->var[1])).'</td><td>'.$LANG[$this->var[0]->race]["terrestre"]["noms_sing"][$key].'</td></tr>';
}
$rapportA .= '</table><br />';
}
}
$titreB = 'Rapport de contre-espionnage';
$rapportB = 'Nous venons d\'apprendre que notre planète : '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.'] a été la cible d\'un espionnage de la part de '.$this->utilA->pseudo;
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($titreB);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
//On envoie un rapport au joueur espionné uniquement s'il a un contre-espionnage
if ($this->var[3] >= 1)
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user.", '$titreB', '$rapportB', '$temps')");
$db->deconnexion();
}
function sendTransport()
{
global $LANG;
$titre = 'Transport vers '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapportA = 'Vos vaisseaux ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilA->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$rapportB = 'Les vaisseaux de '.$this->utilA->pseudo.' ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilB->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapportA', '$temps');");
if ($this->utilA->id_user != $this->utilB->id_user) $db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user.", '$titre', '$rapportB', '$temps');");
$db->deconnexion();
}
function sendColonisation()
{
$titre = 'Colonisation de ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].']';
if ($this->var[1]) $rapport = 'Votre vaisseau a atteint la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] et commence la colonisation.';
else $rapport = 'Nous n\'avons pas pu coloniser la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] car lorsque nous sommes arrivé sur place, elle était déjà colonisée.';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendRecyclage()
{
global $LANG;
$titre = 'Recyclage de '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapport = 'Vos vaisseaux récoltent '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].' et '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendCombat(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$rapportA = new Smarty();
$rapportB = new Smarty();
$rapportA->template_dir = _FCORE.'templates/templates/';
$rapportA->compile_dir = _FCORE.'templates/templates_c/';
$rapportA->config_dir = _FCORE.'templates/configs/';
$rapportA->cache_dir = _FCORE.'templates/cache/';
$rapportB->template_dir = _FCORE.'templates/templates/';
$rapportB->compile_dir = _FCORE.'templates/templates_c/';
$rapportB->config_dir = _FCORE.'templates/configs/';
$rapportB->cache_dir = _FCORE.'templates/cache/';
$this->var[4]['pseudo'] = trouvNom($this->var[4]['id_user']);
$this->var[5]['pseudo'] = trouvNom($this->var[5]['id_user']);
$rapportA->assign('tour', $this->var[3]);
$rapportA->assign('EN', $this->var[4]);
$rapportA->assign('flotte', $this->var[5]);
$rapportA->assign('vaisseaux1', $this->var[0]);
$rapportA->assign('vaisseaux2', $this->var[1]);
$rapportA->assign('defenses1', $this->var[2]);
$rapportA->assign('vaisseaux3', $this->var[7]);
$rapportA->assign('vaisseaux4', $this->var[8]);
$rapportA->assign('defenses2', $this->var[9]);
$rapportA->assign('termine', $this->var[6][0]);
$rapportA->assign('attaquantG', $this->var[6][1]);
$rapportA->assign('pillage', $this->var[11]);
$rapportA->assign('vaisBC', $nomvais_bc);
$rapportA->assign('vaisPV', $nomvais_pv);
$rapportA->assign('defBC', $defense_bc);
$rapportA->assign('defPV', $defense_pv);
$rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('ressources', $ressourc);
$rapportA->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportA->assign('nomdefEN', $nomterra);
$rapportA = $rapportA->fetch('game/ATrapport_combat.tpl');
$rapportB->assign('tour', $this->var[3]);
$rapportB->assign('EN', $this->var[4]);
$rapportB->assign('flotte', $this->var[5]);
$rapportB->assign('vaisseaux1', $this->var[0]);
$rapportB->assign('vaisseaux2', $this->var[1]);
$rapportB->assign('defenses1', $this->var[2]);
$rapportB->assign('vaisseaux3', $this->var[7]);
$rapportB->assign('vaisseaux4', $this->var[8]);
$rapportB->assign('defenses2', $this->var[9]);
$rapportB->assign('termine', $this->var[6][0]);
$rapportB->assign('attaquantG', $this->var[6][1]);
$rapportB->assign('matchnul', $this->var[6][2]);
$rapportB->assign('pillage', $this->var[11]);
$rapportB->assign('vaisBC', $nomvais_bc);
$rapportB->assign('vaisPV', $nomvais_pv);
$rapportB->assign('defBC', $defense_bc);
$rapportB->assign('defPV', $defense_pv);
$rapportB->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportB->assign('ressources', $ressourc);
$rapportB->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$rapportB->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportB->assign('nomdefEN', $nomterra);
$rapportB = $rapportB->fetch('game/ENrapport_combat.tpl');
$titreA = 'Combat contre '.$this->var[4]['pseudo'];
$titreB = 'Combat contre '.$this->var[5]['pseudo'];
$temps = $this->timestamp;
$db = new bdd();
$db->connexion();
$db->escape($titreA);
$db->escape($titreB);
$db->escape($rapportA);
$db->escape($rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user."', '$titreB', '$rapportB', '$temps')");
$db->deconnexion();
}
function show(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$rapportA = new Smarty();
$rapportA->template_dir = _FCORE.'templates/templates/';
$rapportA->compile_dir = _FCORE.'templates/templates_c/';
$rapportA->config_dir = _FCORE.'templates/configs/';
$rapportA->cache_dir = _FCORE.'templates/cache/';
$rapportA->assign('tour', $this->var[3]);
$rapportA->assign('EN', $this->var[4]);
$rapportA->assign('flotte', $this->var[5]);
$rapportA->assign('vaisseaux1', $this->var[0]);
$rapportA->assign('vaisseaux2', $this->var[1]);
$rapportA->assign('defenses1', $this->var[2]);
$rapportA->assign('vaisseaux3', $this->var[7]);
$rapportA->assign('vaisseaux4', $this->var[8]);
$rapportA->assign('defenses2', $this->var[9]);
$rapportA->assign('termine', $this->var[6][0]);
$rapportA->assign('attaquantG', $this->var[6][1]);
$rapportA->assign('pillage', $this->var[11]);
$rapportA->assign('debris', $this->var[12]);
$rapportA->assign('infoPLUS', $this->var[14]);
//$rapportA->assign('infoPLUS2', $this->var[15]);
$rapportA->assign('page', 'simulation');
$rapportA->assign('enligne', $this->var[13][0]);
$rapportA->assign('infos', $this->var[13][1]);
$rapportA->assign('nbinfos', $this->var[13][2]);
$rapportA->assign('count', $this->var[13][3]);
$rapportA->assign('version', $this->var[13][4]);
$rapportA->assign('tpsdejeu', $this->var[13][5]);
$rapportA->assign('vaisBC', $nomvais_bc);
$rapportA->assign('vaisPV', $nomvais_pv);
$rapportA->assign('defBC', $defense_bc);
$rapportA->assign('defPV', $defense_pv);
$rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$rapportA->assign('ressources', $ressourc);
$rapportA->assign('nomvaisAT', $nomvaisa);
$rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$rapportA->assign('nomdefEN', $nomterra);
$rapportA->assign('race', $race);
return $rapportA->fetch('game/SIMrapport_combat.tpl');
return $rapportA;
}
function sendAlliance()
{
$titreA = 'Déclaration officielle de votre alliance !';
$rapportA = 'Félicitations, votre alliance a recueilli suffisament de signature, sa déclaration est maintenant officielle !<br /><br />Vous pouvez dès maintenant administrer votre alliance en vous rendant sur la page Alliance.';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->deconnexion();
}
function sendAlliance2()
{
$titreA = 'Fondation de votre alliance !';
$rapportA = 'Pour terminer la création de votre alliance, trouvez 4 joueurs de cette galaxie sans alliance pour leur faire signer votre traité de fondation d\'alliance.<br /><br />Lien de signature : <a href="?p=alliances&amp;q=signer&amp;i='.$this->var[0].'">http://'.$_SERVER['HTTP_HOST'].'/?p=alliances&amp;q=signer&amp;i='.$this->var[0].'</a>';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titreA);
$db->escape($rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titreA', '$rapportA', '$temps')");
$db->deconnexion();
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
<?php
include_once("game/Class/class.user.php");
/***************************************************************************
* class.surface.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Dimanche 8 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Surface extends User
{
var $id = 0,
$galaxie,
$ss,
$image,
$debris_met,
$debris_cri,
$metal,
$cristal,
$hydrogene,
$alert_ressources = array(false, false, false),
$timestamp,
$file_bat,
$file_vais,
$isolement = false,
$batiments = array(),
$vaisseaux = array(),
$modif = array();
}
?>

View file

@ -0,0 +1,46 @@
<?php
class TinyAsteroide
{
var $id = 0,
$galaxie,
$ss,
$nom_asteroide;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_alliances;
$bdd = new BDD();
//On traite le cas où l'on recoit l'ID ou les coordonnées de l'asteroide
if (is_numeric($id))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche d\'astéroide incorrect !', E_USER_ERROR);
if (!empty($aste))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $aste["id"];
$this->galaxie = $aste["galaxie"];
$this->ss = $aste["ss"];
$this->nom_asteroide = $aste["nom_asteroide"];
}
}
}
?>

View file

@ -0,0 +1,47 @@
<?php
class TinyPlanete{
var $id = 0,
$galaxie,
$ss,
$position,
$nom_planete;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new bdd();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
$this->nom_planete = $plan["nom_planete"];
}
}
}
?>

View file

@ -0,0 +1,163 @@
<?php
//Gestion des dépendances
include_once("game/Class/class.tinyasteroide.php");
/***************************************************************************
* class.user.php
* ----------------
* begin : Dimanche 7 septembre 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class User{
var $id_user,
$pseudo,
$auth_level,
$race,
$alliance,
$id_alliance,
$id_grade_alliance,
$mv,
$mail,
$envoyerMail,
$last_visite,
$points,
$place_points,
$technologies = array(),
$credits,
$politique,
$politique_lastchange,
$destinationsFavoris,
$amis = array(),
$combatAT_tactique,
$combatDE_tactique,
$modifUser = array();
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function User($id = 0){
if (!empty($id)) {
global $var___db, $config, $table_user;
global $technologiesVAR;
$bdd = new bdd();
$bdd->escape($id);
$user = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id;");
$bdd->deconnexion();
if (!empty($user)) {
$this->id_user = $user["id"];
$this->pseudo = $user["pseudo"];
$this->auth_level = $user["auth_level"];
$this->race = $user["race"];
$this->mv = $user["mv"];
$this->id_alliance = $user["id_alliance"];
$this->id_grade_alliance = $user["id_grade_alliance"];
$this->mail = $user["mail"];
$this->envoyerMail = $user["envoyerMail"];
$this->last_visite = $user["last_visite"];
$this->points = $user["points"];
$this->place_points = $user["place_points"];
$this->credits = $user["credits"];
$this->politique = $user["politique"];
$this->politique_lastchange = $user["politique_lastchange"];
if (!empty($user["amis"])) $this->amis = unserialize($user["amis"]);
else $this->amis = array();
if (!empty($user["destinationsFavoris"])) $this->destinationsFavoris = unserialize($user["destinationsFavoris"]);
else $this->destinationsFavoris = array();
$this->combatAT_tactique = $user["combatAT_tactique"];
$this->combatDE_tactique = $user["combatDE_tactique"];
foreach($technologiesVAR as $tech){
$this->technologies[] = $user[$tech];
}
//Si l'ID d'alliance est défini, on charge l'alliance
if (!empty($this->id_alliance))
$this->alliance = new TinyAsteroide($this->id_alliance);
}
else die('Erreur #01 : Utilisateur recherché introuvable dans la base de données. Contactez le support technique ('.$config['mail_support'].') au plus vite en précisant le code d\'erreur.');
}
}
function addCredits($credits)
{
$this->credits += $credits;
$this->addModifUser("credits");
return 0;
}
function addModifUser($modif)
{
if (!in_array($modif, $this->modifUser))
$this->modifUser[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $var___db, $config, $table_user;
$out = array();
$bdd = new bdd();
foreach($this->modifUser as $key => $modif)
{
if ($modif == "force")
$out[] = " ";
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
if (is_int($this->{$modif}) || is_float($this->{$modif})) $out[] .= $modif." = ".$this->{$modif};
else $out[] .= $modif." = '".$this->{$modif}."'";
}
else
{
if (ereg('file', $modif))
{
$prep = implode(';', $this->{$modif});
$bdd->escape($prep);
$out[] .= $modif." = '$prep'";
}
else
{
if ($modif == "batiments")
$calc = "batiment";
elseif ($modif == "technologies")
$calc = "technologies";
elseif ($modif == "casernes")
$calc = "casernen";
elseif ($modif == "terrestres")
$calc = "nomterrn";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++){
$bdd->escape($this->{$modif}[$j]);
$out[] .= ${$calc.'VAR'}[$j]." = ".$this->{$modif}[$j];
}
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_user SET ".implode(', ', $out)." WHERE id = ".$this->id_user.";";
if (DEBUG) echo '<br /><br />'.$sql;
$bdd->query($sql);
}
$bdd->deconnexion();
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
/**
* PHPMailer language file.
* English Version
*/
$PHPMAILER_LANG = array();
$PHPMAILER_LANG["provide_address"] = 'You must provide at least one ' .
'recipient email address.';
$PHPMAILER_LANG["mailer_not_supported"] = ' mailer is not supported.';
$PHPMAILER_LANG["execute"] = 'Could not execute: ';
$PHPMAILER_LANG["instantiate"] = 'Could not instantiate mail function.';
$PHPMAILER_LANG["authenticate"] = 'SMTP Error: Could not authenticate.';
$PHPMAILER_LANG["from_failed"] = 'The following From address failed: ';
$PHPMAILER_LANG["recipients_failed"] = 'Erreur SMTP: The following ' .
'recipients failed: ';
$PHPMAILER_LANG["data_not_accepted"] = 'Erreur SMTP: Données non acceptées.';
$PHPMAILER_LANG["connect_host"] = 'Erreur SMTP: Impossible de se connecter au serveur de mail.';
$PHPMAILER_LANG["file_access"] = 'Accès au fichier impossible: ';
$PHPMAILER_LANG["file_open"] = 'File Error: Ne peut ouvrir le fichier: ';
$PHPMAILER_LANG["encoding"] = 'Type d\'encodage inconnu : ';
?>

View file

@ -0,0 +1,42 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'accueil';
$titre = 'Accueil';
//Affichage de l'alliance du joueur
$bdd->reconnexion();
//$alli = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = '".$planete->id_alliance."';");
//On regarde si le joueur a une flotte en vue
$radar = array();
$nbPlan = count($queryPlanetes);
//$detect = $planete->technologies[1]*1800;
/*for($i = 0; $i < $nbPlan; $i++){
$end_galaxie = $queryPlanetes[$i]['galaxie'];
$end_ss = $queryPlanetes[$i]['ss'];
$end_position = $queryPlanetes[$i]['position'];
$radar[] = array($bdd->query("SELECT F.mission, F.start_galaxie, F.start_ss, F.start_position, F.start_time, F.end_time, F.start_time + F.end_time - ".time()." AS arrive_time, P.nom_planete, U.pseudo FROM $table_flottes F INNER JOIN $table_planete P ON P.galaxie = F.start_galaxie AND P.ss = F.start_ss AND P.position = F.start_position INNER JOIN $table_user U ON U.id = P.id_user WHERE F.effectue != '1' AND F.end_galaxie = '$end_galaxie' AND F.end_ss = '$end_ss' AND F.end_position = '$end_position' AND F.id_user != $id_user AND F.start_time + F.end_time - ".time()." <= $detect;"), array($queryPlanetes[$i]['nom_planete'], $queryPlanetes[$i]['galaxie'], $queryPlanetes[$i]['ss'], $queryPlanetes[$i]['position']));
}*/
$bdd->deconnexion();
unset($nbPlan);
if (SURFACE == "planete") {
//Affichage des informations sur la planète
$template->assign('diametre', $planete->cases * 92);
$template->assign('points', $planete->points);
}
$template->assign('radar',$radar);
//$template->assign('alliance', $alli);
if (SURFACE == "planete")
{
$template->assign('fileBat', $planete->file_bat->printFile($planete));
$template->assign('fileCas', $planete->file_cas->printFile($planete));
$template->assign('fileVais', $planete->file_vais->printFile($planete));
$template->assign('fileTer', $planete->file_ter->printFile($planete));
$template->assign('fileTech', $planete->file_tech->printFile($planete));
}
unset($radar, $alli)
?>

View file

@ -0,0 +1,72 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'arbre';
$titre = 'Arbre des technologies';
if (empty($_GET['q']))
$_GET['q'] = '';
$template->assign('defaut',$_GET['q']);
//Récupération et vérification de la race voulue ou définition d'une race par défaut
if (empty($_GET['r']) || ($_GET['r'] != 'humain' && $_GET['r'] != 'covenant'))
$_GET['r'] = $planete->race;
$race = $_GET['r'];
$template->assign('raceAff', $race);
$TEMP_liste = array();
foreach($planete->batiments as $id => $batiment)
{
if (!empty($LANG[$race]["batiments"]["noms_sing"][$id]))
$TEMP_liste[$id] = array(
'niveau' => $batiment,
'etat' => Donnee::print_neededBatiments($id, $planete, $race)
);
}
$template->assign('batiments', $TEMP_liste);
/*
$TEMP_technologies = array();
$nb = count($technolo);
for ($id=0 ; $id<$nb ; $id++) {
if (!empty($technolo[$id])) $TEMP_technologies[] = array(
'id' => $id,
'nom' => $technolo[$id],
'niveau' => $planete->technologies[$id],
'etat' => readDeblok($technoloTECH[$id], $planete)
);
}
$template->assign('technologies',$TEMP_technologies);
*/
$TEMP_liste = array();
foreach($planete->casernes as $id => $unite)
{
if (!empty($LANG[$race]["caserne"]["noms_sing"][$id]))
$TEMP_liste[$id] = array(
'niveau' => $unite,
'etat' => Donnee::print_neededCaserne($id, $planete, $race)
);
}
$template->assign('caserne', $TEMP_liste);
$TEMP_liste = array();
foreach($planete->terrestres as $id => $unite)
{
if (!empty($LANG[$race]["terrestre"]["noms_sing"][$id]))
$TEMP_liste[$id] = array(
'niveau' => $unite,
'etat' => Donnee::print_neededTerrestre($id, $planete, $race)
);
}
$template->assign('unites', $TEMP_liste);
$TEMP_liste = array();
foreach($planete->vaisseaux as $id => $unite)
{
if (!empty($LANG[$race]["vaisseaux"]["noms_sing"][$id]))
$TEMP_liste[$id] = array(
'niveau' => $unite,
'etat' => Donnee::print_neededVaisseaux($id, $planete, $race)
);
}
$template->assign('vaisseaux', $TEMP_liste);
?>

View file

@ -0,0 +1,56 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'batiments';
$titre = 'Batiments';
//Lancement d'une nouvelle construction
if (isset($_GET['c'])) {
//On vérifie qu'il n'y ait pas de technologie en cours de recherche si l'on veut améliorer le centre de recherche
if($_GET['c'] == 6 && !empty($planete->file_tech[1]))
erreur('Une technologie est en cours de recherche dans votre laboratoire, vous ne pouvez pas faire de travaux !');
$planete->file_bat->batiment_addObjet(intval(gpc('c')), $planete);
redirection($VAR['menu']['batiments']);
}
//Lancement d'une déconstruction
if (isset($_GET['d'])) {
//On vérifie qu'il n'y ait pas de technologie en cours de recherche si l'on veut améliorer le centre de recherche
if($_GET['d'] == 6 && !empty($planete->file_tech[1]))
erreur('Une technologie est en cours de recherche dans votre laboratoire, vous ne pouvez pas faire de travaux !');
$planete->file_bat->batiment_addDemolition(intval(gpc('d')), $planete);
redirection($VAR['menu']['batiments']);
}
//Annulation d'une nouvelle construction
if (isset($_GET['a'])) {
$planete->file_bat->batiment_delObjet(intval(gpc('a')), $planete);
redirection($VAR['menu']['batiments']);
}
$TEMP_liste = array();
foreach($planete->batiments as $i => $niveau)
{
//Si l'on est pas sur la planète mère, on désactive le laboratoire
if ($i == 6 && $queryPlanetes[0]['id'] != $planete->id)
continue;
if (!empty($LANG[$planete->race]['batiments']['noms_sing'][$i]) && Donnee::neededBatiments($i, $planete))
{
$TEMP_liste[] = array (
'id' => $i,
'image' => $batimeni[$i],
'niveau' => $niveau,
'nec_metal' => Donnee::metalBatiments($i, $niveau+1, $planete),
'nec_cristal' => Donnee::cristalBatiments($i, $niveau+1, $planete),
'nec_hydrogene' => Donnee::hydrogeneBatiments($i, $niveau+1, $planete),
'temps' => sec(Donnee::tempsBatiments($i, $niveau+1, $planete)),
'enfile' => $planete->file_bat->batiment_objectInFile($i)
);
}
}
$template->assign('batiments', $TEMP_liste);
$template->assign('file', $planete->file_bat->printFile($planete));
?>

View file

@ -0,0 +1,105 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'carte';
$titre = 'Carte spatiale';
//Récupération d'un numéro d'amas à regarder
if (isset($_GET['galaxie']))
$g = floor($_GET['galaxie']);
else
$g = $planete->galaxie;
//Validation du numéro de l'amas
if ($planete->auth_level >= 5 && $g <= 0)
$g = 0;
elseif ($g < 1)
$g = 1;
if ($g > $VAR['nb_amas'])
$g = 1;
//Récupération d'un numéro de système à regarder
if (isset($_GET['ss']))
$s = floor($_GET['ss']);
else
$s = $planete->ss;
//Validation du numéro de système
if ($s < 1)
$s = 1;
if ($s > $VAR['nb_systeme'])
$s = $VAR['nb_systeme'];
//Calcul des prochains amas et systèmes
if ($s == 1 && $g > 1)
{
$Gmu = $g - 1;
$Smu = $VAR['nb_systeme'];
}
elseif ($s == 1)
{
$Gmu = 15;
$Smu = $VAR['nb_systeme'];
}
else
{
$Gmu = $g;
$Smu = $s - 1;
}
if ($s == $VAR['nb_systeme'])
{
$Gpu = $g + 1;
$Spu = 1;
}
else
{
$Gpu = $g;
$Spu = $s + 1;
}
//Erreur au cas où la zone soit trop lointaine par rapport au niveau de la technologie
//if (($planete->technologies[1] < 1 && ($g != $planete->galaxie || $s != $planete->ss)) || ($planete->technologies[1] < 2 && $g != $planete->galaxie))
// erreur('Pour afficher cette zone de la carte spatiale, vous devez plus développer votre technologie ');
//Génération de la carte à afficher
$TEMP_carte = array();
for ($i = 1; $i <= $VAR['nb_planete']; $i++)
{
//Cas d'un système à astéroïde
if ($s%5 == 2 && $i == ceil($VAR['nb_planete']/2))
{
$bdd->reconnexion();
$bdd->escape($g);
$bdd->escape($s);
$d = $bdd->unique_query("SELECT race, nom_asteroide, debris_met, debris_cri, nom, tag, fondateur FROM $table_alliances WHERE galaxie = $g AND ss = $s;");
$bdd->deconnexion();
if($d) {
if ($d['race'] == 'covenant') $ra = '(c)';
elseif ($auth_level >= 6 && md5($d['race']) == '34c19b21bd4a3dda389e767d32fe9779') $ra = '(f)';
else $ra = '(h)';
$TEMP_carte[] = array('A', $d['nom_asteroide'], $d['debris_met'], $d['debris_cri'], $ra, $d['nom'], '<a href="?p=envoyer&amp;d='.$d['fondateur'].'" class="msg"><span>Message</span></a>', $d['tag']);//, $eA['tag']);
}
else {
$TEMP_carte[] = array('A');
}
}
$bdd->reconnexion();
$bdd->escape($g);
$bdd->escape($s);
$resultat = $bdd->query("SELECT id FROM $table_planete WHERE galaxie = $g AND ss = $s AND position = $i;");
if($resultat) {
$d = $bdd->unique_query("SELECT P.nom_planete, P.image, P.debris_met, P.debris_cri, U.pseudo, U.race, U.politique, U.id_alliance, A.tag FROM $table_planete P INNER JOIN $table_user U ON U.id = P.id_user LEFT OUTER JOIN $table_alliances A ON A.id = U.id_alliance WHERE P.galaxie = $g AND P.ss = $s AND P.position = $i;");
$bdd->deconnexion();
$TEMP_carte[] = array($i, $d['nom_planete'], $d['debris_met'], $d['debris_cri'], $d['race'], $d['pseudo'], $d['tag'], $d['image'], $d['politique']);
}
else {
$bdd->deconnexion();
$TEMP_carte[] = array($i);
}
}
$template->assign('carte', $TEMP_carte);
$template->assign('position', array($g, $s, $Gpu, $Spu, $Gmu, $Smu));
?>

View file

@ -0,0 +1,45 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'caserne';
$titre = $LANG[$planete->race]['batiments']['noms_sing'][9];
//Vérification que le joueur ait bien une caserne avant d'afficher la page
if ($planete->batiments[9] <= 0)
erreur('Vous devez d\'abord construire une '.$LANG[$planete->race]['batiments']['noms_sing'][9], "red", '?p=batiments', 3500);
//Lancement d'une nouvelle construction
if (isset($_GET['v']) && is_numeric($_GET['v']) && $nbv = floor(gpc('nombre', 'post'))) {
$planete->file_cas->caserne_addObjet(intval(gpc('v')), $nbv, $planete);
redirection($VAR['menu']['caserne']);
}
//Annulation d'une nouvelle construction
if (isset($_GET['a'])) {
$n = intval(gpc('n'));
if (empty($n)) $n = 1;
$planete->file_cas->caserne_delObjet(intval(gpc('a')), $n, $planete);
redirection($VAR['menu']['caserne']);
}
$TEMP_liste = array();
foreach($planete->casernes as $i => $nombre)
{
if (!empty($LANG[$planete->race]['caserne']['noms_sing'][$i]) && Donnee::neededCaserne($i, $planete))
{
$TEMP_liste[] = array (
'id' => $i,
'image' => $casernei[$i],
'nombre' => $nombre,
'nec_metal' => Donnee::metalCaserne($i, $planete),
'nec_cristal' => Donnee::cristalCaserne($i, $planete),
'nec_hydrogene' => Donnee::hydrogeneCaserne($i, $planete),
'temps' => sec(Donnee::tempsCaserne($i, $planete)),
'enfile' => $planete->file_cas->objectInFile($i)
);
}
}
$template->assign('unites', $TEMP_liste);
$template->assign('file', $planete->file_cas->printFile($planete));
?>

View file

@ -0,0 +1,45 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'chantierspatial';
$titre = ucfirst($LANG[$planete->race]['batiments']['noms_sing'][8]);
//Vérification que le joueur ait bien un labo avant d'afficher la page
if ($planete->batiments[8] <= 0)
erreur('Vous devez d\'abord construire un '.$LANG[$planete->race]['batiments']['noms_sing'][8], "red", '?p=batiments', 3500);
//Lancement d'une nouvelle construction
if (isset($_GET['v']) && is_numeric($_GET['v']) && $nbv = floor(gpc('nombre', 'post'))) {
$planete->file_vais->vaisseaux_addObjet(intval(gpc('v')), $nbv, $planete);
redirection($VAR['menu']['chantierspatial']);
}
//Annulation d'une nouvelle construction
if (isset($_GET['a'])) {
$n = intval(gpc('n'));
if (empty($n)) $n = 1;
$planete->file_vais->vaisseaux_delObjet(intval(gpc('a')), $n, $planete);
redirection($VAR['menu']['chantierspatial']);
}
$TEMP_liste = array();
foreach($planete->vaisseaux as $i => $nombre)
{
if (!empty($LANG[$planete->race]['vaisseaux']['noms_sing'][$i]) && Donnee::neededVaisseaux($i, $planete))
{
$TEMP_liste[] = array (
'id' => $i,
'image' => $nomvaisi[$i],
'nombre' => $nombre,
'nec_metal' => Donnee::metalVaisseaux($i, $planete),
'nec_cristal' => Donnee::cristalVaisseaux($i, $planete),
'nec_hydrogene' => Donnee::hydrogeneVaisseaux($i, $planete),
'temps' => sec(Donnee::tempsVaisseaux($i, $planete)),
'enfile' => $planete->file_vais->objectInFile($i)
);
}
}
$template->assign('vaisseaux', $TEMP_liste);
$template->assign('file', $planete->file_vais->printFile($planete));
?>

View file

@ -0,0 +1,47 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = $p;
$titre = ucfirst($LANG[$planete->race]['batiments']['noms_sing'][7]);
//Vérification que le joueur ait bien un labo avant d'afficher la page
if ($planete->batiments[7] <= 0)
erreur('Vous devez d\'abord construire un '.$LANG[$planete->race]['batiments']['noms_sing'][7], "red", '?p=batiments', 3500);
//Lancement d'une nouvelle construction
if (isset($_GET['v']) && is_numeric($_GET['v']) && $nbv = floor(gpc('nombre', 'post'))) {
$planete->file_ter->terrestre_addObjet(intval(gpc('v')), $nbv, $planete);
redirection($VAR['menu'][$p]);
}
//Annulation d'une nouvelle construction
if (isset($_GET['a'])) {
$n = intval(gpc('n'));
if (empty($n)) $n = 1;
$planete->file_ter->terrestre_delObjet(intval(gpc('a')), $n, $planete);
redirection($VAR['menu'][$p]);
}
$TEMP_liste = array();
foreach($planete->terrestres as $i => $nombre)
{
$type = Donnee::typeTerrestre($i);
if (!empty($LANG[$planete->race]['terrestre']['noms_sing'][$i]) && (($p == "defenses" && !$type) || ($p == "chantierterrestre" && $type)) && Donnee::neededTerrestre($i, $planete))
{
$TEMP_liste[] = array (
'id' => $i,
'image' => $nomterri[$i],
'nombre' => $nombre,
'nec_metal' => Donnee::metalTerrestre($i, $planete),
'nec_cristal' => Donnee::cristalTerrestre($i, $planete),
'nec_hydrogene' => Donnee::hydrogeneTerrestre($i, $planete),
'temps' => sec(Donnee::tempsTerrestre($i, $planete)),
'enfile' => $planete->file_ter->objectInFile($i)
);
}
}
$template->assign('unites', $TEMP_liste);
$template->assign('file', $planete->file_ter->printFile($planete));
?>

View file

@ -0,0 +1,148 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'description';
$titre = 'D&eacute;tails';
function tableauProd($ibat,$nivo)
{
$return = array();
$c = $nivo-2 < 1 ? 1 : $nivo-2;
$a = $c + 6;
if ($ibat == 0)
{
for ($c; $c < $a; $c++)
{
$production = ceil(pow(1.1, $c) * 52 * $c);
$production_diff = ceil(pow(1.1, $c) * 52 * $c) - ceil(pow(1.1, $nivo) * 52 * $nivo);
$energie = ceil(exp(0.28*$c)*10);
$energie_diff = ceil(exp(0.28*$c)*10) - ceil(exp(0.28*$nivo)*10);
$return[] = array($c, $production, $energie, $production_diff, $energie_diff);
}
}
elseif ($ibat == 1)
{
for ($c; $c < $a; $c++)
{
$production = ceil(pow(1.1, $c) * 34 * $c);
$production_diff = ceil(pow(1.1, $c) * 34 * $c) - ceil(pow(1.1, $nivo) * 52 * $nivo);
$energie = ceil(exp(0.28*$c)*10);
$energie_diff = ceil(exp(0.28*$c)*10) - ceil(exp(0.28*$nivo)*10);
$return[] = array($c, $production, $energie, $production_diff, $energie_diff);
}
}
elseif ($ibat == 2)
{
for ($c; $c < $a; $c++)
{
$production = ceil(pow(1.1, $c) * 21 * ($c + 0.7));
$production_diff = ceil(pow(1.1, $c) * 21 * ($c + 0.7)) - ceil(pow(1.1, $nivo) * 21 * ($nivo + 0.7));
$energie = ceil(exp(0.2849*$c)*13);
$energie_diff = ceil(exp(0.2849*$c)*13) - ceil(exp(0.2849*$nivo)*13);
$return[] = array($c, $production, $energie, $production_diff, $energie_diff);
}
}
elseif ($ibat == 3)
{
for ($c; $c < $a; $c++)
{
$production = ceil(exp(0.28*$c)*22);
$production_diff = ceil(exp(0.28*$c)*22) - ceil(exp(0.28*$nivo)*22);
$return[] = array($c, $production, 0, $production_diff, 0);
}
}
elseif ($ibat == 4) {
for ($c; $c < $a; $c++)
{
$production = ceil(exp(0.297*$c)*25);
$production_diff = ceil(exp(0.297*$c)*25) - ceil(exp(0.297*$nivo)*25);
$energie = ceil(pow(1.34,($c-1)) * 9);
$energie_diff = ceil(pow(1.34,($c-1)) * 9) - ceil(pow(1.34,($nivo-1)) * 9);
$return[] = array($c, $production, $energie, $production_diff, $energie_diff);
}
}
else
return false;
return $return;
}
if (empty($_GET['r']) || ($_GET['r'] != 'humain' && $_GET['r'] != 'covenant'))
$_GET['r'] = $planete->race;
$race = $_GET['r'];
$template->assign('raceAff', $race);
if (isset($_GET['t']) && is_numeric($_GET['t']) && !empty($LANG[$race]["technologies"]["noms_sing"][$_GET['b']][$_GET['t']]))
{
$template->assign('type', 'technologies');
$b = intval($_GET['b']);
$t = intval($_GET['t']);
$template->assign('branche', $b);
$template->assign('id', $t);
$template->assign('ressourcesNext', array(Donnee::creditsTechnologie($b, $t, $planete), Donnee::tempsTechnologie($b, $t, $planete)));
$template->assign('etat', Donnee::print_neededTechnologie($b, $t, $planete, $race));
}
elseif (isset($_GET['b']) && is_numeric($_GET['b']) && !empty($LANG[$race]["batiments"]["noms_sing"][$_GET['b']]))
{
$template->assign('type', 'batiments');
$t = intval($_GET['b']);
$template->assign('id', $t);
$template->assign('image', $batimeni[$t]);
$template->assign('tableau_prod', tableauProd($t, $planete->batiments[$t]));
$n = $planete->batiments[$t] + 1;
$template->assign('ressourcesNext', array(Donnee::metalBatiments($t, $n, $planete), Donnee::cristalBatiments($t, $n, $planete), Donnee::hydrogeneBatiments($t, $n, $planete), Donnee::tempsBatiments($t, $n, $planete)));
$template->assign('etat', Donnee::print_neededBatiments($t, $planete, $race));
}
elseif (isset($_GET['v']) && is_numeric($_GET['v']) && !empty($LANG[$race]["vaisseaux"]["noms_sing"][$_GET['v']]))
{
$template->assign('type', 'vaisseaux');
$t = intval($_GET['v']);
$template->assign('id', $t);
$template->assign('ressourcesNext', array(Donnee::metalVaisseaux($t, $planete), Donnee::cristalVaisseaux($t, $planete), Donnee::hydrogeneVaisseaux($t, $planete), Donnee::tempsVaisseaux($t, $planete)));
$template->assign('etat', Donnee::print_neededVaisseaux($t, $planete, $race));
$template->assign('caract', array($nomvais_at[$t], $nomvais_bc[$t], $nomvais_pv[$t], $nomvais_rs[$t]));
}
elseif (isset($_GET['d']) && is_numeric($_GET['d']) && !empty($LANG[$race]["terrestre"]["noms_sing"][$_GET['v']]))
{
$template->assign('type', 'terrestre');
$t = $_GET['d'];
$template->assign('id', $t);
$template->assign('ressourcesNext', array(Donnee::metalTerrestre($t, $planete), Donnee::cristalTerrestre($t, $planete), Donnee::hydrogeneTerrestre($t, $planete), Donnee::tempsTerrestre($t, $planete)));
$template->assign('etat', Donnee::print_neededTerrestre($t, $planete, $race));
if ($t-8 >= 0) {
$t -= 8;
$template->assign('caract', array($defense_at[$t], $defense_bc[$t], $defense_pv[$t]));
}
}
elseif (isset($_GET['c']) && is_numeric($_GET['c']) && !empty($LANG[$race]["caserne"]["noms_sing"][$_GET['c']]))
{
$template->assign('type', 'caserne');
$t = $_GET['c'];
$template->assign('id', $t);
$template->assign('ressourcesNext', array(Donnee::metalCaserne($t, $planete), Donnee::cristalCaserne($t, $planete), Donnee::hydrogeneCaserne($t, $planete), Donnee::tempsCaserne($t, $planete)));
$template->assign('etat', Donnee::print_neededCaserne($t, $planete, $race));
$template->assign('caract', array('!!', '!!', '!!'));
}
else {
header('Location: ?p=accueil');
}
?>

View file

@ -0,0 +1,371 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Flottes';
$page = 'flotte'; //Définition d'un nom de page inexistant, mais permet de passer le nom de l'onglet dans une erreur
include_once("game/Class/class.flotte.php");
//Création de flotte : envoi final
if (!empty($_POST['cds']))
{
//Récupération des informations envoyées
$end_galaxie = floor(gpc('amas', 'post'));
$end_ss = floor(gpc('ss', 'post'));
$end_pos = floor(gpc('pos', 'post'));
$mission = floor(gpc('mission', 'post'));
$EBmetal = floor(str_replace(' ', '', gpc('metal', 'post')));
$EBcristal = floor(str_replace(' ', '', gpc('cristal', 'post')));
$EBhydrogene = floor(str_replace(' ', '', gpc('hydrogene', 'post')));
$vitesse = floor(gpc('vitesse', 'post'))/100;
$bdd->reconnexion();
$resultat = $bdd->unique_query("SELECT COUNT(id) AS cnt FROM $table_flottes WHERE id_user = $id_user;");
$bdd->deconnexion();
$nbr = $resultat['cnt'];
//Vérification du code anti-bots
/*if (!isset($SESS->values['flcds']) || gpc('cds', 'post') != $SESS->values['flcds']) erreur('Impossible d\'authentifier l\'envoie de la flotte.<br />Si le problème perciste, <a href="mailto:technique@halo-battle.s-fr.com">contactez un administrateur</a>.', "red", '?p=flotte', 4000);
//Si la mission est d'attaquer, on vérifie que les attaques ne soient pas désactivées
else*/if ($mission == 3 && !ATTAQUES)
erreur('Les attaques sont désactivées pour le moment. Pour plus d\'informations, <a href="'.$VAR["link"]["forum"].'">consultez le forum</a>.', "red", '?p=flotte', 5000);
//Vérification que la destination ne soit pas en dehors de la galaxie
elseif ($end_galaxie > $VAR['nb_amas'] || $end_ss > $VAR['nb_systeme'] || $end_pos > $VAR['nb_planete'] || $end_galaxie < 0 || $end_ss < 1 || $end_pos < 1 || ($end_galaxie < 1 && $SESS->level < 6))
erreur('La destination de la flotte n\'est pas correcte.', "red", '?p=flotte');
//Vérification que le nombre de slots ne soit pas dépassé
elseif ($nbr > ceil(count($queryPlanetes)/2 + 1))
erreur('Vous n\'avez pas assez de slots disponibles.', "red", '?p=flotte');
//On vérifie la mission
elseif ($mission < 0 || $mission > 5)
erreur('Mission incorrecte !', "red", '?p=flotte');
//On vérifie la mission, si elle est d'espionner, il faut qu'il y ait des sondes
elseif ($mission == 5 && $SESS->values['vais'][6] <= 0 && $SESS->values['vais'][13] <= 0)
erreur('Vous ne pouvez pas espionner sans sonde d\'espionnage !', "red", '?p=flotte');
//On vérifie la mission, si elle est de coloniser, il faut qu'il y ait des vaisseaux de colonisation
elseif ($mission == 2 && $SESS->values['vais'][2] <= 0)
erreur('Vous ne pouvez pas coloniser sans vaisseau de colonisation !', "red", '?p=flotte');
//On vérifie la mission, si elle est de recycler, il faut qu'il y ait des reclycleurs
elseif ($mission == 4 && $SESS->values['vais'][3] <= 0)
erreur('Vous ne pouvez pas recycler sans recycleur !', "red", '?p=flotte');
//On vérifie que l'on possède assez de ressources
elseif ((!empty($EBmetal) && !$EBmetal > $planete->metal) || (!empty($EBcristal) && !$EBcristal > $planete->cristal) || (!empty($EBhydrogene) && !$EBhydrogene > $planete->hydrogene))
erreur('Vous ne pouvez pas envoyer plus de ressources que vous n\'en posséder.', "red", '?p=flotte');
//On vérifie que l'on n'envoie pas des ressources négatives
elseif ((!empty($EBmetal) && $EBmetal < 0) || (!empty($EBcristal) && $EBcristal < 0) || (!empty($EBhydrogene) && $EBhydrogene < 0))
erreur('Vous avez spécifié des valeurs de ressources à embarquer incorrectes !', "red", '?p=flotte', 4000);
//On vérifie la vitesse du vaisseau
elseif (!is_numeric($vitesse) || $vitesse < 0 || $vitesse > 1)
erreur('La vitesse de votre flotte est incorrecte !', "red", '?p=flotte');
else
{
//On vérifie qu'il n'y ait pas une interaction entre deux multi-comptes
$cnt = count($multi);
if ($cnt > 1 && $mission == 1)
{
for($i = 0; $i < $cnt; $i++)
{
if ($multi[$i]['id_util'] == $resultat['id_user'])
erreur('Vous ne pouvez pas avoir d\'interaction avec ce joueur pour raison de multi-compte (voir page d\'accueil).');
}
}
$bdd->reconnexion();
$resultat = $bdd->unique_query("SELECT id, id_user, debris_met, debris_cri FROM $table_planete WHERE galaxie = $end_galaxie AND ss = $end_ss AND position = $end_pos;");
$bdd->deconnexion();
//Si la mission est d'attaquer, on vérifie que le joueur cible ne soit pas ne mode vacances ou qu'il soit tout jeune
if ($mission == 3)
{
//Récupération de l'ID du joueur cible
$bdd->reconnexion();
$resultatu = $bdd->unique_query("SELECT mv, time_inscription FROM $table_user WHERE id = ".$resultat['id_user'].";");
$bdd->deconnexion();
if ($resultatu['mv'] > 0)
erreur('Le joueur que vous tentez d\'attaquer est actuellement en mode vacances, vous ne pouvez donc pas l\'attaquer avant son retour de vacances.', "red", '?p=flotte', 3000); //TODO Mettre le numéro du mode vacances et non > 0 !!!
elseif ($resultatu['time_inscription'] + 604800 > time())
erreur('Le joueur que vous tentez d\'attaquer s\'est inscrit récemment, laissez-lui le temps de se préparer au combat !', "red", '?p=flotte', 3000);
elseif (!$resultat)
erreur('La planète que vous tentez d\'attaquer est inhabitée.', "red", '?p=flotte');
elseif ($resultat['id_user'] == $id_user)
erreur('La planète que vous tentez d\'attaquer vous appartient.', "red", '?p=flotte');
}
//TODO Autoriser l'espionnage sur les planètes inhabités
elseif ($mission == 5 && !$resultat)
erreur('Impossible d\'espionner des ressources vers la planète ['.$end_galaxie.':'.$end_ss.':'.$end_pos.'] car elle est inhabitée.', "red", '?p=flotte', 4000);
elseif ($mission == 1 && !$resultat)
erreur('Impossible de transporter des ressources vers la planète ['.$end_galaxie.':'.$end_ss.':'.$end_pos.'] car elle est inhabitée.', "red", '?p=flotte', 4000);
elseif ($mission == 2 && $resultat)
erreur('La planète que vous voulez coloniser est déjà habitée.', "red", '?p=flotte', 3000);
elseif ($mission == 0 && $resultat['id_user'] != $id_user)
erreur('La planète sur laquelle vous désirez stationner ne vous appartient pas.', "red", '?p=flotte', 3000);
elseif ($mission == 5 && $resultat['id_user'] == $id_user)
erreur('La planète que vous désirez espionner vous appartient !', "red", '?p=flotte', 3000);
elseif ($mission == 4 && ($resultat['debris_met'] <= 0 || $resultat['debris_cri'] <= 0) && empty($SESS->values['forceFlotte']))
{
$SESS->values['forceFlotte'] = true;
$SESS->put();
erreur('Il n\'y a rien à recycler sur la planète ['.$end_galaxie.':'.$end_ss.':'.$end_pos.'].<br />Vous pouvez forcer le lancement de la flotte en rechargeant cette page.', "orange");
}
if (!isset($SESS->values['vais']) || !is_array($SESS->values['vais']))
erreur('Erreur lors de la création de la flotte, absence de données des vaisseaux !', "red", '?p=flotte');
else {
//Envoie de la flotte
$flotte = new flotte();
$sauv = $planete->vaisseaux; //Sauvegarde du contenu de la flotte avant lancement
$nbVais = 0;
foreach ($SESS->values['vais'] as $key => $vaisseau)
{
if ($vaisseau > 0)
{
if ($vaisseau > $planete->vaisseaux[$key])
erreur('Vous avez envoyé plus de vaisseaux que vous n\'en posséder sur cette planète.', "red", '?p=flotte');
else
$nbVais += $vaisseau;
}
elseif ($vaisseau < 0) $vaisseau = 0;
$flotte->vaisseaux[$key] = $vaisseau;
$sauv[$key] -= $vaisseau;
}
if ($nbVais <= 0)
erreur('Vous devez envoyer au moins un vaisseau pour former une flotte !', "red", '?p=flotte');
elseif (!isset($SESS->values['flnbvais']) || $SESS->values['flnbvais'] != $nbVais)
erreur('Une erreur est survenue lors de la création de la flotte :<br /><br /><i>Calcul du nombre de vaisseaux incorrect !</i><br /><br />Si le problème perciste, <a href="mailto:'.$VAR['mail_admin'].'">contactez un administrateur</a>.', "red", '?p=flotte', 4500);
$flotte->nom = gpc('nomflotte', 'post');
$flotte->mission = $mission;
$flotte->start_planete = $planete;
$flotte->start_time = time();
//On traite le cas des planètes qui n'existent pas (dans le cas de la mission colonisation)
if ($mission == 2)
{
$flotte->end_type = 1;
$flotte->end_planete = $end_galaxie.':'.$end_ss.':'.$end_pos;
}
else
{
$flotte->end_type = 0;
$flotte->end_planete = $resultat['id'];
}
$calc = $flotte->calc_deplacement($planete->galaxie, $planete->ss, $planete->position, $end_galaxie, $end_ss, $end_pos, $vitesse, false, true);
$flotte->end_time = $calc[0];
$conso = $calc[1];
//On double la consomation si on fait un aller-retour
if ($mission == 1 || $mission == 2 || $mission == 4 || $mission == 5)
$conso *= 2;
//On vérifie qu'il y a assez de place dans les cales des vaisseaux avant l'envoie ainsi que de ressources sur la planète
$flotte->calculer();
if ($flotte->contenuMax < $EBmetal + $EBcristal + $EBhydrogene + $conso)
erreur('Vous ne pouvez pas embarquer autant de ressources, les cales débordent. '.$flotte->contenuMax, "red", '?p=flotte', 3500);
elseif ($planete->metal < $EBmetal || $planete->cristal < $EBcristal || $planete->hydrogene < $EBhydrogene + $conso)
erreur('Vous n\'avez pas assez de ressources sur cette planète pour envoyer cette flotte.', "red", '?p=flotte', 3500);
else
{
$flotte->contenu = array($EBmetal, $EBcristal, $EBhydrogene);
$flotte->modifFlotte = "INSERT";
//On actualise la planète
$planete->metal -= $EBmetal;
$planete->cristal -= $EBcristal;
$planete->hydrogene -= floor($EBhydrogene + $conso);
$planete->vaisseaux = $sauv;
$planete->addModif("vaisseaux");
unset($flotte);
unset($SESS->values['vais']);
$SESS->put();
erreur('Votre flotte a été envoyée avec succès.', "green", '?p=flotte', 4000);
}
}
}
}
//Création de flotte : page 2
elseif (!empty($_POST['envoie']))
{
$nombreVaisseau = 0;
foreach ($planete->vaisseaux as $key => $vaisseau){
$v = gpc('v'.$key, 'post');
if (!is_numeric($v))
$v = 0;
else
$v = (int)abs($v);
//On vérifie qu'il y a suffisamment de vaisseaux sur la planète
if ($vaisseau < $v)
erreur('Il ne vous reste plus assez de vaisseaux !', "red", '?p=flotte');
$SESS->values['vais'][$key] = $v;
$nombreVaisseau += $v;
}
//On vérifie que l'utilisateur a bien envoyé plus d'un vaisseau
if ($nombreVaisseau <= 0) erreur('Vous devez envoyer au moins un vaisseau.', "red", '?p=flotte');
//On enregistre les paramètres en session
$SESS->values['flnbvais'] = $nombreVaisseau;
$SESS->values['forceFlotte'] = false;
//Génération de la liste de mission possible avec les vaisseaux de la flotte
$missions = array("Stationner", "Transporter");
if ($SESS->values['vais'][2]) $missions[2] = "Coloniser";
if ($planete->technologies[7]& 16) $missions[3] = "Attaquer";
if ($SESS->values['vais'][3]) $missions[4] = "Recycler";
if ($SESS->values['vais'][6] || $SESS->values['vais'][13]) $missions[5] = "Espionner";
$template->assign('missions', $missions);
//On enregistre les modification de la session
$SESS->values['fltime'] = time();
$SESS->put();
$page = 'flotte2';
$template->assign('scripth', '<script src="js/prototype.js" type="text/javascript"></script>');
$template->assign('script', '<script type="text/javascript">document.getElementById(\'nom\').focus();</script><script src="js/flotte.js" type="text/javascript"></script>');
//Récupération des destinations favorites et des colonies
$favoris = array();
include_once("game/Class/class.tinyplanete.php");
foreach ($planete->destinationsFavoris as $fav)
{
$fav_Planete = new TinyPlanete($fav);
if (!empty($fav_Planete->nom_planete)) $favoris[$fav_Planete->id] = $fav_Planete->nom_planete;
else $favoris[$fav_Planete->id] = '['.$fav_Planete->galaxie.':'.$fav_Planete->ss.':'.$fav_Planete->position.']';
}
$favorisC = array();
foreach ($queryPlanetes as $fav)
{
if (!empty($fav['nom_planete'])) $favorisC[$fav['id']] = $fav['nom_planete'];
else $favorisC[$fav['id']] = '['.$fav['galaxie'].':'.$fav['ss'].':'.$fav['position'].']';
}
$template->assign('favoris', $favoris);
$template->assign('favorisColonies', $favorisC);
}
//Affichage du détail d'une flotte
elseif (!empty($_GET['n']))
{
$idN = ceil(gpc('n'));
$flotteN = new Flotte($idN, false);
$flotteN->load_planete();
if ($flotteN->id_flotte == 0 || $flotteN->start_planete->id_user != $planete->id_user)
erreur('Impossible de trouver cette flotte !', "red", '?p=flotte', 1500);
else
{
//Changement du nom de la flotte
if (!empty($_POST['nomflotte']))
{
$nouvNom = gpc('nomflotte', 'post');
$flotteN->nom = $nouvNom;
$flotteN->addModifFlotte("nom");
redirection("?p=flotte&n=".$idN);
}
//Annulation de la mission
if (isset($_GET['a']) && isset($SESS->values['ret_fleet']) && $_GET['a'] == $SESS->values['ret_fleet'])
{
//Calcul du temps passé depuis le lancement de la flotte
$tpsDD = time() - $flotteN->start_time;
if ($flotteN->mission == '6')
erreur('Votre flotte est déjà en train de revenir !', 'red', '?p=flotte&n='.$idN, 1500);
elseif ($flotteN->end_time > $tpsDD)
{
$bdd->query("UPDATE $table_flottes SET mission = '6', effectue = '1', end_time = '$tpsDD', end_galaxie = start_galaxie, end_ss = start_ss, end_position = start_position WHERE id_user = '$id_user' AND id = '$idN';");
redirection("?p=flotte&n=".$idN);
}
else
erreur('Impossible d\'annuler la mission, elle a déjà commencée.', "red", '?p=flotte&n='.$idN, 1500);
}
$SESS->values['ret_fleet'] = md5('HB.fleet_'.rand().'☺ß☻');
$SESS->put();
$template->assign('ret_fleet', $SESS->values['ret_fleet']);
$template->assign('flotte', $flotteN);
$page = 'flotten';
}
}
//Affichage de la page générale
else
{
//Demande de mise à jour des tactiques par défaut
$attaque = gpc('attaque', 'post');
$defense = gpc('defense', 'post');
if (is_numeric($attaque) && is_numeric($defense))
{
$chang = false;
if (($attaque != $planete->combatAT_tactique) && (($attaque == 1 && $planete->technologies[3] & 4096) || ($attaque == 2 && $planete->technologies[3] & 8192) || ($attaque == 3 && $planete->technologies[3] & 16384) || $attaque == 0))
{
$planete->combatAT_tactique = $attaque;
$planete->addModifUser('combatAT_tactique');
$chang = true;
}
if (($defense != $planete->combatDE_tactique) && (($defense == 1 && $planete->technologies[3] & 4096) || ($defense == 2 && $planete->technologies[3] & 8192) || ($defense == 3 && $planete->technologies[3] & 16384) || $defense == 0))
{
$planete->combatDE_tactique = $defense;
$planete->addModifUser('combatDE_tactique');
$chang = true;
}
if ($chang)
erreur('Tactiques mises à jour avec succès.', 'green', '?p=flotte', 1100);
}
//Affichage des flottes en cours dans la galaxie
$bdd->reconnexion();
$flottes = $bdd->query("SELECT * FROM $table_flottes WHERE id_user = $id_user;");
$bdd->deconnexion();
$nbr = $bdd->num_rows;
//Extraction des flottes en cours
$TEMP_flottesEC = array();
if ($flottes)
{
foreach ($flottes as $flotte)
{
if (($flotte['mission'] != 2 || $flotte['statut'] == '1') && $flotte['mission'] != 0)
{
$planete_retour = new Planete($flotte['start_planete']);
$retour = $planete_retour->galaxie.':'.$planete_retour->ss.':'.$planete_retour->position;
$Hretour = date('d/m H:i:s',$flotte['start_time']+2*$flotte['end_time']);
}
/*elseif ($flotte['mission'] == 1) {
$retour = $flotte['start_galaxie'].':'.$flotte['start_ss'].':'.$flotte['start_position'];
if (empty($flotte['ret_time'])) $Hretour = '-';
else $Hretour = date('d/m H:i:s',$flotte['ret_time']+$flotte['end_time']);
}*/
else
{
$retour = '-';
$Hretour = '-';
}
$end_planete = new Planete($flotte['end_planete']);
if ($flotte['mission'] == 2)
{
preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $flotte['end_planete'], $position);
$TEMP_flottesEC[] = array($flotte['id'], $flotte['nom'], txtmission($flotte['mission']), $flotte['nb_vais'], ' ['.$position[1].':'.$position[2].':'.$position[3].']', date('d/m H:i:s',$flotte['start_time']+$flotte['end_time']), $retour, $Hretour);
}
else
$TEMP_flottesEC[] = array($flotte['id'], $flotte['nom'], txtmission($flotte['mission']), $flotte['nb_vais'], $end_planete->nom_planete.' ['.$end_planete->galaxie.':'.$end_planete->ss.':'.$end_planete->position.']', date('d/m H:i:s',$flotte['start_time']+$flotte['end_time']), $retour, $Hretour);
}
}
$template->assign('flottesEC', $TEMP_flottesEC);
//Calcul du nombre de slot disponible et vérouillage de l'envoie si besoin
if ($nbr <= ceil(count($queryPlanetes)/2 + 1)) $template->assign('action', '<input class="submit" name="envoie" type="submit" value="OK" />');
else $template->assign('action', '<span class="lack">Nombre de flottes maximum simultanées atteint</span>');
$template->assign('nbflotte', $nbr);
$template->assign('nbflottemax', ceil(count($queryPlanetes)/2 + 1));
$page = 'flotte1';
}
?>

View file

@ -0,0 +1,40 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'gestion';
$titre = 'Gestion';
//Demande de changement de politique
$politique = gpc('politique', 'post');
if (is_numeric($politique)) {
//On annule le changement politique si le dernier a eu lieu dans la semaine.
if ($planete->politique_lastchange > time() - 604800) erreur("La population de votre empire planètaire vient d'entrer dans une phase de révolution contre le changement de régime.<br />Pour ne pas perdre votre place au sommet de l'empire, le système politique n'a pas été changé.");
if (($planete->technologies[3] & 2048 && ($politique == 3 || $politique == 2 || $politique == 1) || $politique == 0) && $planete->politique != $politique) {
$planete->politique = $politique;
$planete->politique_lastchange = time();
$planete->addModifUser("politique");
$planete->addModifUser("politique_lastchange");
erreur("Le changement politique a bien été pris en compte par la population de vos différentes planètes.", "green");
}
elseif ($planete->politique == $politique) erreur("Ce système politique est actuellement en vigueur.", "orange");
else erreur("Impossible de choisir ce système politique !");
}
$template->assign('planeteEC', array(
'id' => $planete->id,
'metal' => $planete->metal,
'cristal' => $planete->cristal,
'hydrogene' => $planete->hydrogene,
'energie' => $planete->energie,
'population' => $planete->population,
)
);
$politiques = array('Anarchie');
if ($planete->technologies[3] & 2048) {
$politiques[] = 'Fascisme (Mouvement Frieden)';
$politiques[] = 'Communisme (Mouvement Koslovic)';
$politiques[] = 'Démocratie (Administration coloniale)';
}
$template->assign('politiques', $politiques);
$template->assign('moraldetails', $politiques);
?>

View file

@ -0,0 +1,57 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'laboratoire';
$titre = ucfirst($LANG[$race]['batiments']['noms_sing'][6]);
//Si l'on est pas sur la planète mère, on bloque le laboratoire
if ($queryPlanetes[0]['id'] != $planete->id)
erreur('Vous devez être sur votre planète mère pour faire des recherches dans le '.$LANG[$race]['batiments']['noms_sing'][6]);
//Vérification que le joueur ait bien un labo avant d'afficher la page
if ($planete->batiments[6] <= 0)
erreur('Vous devez d\'abord construire un '.$LANG[$race]['batiments']['noms_sing'][6], "red", '?p=batiments', 3500);
//Lancement d'une nouvelle recherche
if (isset($_GET['t']) && isset($_GET['f'])) {
//On vérifie que le laboratoire ne soit pas en construction
if($planete->file_bat->batiment_objectInFile(6))
erreur("Votre ".$LANG[$race]["batiments"]["noms_sing"][6]." est en travaux, vous ne pouvez pas faire de recherches pendant ce temps !");
$planete->file_tech->technologie_addObjet(intval(gpc('t')), intval(gpc('f')), $planete);
redirection($VAR['menu']['laboratoire']);
}
//Annulation d'une nouvelle recherche
if (isset($_GET['a'])) {
$planete->file_tech->technologie_delObjet(intval(gpc('a')), $planete);
redirection($VAR['menu']['laboratoire']);
}
$TEMP_liste = array();
foreach($planete->technologies as $i => $bits)
{
foreach($technoli[$i] as $j => $img)
{
if (!empty($LANG[$planete->race]['technologies']['noms_sing'][$i][$j]) && Donnee::neededTechnologie($i, $j, $planete) && ((int)$bits& pow(2, $j)) != pow(2, $j))
{
$nec = Donnee::donneeTechnologie($i, $j, "array" , $planete);
$TEMP_liste[] = array (
'id' => $i,
'tech' => $j,
'image' => $img,
'nec_metal' => $nec[0],
'nec_cristal' => $nec[1],
'nec_hydrogene' => $nec[2],
'nec_credits' => $nec[3],
'temps' => sec($nec[4]),
'enfile' => $planete->file_tech->technologie_objectInFile($i, $j)
);
}
}
}
$template->assign('recherches', $TEMP_liste);
$template->assign('file', $planete->file_tech->printFile($planete));
?>

View file

@ -0,0 +1,87 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Bourse';
$a = gpc('a');
$v = gpc('v');
if(is_numeric($a) && is_numeric(gpc('a'.$a, 'post'))){
$nb = gpc('a'.$a, 'post');
if ($nb <= 0 || $nb > 99999999) erreur("Nombre de ressources invalide !");
if ($a == 0) $var = 'metal';
elseif ($a == 1) $var = 'cristal';
elseif ($a == 2) $var = 'hydrogene';
$bdd->reconnexion();
$action = $bdd->unique_query("SELECT dispo, graph FROM $table_bourse_ressources WHERE id = $a;");
$bdd->deconnexion();
//On vérifie que la bourse ait suffisament de ressources à distribuer :
if ($action['dispo'] <= $nb) erreur("Il n'y a pas assez de ressources dans la galaxie pour que vous puissiez en acheter autant.");
//On vérifie qu'il reste suffisamment de place dans les silos du joueur
if ($planete->cap < $planete->$var + $nb) $nb = $planete->cap - $planete->$var;
if ($nb <= 0) erreur("Vous n'avez pas assez de place pour stocker ces ressources !");
$prix = ceil(pow($action['dispo'], -0.1) * $nb * 2.20)/10;
//On vérifie que le joueur ait assez de crédits pour acheter
if ($prix <= $planete->credits) {
$planete->credits -= $prix;
$planete->$var += $nb;
if (empty($action['graph'])) $action['graph'] = array();
else $action['graph'] = unserialize($action['graph']);
$action['graph'][date('w')] = $action['dispo'];
$graph = serialize($action['graph']);
$bdd->reconnexion();
$bdd->escape($graph);
$bdd->query("UPDATE $table_bourse_ressources SET dispo = dispo - $nb, graph = '$graph' WHERE id = $a;");
$bdd->deconnexion();
}
else erreur("Vous n'avez pas assez de crédits pour faire cet achat !");
}
elseif(is_numeric($v) && is_numeric(gpc('a'.$v, 'post'))){
$nb = gpc('a'.$v, 'post');
if ($nb <= 1000 || $nb > 99999999) erreur("Nombre de ressources invalide !<br />Vous pouvez vendre au minimum 1000 ressources !");
if ($v == 0) $var = 'metal';
elseif ($v == 1) $var = 'cristal';
elseif ($v == 2) $var = 'hydrogene';
//On vérifie que le joueur ait assez de ressources pour vendre, sinon, on ajuste à son maximum
if ($nb > $planete->$var) $nb = $planete->$var;
$bdd->reconnexion();
$action = $bdd->unique_query("SELECT dispo, graph FROM $table_bourse_ressources WHERE id = $v;");
$bdd->deconnexion();
$prix = ceil(pow($action['dispo'], -0.1) * $nb * 1.8)/10;
$planete->credits += $prix;
$planete->$var -= $nb;
if (empty($action['graph'])) $action['graph'] = array();
else $action['graph'] = unserialize($action['graph']);
$action['graph'][date('w')] = $action['dispo'];
$graph = serialize($action['graph']);
$bdd->reconnexion();
$bdd->escape($graph);
$bdd->query("UPDATE $table_bourse_ressources SET dispo = dispo + $nb, graph = '$graph' WHERE id = $v;");
$bdd->deconnexion();
}
$bdd->reconnexion();
$bourse = $bdd->query("SELECT id, dispo FROM $table_bourse_ressources;");
$bdd->deconnexion();
foreach($bourse as $key => $action){
$bourse[$key]['prix'] = pow($action['dispo'], -0.1) * 200;
$bourse[$key]['prixV'] = $bourse[$key]['prix'] * 0.9;
$bourse[$key]['prixA'] = $bourse[$key]['prix'] * 1.07;
}
$page = 'marche';
$template->assign('bourse', $bourse);
?>

View file

@ -0,0 +1,51 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'rename';
$titre = 'Renommer une planète';
if (isset($_POST['planete']))
{
$nouvNom = trim(str_replace('&nbsp;', ' ', $_POST['planete']));
if (empty($nouvNom))
erreur('Vous n\'avez indiqué aucun nom de planète.', "red", '?p=rename');
elseif (limite($nouvNom, 18))
erreur('Le nom de votre planète est trop long.', "red", '?p=rename');
elseif (ereg('staf', strtolower($nouvNom)) && $SESS->level < 4)
erreur('Vous devez faire parti du staff pour afficher le nom "staff" dans le nom de votre planète !', "red", '?p=rename');
else
{
$planete->nom_planete = $nouvNom;
$planete->addModif("nom_planete");
header('Location: ?p=accueil');
exit;
//erreur('Le nom de votre planète a été modifié avec succès.', "green", '?p=accueil');
}
}
elseif(isset($_GET['a']) && isset($_GET['i']) && $_GET['a'] == $SESS->values['abandon'] && !empty($idPlan) && $idPlan == $_GET['i'])
{
$galaxie = $planete->galaxie; $ss = $planete->ss; $position = $planete->position;
$bdd->reconnexion();
$bdd->query("DELETE FROM $table_planete WHERE id_user = $id_user AND id = $idPlan AND galaxie = $galaxie AND ss = $ss AND position = $position LIMIT 1;");
$bdd->query("DELETE FROM $table_flottes WHERE id_user = $id_user AND start_galaxie = $galaxie AND start_ss = $ss AND start_position = $position;");
$req = $bdd->unique_query("SELECT * FROM $table_planete WHERE id_user = $id_user LIMIT 1;");
$bdd->deconnexion();
$SESS->values['abandon'] = 0;
unset($SESS->values['abandon']);
$SESS->values['idPlan'] = $req['id'];
$SESS->put($planete->id_user);
erreur('Cette planète n\'est désormais plus sous votre contrôle.', "green", '?p=accueil');
}
$bdd->reconnexion();
$reqnb = $bdd->unique_query("SELECT COUNT(id) AS total FROM $table_planete WHERE id_user = $id_user;");
$bdd->deconnexion();
if ($reqnb['total'] > 1) $hashA = md5(rand(123456789,9876543210));
else $hashA = false;
$SESS->values['abandon'] = $hashA;
$SESS->put();
$template->assign('abandonH', $hashA);
?>

View file

@ -0,0 +1,27 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'ressources';
$titre = 'Ressources';
if (isset($_POST['coeff_metal']) && isset($_POST['coeff_cs'])) {
$planete->coeff_bat[0] = floor($_POST['coeff_metal'])/100;
if (isset($_POST['coeff_cristal'])) $planete->coeff_bat[1] = floor($_POST['coeff_cristal'])/100;
if (isset($_POST['coeff_hydrogene'])) $planete->coeff_bat[2] = floor($_POST['coeff_hydrogene'])/100;
$planete->coeff_bat[3] = floor($_POST['coeff_cs'])/100;
if (isset($_POST['coeff_ce'])) $planete->coeff_bat[4] = floor($_POST['coeff_ce'])/100;
$planete->addModif("coeff_bat");
redirection('?p=ressources');
}
$tablo = $planete->production(3600, true);
$template->assign('ressources_prod', $tablo[1]);
$template->assign('ressources_conso', $tablo[2]);
$template->assign('ressources_coef', $tablo[0]);
$template->assign('ressources_silo', array($planete->batiments[10], pow(2, $planete->batiments[10]) * 100000));
$template->assign('ressources_toto', array($tablo[1][2] - $tablo[2][3], '(0)'));
$template->assign('ressources_tab', array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100));
?>

122
onyx2/include/game/noms.php Normal file
View file

@ -0,0 +1,122 @@
<?php
if (!isset($race)) $race = $sess->values['race'];
if ($race == 'covenant') {
$casernei = array('grunt1.jpg','jackal.jpg','94990342wb4.jpg','98004530fx3.jpg','88091275ja8.jpg','hunter1.jpg','81770345oo4.jpg','88218731ts1.jpg','72188202fg9.jpg');
$batimeni = array('batimentcovieux4.jpg','cristaloo3.png','powersupplycoviejq1.jpg','solaire.jpg','sanstitrevi7.jpg','oeilduprophetewj6.jpg','covielabocn5.jpg','chantierterrestrehg1.jpg','sanstitretruecolor09zn6.jpg','caserncov0ry.jpg','stockagebasement1cs10bl.jpg','ordianteur_hologramme.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg');
$technoli = array(
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg'),
array('../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg')
);
$nomvaisi = array('cargo2pb6.jpg','sanstitre2copiegw9.jpg','colocopiers4.jpg','sonde_despionnage1.jpg','charognard.jpg','chasseurlourd7id.jpg','contactharvestbynameleszk3.jpg','vaisseauuu0.jpg','vaisseaudebataille9na.jpg','pv.jpg','stationorbitalezt7.jpg','citecovenant.jpg', '../covenant_na.jpg', '../covenant_na.jpg');
$nomterri = array('bansheeqp0.jpg', 'spirit1.jpg', 'phantomfu2.jpg', 'boardingcraft.jpg', 'ghostic1.jpg', 'shadow.jpg', 'spectre.jpg', 'wraith.jpg', 'shade.jpg', 'defcovie.jpg', 'tourellebarreau.jpg', 'tourelle.jpg', 'lanceur_torpilles.jpg', '../covenant_na.jpg', '../covenant_na.jpg', '../covenant_na.jpg');
}
elseif (isset($sess->values['auth_level']) && $sess->values['auth_level'] >= 6 && md5($race) == '34c19b21bd4a3dda389e767d32fe9779') {
$ressourc = array('M&eacute;tal','Cristal','Hydrog&egrave;ne','&Eacute;nergie','Cr&eacute;dits');
$casernen = array('Constructor','Sentinelle L&eacute;g&egrave;re','Sentinelle Lourde','Enforcer L&eacute;ger','Enforcer Lourd','Monitor','~#PAS DE NOM#~ M&eacute;decin','~#PAS DE NOM#~ Ing&eacute;nieur','~#PAS DE NOM#~ Brute');
$casernde = array( 'Les Constructors sont des minis sentinelles capable d\'effectuer certaine reparation mineur, ils peuvent r&eacute;par&eacute;s les sentinelles endommager ainsi que les chasseurs l&eacute;gers.',
'~#DESCRIPTION MANQUANTE#~ Sentinelle L&eacute;g&egrave;re',
'~#DESCRIPTION MANQUANTE#~ Sentinelle Lourde',
'Les Enforcers L&eacute;ger, sont des sentinelles massifs qui servent &agrave; contenir des grosses infections Floods. Ils sont prot&eacute;g&eacute;s par un bouclier d\'&eacute;nergie, mais il semble seulement prot&eacute;ger que l\'avant de la machine. Il est arm&eacute; de faisceaux laser &agrave; impulsion rapides.',
'Les Enforcers Lourd, sont des sentinelles massifs qui servent &agrave; contenir des grosses infections Floods. Ils sont prot&eacute;g&eacute;s par un bouclier d\'&eacute;nergie qui recouvre toute la machine. Il est arm&eacute; de mortiers.',
'Les monitors ont &eacute;t&eacute; plac&eacute;s sur les mondes-forteresse par les Forruner pour entretenir et maintenir leurs syst&egrave;mes, et pour s\'assurer que les Floods reste emprisonn&eacute;.',
'~#DESCRIPTION MANQUANTE#~ ',
'~#DESCRIPTION MANQUANTE#~ ',
'~#DESCRIPTION MANQUANTE#~ ');
$casernea = array('constructor(s)','sentinelle(s) l&eacute;g&egrave;re(s)','sentinelle(s) lourde(s)','enforcer(s) l&eacute;ger(s)','enforcer(s) lourd(s)','monitor(s)','m&eacute;decin(s)','ing&eacute;nieur(s)','brute(s)');
$casernei = array('scoutma3.jpg','sentinellelegerecn4.jpg','nanw9.jpg','defenseurlegerhs8.jpg','defenseurlourdhr3.jpg','nanw9.jpg','nanw9.jpg','nanw9.jpg','nanw9.jpg');
$batimend = array('purificateur_m','purificateur_c','ionisateur','centrale_s','centrale_fusion','oeil','recherches','chantier_terrestre','???','caserne','silo','centre_info');
$batimeni = array('generateurdemetalsg0.jpg','generateurdecristalmh5.jpg','generateurdhydrognedh3.jpg','generateurd&Eacute;nergievb7.jpg','generateurafusiondb2.jpg',0,'centrederecherchegu9.jpg','chantierterrestrehg1.jpg','chantierspatialff8.jpg',0,'nanw9.jpg',0);
$batiment = array('G&eacute;n&eacute;rateur de M&eacute;tal','G&eacute;n&eacute;rateur de Cristal','G&eacute;n&eacute;rateur d\'Hydrog&egrave;ne','G&eacute;n&eacute;rateur d\'&Eacute;nergie',0,0,'Centre de recherches','Chantier terrestre','Chantier spatial',0,'Entrep&ocirc;t',0);
$batimede = array( 'Le g&eacute;n&eacute;rateur de m&eacute;tal vous fournit les mati&egrave;res premi&egrave;res pour la construction de vos infrastructures et de vos unit&eacute;s. Plus vous d&eacute;velopperez vos g&eacute;n&eacute;rateurs, plus uls vous rapportera. Les g&eacute;n&eacute;rateurs plus d&eacute;velopp&eacute;s ont aussi besoin de plus d\'&eacute;nergie.',
'Le g&eacute;n&eacute;rateur de cristal vous fourni les ressources pour vos installations &eacute;lectroniques et pour les alliages. Le g&eacute;n&eacute;rateur consomme deux fois plus d\'&eacute;nergie que celui du m&eacute;tal. Tous les vaisseaux et b&acirc;timents ont besoin de cristal pour leur bouclier ou encore leur composant &eacute;lectronique. La production augmente avec le d&eacute;veloppement du g&eacute;n&eacute;rateur ainsi que sa consommation.',
'L\'hydrog&egrave;ne n\'est pas directement disponible dans la nature. On doit le produire : par electrolyse de l\'eau ce qui consiste &agrave; faire passer un courant &eacute;lectrique dans de l\'eau pour que les mol&eacute;cules se s&eacute;parent et forme du dihydrog&egrave;ne. Mais cette technique utilise de trop grande quantit&eacute;e d\'&eacute;nergie.',
'Pour assurer l\'approvisionnement des g&eacute;n&eacute;rateurs, des g&eacute;n&eacute;rateurs &eacute;nergie g&eacute;antes sont n&eacute;cessaires. Plus ces installations sont d&eacute;velopp&eacute;es, plus vous obtiendrez d\'&eacute;nergie pour vos g&eacute;n&eacute;rateurs. Les g&eacute;n&eacute;rateurs d\'&eacute;nergies sont la base de l\'approvisionnement pour votre plan&egrave;te en &eacute;nergie.',
0,
0,
'Le centre de recherche est n&eacute;cessaire pour d&eacute;velopper de nouvelles technologies. Le niveau du centre d&eacute;termine la vitesse de la recherche. Chaque plan&egrave;te que vous coloniserez devra &ecirc;tre &eacute;quip&eacute;e d\'un centre de recherche.',
'~#DESCRIPTION MANQUANTE#~ Chantier terrestre',
'Le chantier spatial vous permet de construire des vaisseaux, de l\'infanterie et vos installations de d&eacute;fense. Plus le chantier est grand, plus la construction de vaisseaux, le recrutement de l\'infanterie et la cr&eacute;ation d\'installations de d&eacute;fense est rapide.',
0,
'Les ressources qui ne sont pas encore trait&eacute;es sont mises en stock dans ces entrep&ocirc;ts g&eacute;ants. Un entrep&ocirc;t plus grand permet le stockage d\'une plus grande quantit&eacute; de ressources. Lorsque l\'entrep&ocirc;t est plein, l\'extraction est stopp&eacute;e. Il est grandement conseill&eacute; de d&eacute;velopper ce genre d\'infrastructure.',
0);
$technolo = array(
array('Forage niveau 1', 'Forage niveau 2', 'Commerce galactique niveau 1', 'Rendement m&eacute;tal niveau 1', 'Rendement cristal niveau 1', 'Rendement hydrogène niveau 1', 'Forage niveau 3', 'Th&eacute;orie du March&eacute; niveau 1', 'Rendement m&eacute;tal niveau 2', 'Rendement m&eacute;tal niveau 3', 'Rendement cristal niveau 2', 'Rendement cristal niveau 3', 'Rendement hydrogène niveau 2', 'Fonderies avanc&eacute;es niveau 1', 'Rendement hydrogène niveau 3', 'Th&eacute;orie du March&eacute; niveau 2', 'Th&eacute;orie du March&eacute; niveau 3', 'Fonderies avanc&eacute;es niveau 2', 'Fonderies avanc&eacute;es niveau 3'),
array('Maîtrise &eacute;nergie niveau 1', 'Informatique', 'Constructions plan&eacute;taires', 'Maîtrise &eacute;nergie', 'R&eacute;acteur &agrave; combustion', 'Maîtrise &eacute;nergie', 'R&eacute;acteur &agrave; combustion', 'R&eacute;acteur &agrave; fusion', 'R&eacute;acteur &agrave; combustion', 'R&eacute;acteur &agrave; fusion', 'R&eacute;acteur &agrave; fusion type II ', 'R&eacute;acteur &agrave; fusion', 'R&eacute;acteur &agrave; fusion type II ', 'R&eacute;acteur &agrave; fusion type II ', 'Informatique', 'IA ', 'T&eacute;l&eacute;communications', 'Espionnage', 'Contre-espionnage', 'Informatique', 'IA ', 'IA ', 'T&eacute;l&eacute;communications', 'Polymères radars', 'T&eacute;l&eacute;communications', 'Polymères radars', 'Polymères radars', 'Espionnage', 'Espionnage', 'Contre-espionnage', 'Contre-espionnage', 'Constructions plan&eacute;taires', 'Construction optimis&eacute;e', 'Ing&eacute;nierie orbitale', 'Constructions plan&eacute;taires', 'Am&eacute;nagement territorial', 'Am&eacute;nagement territorial', 'Am&eacute;nagement territorial'),
array('Immigration coloniale', 'Sciences politiques', 'Immigration coloniale', 'Urbanisme', 'Immigration coloniale', 'Urbanisme', 'Grandes surfaces', 'Centre de loisirs', 'Arcologie', 'Urbanisme', 'Sciences politiques', 'Strat&eacute;gie militaire', 'Sciences politiques', 'Strat&eacute;gie militaire', 'Strat&eacute;gie militaire'),
);
$technode = array( 'L\'informatique vous permet de traiter les informations de façon tr&egrave;s rapide r&eacute;duisant ainsi les temps de r&eacute;actions qui dans les combats peuvent s\'av&eacute;rer fatales.',
'La d&eacute;tection est cruciale pour pr&eacute;server sa flotte et ses plan&egrave;tes. D&eacute;velopper cette technologie vous permet de construire une base « œil des proph&egrave;tes » qui rep&egrave;rera les vaisseaux s\'approchant de votre plan&egrave;te.',
'Un soldat n\'est rien sans son arme, et qu\'est-ce qu\'un soldat d&eacute;muni face aux assauts f&eacute;roces adverses ? Cette technologie vous permettra de rechercher de nouveaux syst&egrave;mes d\'armements afin de rendre vos outils de guerre plus pr&eacute;cis et mortels.',
'Le bouclier est un champ de force qui entoure vos vaisseaux et les prot&egrave;ge. Ainsi il permet &agrave; vos vaisseaux de tenir plus longtemps face aux missiles adverses, ceci s\'av&eacute;rant peut &ecirc;tre d&eacute;cisif dans l\'issue de la bataille.',
'L\'&eacute;nergie est la base de tout. Sans &eacute;nergie, pas de voyages stellaires ni m&ecirc;me de quoi faire marcher vos installations. C\'est pourquoi l\'&eacute;tude de nouvelles façons de produire de l\'&eacute;nergie est vitale pour vos plan&egrave;tes et vaisseaux ; vos chercheurs vous permettront &eacute;galement d\'acc&eacute;der &agrave; de nouveaux types d\'&eacute;nergies, beaucoup plus int&eacute;ressants.',
'Les r&eacute;acteurs &agrave; antigravit&eacute; sont les moteurs basiques covenant. Ils utilisent une technologie complexe projetant des particules quantiques cr&eacute;ant un champ gravitationnel inverse annulant ainsi la gravit&eacute; pr&eacute;sente. Le principe fonctionne &eacute;galement dans l\'espace puisque l\'absence de gravit&eacute; dans l\'espace, sans compter les &eacute;toiles et les autres anomalies spatiales, permet une projection plus puissante du champ.',
'Apr&egrave;s la combustion, voici la fusion. Ce type de r&eacute;acteur est beaucoup plus puissant que la combustion utilis&eacute;e depuis d&eacute;j&agrave; des centaines d\'ann&eacute;es. Il g&eacute;n&egrave;re une &eacute;nergie cin&eacute;tique de grande envergure. Aucun dirigeant politique d&eacute;sirant voyager dans le cosmos ne pourrait s\'en passer.',
'Les covenants ont d&eacute;couvert d\'anciens r&eacute;acteurs &agrave; fusion utilisant la technologie d\'hyperpropulsion Forruner. Cette technologie, beaucoup plus puissante que le r&eacute;acteur conventionnel au Plasma, autorise des sauts dans le sous-espace ultra pr&eacute;cis. Ce type de r&eacute;acteur est le plus cher mais aussi le plus rapide et puissant de toute la flotte covenante.',
'La m&eacute;decine vous permet d\'avoir moins de pertes au combat et ainsi d\'avoir une force de frappe qui r&eacute;siste plus longtemps. Au lieu de laisser mourir les soldats bless&eacute;s, le m&eacute;decin les soigne pour les remettre sur pied et les rendre de nouveau aptes au combat.',
'En tant que g&eacute;n&eacute;ral, vous devez avoir un esprit fin pour gagner vos batailles terrestres aussi bien que les affrontements spatiaux. C\'est pourquoi il vous faudra toujours innover en mati&egrave;re de strat&eacute;gie, vous montrer toujours plus rus&eacute; que votre impitoyable adversaire, aussi feriez-vous bien d\'&eacute;tudier de nouvelles tactiques de combat pour vous assurer une franche victoire.');
$technoli = array('informatique1.jpg','detection.jpg','sanstitretruecolor04no6.jpg','boucliervaiseaucovenantey4.jpg','&Eacute;nergie.jpg','reacteurantigravyd1.jpg','reacteur_f.jpg','reacteurfusionforerunnewu0.jpg','medecine.JPG','commandement.jpg');
$nomvaisa = array('cargos de classe Inquisitor','grand(s) transporteur(s)','vaisseau(x) de colonisation','sonde(s)','recycleur(s)','s&eacute;raphin(s)','fr&eacute;gate(s)','croiseur(s) de classe CCS','croiseur(s) de classe Reverence','porte-vaisseaux','station(s) orbitale','super(s) porte-vaisseaux');
$nomvaisi = array('nanw9.jpg','nanw9.jpg','nanw9.jpg',0,'nanw9.jpg','croiseurforrunerns4.jpg','superdestroyerwa6.jpg','nanw9.jpg','chasseurlourdfk8.jpg','nanw9.jpg','nanw9.jpg','nanw9.jpg');
$nomvaisn = array('Transporteur Leger','Transporteur Lourd','Colonisateur',0,'Recycleur','Croiseur Forruner','Super-Destroyer','Chasseur Leger','Chasseur Lourd','Porte-Vaisseaux','Station orbitale','Super porte-vaisseaux');
$nomvaisd = array( '~#DESCRIPTION MANQUANTE#~ Transporteur Leger',
'~#DESCRIPTION MANQUANTE#~ Transporteur Lourd',
'~#DESCRIPTION MANQUANTE#~ Colonisateur',
0,
'~#DESCRIPTION MANQUANTE#~ Recycleur',
'~#DESCRIPTION MANQUANTE#~ Croiseur Forruner',
'~#DESCRIPTION MANQUANTE#~ Super-Destroyer',
'~#DESCRIPTION MANQUANTE#~ Chasseur Leger',
'~#DESCRIPTION MANQUANTE#~ Chasseur Lourd',
'~#DESCRIPTION MANQUANTE#~ Porte-Vaisseaux',
'~#DESCRIPTION MANQUANTE#~ Station spatiale',
'~#DESCRIPTION MANQUANTE#~ Super porte-Vaisseaux');
$nomterra = array(0,0,0,0,0,0,0,0,'tour(s) &agrave; plasma','tour(s) ion','canon(s) Orbital','drone(s)','station(s) de defense');
$nomterri = array(0,0,0,0,0,0,0,0,'tourplasmasl4.jpg','tourioniquegr6.jpg','nanw9.jpg','nanw9.jpg','stationdedefensent8.jpg');
$nomterrn = array(0,0,0,0,0,0,0,0,'Tour &agrave; plasma','Tour Ion','Canon Orbital','Drone','Station de defense');
$nomterde = array( 0,
0,
0,
0,
0,
0,
0,
0,
'~#DESCRIPTION MANQUANTE#~ Tour &agrave; plasma',
'~#DESCRIPTION MANQUANTE#~ Tour Ion',
'~#DESCRIPTION MANQUANTE#~ Canon Orbital',
'~#DESCRIPTION MANQUANTE#~ Drone',
'~#DESCRIPTION MANQUANTE#~ Station de defense');
}
elseif ($race == 'humain' || $race == "none") {
$casernei = array('marines.jpg','marinehf0.jpg','grenadier.jpg','TCAO2.jpg','sniper.jpg','spartan.jpg','medecin.jpg','ingenieurs.jpg','exosquelettehbpb2.jpg');
$batimeni = array('mine_m.jpg','mine_c.png','synchroniseur.jpg','centrale solaire.jpg','centrale electrique.jpg','baseradardl3.jpg','recherches.jpg','chantierterrestrecopybj8.jpg','chantier spatial.jpg','ecole militaire.jpg','stockage.jpg','search0yp.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg');
$technoli = array(
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg'),
array('../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg', '../humain_na.jpg')
);
$nomvaisi = array('csnucargoparabola2mc9.jpg','csnucargoladen2al8.jpg','colonisation.jpg','../humain_na.jpg','longsworduf9.jpg','../humain_na.jpg','../humain_na.jpg','frgatecopiegw1.jpg','../humain_na.jpg','halcyo15.jpg','qsu169.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg');
$nomterri = array('csnusparrowhawkkp4.jpg','pelican.jpg','csnushortswordad3.jpg','albatross.jpg','warthog-vrl.jpg','M12G1_LAAV_Warthog.jpg','M12A1_LAAV_Warthog.jpg','scorpionN.jpg',
'../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg','../humain_na.jpg');
}
else {
$template->assign("race", "humain");
erreur('Erreur dans le fichier de race, rapporter le bug. Veuillez indiquer dans le rapport de bug l\'adresse de la page sur laquelle vous vous trouver.');
}
?>

View file

@ -0,0 +1,20 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Aide';
if (empty($_GET['q'])) $_GET['q'] = '';
switch($_GET['q']){
case '1':
$page = '../aide/avertissements'; break;
case '2':
$page = '../aide/config'; break;
case '3':
$page = '../aide/intro'; break;
case '4':
$page = '../aide/commentjouer'; break;
default:
$page = '../aide/sommaire';
}
?>

View file

@ -0,0 +1,57 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Amis';
$a = gpc('a');
$nom = gpc('nom', 'post');
//Suppression d'un ami
if (!empty($a)) {
$d = gpc('d');
if (!empty($d) && $a == md5(date('GA').'@'.$d)) {
$f = array_keys($planete->amis, $d);
unset($planete->amis[$f[0]]);
$bdd->reconnexion();
$bdd->query("UPDATE $table_user SET amis = '".serialize($planete->amis)."' WHERE id = $id_user;");
$bdd->deconnexion();
}
header('Location: ?p=amis');
exit;
}
//Ajout d'un ami dans la liste
elseif (!empty($nom)) {
$bdd->reconnexion();
$plan = $bdd->unique_query("SELECT id FROM $table_user WHERE pseudo = '$nom';");
if ($plan) {
if (in_array($plan['id'], $planete->amis)) {
$bdd->deconnexion();
erreur('Ce joueur est déjà dans votre liste d\'amis.', "red", "?p=amis", 2000);
}
$planete->amis[] = $plan['id'];
$bdd->query("UPDATE $table_user SET amis = '".serialize($planete->amis)."' WHERE id = $id_user;");
}
else {
$bdd->deconnexion();
erreur('Joueur introuvable.', "red", "?p=amis", 2000);
}
$bdd->deconnexion();
header('Location: ?p=amis');
exit;
}
//Affichage de la liste d'amis
else {
$page = 'amis';
$destins = array();
$bdd->reconnexion();
foreach($planete->amis as $ami){
$res = $bdd->unique_query("SELECT pseudo FROM $table_user WHERE id = ".$ami.";");
if ($res != false) {
$destins[] = array($ami, $res['pseudo'], md5(date('GA').'@'.$ami));
}
}
$bdd->deconnexion();
$template->assign('destins', $destins);
}
?>

View file

@ -0,0 +1,29 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'vide';
$titre = 'Multicompte';
$template->assign('titreP', '<span style="color: red;">! ATTENTION AU MULTICOMPTE !</span>');
$bdd->reconnexion();
$multi = $bdd->query("SELECT U.pseudo, R.id_util FROM $table_registre_identification R INNER JOIN $table_user U ON U.id = R.id_util WHERE R.ip = '".$_SERVER["REMOTE_ADDR"]."' GROUP BY R.ip, R.id_util");
$bdd->deconnexion();
$cnt = count($multi);
$joueurs = '';
for($i = 0; $i < $cnt; $i++){
if ($multi[$i]['id_util'] == $id_user) continue;
if ($joueurs != '') $joueurs .= ', '.$multi[$i]['pseudo'];
else $joueurs = $multi[$i]['pseudo'];
}
//Si pas de multi-compte, on redirige vers la page d'accueil
if ($cnt)
redirection('./'.$config['first_page']);
$template->assign('contenu', '<div class="error">Nous avons détecté que plus d\'un compte s\'est connecté sur cette adresse IP.<br />Pour ne pas être considéré comme multi-compte, évitez toute interraction avec '.$joueurs.'<br /><br />Si vous êtes plusieurs dans la même famille à jouer à Halo-Battle dans cette galaxie, <ins>vous devez impérativement</ins> <a href="'.$config['link']["operateur"].'">prendre contact avec un opérateur</a> afin que vos comptes ne soient pas considérés comme du multi-compte.<br /><br />Si vous vous connectez depuis un lieu public (cybercafé, aéroport, hôtel, wifi public, ...), vous pouvez prévenir <a href="'.$config['link']["operateur"].'">les opérateurs de la galaxie</a> afin que cette connexion ne soit pas considérée comme du multi-compte.<br /><br />Pour plus d\'informations, reportez-vous <a href="?p=regles#comptes">au chapitre <i>Comptes</i> des régles du jeu</a>.</div>');
unset($multi, $cnt, $joueurs);
?>

View file

@ -0,0 +1,161 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
if (!empty($SESS->values['connected'])) $page = '../cms/vide';
else $page = 'vide';
$titre = 'Conditions générales d\'utilisation';
$template->assign('contenu','
<h1>Conditions générales pour le site Halo-Battle.s-fr.com</h1>
<div style="text-align: left; margin: 15px; font-size: 115%;">
<br />
Halo, Bungie et Microsoft sont des marques et logos déposés par Microsoft Corporation.<br />
Tous droits réservés Copyright © 2006-2007<br />
halo-battle.s-fr.com Tous droits reservés.<br />
<br />
Le site d\'halo-battle.s-fr.com demande à tous les utilisateurs du jeu de lire et d\'accepter les Conditions Générales énoncées ci-dessous avant de s\'inscrire.<br />
<br />
<br />
Ces Conditions Générales d\'Utilisation ont été publiées le 23/04/2008 et sont applicables à partir du 30/04/2008.<br />
<br />
<br />
<a href="#services">I. Services</a><br />
<a href="#adhesion">II. Adhésion</a><br />
<a href="#protection">III. Protections des données</a><br />
<a href="#responsabilite">IV. Responsabilité</a><br />
<a href="#contenu">V. Contenu / responsabilité envers le contenu</a><br />
<a href="#actions">VI. Actions prohibées</a><br />
<a href="#restrictions">VII. Restrictions</a><br />
<a href="#droits">VIII. Droits de société concernant les comptes</a><br />
<a href="#modification">IX. Modification des Conditions Générales</a><br />
<a href="#loi">X. Loi applicable</a><br />
<br />
<br /><h3 id="services">I. Services</h3><br />
<h4>1 - Conditions de participation</h4><br />
Pour participer à Halo-Battle, l\'utilisateur doit accepter les Conditions Générales. Ces Conditions Générales sont principalement, mais non exclusivement, portées sur les services proposés par la présence en ligne de Halo-Battle.s-fr.com<br />
<br /><h4>2 - Responsabilité</h4><br />
Halo-Battle.s-fr.com est toujours attentif au bon fonctionnement de toutes les prestations qu\'il propose. Néanmoins, certaines desdites prestations peuvent ne pas être disponibles pour des circonstances indépendantes de notre volonté. Pour cette raison, l\'utilisateur ne peut avoir de halo-battle.s-fr.com ne peut être tenu pour responsable du mauvais fonctionnement du serveur ou pour un défaut de programmation. Les exemples précités ne sont pas exclusifs d\'autres possibilités.<br />
<br /><h3 id="adhesion">II. Adhésion</h3><br />
<br /><h4>1 - Conditions d\'adhésion</h4><br />
L\'adhésion commence à partir de l\'enregistrement d\'un compte sur le jeu ou le forum. L\'adresse e-mail utilisée pour cet enregistrement doit être valide. halo-battle.s-fr.com se réserve le droit de vérifier cette validité à n\'importe quel moment.<br />
Les utilisateurs reconnaissent disposer d\'une expérience suffisante en matière d\'utilisation d\'Internet et des fonctionnalités de communication électronique qui y sont liées.<br />
Les utilisateurs du site de halo-battle.s-fr.com sont tenus de s\'assurer de la compatibilité de leur logiciel de navigation avec le site de Halo-Battle.s-fr.com.<br />
<br /><h4>2 - Résiliation par l\'utilisateur</h4><br />
L\'adhésion peut être résiliée par l\'utilisateur par le biais de l\'effacement du compte. Cet effacement peut être retardé pour des questions d\'ordre technique. La gestion des informations concernant les données personnelles du compte est relatif au chapitre 3 des conditions générales d\'utilisation.<br />
<br /><h4>3 - Résiliation par Halo-Battle.s-fr.com</h4><br />
L\'utilisateur ne peut participer à la gestion des services proposés par Halo-Battle.s-fr.com. A ce titre, l\'équipe du jeu se réserve le droit d\'effacer ou de bloquer le compte de l\'utilisateur, en cas de violation des Conditions Générales, sans que cela ne soit exclusif d\'autres possibilités.<br />
L\'effacement du compte est décidé par l\'ensemble de l\'équipe. Les quelconques revendications concernant un effacement de compte peuvent être portées auprès de l\'équipe du jeu. Il ne peut y avoir de revendications légales concernant la clotûre du compte.<br />
<br /><h3 id="protection">III. Protections des données</h3><br />
<br /><h4>1 - Droit d\'accès aux données</h4><br />
Conformément à la loi du 7 janvier 1978, vous disposez d\'un droit d\'accès, de rectification, de vérification et de suppression relatif aux données vous concernant.<br />
Il vous suffit pour ce faire d\'adresser une demande par e-mail à contact@halo-battle.s-fr.com, Halo-Battle.s-fr.com modifiera et mettra ses informations à jour en conséquent.<br />
<br /><h4>2 - Stockage des données personnelles</h4><br />
Halo-Battle.s-fr.com se réserve le droit de stocker les données personnelles des utilisateurs dans le but de contrôler le respect des règles, des Conditions Générales et des dispositions législatives par lesdits utilisateurs. Les données personnelles concernées peuvent être les adresse IP par connexion, la méthode, l\'heure et les durées de connections, l\'adresse e-mail fournie lors de la création du compte ainsi que, le cas échéant, les données personnelles fournies volontairement par l\'utilisateur par le biais de son profil. Sur les forums, les données personnelles des profils des utilisateurs sont conservées.<br />
<br /><h4>3 - Communication et utilisation des données</h4><br />
Halo-Battle.s-fr.com se réserve le droit, en conformité avec les dispositions du droit français concernant la protection des données personnelles et toutes dispositions législatives applicables, de divulguer les données personnelles aux autorités, qui les requièrent en vue de protéger les intérêts des sociétés ou les éventuels manquements aux dispositions légales concernant la protection des données.
<br /><h4>4 - Opposition</h4><br />
L\'utilisateur peut s\'opposer au stockage de ses données personnelles à tout moment. La participation aux jeux nécessitant le stockage de ces données personnelles, le(s) compte(s) de l\'utilisateur sera(ont) supprimé(s) le plus rapidement possible en fonction des contraintes techniques.<br />
<br /><h3 id="responsabilite">IV. Responsabilité</h3><br />
Halo-Battle.s-fr.com n\'est pas responsable pour les dommages, quelle qu\'en soit la gravité, causés par l\'utilisation du jeu Halo-Battle. halo-battle.s-fr.com rappelle aux joueurs que l\'utilisation excessive des jeux informatiques peut causer de sévères troubles physiques.<br />
<br /><h3 id="contenu">V. Contenu / responsabilité envers le contenu</h3><br />
<br /><h4>1 - Utilisation de la plateforme des utilisateurs</h4><br />
Halo-Battle.s-fr.com fournit une plateforme qui permet à l\'utilisateur de communiquer avec chacun des autres utilisateurs. L\'utilisateur est responsable du contenu de ses propos : les propos pornographiques, xénophobes, insultants ou à contenu illégaux ne sont pas autorisés et relèvent de la responsabilité de leur auteur. En cas de violation, Halo-Battle.s-fr.com se réserve le droit d\'effacer ou de bloquer le compte de l\'utilisateur fautif et de l\'interdire d\'accès sur l\'ensemble des services proposés par l\'équipe. Ces sanctions ne sont pas exclusives d\'éventuelles poursuites judiciaires et/ou pénales.<br />
<br /><h4>2 - Dommages internes au contenu</h4><br />
L\'utilisateur du site est conscient du fait qu\'Internet n\'est pas un média parfaitement protégé et qu\'une sécurité totale quant au respect de la vie privée ne peut être garantie. Par conséquent, halo-battle.s-fr.com ne sera en aucune manière responsable des dommages éventuels subis par l\'utilisateur du site à la suite de l\'introduction par ce dernier d\'informations confidentielles ou délicates.<br />
<br /><h4>3 - Engagement de Halo-Battle.s-fr.com</h4><br />
halo-battle.s-fr.com s\'engage à mettre en oeuvre tous les moyens raisonnables à sa disposition en vue de permettre aux utilisateurs une utilisation optimale des services proposés. halo-battle.s-fr.com n\'est en conséquence tenue qu\'à une obligation de moyen, et en aucun cas à une obligation de résultat.<br />
halo-battle.s-fr.com ne peut être tenu pour responsable des conséquences de circonstances indépendantes de sa volonté telles que les grèves, lock-out, guerres, intempéries, etc., les défaillances des systèmes informatiques ou des moyens de communication, ou de tout autre événement constitutif d\'un cas de force majeure.<br />
<br /><h4>4 - Mise à disposition des informations</h4><br />
halo-battle.s-fr.com assure la mise à disposition via ce site d\'informations correctes et actualisées et se réserve donc le droit de modifier à tout moment le contenu du site. Toutefois, halo-battle.s-fr.com n\'est en aucun cas responsable des dommages causés à la suite de données éventuellement incorrectes, non actualisées ou incomplètes communiquées via le site.<br />
Les utilisateurs du site de halo-battle.s-fr.com s\'engagent à avertir immédiatement l\'équipe de toute utilisation frauduleuse du site de halo-battle.s-fr.com et à ne pas chercher à nuire à l\'intégrité ou au fonctionnement du site.<br />
<br /><h4>5 - Liens</h4><br />
halo-battle.s-fr.com n\'a aucun pouvoir de vérification et de contrôle quant à la création de liens vers des sites extérieurs et quant au contenu des dits sites, que ces sites soient marchands ou non.<br />
Les propriétaires des sites consultés à partir du site de Halo-Battle.s-fr.com sont, notamment, seuls responsables du respect de l\'ensemble des réglementations s\'appliquant dans le cadre des prestations offertes en ligne, et notamment, des lois et règlements relatifs à la vente à distance, la protection du consommateur, la publicité mensongère ou trompeuse, les prix, la conformité des produits, etc.<br />
Aussi, l\'utilisateur accepte que son choix d\'accéder à un autre site, par l\'intermédiaire d\'un lien hypertexte s\'effectue à ses risques et périls.<br />
En conséquence, tout préjudice direct ou indirect résultant de l\'accès à un site relié par un lien hypertexte ne peut engager la responsabilité de Halo-Battle.s-fr.com<br />
<br /><h3 id="actions">VI. Actions prohibées</h3><br />
<br /><h4>1 - Actions de manipulations</h4><br />
L\'utilisateur n\'a le droit d\'utiliser, un quelconque programme, mécanisme ou logiciel qui pourrait interférer avec les fonctions et/ou le développement du jeu. L\'utilisateur n\'a pas de le droit d\'effectuer une quelconque action qui causerait un ralentissement excessif des capacités techniques du site. L\'utilisateur n\'a pas le droit de bloquer, modifier ou reformuler le contenu créé par l\'équipe de dévellopement du projet.<br />
<br /><h4>2 - Programmes prohibés</h4><br />
Il est interdit de visualiser une quelconque partie du jeu avec un autre programme que les navigateurs Internet prévus à cet effet. Sont visés, tous autres programmes, en particulier ceux connus sous la dénomination de bots (sans que cette appellation soit exclusive), ainsi que tous
outils permettant de simuler, remplacer ou de suppléer le navigateur
internet. De la même manière, sont visés les scripts et les programmes
partiellement ou totalement automatiques qui peuvent procurer un
avantage par rapport aux autres utilisateurs. Les fonctions de
rafraîchissement automatique ("auto-refresh") et autres mécanismes
intégrés dans les navigateurs Internet sont également visés en tant
qu\'actions automatiques. L\'intégralité de ces mécanismes, sans que cela
soit exclusif d\'autres possibilités, est interdit. Le fait de bloquer la
publicité soit intentionnellement soit par le biais d\'un bloqueur de
pop-up voire par le biais d\'un module intégré aux navigateurs Internet
est sans conséquence sur cette interdiction. Les seules exceptions
possibles nécessitent la permission expresse de l\'équipe de Halo-Battle.s-fr.com<br />
<br /><h4>4 - Connexion directe</h4><br />
La connexion au compte de l\'utilisateur est uniquement permise par le
biais de la page d\'accueil du jeu. L\'ouverture automatique ou
automatisée, est interdite, que la page d\'accueil soit affichée ou non.<br />
<br /><h3 id="restrictions">VII. Restrictions</h3><br />
<br /><h4>1 - Nombre maximum de comptes</h4><br />
Chaque utilisateur n\'est autorisé qu\'à utiliser un compte par univers.
Sont dénommés "Multis" les utilisateurs qui n\'agissent pas en accord
avec cette règle. Les "Multis" sont susceptibles de voir leurs comptes
effacés ou bloqués sans avertissement préalable.<br />
<br /><h4>2 - Règles</h4><br />
Les particularités sont visées par les règles du jeu. Tous les
utilisateurs sont soumis à ces dispositions.<br />
<br /><h4>3 - Blocages</h4><br />
L\'utilisateur peut être bloqué de manière temporaire ou définitive. Le
blocage peut être valable sur une partie ou la totalité des services
proposés par Halo-Battle.s-fr.com<br />
<br /><h3 id="droits">VIII. Droits de société concernant les comptes</h3><br />
<br /><h4>1 - Généralités</h4><br />
L\'ensemble des comptes, incluant les ressources, unités, etc, sont des objets virtuels du jeu. L\'utilisateur n\'a pas la propriété ou tout autre type de droits sur le compte. L\'ensemble des droits sont de la propriété de Bungie et Microsoft Corporation. Aucun droit, en particulier ceux concernant l\'exploitation, ne peut être conféré à l\'utilisateur.<br />
<br /><h4>2 - Interdiction d\'exploitation</h4><br />
Il est interdit de contracter avec une tierce partie un quelconque accord concernant le transfert, l\'utilisation ou le stockage des comptes ou des données personnelles. Il est particulièrement interdit de vendre les comptes ou les ressources, voire de faire un quelconque profit en quittant son compte ou ses ressources au profit d\'un tiers. Les mêmes interdictions sont valables pour les données personnelles et les droits d\'utilisation. La violation de ces règles ou de tout autre droit de Bungie et Microsoft Corporation, particulièrement celles concernant le copyright, sera transmise aux autorités et sanctionnée par des poursuites judiciaires et/ou pénales.<br />
<br /><h4>3 - Exceptions</h4><br />
Il est permis de transférer les comptes de manière gratuite, ainsi que d\'échanger des ressources dans les limites permises par les règles du jeu.<br />
<br /><h3 id="modification">IX. Modification des Conditions Générales</h3><br />
Halo-Battle.s-fr.com se réserve le droit de modifier ou d\'étendre les Conditions Générales et les autres dispositions à tout moment. Cette modification ou extension sera publiée au minimum deux semaines avant l\'effectivité des changements.<br />
<br /><h3 id="loi">X. Loi applicable</h3><br />
La législation française est appliquée en cas de recours légal.<br />
</div>');
?>

View file

@ -0,0 +1,230 @@
<?php
//On traite la demande de loggin de l'utilisateur
if ((isset($_GET['l']) && isset($_GET['p'])) || (isset($_POST['HB_login']) && isset($_POST['HB_password'])))
{
//Récupération des données POST ou GET
if (isset($_POST['HB_login']) && isset($_POST['HB_password']) && gpc('p') == 'connexion')
{
$HB_login = gpc('HB_login', 'post');
$HB_password = gpc('HB_password', 'post');
$HB_auth = hash("sha512", $HB_login.'Ņ♂↨'.$HB_password.'☻♫☼'.date('W!Y¨D@j').$_SERVER["HTTP_USER_AGENT"].$_SERVER["REMOTE_ADDR"]);
}
else
{
$HB_login = gpc('l');
if (is_numeric('0x'.gpc('p')))
$HB_password = cxor(hexstr(gpc('p')), date('WYDj'));
$HB_auth = gpc('a');
}
if (empty($HB_login) || empty($HB_password))
{
$template->assign('message', $LANG['badNomMdp']);
$template->assign('couleur', 'red');
$template->display('cms/erreur.tpl');
exit;
}
elseif (hash("sha512", $HB_login.'Ņ♂↨'.$HB_password.'☻♫☼'.date('W!Y¨D@j').$_SERVER["HTTP_USER_AGENT"].$_SERVER["REMOTE_ADDR"]) != $HB_auth && hash("sha512", $HB_login.'Ņ♂↨'.$HB_password.'☻♫☼'.date('W!Y¨D@j', time()-300)) != $HB_auth)
{
$template->assign('message', $LANG['badAuthConnect'].'<br /><br />'.$LANG['contactAdmin']);
$template->assign('couleur', 'red');
$template->display('cms/erreur.tpl');
exit;
}
else
{
$ip = $_SERVER["REMOTE_ADDR"];
//Connexion à la base de données
if (!isset($bdd)) $bdd = new BDD();
else $bdd->reconnexion();
//Sauvegarde du nombre d'essai pour éviter les brute-force
$bruteforce = $bdd->unique_query("SELECT nombre FROM securite_identification WHERE ip = '$ip';");
if ($bruteforce['nombre'] >= 10)
{
$fichier = fopen(ONYX."ban.xlist",'a+');
fwrite($fichier, $ip."\n\r");
fclose($fichier);
}
$bdd->escape($HB_login);
if (!$var = $bdd->unique_query("SELECT mdp_var, mdp FROM $table_user WHERE pseudo = '$HB_login';"))
{
if (isset($bruteforce['nombre']))
$bdd->query("UPDATE securite_identification SET nombre = nombre + 1 WHERE ip = '$ip';");
else
$bdd->query("INSERT INTO securite_identification VALUES ('$ip', '1', '".time()."');");
$bdd->deconnexion();
$template->assign('message', $LANG['badNomMdp']);
$template->assign('couleur','red');
$template->assign('script','<script type="text/javascript">setTimeout(\'document.location.href="'.$VAR['link']['accueil'].'";\', 2500);</script>');
$template->display('cms/erreur.tpl');
exit;
}
$bdd->deconnexion();
$HB_password = mdp($HB_login, $HB_password, $var['mdp_var']);
//Limiter le nombre de personnes en ligne simutanément
if ($header['count'][2] > 1500)
{
$template->assign('message', $LANG['servSature']);
$template->assign('couleur', 'red');
$template->display('cms/erreur.tpl');
exit;
}
unset($bruteforce, $fichier);
$time = time();
$bdd->reconnexion();
$bdd->escape($HB_password);
$resultat = $bdd->unique_query("SELECT id, race, mv, last_visite, auth_level, raisonmv FROM $table_user WHERE pseudo = '$HB_login' AND mdp = '$HB_password';");
if ($resultat)
{
$id = $resultat['id'];
$reqPlan = $bdd->query("SELECT id, file_bat, file_tech, file_cas, file_vais, file_ter, timestamp FROM $table_planete WHERE id_user = '$id' ORDER BY id ASC;");
$resultatP = $reqPlan[0];
$race = $resultat['race'];
if (!$reqPlan)
{
$template->assign('message', $LANG['badPlanete']);
$template->assign('couleur', 'red');
$template->display('cms/erreur.tpl');
exit;
}
if ($resultat['mv'] > 0)
{
if (($resultat['last_visite'] + 259200 > time() || $resultat['mv'] == 3) && $resultat['auth_level'] < 2)
{
if ($resultat['mv'] == 3)
$template->assign('message', sprintf($LANG['banInf'], $resultat['raisonmv']));
elseif ($resultat['mv'] == 2)
$template->assign('message', sprintf($LANG['banVac'], $resultat['raisonmv'], strftime("%A %d %B à %H:%M", $resultat['last_visite']+259200)));
else
$template->assign('message', sprintf($LANG['modVac'], strftime("%A %d %B à %H:%M", $resultat['last_visite']+259200)));
$template->assign('couleur', 'red');
$template->display('cms/erreur.tpl');
exit;
}
$bdd->query("UPDATE $table_user SET mv = '0' WHERE id = $id;");
$bdd->query("UPDATE $table_planete SET timestamp = '".time()."' WHERE id_user = $id;");
$bdd->deconnexion();
//On fait repartir à 0 les files d'attente
include_once("game/vars.php");
include_once("Class/class.file.php");
include_once("Class/class.user.php");
include_once("Class/class.planete.php");
foreach ($reqPlan as $plan)
{
if (!empty($plan['file_bat']))
{
$file = new File($plan['file_bat']);
$fileBat = $file->reajusteVacances($plan['timestamp']);
}
else
$fileBat = '';
if (!empty($plan['file_tech']))
{
$file = new File($plan['file_tech']);
$fileTech = $file->reajusteVacances($plan['timestamp']);
}
else
$fileTech = '';
if (!empty($plan['file_cas']))
{
$file = new File($plan['file_cas']);
$fileCas = $file->reajusteVacances($plan['timestamp']);
}
else
$fileCas = '';
if (!empty($plan['file_vais']))
{
$file = new File($plan['file_vais']);
$fileVais = $file->reajusteVacances($plan['timestamp']);
}
else
$fileVais = '';
if (!empty($plan['file_ter']))
{
$file = new File($plan['file_ter']);
$fileTer = $file->reajusteVacances($plan['timestamp']);
}
else
$fileTer = '';
$idPlan = $plan['id'];
$bdd->reconnexion();
$bdd->escape($fileBat);
$bdd->escape($fileTech);
$bdd->escape($fileCas);
$bdd->escape($fileVais);
$bdd->escape($fileTer);
$bdd->query("UPDATE $table_planete SET file_bat = '$fileBat', file_tech = '$fileTech', file_cas = '$fileCas', file_vais = '$fileVais', file_ter = '$fileTer' WHERE id = $idPlan;");
$bdd->deconnexion();
//On met à jour la planète pour tout le reste
$plan = new Planete($idPlan, true);
}
}
//On met à jour toutes les planètes si le nombre de joueurs n'est pas trop important
elseif ($header['count'][2] > 400)
{
include_once("game/vars.php");
include_once("Class/class.file.php");
include_once("Class/class.user.php");
include_once("Class/class.planete.php");
foreach ($reqPlan as $plan)
{
$plan = new Planete($plan['id'], true);
}
}
unset($plan);
$bdd->reconnexion();
$bdd->query("UPDATE $table_user SET last_visite = '$time', last_ip = '$ip' WHERE id = $id;");
$bdd->query("INSERT INTO $table_registre_identification (id_util, ip) VALUES (".$id.",'".$ip."');");
$multi = $bdd->unique_query("SELECT COUNT(*) FROM $table_registre_identification WHERE ip = '$ip' GROUP BY ip, id_util;");
$message = $bdd->unique_query("SELECT time FROM $table_messages_demarrage ORDER BY time DESC LIMIT 1;");
$bdd->deconnexion();
$SESS->values['connected'] = TRUE;
$SESS->values['id'] = $resultat['id'];
$SESS->values['race'] = $resultat['race'];
$SESS->values['idPlan'] = $resultatP['id'];
$SESS->values['idAsteroide'] = 0;
//Si on détecte le multi-compte, on interdit l'accès au panneau d'admin
if (empty($multi)) $SESS->level = 1;
else $SESS->level = $resultat['auth_level'] + 1;
$SESS->put($resultat['id']);
if ($message['time'] > $resultat['last_visite']) redirection('./'.$VAR['first_page'].'?p=demarrage');
elseif (empty($multi)) redirection('./'.$VAR['first_page'].'?p=avertmulti');
else redirection('./'.$VAR['first_page'].'?p=accueil');
exit;
}
else
{
$bdd->deconnexion();
$template->assign('message', $LANG['badNomMdp']);
$template->assign('couleur', 'red');
$template->assign('script', '<script type="text/javascript">setTimeout(\'document.location.href="'.$VAR['link']['accueil'].'";\', 2500);</script>');
$template->display('cms/erreur.tpl');
exit;
}
}
}
?>

View file

@ -0,0 +1,12 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'vide';
$bdd->reconnexion();
$message = $bdd->unique_query("SELECT * FROM $table_messages_demarrage ORDER BY time DESC LIMIT 1;");
$bdd->deconnexion();
$titre = $message['titre'];
$template->assign('contenu', '<p style="margin: 0 5px;">'.bbcode(nl2br($message['contenu']), 1).'<br /><br /><a class="submit" href="?p=accueil">Continuer</a></p>');
unset($message);
?>

View file

@ -0,0 +1,59 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$titre = 'Destinations rapides';
$a = gpc('a');
$amas = gpc('amas', 'post');
$ss = gpc('ss', 'post');
$pos = gpc('pos', 'post');
//Suppression d'une destination rapide
if (!empty($a)) {
$d = gpc('d');
if (!empty($d) && $a == md5(date('AG').'@'.$d)) {
$f = array_keys($planete->destinationsFavoris, $d);
unset($planete->destinationsFavoris[$f[0]]);
$bdd->reconnexion();
$bdd->query("UPDATE $table_user SET destinationsFavoris = '".serialize($planete->destinationsFavoris)."' WHERE id = $id_user;");
$bdd->deconnexion();
}
header('Location: ?p=destinationsrapides');
exit;
}
//Ajout d'une destination rapide
elseif (!empty($amas) && !empty($ss) && !empty($pos)) {
$bdd->reconnexion();
$plan = $bdd->unique_query("SELECT id FROM $table_planete WHERE galaxie = $amas AND ss = $ss AND position = $pos;");
if ($plan) {
if (in_array($plan['id'], $planete->destinationsFavoris)) {
$bdd->deconnexion();
erreur('Cette planète est déjà dans vos destinations rapides.', "red", '?p=destinationsrapides');
}
$planete->destinationsFavoris[] = $plan['id'];
$bdd->query("UPDATE $table_user SET destinationsFavoris = '".serialize($planete->destinationsFavoris)."' WHERE id = $id_user;");
}
else {
$bdd->deconnexion();
erreur('Impossible d\'ajouter cette planète, elle n\'est pas habitée !', "red", '?p=destinationsrapides');
}
$bdd->deconnexion();
header('Location: ?p=destinationsrapides');
exit;
}
//Affichage de la liste des destinations rapides
else {
$page = 'destinsrapid';
$destins = array();
$bdd->reconnexion();
foreach($planete->destinationsFavoris as $fav){
$res = $bdd->unique_query("SELECT nom_planete, galaxie, ss, position FROM $table_planete WHERE id = ".$fav.";");
if ($res != false) {
$destins[] = array($fav, $res['nom_planete'], '['.$res['galaxie'].':'.$res['ss'].':'.$res['position'].']', md5(date('AG').'@'.$fav));
}
}
$bdd->deconnexion();
$template->assign('destins', $destins);
}
?>

View file

@ -0,0 +1,52 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'envoyer';
$titre = 'Envoyer un message';
if (!empty($_POST['objet']) && !empty($_POST['nom']) && !empty($_POST['message'])) {
$utils = explode(';', gpc('nom', 'post'));
$nbutil = count($utils);
$time = time();
$message = htmlspecialchars(gpc('message', 'post'));
$objet = htmlspecialchars(gpc('objet', 'post'));
if (strlen($message) > 9999) erreur('Le contenu de votre message est trop long. Limite : 9 999 caractères.');
$bdd->reconnexion();
$bdd->escape($message);
$bdd->escape($objet);
$bdd->escape($pseudo);
$introuv = array();
for($i = 0; $i < $nbutil; $i++){
$util = trim($utils[$i]);
if (empty($util)) continue;
$bdd->escape($util);
if ($util != $planete->pseudo && $env = $bdd->unique_query("SELECT id, pseudo, mail, envoyerMail FROM $table_user WHERE pseudo = '$util';")) {
$bdd->query("INSERT INTO $table_mail (destinataire, expediteur, sujet, contenu, temps) VALUES(".$env['id'].", '$id_user', '$objet', '$message', '$time');");
if ($env["envoyerMail"] >= 1 && !empty($env["mail"])) send_mail($env["mail"], 'Nouveau message privé', 'Bonjour '.$env["pseudo"].',<br /><br />Un nouveau message privé vous a été envoyé dans la galaxie '.$config['serveur_name']);
}
else $introuv[] = htmlentities($util);
}
$bdd->deconnexion();
if (!empty($introuv[0])) erreur('Impossible de trouver le/les destinataire(s) suivant(s) : '.implode(', ', $introuv).'.<br />Les autres ont bien reçu votre message.', "red", '?p=envoyer');
else erreur('Votre message a été envoyé avec succès.', "green", '?p=messagerie');
}
$amis = array();
$amisn = array();
$bdd->reconnexion();
foreach($planete->amis as $ami) {
$res = $bdd->unique_query("SELECT pseudo FROM $table_user WHERE id = ".$ami.";");
if ($res != false) {
$amis[] = $res['pseudo'];
$amisn[] = $ami;
}
}
$bdd->deconnexion();
$template->assign('amis', $amis);
$template->assign('amisn', $amisn);
if (isset($_GET['d'])) $template->assign('destinataire', gpc('d'));
if (isset($_GET['o'])) $template->assign('objet', gpc('o'));
?>

View file

@ -0,0 +1,17 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$SESS->values['connected'] = FALSE;
$SESS->close();
if (!empty($HB_login))
{
redirection($_SERVER["REQUEST_URI"]);
exit('HALO-BATTLE<br /><br />A bientôt !<br />See you soon !');
}
else
{
redirection($VAR['first_page']);
exit('HALO-BATTLE<br /><br />A bientôt !<br />See you soon !');
}
?>

View file

@ -0,0 +1,80 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'messagerie';
$titre = 'Messagerie';
//On interdit l'accès à la messagerie en cas de prise de contrôle d'un joueur
if (!empty($sess->values['souscontrole'][0])) erreur('Vous êtes en mode prise de contrôle, vous ne pouvez pas accèder aux messages privés des joueurs.');
if (isset($_POST['IM'])) {
$stop = false;
for($i=1 ; $i<=$_POST['IM'] ; $i++) {
if (!empty($_POST['m'.$i])) {
$mes = $_POST['m'.$i];
$bdd->reconnexion();
$bdd->query("DELETE FROM $table_mail WHERE destinataire = $id_user AND id = '$mes';");
$bdd->deconnexion();
$stop = true;
}
}
if ($stop) { header('Location: ?p=messagerie'); exit; }
}
if (isset($_POST['IR'])) {
$stop = false;
for($i=1 ; $i<=$_POST['IR'] ; $i++) {
if (!empty($_POST['r'.$i])) {
$mes = $_POST['r'.$i];
$bdd->reconnexion();
$bdd->query("UPDATE $table_mail SET vu='s' WHERE destinataire = $id_user AND id = '$mes';");
$bdd->deconnexion();
$stop = true;
}
}
if ($stop) { header('Location: ?p=messagerie'); exit; }
}
if (gpc('avertir')) {
$id = gpc('avertir');
$bdd->reconnexion();
$bdd->escape($id);
$bdd->query("UPDATE $table_mail SET statut = 1 WHERE destinataire = $id_user AND id = $id;");
if ($bdd->affected()) erreur('La demande de vérification de contenu par les opérateurs a été transmise avec succès.', 'green', '?p=messagerie');
else erreur('Une demande est déjà en cours ou vous n\'êtes pas autorisé à avertir ce message.', 'red', '?p=messagerie');
$bdd->deconnexion();
}
$bdd->reconnexion();
$messcomp = $bdd->query("SELECT M.*, U.pseudo AS expediteur FROM $table_mail M INNER JOIN $table_user U ON U.id = M.expediteur WHERE M.destinataire = $id_user AND M.expediteur != false ORDER BY M.id DESC;");
$nbmax = $bdd->num_rows;
$result = $bdd->query("SELECT M.*, U.pseudo AS expediteur FROM $table_mail M INNER JOIN $table_user U ON U.id = M.expediteur WHERE M.destinataire = $id_user AND M.expediteur != false ORDER BY M.id DESC LIMIT 50;");
if ($planete->auth_level >= 3 && $nbmax > $bdd->num_rows) $result = $messcomp;
elseif ($nbmax > $bdd->num_rows) $template->assign('avertissement', '<p style="color: red; "><b>Vous avez des messages en attente de réception. Libérez de la place dans votre messagerie pour les afficher.</b></p>');
$TEMP_messages = array();
$i=0;
$nbc = count($result);
for ($i=0 ; $i < $nbc ; $i++) {
$TEMP_messages[] = array($result[$i]['sujet'], date("d/m/y H:i:s", $result[$i]['temps']), $result[$i]['expediteur'], bbcode($result[$i]['contenu']), $i+1, $result[$i]['id']);
}
$template->assign('messages', $TEMP_messages);
$template->assign('IM', $i);
$data = $bdd->query("SELECT * FROM $table_mail WHERE destinataire = $id_user AND expediteur = false AND vu != 's' ORDER BY id DESC;");
$nbres = $bdd->num_rows;
$TEMP_rapport = array();
for($i = 0; $i < $nbres; $i++){
$TEMP_rapport[] = array($data[$i]['sujet'], date("d/m/y H:i:s", $data[$i]['temps']), 0, bbcode($data[$i]['contenu']), $i+1, $data[$i]['id']);
}
$template->assign('rapports', $TEMP_rapport);
$template->assign('IR', $i);
$template->assign('script', '<script>
for (j=2; document.getElementsByName(\'m\'+j)[0]; j++) hide(document.getElementsByName(\'m\'+j)[0].previousSibling);
for (j=2; document.getElementsByName(\'r\'+j)[0]; j++) hide(document.getElementsByName(\'r\'+j)[0].previousSibling);
</script>');
$bdd->query("UPDATE $table_mail SET vu = '0' WHERE destinataire = $id_user AND vu != 's'");
$bdd->deconnexion();
?>

View file

@ -0,0 +1,70 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'operateur';
$titre = 'Contact opérateur';
if (!empty($_POST['titre']) && !empty($_POST['description'])) {
$titre = $_POST['titre'];
$description = $_POST['description'];
$time = time();
$bdd->reconnexion();
$bdd->escape($titre);
$bdd->escape($description);
$bdd->query("INSERT INTO $table_ope_mail (id_user, titre, contenu, time) VALUES ('$id_user', '$titre', '$description', '$time');");
$bdd->deconnexion();
erreur('Votre demande à bien été transmise aux opérateurs de la galaxie.<br />Une réponse vous sera donnée dans les plus brefs délais.', "green");
}
elseif (!empty($_POST['O_titre']) && !empty($_POST['O_description']) && $SESS->level > 4) {
$titre = $_POST['O_titre'];
$description = $_POST['O_description'];
$bdd->reconnexion();
$bdd->escape($titre);
$bdd->escape($description);
$bdd->query("INSERT INTO $table_ope_faq (titre, contenu, ordre) VALUES ('$titre', '$description', 100);");
$bdd->deconnexion();
header('Location: ?p=operateur');
exit;
}
elseif (isset($_GET['a']) && $_GET['a'] == 'top' && isset($_GET['i']) && $SESS->level > 4) {
$i = $_GET['i'];
$bdd->reconnexion();
$bdd->escape($i);
$bdd->query("UPDATE $table_ope_faq SET ordre = ordre - 1 WHERE id = '$i' LIMIT 1;");
$bdd->deconnexion();
header('Location: ?p=operateur');
exit;
}
elseif (isset($_GET['a']) && $_GET['a'] == 'bas' && isset($_GET['i']) && $SESS->level > 4) {
$i = $_GET['i'];
$bdd->reconnexion();
$bdd->escape($i);
$bdd->query("UPDATE $table_ope_faq SET ordre = ordre + 1 WHERE id = '$i' LIMIT 1;");
$bdd->deconnexion();
header('Location: ?p=operateur');
exit;
}
elseif (isset($_GET['a']) && $_GET['a'] == 'del' && isset($_GET['i']) && $SESS->level > 4) {
$i = $_GET['i'];
$bdd->reconnexion();
$bdd->escape($i);
$bdd->query("DELETE FROM $table_ope_faq WHERE id = '$i' LIMIT 1;");
$bdd->deconnexion();
header('Location: ?p=operateur');
exit;
}
$bdd->reconnexion();
$operateurs = $bdd->query("SELECT * FROM $table_user WHERE auth_level > 2 ORDER BY auth_level ASC;");
$questions = $bdd->query("SELECT * FROM $table_ope_faq ORDER BY ordre ASC;");
$bdd->deconnexion();
$template->assign('operateurs', $operateurs);
$TEMP_questions = array();
for ($i = 0; $i < $bdd->num_rows; $i++) {
$TEMP_questions[] = array($questions[$i]['titre'], bbcode(nl2br(htmlspecialchars($questions[$i]['contenu']))), $questions[$i]['id']);
}
$template->assign('questions', $TEMP_questions);
?>

View file

@ -0,0 +1,16 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'pilori';
$titre = 'Pilori de la galaxie';
if (isset($bdd))
$bdd->reconnexion();
else
$bdd = new BDD();
$pilori = $bdd->query("SELECT U.pseudo, U.operateurmv, 0 AS mail, U.mv, U.raisonmv, U.last_visite FROM $table_user U WHERE U.mv > 1 AND U.operateurmv = 0 UNION SELECT U.pseudo, O.pseudo AS operateurmv, O.mail, U.mv, U.raisonmv, U.last_visite FROM $table_user U INNER JOIN $table_user O ON U.operateurmv = O.id WHERE U.mv > 1;");
$bdd->deconnexion();
$template->assign('joueurs', $pilori);
unset($pilori);
?>

View file

@ -0,0 +1,125 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
if (!empty($SESS->values['connected'])) $page = '../cms/vide';
else $page = 'vide';
$titre = 'Règles du jeu';
$template->assign('contenu','<h1>R&egrave;gles de Halo-Battle</h1><div style="text-align: left; margin: 15px; font-size: 115%;">
<u>Pr&eacute;ambule :</u> tous les joueurs ayant cr&eacute;&eacute; un compte de jeu, et l&#39;utilisant ou non, s&#39;engagent &agrave; avoir lu et &agrave; respecter les r&egrave;gles de Halo-Battle dans leur int&eacute;gralit&eacute;. Si l&#39;une des r&egrave;gles &eacute;nonc&eacute;es ci-dessous est transgress&eacute;e, merci de vous r&eacute;f&eacute;rer au chapitre des infractions afin de conna&icirc;tre toutes les modalit&eacute;s relatives aux punitions encourues.<br />
<br />
Ce r&egrave;glement peut &ecirc;tre l&#39;objet d&#39;une modification, partielle ou totale, et il est du ressort du joueur de se tenir inform&eacute; de toute modification quelle qu&#39;elle soit. Toute modification sera publi&eacute;e sur le forum avec sa date de mise en application, avant de se trouver effective au sein du jeu.<br />
<br />
Ces r&egrave;gles du jeu ont &eacute;t&eacute; publi&eacute;es le 14/04/2008 et rentrent en vigueur &agrave; partir du 24/04/2008
<br />
<br /><u>Plan des r&egrave;gles :</u>
<br />
<br /><a href="#comportement">I. Comportement</a>
<br /><a href="#comptes">II. Comptes</a>
<br /><a href="#commerce">III. Commerce et ressources</a>
<br /><a href="#mercenariat">IV. Mercenariat</a>
<br /><a href="#guerre">V. Guerre</a>
<br /><a href="#bash">VI. Bash</a>
<br /><a href="#alliances">VII. Alliances</a>
<br /><a href="#sanctions">VIII. Sanctions</a>
<br /><br /><br />
<h3 id="comportement">I. Comportement</h3><br />
<h4>1 - Comportement g&eacute;n&eacute;ral</h4><br />
- La convivialit&eacute; et le respect des autres joueurs sont de rigueur. Par cons&eacute;quent, les propos injurieux, racistes, x&eacute;nophobes, pornographiques et antis&eacute;mites sont prohib&eacute;s. Tous les outils de communications utilis&eacute;s pour et par Halo-Battle sont soumis &agrave; cette r&egrave;gle (jeu, forum et IRC).<br />
- L&#39;utilisation de pseudo et/ou nom de plan&egrave;te en rapport direct avec des propos racistes, x&eacute;nophobes, pornographiques ou encore antis&eacute;mites est totalement prohib&eacute;. Il en va de m&ecirc;me pour toute revendication politique, religieuse ou ayant un rapport avec l&#39;actualit&eacute; (une certaine libert&eacute; peut &ecirc;tre tol&eacute;r&eacute;e mais ceci reste &agrave; l&#39;appr&eacute;ciation du staff).<br />
- Les menaces sortant du cadre du jeu ne seront pas tol&eacute;r&eacute;es et lourdement sanctionn&eacute;es par les op&eacute;rateurs. Elles pourront de plus faire l&#39;objet de poursuites judiciaires de la part de la personne concern&eacute;e devant les juridictions comp&eacute;tentes.<br />
- Utiliser le bouton Signaler pour signaler un message qui ne contient pas d&#39;insultes ou qui n&#39;enfreint pas les r&egrave;gles du jeu est interdit. Le signalement de message ne doit servir qu&#39;&agrave; informer les op&eacute;rateurs d&#39;infractions aux r&egrave;gles du jeu et &agrave; rien d&#39;autre.<br />
- Le spam, les insultes et les messages &agrave; contenus offensants sont interdits, de m&ecirc;me que tout contenu x&eacute;nophobe, antis&eacute;mite ou raciste.<br />
- Toute manoeuvre visant &agrave; exploiter le r&egrave;glement &agrave; son avantage, ou &agrave; le contourner sciemment, est interdite.<br />
<br /><h4>2 - Bugusing</h4><br />
- Tout bug trouv&eacute; doit &ecirc;tre imm&eacute;diatement signal&eacute; au staff de Halo-Battle.<br />
- Il est totalement prohib&eacute; d&#39;exploiter un bug &agrave; son avantage.<br />
- Toute action visant &agrave; paralyser d&#39;une quelconque mani&egrave;re le compte d&#39;un autre joueur est absolument interdit.<br />
- Ne pas signaler un bug d&eacute;couvert est passible de bannissement.<br />
<br /><h3 id="comptes">II. Comptes</h3><br />
<br /><h4>1 - Les comptes de jeu</h4><br />
- Les comptes restent la propri&eacute;t&eacute; de Halo-Battle ; par cons&eacute;quent, ils ne peuvent faire l&#39;objet d&#39;une vente ou faire office de monnaie d&#39;&eacute;change.<br />
- Un compte ne peut &ecirc;tre jou&eacute; que par une seule et m&ecirc;me personne physique dans une seule et m&ecirc;me galaxie (sauf cas relatif &agrave; la surveillance de compte).<br />
- La langue utilis&eacute;e dans Halo-Battle est le fran&ccedil;ais ; toutefois, seul l&#39;anglais est tol&eacute;r&eacute; pour les personnes ne sachant pas ou peu le parler.<br />
<br /><h4>2 - Multicomptes</h4><br />
- Jouer plus d&#39;un compte par galaxie est strictement interdit.<br />
- Pour les joueurs jouant depuis un lieu commun (famille, collocation, &eacute;coles, lieux de travail...) il est imp&eacute;ratif de pr&eacute;venir l&#39;op&eacute;rateur de votre galaxie.<br />
- Aucune interaction, directe ou non, entre comptes de joueurs se connectant r&eacute;guli&egrave;rement de lieux communs n&#39;est autoris&eacute;e.<br />
- Pour les joueurs d&#39;une m&ecirc;me famille, faire partie d&#39;une m&ecirc;me alliance est tol&eacute;r&eacute;. Dans ce cas pr&eacute;cit, merci d&#39;en avertir l&#39;op&eacute;rateur de votre galaxie. Toute exploitation abusive de cette autorisation sera s&eacute;v&eacute;rement sanctionn&eacute;e.<br />
- La r&egrave;gle de la surveillance de compte et le partage de compte s&#39;appliquent normalement : m&ecirc;me connect&eacute; du m&ecirc;me lieu, chaque joueur n&#39;est autoris&eacute; &agrave; surveiller ou jouer que son propre compte.<br />
<br /><h4>3 - Surveillance de compte</h4><br />
- Toute surveillance de compte doit &ecirc;tre obligatoirement signal&eacute;e &agrave; l&#39;op&eacute;rateur de votre galaxie. Le propri&eacute;taire du-dit compte doit indiquer quel compte va &ecirc;tre surveill&eacute;, donner la dur&eacute;e exacte de la surveillance, et donner le pseudonyme du surveillant. Il n&#39;est pas n&eacute;cessaire d&#39;attendre une r&eacute;ponse de l&#39;op&eacute;rateur pour pouvoir commencer la surveillance du compte.<br />
- Une seule et m&ecirc;me personne ne peut surveiller qu&#39;un seul compte &agrave; la fois. Aucun d&eacute;lais minimum n&#39;est exig&eacute; entre la surveillance de deux comptes diff&eacute;rents. Les surveillances de comptes ne peuvent faire l&#39;objet d&#39;aucune r&eacute;mun&eacute;ration.<br />
- Le surveillant ainsi que le joueur qui fait surveiller son compte sont responsables des actions faites via un compte durant une surveillance.<br />
- Le surveillant peut effectuer n&#39;importe quelle op&eacute;ration sur la ou les plan&egrave;tes du propri&eacute;taire durant la surveillance. Est n&eacute;anmoins interdit le transfert de ressources vers des plan&egrave;tes appartenant &agrave; un joueur autre. L&#39;activation du mode vacances est &eacute;galement autoris&eacute;.<br />
- La surveillance du compte prend fin lorsque le propri&eacute;taire du compte se reconnecte &agrave; celui-ci, ou que le d&eacute;lai de surveillance a expir&eacute;. Dans ce cas pr&eacute;cit, le surveillant est tenu de ne plus s&#39;en occuper et de faire passer obligatoirement le compte en mode vacances.<br />
<br /><h4>4 - Don de compte</h4><br />
- Tout changement de compte doit &ecirc;tre au pr&eacute;alable signal&eacute; &agrave; un op&eacute;rateur. Tout changement sans l&#39;intervention de l&#39;op&eacute;rateur sera sanctionn&eacute;.<br />
- Le propri&eacute;taire du mail permanent du compte est tenu d&#39;envoyer un mail informatif aux op&eacute;rateurs en pr&eacute;cisant le pseudonyme du repreneur et le futur mail permanent du compte.<br />
- L&#39;op&eacute;rateur modifiera lui-m&ecirc;me le mail permanent du compte et informera le donneur et le repreneur que le compte est c&eacute;d&eacute;.<br />
- Le repreneur peut se connecter au compte d&egrave;s qu&#39;il en re&ccedil;oit l&#39;autorisation par l&#39;op&eacute;rateur, et peut alors changer l&#39;adresse dynamique, le pseudonyme et le mot de passe du compte.<br />
- Une fois que le repreneur s&#39;est connect&eacute; sur le compte, il est strictement interdit au donneur de s&#39;y reconnecter.<br />
- La m&ecirc;me r&egrave;gle s&#39;applique dans le cas d&#39;un &eacute;change de comptes entre deux joueurs d&#39;une m&ecirc;me galaxie.<br />
- Aucun don de compte ne peut faire l&#39;objet d&#39;une transaction mon&eacute;taire.<br />
<br /><h3 id="commerce">III. Commerce et ressources</h3><br />
- Les joueurs sont libres de commercer comme ils l&#39;entendent, tant que leurs transactions ne se trouvent pas en infraction avec le r&eacute;glement.<br />
- Le commerce doit prendre la forme d&#39;un arrangement entre les diff&eacute;rents joueurs. Chaque joueur engage sa propre responsabilit&eacute; lors de la transaction de ressources. Par cons&eacute;quent, dans le cas de vols, d&#39;arnaques ou de toute autre forme crapuleuse de n&eacute;gociation, il ne peut y avoir de recours aupr&egrave;s d&#39;un op&eacute;rateur.<br />
- Il est interdit d&#39;exercer une pression ou de s&#39;acharner sur un joueur dans le but de lui soutirer ses ressources (sauf si les motifs sont valables, comme dans le cas d&#39;une guerre d&eacute;clar&eacute;e).<br />
- L&#39;envoie de ressources &agrave; des joueurs plus haut class&eacute;s que soi doit &ecirc;tre motiv&eacute; par des motifs valables. Si l&#39;op&eacute;rateur juge l&#39;action outranci&egrave;re, des r&eacute;parations de dommages peuvent &ecirc;tre demand&eacute;es au joueur b&eacute;n&eacute;ficiaire des ressources.<br />
- Les transactions de ressources ne peuvent faire l&#39;objet d&#39;une transaction mon&eacute;taire r&eacute;elle.<br />
<br /><h3 id="mercenariat">IV. Mercenariat</h3><br />
- Le mercenariat est autoris&eacute;. Ces contrats r&eacute;tribuent un joueur ou une alliance en fonction de services rendus.<br />
- Un contrat de mercenariat doit prendre la forme d&#39;un arrangement entre les diff&eacute;rents joueurs et ceux-ci y engagent leur responsabilit&eacute; propre. Par cons&eacute;quent, il ne peut y avoir de recours aupr&egrave;s d&#39;un op&eacute;rateur si, par exemple, le contrat n&#39;est pas ex&eacute;cut&eacute;, ou n&#39;est pas r&eacute;mun&eacute;r&eacute;.<br />
- Toute mission de mercenariat est possible, tant qu&#39;elle n&#39;interf&egrave;re pas avec le pr&eacute;sent r&eacute;glement.<br />
- Un contrat de mercenariat ne peut &ecirc;tre r&eacute;mun&eacute;r&eacute; par des unit&eacute;s mon&eacute;taires r&eacute;elles.<br />
<br /><h3 id="guerre">V. Guerre</h3><br />
- Une guerre ne peut &ecirc;tre d&eacute;clar&eacute;e que contre une alliance ou un joueur sans alliance. Ainsi il est possible de d&eacute;clarer la guerre &agrave; une alliance enti&egrave;re ou &agrave; joueur qui n&#39;a pas d&#39;alliance, mais pas &agrave; un seul joueur d&#39;une alliance ou &agrave; quelques joueurs d&#39;une alliance.<br />
- Il n&#39;est pas n&eacute;cessaire de motiver la d&eacute;cision ou de pr&eacute;venir l&#39;alliance agress&eacute;e pour d&eacute;clarer une guerre.<br />
- Il est obligatoire de d&eacute;clarer officiellement une guerre sur le forum, dans la section appropri&eacute;e, dans les 24 heures qui suivent l&#39;agression. Les joueurs sont libres de formuler les objectifs et les conditions de fin de la guerre.<br />
- Il est strictement interdit d&#39;&eacute;tablir des objectifs portant atteinte aux libert&eacute;s fondamentales dont disposent les joueurs, comme la suppression d&#39;un compte, l&#39;interdiction de jouer, suppression de colonies ou d&#39;unit&eacute;s, etc...<br />
- En cas de guerre, le bash n&#39;est pas interdit.<br />
- Les joueurs sont libres de mener leurs campagnes militaires comme ils l&#39;entendent, pourvu que cela n&#39;entre pas en conflit avec le r&egrave;glement.<br />
- Une guerre prend fin lorsque les bellig&eacute;rants trouvent un accord. Ils devront le signaler obligatoirement, comme pour la d&eacute;claration de guerre.<br />
<br /><h3 id="bash">VI. Bash</h3><br />
- Le bash est relatif &agrave; l&#39;attaque &agrave; outrance de plan&egrave;tes particuli&egrave;res. Attaquer une plan&egrave;te plus de quatre fois en 24 heures est par cons&eacute;quent interdit.<br />
- La r&egrave;gle du bash s&#39;applique aux joueurs actifs et inactifs.<br />
- En cas de guerre, le bash est autoris&eacute;.<br />
<br /><h3 id="alliances">VII. Alliances</h3><br />
- Toute alliance poss&egrave;de le privil&egrave;ge de se constituer comme elle l&#39;entend.<br />
- Toute alliance peut recruter autant de joueurs qu&#39;elle le souhaite.<br />
- Les alliances mixtes sont autoris&eacute;es ; cependant, une race dominante doit y &ecirc;tre repr&eacute;sent&eacute;e et les joueurs de la race oppos&eacute;e ne doivent pas s&#39;y trouver en trop grand nombre sous peine de sanction.<br />
- Toute alliance peut recruter autant de joueurs qu&#39;elle le souhaite.<br />
- Toute alliance peut signer autant de pactes qu&#39;elle le souhaite.<br />
- Toute alliance a le droit de se donner comme mission celle qu&#39;elle entend.<br />
- Il est strictement interdit de copier totalement ou en partie, les textes, images, etc, cr&eacute;&eacute;s par les joueurs des diff&eacute;rentes alliances d&eacute;j&agrave; existantes. Les alliances fond&eacute;es sur le principe du CSNU ou de l&#39;Alliance ne sont pas concern&eacute;es par la clause du plagiat de nom. Pour pouvoir recopier l&#39;un des &eacute;l&eacute;ments se trouvant dans une alliance, il est n&eacute;cessaire d&#39;avoir une autorisation &eacute;crite de ou des auteurs vous autorisant &agrave; y proc&eacute;der sous peine de sanctions.<br />
- Tout recrutement dans les autres alliances d&eacute;j&agrave; existantes est formellement interdit.<br />
<br /><h3 id="sanctions">VIII. Sanctions</h3><br />
- En cas de non respect de ce r&egrave;glement, les op&eacute;rateurs du jeu infligeront un blocage pouvant aller de un jour, &agrave; un blocage d&eacute;finitif selon la gravit&eacute; de la faute, ainsi qu&#39;en cas de r&eacute;cidive.<br />
- Chaque bannissement est mentionn&eacute; dans le pilori du jeu. Par ailleurs, le staff de Halo-Battle se r&eacute;serve le droit de prendre &agrave; l&#39;encontre des joueurs toute autre sanction.<br />
- En cas de r&eacute;clamation, merci d&#39;envoyer un mail &agrave; l&#39;un des op&eacute;rateurs en pr&eacute;cisant votre pseudonyme ingame et votre galaxie.<br />
- Toute manoeuvre visant &agrave; faire bloquer d&eacute;lib&eacute;r&eacute;ment un adversaire est interdite et pourra &ecirc;tre sanctionn&eacute;e par l&#39;op&eacute;rateur.<br />
</div>');
?>

View file

@ -0,0 +1,24 @@
<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'version';
$titre = 'Historique des mises à jours';
$data = Cache::read('versionsDATA');
if (empty($data))
{
$bdd->reconnexion();
$data = $bdd->query("SELECT * FROM $table_version ORDER BY id DESC");
$bdd->deconnexion();
Cache::set('versionsDATA', $data);
}
$TEMP_versions = array();
foreach($data as $version)
{
$TEMP_versions[] = array('numero' => $version['version'], 'date' => date("d/m/y", $version['temps']), 'description' => str_replace('<br />', '', $version['contenu']));
}
$template->assign('versions', $TEMP_versions);
unset($TEMP_versions, $data);
?>

329
onyx2/include/game/vars.php Normal file
View file

@ -0,0 +1,329 @@
<?php //vars.php : contient toutes les valeurs pour construire chaque batiments, unités ou technologies
if (!isset($technolo))
{
if (empty($race) && empty($sess->values['race'])) $race = "none";
elseif (empty($race)) $race = $sess->values['race'];
include_once("game/noms.php");
}
/*
* Défenses
*/
//Attaque
$defense_at = array(200,800,1500,500,4500,15000,10000,25000);
//Défense (bouclier)
$defense_bc = array(100,300,600,400,1000,4000,10000,20000);
//Coque (pv)
$defense_pv = array(1000,3000,6000,1800,4000,1000,15000,25000);
//Débris de métal
$defense_md = array(300,300,300,300,300,300,300,300);
//Débris de cristal
$defense_cd = array(300,300,300,300,300,300,300,300);
//Rapide fire (nombre d'attaque par phase envers un vaisseau)
$defense_rf = array(
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1),
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1)
);
/*
* Vaisseaux
*/
//Nombre maximal de ressources embarquées
$nomvais_rs = array(10000,50000,25000,25000,100,50,200,400,800,1000,1500,50000,100000,500);
//Coefficient vitesse
$nomvais_vitesseP = array(5,5,6,5,10,8,5,7,6,5,4,2,1,6);
//Temps de préparation
$nomvais_vitesseS = array(5,5,6,5,4,4,5,7,6,5,4,3,2,10);
//Temps de chauffe
$nomvais_vitesseG = array(5,5,6,5,1,1,5,7,7,7,6,4,3,10);
//Attaque
$nomvais_at = array(50,50,50,50,150,200,400,900,1500,3500,6000,7000,10000,100);
//Défense (bouclier)
$nomvais_bc = array(0,0,0,50,0,200,500,1250,2500,6000,5000,8000,10000,800);
//Coque (pv)
$nomvais_pv = array(1000,1500,1000,1000,1000,1000,2500,5500,9000,15000,25000,35000,50000,3000);
//Débris de métal
$nomvais_md = array(300,300,300,300,300,300,300,300,300,300,300,36000);
//Débris de cristal
$nomvais_cd = array(300,300,300,300,300,300,300,300,300,300,300,24000);
//Rapide fire (nombre d'attaque par phase envers un vaisseau)
$nomvais_rf = array( array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Cargos petit
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Cargos grand
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Vaisseaux de colonisation
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Espionnage
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Recycleurs
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Longsword/Seraph
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Frégate
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Croiseurs de classe Halcyon
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Croiseurs de classe Marathon
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Porte vaisseaux
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Station orbitale
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Super porte-vaisseaux
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1), //Super porte-vaisseaux
array(1,1,1,1,1,1,1,1,1,1,1,1,1,1) //Super porte-vaisseaux
);
/*
Aide-mémoire pour le format des tableaux des nécessités
- Type général : batiments, technologies, ...
- ID de l'objet ou branche pour les technologies
- Niveau requis ou id pour les technologies
- Bits requis (technologies uniquement)
*/
$neededCaserne =
array(
array(
array('batiments', 9, 1)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 3)
),
array(
array('batiments', 9, 5)
),
array(
array('batiments', 9, 3)
),
array(
array('batiments', 9, 10)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 5)
)
);
$neededBatiments =
array(
0,
0,
0,
0,
array(
array('batiments', 3, 12)
),
0,
0,
array(
array('technologies', 2,3, 9)
),
array(
array('technologies', 2,4, 17)
),
0,
0,
array(
array('technologies', 1,12, 4096)
),
0,
array(
array('technologies', 3,8, 256)
),
array(
array('technologies', 7,12, 4096)
),
array(
array('technologies', 3,6, 64)
),
array(
array('technologies', 3,7, 128)
),
0
);
$neededTerrestre = array(
array(
array('batiments', 7, 1)
),
array(
array('batiments', 7, 3)
),
array(
array('batiments', 7, 4)
),
array(
array('batiments', 7, 6)
),
array(
array('batiments', 7, 1)
),
array(
array('batiments', 7, 2)
),
array(
array('batiments', 7, 3)
),
array(
array('batiments', 7, 5)
),
//Défenses
array(
array('batiments', 7, 1),
array('technologies', 6, 0, 1)
),
array(
array('batiments', 7, 3),
array('technologies', 6, 3, 8)
),
array(
array('batiments', 7, 4),
array('technologies', 6, 1, 2)
),
array(
array('batiments', 7, 4),
array('technologies', 6, 4, 16)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 2, 4)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 5, 32)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 6, 64)
),
array(
array('batiments', 7, 10),
array('technologies', 7, 11, 2048)
)
);
$neededVaisseaux =
array(
array(
array('batiments', 8, 1),
array('technologies', 0,3, 8)
),
array(
array('batiments', 8, 5),
array('technologies', 0,3, 8),
array('technologies', 1,6, 64)
),
array(
array('batiments', 8, 5),
array('technologies', 8,0, 1)
),
array(
array('batiments', 8, 5),
array('technologies', 7,4, 16)
),
array(
array('batiments', 8, 5),
array('technologies', 7,0, 1)
),
array(
array('batiments', 8, 3),
array('technologies', 7,1, 2)
),
array(
array('batiments', 8, 5),
array('technologies', 7,2, 4)
),
array(
array('batiments', 8, 1),
array('technologies', 7,3, 8)
),
array(
array('batiments', 8, 3),
array('technologies', 7,5, 32)
),
array(
array('batiments', 8, 6),
array('technologies', 7,6, 64)
),
array(
array('batiments', 8, 6),
array('technologies', 7,1, 128)
),
array(
array('batiments', 8, 8),
array('technologies', 7,8, 256)
),
array(
array('batiments', 8, 10),
array('technologies', 7,9, 512)
),
array(
array('batiments', 8, 10),
array('technologies', 7,10, 1024)
)
);
$alli_batimentVAR = array('centre', 'port', 'forge', 'urgence', 'propagande', 'economie');
$alli_batimentLIMIT = array(5, 5, 5, 5, 5, 5);
$alli_batimentCALC = array(
array(
'$a = ceil(pow(1.5,$n)*68);',
'$b = ceil(pow(1.5,$n)*17);',
'$c = 0;',
'$sec = (ceil(1.02*(3/(1+$planete->batiments[11]))*pow(1.5,$n))*(1/(1+$planete->casernes[7]*0.005)))*60;'
),
array(
'$a = ceil(pow(1.6,$n)*53);',
'$b = ceil(pow(1.6,$n)*27);',
'$c = 0;',
'$sec = (ceil(1.2*(3/(1+$planete->batiments[11]))*pow(1.55,$n))*(1/(1+$planete->casernes[7]*0.005)))*60;'
),
array(
'$a = ceil(pow(1.5,$n)*242);',
'$b = ceil(pow(1.5,$n)*72);',
'$c = 0;',
'$sec = (ceil(1.5*(3/(1+$planete->batiments[11]))*pow(1.624,$n))*(1/(1+$planete->casernes[7]*0.005)))*60;'
),
array(
'$a = ceil(pow(1.5,$n)*92);',
'$b = ceil(pow(1.5,$n)*37);',
'$c = 0;',
'$sec = (ceil(1.36*(3/(1+$planete->batiments[11]))*pow(1.597,$n))*(1/(1+$planete->casernes[7]*0.005)))*60;'
),
array(
'$a = ceil(pow(1.73,$n)*800);',
'$b = ceil(pow(1.73,$n)*420);',
'$c = ceil(pow(1.68,$n)*285);',
'$sec = (ceil(1.8*(3/(1+$planete->batiments[11]))*pow(1.7,$n))*(1/(1+$planete->casernes[7]*0.005)))*60;'
),
array(
'$a = ceil(pow(2,$planete->batiments[5])*750);',
'$b = ceil(pow(2,$planete->batiments[5])*500);',
'$c = 0;',
'$sec = ceil((pow(2,$planete->batiments[5])*720)/(pow(1.23,$planete->batiments[11])+0.0025*$planete->casernes[7]));'
)
);
$alli_batimentTECH = array(
0,
0,
0,
0,
array(
array($batimeni[3], 'centrale_s', 12)
),
0
);
$batimentVAR = array('mine_m','mine_c','mine_h','centrale_s','centrale_f','radar','labo','chantier_terrestre','chantier_spatial','caserne','silo','centre_info','habitation','arcologies','bunker','commercial','loisir','administration');
$casernenVAR = array('soldat1','soldat2','soldat3','soldat4','sniper','spartan','medecin','ingenieur','soldat_lourd');
$nomterrnVAR = array('vais_0', 'vais_1', 'vais_2', 'vais_3', 'vcl_1', 'vcl_2', 'vcl_3', 'vcl_4', 'def_1', 'def_2', 'def_3', 'def_4', 'def_5', 'def_6', 'def_7', 'def_8');
$nomvaisnVAR = array('vaisseau_1','vaisseau_2','vaisseau_3','vaisseau_4','vaisseau_5','vaisseau_6','vaisseau_7','vaisseau_8','vaisseau_9','vaisseau_10','vaisseau_11','vaisseau_12','vaisseau_13','vaisseau_14');
$coeffVAR = array('coeff_mine_m', 'coeff_mine_c', 'coeff_mine_h', 'coeff_centrale_s', 'coeff_centrale_f');
$ressoVAR = array('contenu_metal', 'contenu_cristal', 'contenu_hydrogene');
//Nouvel arbre de technologie
$technologiesVAR = array("techno_indu", "techno_inge", "techno_inge2", "techno_poli", "techno_arme", "techno_defe", "techno_defe2", "techno_proj", "techno_expansion");
?>

View file

@ -0,0 +1,77 @@
****************************************************************
CHANGELOG 2.3.0 to 2.3.3
****************************************************************
Requested new features:
=======================
CR#450 - Add option to specify window target for CSIM
CR#453 - Add additional style option for plot lines
CR#464 - Automatically adjust label precision
CR#465 - Add option for vertical text in graphic tables
CR#000 - Added flags for Bangladesh and Republic of Serbia
CR#000 - Added Example combgraphex1.php to 2.x tree
Reported Defect fixes:
======================
PR#250 - Off by one - rounding error for filled gradients
PR#445 - Example code: Image::SetAntiAliasing() expects boolean
PR#448 - Workaround for bug in PHP 4.4.7 (Affects Pie)
PR#449 - Adding text to rotated graphs gets wrong angle for box
PR#454 - Localized error message can only be shown once
PR#455 - Startangle is ignored if only one slice in a Pie is !=0
PR#456 - German locale problem with punctuation
PR#457 - Array with non-consequtive indexes are not handled as
URL argument for CSIM
PR#458 - Add additional error check for accumulated line plot
PR#459 - UPCA with first digit != 0 will be encoded wrongly
PR#461 - Windroses does not handle title correctly
PR#463 - Wrong handling of small slices
PR#466 - Further wrong handling of small slices in Pie
PR#000 - Typo in jpgraph_table.php ',' instead of ';'
PR#000 - Initialize output parameters to headers_sent() method call
Performance enhancements:
=========================
* Remove one uneccessary call to StrokeDataVal for markers
on linegraphs
* Modified Wu-algorithm for better handling of start-end points
* Refactored Image class and added error check for use of
anti-alias together with dashed styled lines
****************************************************************
CHANGELOG 2.2.0 to 2.3.0
****************************************************************
Requested new features:
=======================
CR#443 - Add support for russian LED characters
CR#431 - Make it possible to add an alternate text to linear barcodes
CR#427 - Feature request to add trademark symbol to SymChar class
CR#433 - Make it possible to add images to tables without constrains
CR#450 - Add option to specify window target for CSIM
Reported Defect fixes:
======================
PR#430 - Wrong scope for protected variable in PHP5 version of PDF417
PR#432 - Unquoted % sign in error message 22001
PR#438 - v2.x does not handle line weight==0 properly
PR#441 - Wrong HTML for circle CSIM in v2.x
PR#442 - Fixed possible undefined sval for CSIM when no alt titles are given
PR#444 - Divide by zero in certain date scale ranges
PR#445 - Example code: Image::SetAntiAliasing() expects boolean
PR#250 - Off by one - rounding error for filled gradients
PR#448 - Workaround for bug imagefilledarc() (Affects Pie)
PR#449 - Adding text to rotated graphs gets wrong angle for box
PR#451 - Various code cleanup for 2.x branch
Additional code fixes:
======================
* Make minimum automatic margin smaller
* Added support for XPM image format
* Add error check to see if imageantialias() GD function exists
* Added flags for Bangladesh and Republic of Serbia
* Wrong unicode value for TM
* Corrected wrong error message and uninitialized variable
* Potential divide by zero case for tick positioning
* Removed deprecated call to AdjBackgroundImage() in Example
* Updated CSIM examples to not include the filename in the StrokeCSIM() call
* Added Example combgraphex1.php to 2.x tree

View file

@ -0,0 +1,40 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
$data1y=array(-8,8,9,3,5,6);
$data2y=array(18,2,1,7,5,4);
// Create the graph. These two calls are always required
$graph = new Graph(500,400,"auto");
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->img->SetMargin(40,30,20,40);
// Create the bar plots
$b1plot = new BarPlot($data1y);
$b1plot->SetFillColor("orange");
$b1plot->value->Show();
$b2plot = new BarPlot($data2y);
$b2plot->SetFillColor("blue");
$b2plot->value->Show();
// Create the grouped bar plot
$gbplot = new AccBarPlot(array($b1plot,$b2plot));
// ...and add it to the graPH
$graph->Add($gbplot);
$graph->title->Set("Accumulated bar plots");
$graph->xaxis->title->Set("X-title");
$graph->yaxis->title->Set("Y-title");
$graph->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
// Display the graph
$graph->Stroke();
?>

View file

@ -0,0 +1,75 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// Some data
$datay1=array(140,110,50,60);
$datay2=array(35,90,190,190);
$datay3=array(20,60,70,140);
// Create the basic graph
$graph = new Graph(450,250,'auto');
$graph->SetScale("textlin");
$graph->img->SetMargin(40,80,30,40);
// Adjust the position of the legend box
$graph->legend->Pos(0.02,0.15);
// Adjust the color for theshadow of the legend
$graph->legend->SetShadow('darkgray@0.5');
$graph->legend->SetFillColor('lightblue@0.3');
// Get localised version of the month names
$graph->xaxis->SetTickLabels($gDateLocale->GetShortMonth());
// Set a nice summer (in Stockholm) image
$graph->SetBackgroundImage('stship.jpg',BGIMG_COPY);
// Set axis titles and fonts
$graph->xaxis->title->Set('Year 2002');
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetColor('white');
$graph->xaxis->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->SetColor('white');
$graph->yaxis->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->SetColor('white');
//$graph->ygrid->Show(false);
$graph->ygrid->SetColor('white@0.5');
// Setup graph title
$graph->title->Set('Using alpha blending with a background');
// Some extra margin (from the top)
$graph->title->SetMargin(3);
$graph->title->SetFont(FF_ARIAL,FS_NORMAL,12);
// Create the three var series we will combine
$bplot1 = new BarPlot($datay1);
$bplot2 = new BarPlot($datay2);
$bplot3 = new BarPlot($datay3);
// Setup the colors with 40% transparency (alpha channel)
$bplot1->SetFillColor('orange@0.4');
$bplot2->SetFillColor('brown@0.4');
$bplot3->SetFillColor('darkgreen@0.4');
// Setup legends
$bplot1->SetLegend('Label 1');
$bplot2->SetLegend('Label 2');
$bplot3->SetLegend('Label 3');
// Setup each bar with a shadow of 50% transparency
$bplot1->SetShadow('black@0.4');
$bplot2->SetShadow('black@0.4');
$bplot3->SetShadow('black@0.4');
$gbarplot = new GroupBarPlot(array($bplot1,$bplot2,$bplot3));
$gbarplot->SetWidth(0.6);
$graph->Add($gbarplot);
$graph->Stroke();
?>

View file

@ -0,0 +1,18 @@
<?php
// Antispam example using a random string
require_once "../jpgraph_antispam.php";
// Create new anti-spam challenge creator
// Note: Neither '0' (digit) or 'O' (letter) can be used to avoid confusion
$spam = new AntiSpam();
// Create a random 5 char challenge and return the string generated
$chars = $spam->Rand(5);
// Stroke random cahllenge
if( $spam->Stroke() === false ) {
die('Illegal or no data to plot');
}
?>

View file

@ -0,0 +1,51 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_line.php");
// Some data
$datay = array(28,19,18,23,12,11);
$data2y = array(14,18,33,29,39,55);
// A nice graph with anti-aliasing
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(40,180,40,40);
$graph->SetBackgroundImage("tiger_bkg.png",BGIMG_FILLPLOT);
$graph->img->SetAntiAliasing("white");
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->title->Set("Background image");
// Use built in font
$graph->title->SetFont(FF_FONT1,FS_BOLD);
// Slightly adjust the legend from it's default position in the
// top right corner.
$graph->legend->Pos(0.05,0.5,"right","center");
// Create the first line
$p1 = new LinePlot($datay);
$p1->mark->SetType(MARK_FILLEDCIRCLE);
$p1->mark->SetFillColor("red");
$p1->mark->SetWidth(4);
$p1->SetColor("blue");
$p1->SetCenter();
$p1->SetLegend("Triumph Tiger -98");
$graph->Add($p1);
// ... and the second
$p2 = new LinePlot($data2y);
$p2->mark->SetType(MARK_STAR);
$p2->mark->SetFillColor("red");
$p2->mark->SetWidth(4);
$p2->SetColor("red");
$p2->SetCenter();
$p2->SetLegend("New tiger -99");
$graph->Add($p2);
// Output line
$graph->Stroke();
?>

View file

@ -0,0 +1,51 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_line.php");
// Some data
$datay = array(28,19,18,23,12,11);
$data2y = array(14,18,33,29,39,55);
// A nice graph with anti-aliasing
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(40,180,40,40);
$graph->SetBackgroundImage("tiger_bkg.png",BGIMG_FILLFRAME);
$graph->img->SetAntiAliasing();
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->title->Set("Background image");
// Use built in font
$graph->title->SetFont(FF_FONT1,FS_BOLD);
// Slightly adjust the legend from it's default position in the
// top right corner.
$graph->legend->Pos(0.05,0.5,"right","center");
// Create the first line
$p1 = new LinePlot($datay);
$p1->mark->SetType(MARK_FILLEDCIRCLE);
$p1->mark->SetFillColor("red");
$p1->mark->SetWidth(4);
$p1->SetColor("blue");
$p1->SetCenter();
$p1->SetLegend("Triumph Tiger -98");
$graph->Add($p1);
// ... and the second
$p2 = new LinePlot($data2y);
$p2->mark->SetType(MARK_STAR);
$p2->mark->SetFillColor("red");
$p2->mark->SetWidth(4);
$p2->SetColor("red");
$p2->SetCenter();
$p2->SetLegend("New tiger -99");
$graph->Add($p2);
// Output line
$graph->Stroke();
?>

View file

@ -0,0 +1,51 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_line.php");
// Some data
$datay = array(28,19,18,23,12,11);
$data2y = array(14,18,33,29,39,55);
// A nice graph with anti-aliasing
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(40,180,40,40);
$graph->SetBackgroundImage("tiger_bkg.png",BGIMG_COPY);
$graph->img->SetAntiAliasing("white");
$graph->SetScale("textlin");
$graph->SetShadow();
$graph->title->Set("Background image");
// Use built in font
$graph->title->SetFont(FF_FONT1,FS_BOLD);
// Slightly adjust the legend from it's default position in the
// top right corner.
$graph->legend->Pos(0.05,0.5,"right","center");
// Create the first line
$p1 = new LinePlot($datay);
$p1->mark->SetType(MARK_FILLEDCIRCLE);
$p1->mark->SetFillColor("red");
$p1->mark->SetWidth(4);
$p1->SetColor("blue");
$p1->SetCenter();
$p1->SetLegend("Triumph Tiger -98");
$graph->Add($p1);
// ... and the second
$p2 = new LinePlot($data2y);
$p2->mark->SetType(MARK_STAR);
$p2->mark->SetFillColor("red");
$p2->mark->SetWidth(4);
$p2->SetColor("red");
$p2->SetCenter();
$p2->SetLegend("New tiger -99");
$graph->Add($p2);
// Output line
$graph->Stroke();
?>

View file

@ -0,0 +1,56 @@
<?php
// $Id: balloonex1.php,v 1.5 2002/12/15 16:08:51 aditus Exp $
include ("../jpgraph.php");
include ("../jpgraph_scatter.php");
// Some data
$datax = array(1,2,3,4,5,6,7,8);
$datay = array(12,23,95,18,65,28,86,44);
// Callback for markers
// Must return array(width,color,fill_color)
// If any of the returned values are "" then the
// default value for that parameter will be used.
function FCallback($aVal) {
// This callback will adjust the fill color and size of
// the datapoint according to the data value according to
if( $aVal < 30 ) $c = "blue";
elseif( $aVal < 70 ) $c = "green";
else $c="red";
return array(floor($aVal/3),"",$c);
}
// Setup a basic graph
$graph = new Graph(400,300,'auto');
$graph->SetScale("linlin");
$graph->img->SetMargin(40,100,40,40);
$graph->SetShadow();
$graph->title->Set("Example of ballon scatter plot");
// Use a lot of grace to get large scales
$graph->yaxis->scale->SetGrace(50,10);
// Make sure X-axis as at the bottom of the graph
$graph->xaxis->SetPos('min');
// Create the scatter plot
$sp1 = new ScatterPlot($datay,$datax);
$sp1->mark->SetType(MARK_FILLEDCIRCLE);
// Uncomment the following two lines to display the values
$sp1->value->Show();
$sp1->value->SetFont(FF_FONT1,FS_BOLD);
// Specify the callback
$sp1->mark->SetCallback("FCallback");
// Setup the legend for plot
$sp1->SetLegend('Year 2002');
// Add the scatter plot to the graph
$graph->Add($sp1);
// ... and send to browser
$graph->Stroke();
?>

View file

@ -0,0 +1,81 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_scatter.php");
// Each ballon is specificed by four values.
// (X,Y,Size,Color)
$data = array(
array(1,12,10,'orange'),
array(3,41,15,'red'),
array(4,5,19,'lightblue'),
array(5,70,22,'yellow')
);
// We need to create X,Y data vectors suitable for the
// library from the above raw data.
$n = count($data);
for( $i=0; $i < $n; ++$i ) {
$datax[$i] = $data[$i][0];
$datay[$i] = $data[$i][1];
// Create a faster lookup array so we don't have to search
// for the correct values in the callback function
$format[strval($datax[$i])][strval($datay[$i])] = array($data[$i][2],$data[$i][3]);
}
// Callback for markers
// Must return array(width,border_color,fill_color,filename,imgscale)
// If any of the returned values are '' then the
// default value for that parameter will be used (possible empty)
function FCallback($aYVal,$aXVal) {
global $format;
return array($format[strval($aXVal)][strval($aYVal)][0],'',
$format[strval($aXVal)][strval($aYVal)][1],'','');
}
// Setup a basic graph
$graph = new Graph(450,300,'auto');
$graph->SetScale("intlin");
$graph->SetMargin(40,40,40,40);
$graph->SetMarginColor('wheat');
$graph->title->Set("Example of ballon scatter plot with X,Y callback");
$graph->title->SetFont(FF_ARIAL,FS_BOLD,12);
$graph->title->SetMargin(10);
// Use a lot of grace to get large scales since the ballon have
// size and we don't want them to collide with the X-axis
$graph->yaxis->scale->SetGrace(50,10);
$graph->xaxis->scale->SetGrace(50,10);
// Make sure X-axis as at the bottom of the graph and not at the default Y=0
$graph->xaxis->SetPos('min');
// Set X-scale to start at 0
$graph->xscale->SetAutoMin(0);
// Create the scatter plot
$sp1 = new ScatterPlot($datay,$datax);
$sp1->mark->SetType(MARK_FILLEDCIRCLE);
// Uncomment the following two lines to display the values
$sp1->value->Show();
$sp1->value->SetFont(FF_FONT1,FS_BOLD);
// Specify the callback
$sp1->mark->SetCallbackYX("FCallback");
// Add the scatter plot to the graph
$graph->Add($sp1);
// ... and send to browser
$graph->Stroke();
?>

View file

@ -0,0 +1,48 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
$datay=array(20,30,50,80);
$datay2=array(430,645,223,690);
$datazero=array(0,0,0,0);
// Create the graph.
$graph = new Graph(450,200);
$graph->title->Set('Example with 2 scale bars');
// Setup Y and Y2 scales with some "grace"
$graph->SetScale("textlin");
$graph->SetY2Scale("lin");
$graph->yaxis->scale->SetGrace(30);
$graph->y2axis->scale->SetGrace(30);
//$graph->ygrid->Show(true,true);
$graph->ygrid->SetColor('gray','lightgray@0.5');
// Setup graph colors
$graph->SetMarginColor('white');
$graph->y2axis->SetColor('darkred');
// Create the "dummy" 0 bplot
$bplotzero = new BarPlot($datazero);
// Create the "Y" axis group
$ybplot1 = new BarPlot($datay);
$ybplot1->value->Show();
$ybplot = new GroupBarPlot(array($ybplot1,$bplotzero));
// Create the "Y2" axis group
$ybplot2 = new BarPlot($datay2);
$ybplot2->value->Show();
$ybplot2->value->SetColor('darkred');
$ybplot2->SetFillColor('darkred');
$y2bplot = new GroupBarPlot(array($bplotzero,$ybplot2));
// Add the grouped bar plots to the graph
$graph->Add($ybplot);
$graph->AddY2($y2bplot);
// .. and finally stroke the image back to browser
$graph->Stroke();
?>

View file

@ -0,0 +1,52 @@
<?php
include_once ("../jpgraph.php");
include_once ("../jpgraph_bar.php");
$datay=array(12,26,9,17,31);
// Create the graph.
// One minute timeout for the cached image
// INLINE_NO means don't stream it back to the browser.
$graph = new Graph(310,250,'auto');
$graph->SetScale("textlin");
$graph->img->SetMargin(60,30,20,40);
$graph->yaxis->SetTitleMargin(45);
$graph->yaxis->scale->SetGrace(30);
$graph->SetShadow();
// Turn the tickmarks
$graph->xaxis->SetTickSide(SIDE_DOWN);
$graph->yaxis->SetTickSide(SIDE_LEFT);
// Create a bar pot
$bplot = new BarPlot($datay);
// Create targets for the image maps. One for each column
$targ=array("bar_clsmex1.php#1","bar_clsmex1.php#2","bar_clsmex1.php#3","bar_clsmex1.php#4","bar_clsmex1.php#5","bar_clsmex1.php#6");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$bplot->SetCSIMTargets($targ,$alts);
$bplot->SetFillColor("orange");
// Use a shadow on the bar graphs (just use the default settings)
$bplot->SetShadow();
$bplot->value->SetFormat(" $ %2.1f",70);
$bplot->value->SetFont(FF_ARIAL,FS_NORMAL,9);
$bplot->value->SetColor("blue");
$bplot->value->Show();
$graph->Add($bplot);
$graph->title->Set("Image maps barex1");
$graph->xaxis->title->Set("X-title");
$graph->yaxis->title->Set("Y-title");
$graph->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
// Send back the HTML page which will call this script again
// to retrieve the image.
$graph->StrokeCSIM();
?>

View file

@ -0,0 +1,51 @@
<?php
include_once ("../jpgraph.php");
include_once ("../jpgraph_bar.php");
$data1y=array(12,8,19,3,10,5);
$data2y=array(8,2,12,7,14,4);
// Create the graph. These two calls are always required
$graph = new Graph(310,200,'auto');
$graph->SetScale("textlin");
$graph->img->SetMargin(40,30,20,40);
$graph->SetShadow();
// Create the bar plots
$b1plot = new BarPlot($data1y);
$b1plot->SetFillColor("orange");
$targ=array("bar_clsmex2.php#1","bar_clsmex2.php#2","bar_clsmex2.php#3",
"bar_clsmex2.php#4","bar_clsmex2.php#5","bar_clsmex2.php#6");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$b1plot->SetCSIMTargets($targ,$alts);
$b2plot = new BarPlot($data2y);
$b2plot->SetFillColor("blue");
$targ=array("bar_clsmex2.php#7","bar_clsmex2.php#8","bar_clsmex2.php#9",
"bar_clsmex2.php#10","bar_clsmex2.php#11","bar_clsmex2.php#12");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$b2plot->SetCSIMTargets($targ,$alts);
// Create the grouped bar plot
$abplot = new AccBarPlot(array($b1plot,$b2plot));
$abplot->SetShadow();
$abplot->value->Show();
// ...and add it to the graPH
$graph->Add($abplot);
$graph->title->Set("Image map barex2");
$graph->xaxis->title->Set("X-title");
$graph->yaxis->title->Set("Y-title");
$graph->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
// Send back the HTML page which will call this script again
// to retrieve the image.
$graph->StrokeCSIM();
?>

View file

@ -0,0 +1,88 @@
<?php
// $Id: bar_csimex3.php,v 1.3 2002/08/31 20:03:46 aditus Exp $
// Horiontal bar graph with image maps
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
$data1y=array(5,8,19,3,10,5);
$data2y=array(12,2,12,7,14,4);
// Setup the basic parameters for the graph
$graph = new Graph(400,700);
$graph->SetAngle(90);
$graph->SetScale("textlin");
// The negative margins are necessary since we
// have rotated the image 90 degress and shifted the
// meaning of width, and height. This means that the
// left and right margins now becomes top and bottom
// calculated with the image width and not the height.
$graph->img->SetMargin(-80,-80,210,210);
$graph->SetMarginColor('white');
// Setup title for graph
$graph->title->Set('Horizontal bar graph');
$graph->title->SetFont(FF_FONT2,FS_BOLD);
$graph->subtitle->Set("With image map\nNote: The URL just points back to this image");
// Setup X-axis.
$graph->xaxis->SetTitle("X-title",'center');
$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
$graph->xaxis->title->SetAngle(90);
$graph->xaxis->SetTitleMargin(30);
$graph->xaxis->SetLabelMargin(15);
$graph->xaxis->SetLabelAlign('right','center');
// Setup Y-axis
// First we want it at the bottom, i.e. the 'max' value of the
// x-axis
$graph->yaxis->SetPos('max');
// Arrange the title
$graph->yaxis->SetTitle("Turnaround (mkr)",'center');
$graph->yaxis->SetTitleSide(SIDE_RIGHT);
$graph->yaxis->title->SetFont(FF_FONT2,FS_BOLD);
$graph->yaxis->title->SetAngle(0);
$graph->yaxis->title->Align('center','top');
$graph->yaxis->SetTitleMargin(30);
// Arrange the labels
$graph->yaxis->SetLabelSide(SIDE_RIGHT);
$graph->yaxis->SetLabelAlign('center','top');
// Create the bar plots with image maps
$b1plot = new BarPlot($data1y);
$b1plot->SetFillColor("orange");
$targ=array("bar_clsmex2.php#1","bar_clsmex2.php#2","bar_clsmex2.php#3",
"bar_clsmex2.php#4","bar_clsmex2.php#5","bar_clsmex2.php#6");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$b1plot->SetCSIMTargets($targ,$alts);
$b2plot = new BarPlot($data2y);
$b2plot->SetFillColor("blue");
$targ=array("bar_clsmex2.php#7","bar_clsmex2.php#8","bar_clsmex2.php#9",
"bar_clsmex2.php#10","bar_clsmex2.php#11","bar_clsmex2.php#12");
$alts=array("val=%d","val=%d","val=%d","val=%d","val=%d","val=%d");
$b2plot->SetCSIMTargets($targ,$alts);
// Create the accumulated bar plot
$abplot = new AccBarPlot(array($b1plot,$b2plot));
$abplot->SetShadow();
// We want to display the value of each bar at the top
$abplot->value->Show();
$abplot->value->SetFont(FF_FONT1,FS_NORMAL);
$abplot->value->SetAlign('left','center');
$abplot->value->SetColor("black","darkred");
$abplot->value->SetFormat('%.1f mkr');
// ...and add it to the graph
$graph->Add($abplot);
// Send back the HTML page which will call this script again
// to retrieve the image.
$graph->StrokeCSIM();
?>

View file

@ -0,0 +1,30 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
$data = array(0.1235,0.4567,0.67,0.45,0.832);
// Callback function
// Get called with the actual value and should return the
// value to be displayed as a string
function cbFmtPercentage($aVal) {
return sprintf("%.1f%%",100*$aVal); // Convert to string
}
// Create the graph.
$graph = new Graph(400,300);
$graph->SetScale("textlin");
// Create a bar plots
$bar1 = new BarPlot($data);
// Setup the callback function
$bar1->value->SetFormatCallback("cbFmtPercentage");
$bar1->value->Show();
// Add the plot to the graph
$graph->Add($bar1);
// .. and send the graph back to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,47 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 20:32
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(0.13,0.25,0.21,0.35,0.31,0.06);
$datax=array("Jan","Feb","Mar","Apr","May","June");
// Setup the graph.
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(60,20,30,50);
$graph->SetScale("textlin");
$graph->SetMarginColor("lightblue");
$graph->SetShadow();
// Set up the title for the graph
$graph->title->Set("Bar gradient (Left reflection)");
$graph->title->SetFont(FF_VERDANA,FS_NORMAL,12);
$graph->title->SetColor("darkred");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
// Show 0 label on Y-axis (default is not to show)
$graph->yscale->ticks->SupressZeroLabel(false);
// Setup X-axis labels
$graph->xaxis->SetTickLabels($datax);
$graph->xaxis->SetLabelAngle(50);
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","#EEEEEE",GRAD_LEFT_REFLECTION);
// Set color for the frame of each bar
$bplot->SetColor("white");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,48 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 20:32
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(-0.13,0.25,-0.21,0.35,0.31,0.04);
$datax=array("Jan","Feb","Mar","Apr","May","June");
// Setup the graph.
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(60,20,30,50);
$graph->SetScale("textlin");
$graph->SetMarginColor("silver");
$graph->SetShadow();
// Set up the title for the graph
$graph->title->Set("Example negative bars");
$graph->title->SetFont(FF_VERDANA,FS_NORMAL,18);
$graph->title->SetColor("darkred");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,12);
$graph->xaxis->SetColor("black","red");
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,11);
// Show 0 label on Y-axis (default is not to show)
$graph->yscale->ticks->SupressZeroLabel(false);
// Setup X-axis labels
$graph->xaxis->SetTickLabels($datax);
$graph->xaxis->SetLabelAngle(50);
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","steelblue",GRAD_MIDVER);
// Set color for the frame of each bar
$bplot->SetColor("navy");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,50 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 20:32
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(-0.13,0.25,-0.21,0.35,0.31,0.04);
$datax=array("Jan","Feb","Mar","Apr","May","June");
// Setup the graph.
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(60,20,30,50);
$graph->SetScale("textlin");
$graph->SetMarginColor("silver");
$graph->SetShadow();
// Set up the title for the graph
$graph->title->Set("Example negative bars");
$graph->title->SetFont(FF_VERDANA,FS_NORMAL,16);
$graph->title->SetColor("darkred");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
// Show 0 label on Y-axis (default is not to show)
$graph->yscale->ticks->SupressZeroLabel(false);
// Setup X-axis labels
$graph->xaxis->SetTickLabels($datax);
$graph->xaxis->SetLabelAngle(50);
// Set X-axis at the minimum value of Y-axis (default will be at 0)
$graph->xaxis->SetPos("min"); // "min" will position the x-axis at the minimum value of the Y-axis
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","steelblue",GRAD_MIDVER);
// Set color for the frame of each bar
$bplot->SetColor("navy");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,47 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 19:44
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(0.3031,0.3044,0.3049,0.3040,0.3024,0.3047);
// Setup the graph.
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(60,30,30,40);
$graph->SetScale("textlin");
$graph->SetMarginColor("teal");
$graph->SetShadow();
// Set up the title for the graph
$graph->title->Set("Bargraph with small variations");
$graph->title->SetColor("white");
$graph->title->SetFont(FF_VERDANA,FS_BOLD,12);
// Setup color for axis and labels
$graph->xaxis->SetColor("black","white");
$graph->yaxis->SetColor("black","white");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
// Setup X-axis title (color & font)
$graph->xaxis->title->Set("X-axis");
$graph->xaxis->title->SetColor("white");
$graph->xaxis->title->SetFont(FF_VERDANA,FS_BOLD,10);
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$tcol=array(100,100,255);
$fcol=array(255,100,100);
$bplot->SetFillGradient($fcol,$tcol,GRAD_HOR);
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,52 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 19:44
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
include ("../jpgraph_line.php");
// We need some data
$datay=array(0.3031,0.3044,0.3049,0.3040,0.3024,0.3047);
// Setup the graph.
$graph = new Graph(400,200,"auto");
$graph->img->SetMargin(60,30,30,40);
$graph->SetScale("textlin");
$graph->SetMarginColor("teal");
$graph->SetShadow();
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// This is how you make the bar graph start from something other than 0
$bplot->SetYMin(0.302);
// Setup color for gradient fill style
$tcol=array(100,100,255);
$fcol=array(255,100,100);
$bplot->SetFillGradient($fcol,$tcol,GRAD_HOR);
$bplot->SetFillColor("orange");
$graph->Add($bplot);
// Set up the title for the graph
$graph->title->Set("Bargraph which doesn't start from y=0");
$graph->title->SetColor("yellow");
$graph->title->SetFont(FF_VERDANA,FS_BOLD,12);
// Setup color for axis and labels
$graph->xaxis->SetColor("black","white");
$graph->yaxis->SetColor("black","white");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
// Setup X-axis title (color & font)
$graph->xaxis->title->Set("X-axis");
$graph->xaxis->title->SetColor("white");
$graph->xaxis->title->SetFont(FF_VERDANA,FS_BOLD,10);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,51 @@
<?php
// Example for use of JpGraph,
// ljp, 01/03/01 20:32
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(-0.13,0.25,-0.21,0.35,0.31,0.04);
$datax=array("Jan","Feb","Mar","Apr","May","June");
// Setup the graph.
$graph = new Graph(500,200,"auto");
$graph->img->SetMargin(60,150,30,50);
$graph->SetScale("textlin");
$graph->SetMarginColor("silver");
$graph->SetShadow();
// Set up the title for the graph
$graph->title->Set("Example negative bars");
$graph->title->SetFont(FF_VERDANA,FS_NORMAL,16);
$graph->title->SetColor("darkred");
// Setup font for axis
$graph->xaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
$graph->yaxis->SetFont(FF_VERDANA,FS_NORMAL,10);
// Show 0 label on Y-axis (default is not to show)
$graph->yscale->ticks->SupressZeroLabel(false);
// Setup X-axis labels
$graph->xaxis->SetTickLabels($datax);
$graph->xaxis->SetLabelAngle(50);
// Set X-axis at the minimum value of Y-axis (default will be at 0)
$graph->xaxis->SetPos("min"); // "min" will position the x-axis at the minimum value of the Y-axis
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
$bplot->SetLegend("Result 1999","blue");
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","steelblue",GRAD_MIDVER);
// Set color for the frame of each bar
$bplot->SetColor("navy");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,34 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(4,8,6);
// Setup the graph.
$graph = new Graph(200,150,"auto");
$graph->SetScale("textlin");
$graph->img->SetMargin(25,15,25,25);
$graph->title->Set('"GRAD_MIDVER"');
$graph->title->SetColor('darkred');
// Setup font for axis
$graph->xaxis->SetFont(FF_FONT1);
$graph->yaxis->SetFont(FF_FONT1);
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","lightsteelblue",GRAD_MIDVER);
// Set color for the frame of each bar
$bplot->SetColor("navy");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

View file

@ -0,0 +1,34 @@
<?php
include ("../jpgraph.php");
include ("../jpgraph_bar.php");
// We need some data
$datay=array(4,8,6);
// Setup the graph.
$graph = new Graph(200,150,"auto");
$graph->SetScale("textlin");
$graph->img->SetMargin(25,15,25,25);
$graph->title->Set('"GRAD_MIDHOR"');
$graph->title->SetColor('darkred');
// Setup font for axis
$graph->xaxis->SetFont(FF_FONT1);
$graph->yaxis->SetFont(FF_FONT1);
// Create the bar pot
$bplot = new BarPlot($datay);
$bplot->SetWidth(0.6);
// Setup color for gradient fill style
$bplot->SetFillGradient("navy","lightsteelblue",GRAD_MIDHOR);
// Set color for the frame of each bar
$bplot->SetColor("navy");
$graph->Add($bplot);
// Finally send the graph to the browser
$graph->Stroke();
?>

Some files were not shown because too many files have changed in this diff Show more