1
0
mirror of https://gitlab.com/animath/si/plateforme-corres2math.git synced 2025-06-24 04:28:46 +02:00

Copie du site du TFJM² à adapter aux Correspondances

This commit is contained in:
galaxyoyo
2019-09-10 01:48:52 +02:00
commit fa5202fe4f
77 changed files with 5620 additions and 0 deletions

View File

@ -0,0 +1,63 @@
<?php
if (!isset($_SESSION["role"]) || ($_SESSION["role"] != Role::PARTICIPANT && $_SESSION["role"] != Role::ENCADRANT))
require_once "server_files/403.php";
$tournaments_response = $DB->query("SELECT `id`, `name` FROM `tournaments` WHERE `date_inscription` > CURRENT_DATE AND `year` = '$YEAR';");
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$new_team = new NewTeam($_POST);
try {
$new_team->makeVerifications();
$new_team->register();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class NewTeam {
public $name;
public $trigram;
public $tournament_id;
public $tournament;
public $access_code;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications() {
ensure($_SESSION["team"] == null, "Vous êtes déjà dans une équipe.");
ensure($this->name != null && $this->name != "", "Vous devez spécifier un nom d'équipe.");
ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme entré n'est pas valide.");
ensure(!teamExists($this->name), "Une équipe existe déjà avec ce nom.");
ensure(!trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme.");
$this->tournament = Tournament::fromId($this->tournament_id);
ensure($this->tournament != null, "Le tournoi spécifié n'existe pas.");
}
public function register() {
global $DB, $YEAR;
$this->access_code = genRandomPhrase(6);
$req = $DB->prepare("INSERT INTO `teams` (`name`, `trigram`, `tournament`, `encadrant_1`, `participant_1`, `validation_status`, `access_code`, `year`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
$req->execute([$this->name, $this->trigram, $this->tournament_id, $_SESSION["role"] == Role::ENCADRANT ? $_SESSION["user_id"] : NULL,
$_SESSION["role"] == Role::PARTICIPANT ? $_SESSION["user_id"] : NULL, ValidationStatus::NOT_READY, $this->access_code, $YEAR]);
$_SESSION["team"] = Team::fromTrigram($this->trigram);
$_SESSION["user"]->setTeamId($_SESSION["team"]->getId());
Mailer::sendAddTeamMail($_SESSION["user"], $_SESSION["team"], $this->tournament);
}
}
require_once "server_files/views/ajouter_equipe.php";

View File

@ -0,0 +1,57 @@
<?php
if (!isset($_SESSION["role"]) || $_SESSION["role"] != Role::ADMIN)
require_once "server_files/403.php";
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$orga = new NewOrganizer($_POST);
try {
$orga->makeVerifications();
$orga->register();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class NewOrganizer {
public $surname;
public $first_name;
public $email;
public $admin;
public $password;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
ensure($this->surname != null && $this->surname != "", "Le nom est invalide.");
ensure($this->first_name != null && $this->first_name != "", "Le prénom est invalide.");
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail est invalide.");
$this->email = strtolower($this->email);
ensure(!userExists($this->email), "Cette adresse e-mail est déjà utilisée.");
$this->admin = $this->admin == "on" ? true : false;
}
public function register() {
global $DB, $YEAR;
$this->password = genRandomPhrase(16, true);
$req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `surname`, `first_name`, `role`, `year`)
VALUES (?, ?, ?, ?, ?, ?);");
$req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->surname, $this->first_name, $this->admin ? "ADMIN" : "ORGANIZER", $YEAR]);
Mailer::sendAddOrganizerMail($this);
}
}
require_once "server_files/views/ajouter_organisateur.php";

View File

@ -0,0 +1,104 @@
<?php
if (!isset($_SESSION["role"]) || $_SESSION["role"] != Role::ADMIN)
require_once "server_files/403.php";
$orgas_response = $DB->query("SELECT `id`, `surname`, `first_name` FROM `users` WHERE (`role` = 'ORGANIZER' OR `role` = 'ADMIN') AND `year` = '$YEAR';");
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$tournament = new NewTournament($_POST);
try {
$tournament->makeVerifications();
$tournament->register();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class NewTournament {
public $name;
public $organizers;
public $size;
public $place;
public $price;
public $date_start;
public $date_end;
public $date_inscription;
public $time_inscription;
public $date_solutions;
public $time_solutions;
public $date_syntheses;
public $time_syntheses;
public $description;
public $final;
public $tournament;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = ($key == "organizers" ? $value : htmlspecialchars($value));
}
public function makeVerifications()
{
global $FINAL;
ensure($this->name != null && $this->name != "", "Le nom est invalide.");
ensure(!tournamentExists($this->name), "Un tournoi existe déjà avec ce nom.");
ensure(sizeof($this->organizers) > 0, "Aucun organisateur n'a été choisi.");
$orgas = [];
foreach ($this->organizers as $orga_id) {
$orga = User::fromId($orga_id);
ensure($orga != null, "Un organisateur spécifié n'existe pas.");
ensure($orga->getRole() == Role::ORGANIZER || $orga->getRole() == Role::ADMIN, "Une personne indiquée ne peut pas organiser de tournoi.");
$orgas[] = $orga;
}
$this->organizers = $orgas;
ensure(preg_match("#[0-9]*#", $this->size), "Le nombre d'équipes indiqué n'est pas un nombre valide.");
$this->size = intval($this->size);
ensure($this->size >= 3 && $this->size <= 15, "Un tournoi doit avoir au moins 3 et au plus 15 équipes.");
ensure(preg_match("#[0-9]*#", $this->price), "Le tarif pour les participants n'est pas un entier valide.");
$this->price = intval($this->price);
ensure($this->price >= 0, "Le TFJM² ne va pas payer les élèves pour venir.");
ensure($this->price <= 50, "Soyons raisonnable sur le prix.");
ensure(dateWellFormed($this->date_start), "La date de début n'est pas valide.");
ensure(dateWellFormed($this->date_end), "La date de fin n'est pas valide.");
ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date de clôture des inscriptions n'est pas valide.");
ensure(dateWellFormed($this->date_solutions . " " . $this->time_solutions), "La date limite de remise des solutions n'est pas valide.");
ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse n'est pas valide.");
$this->final = $this->final ? 1 : 0;
ensure(!$this->final || $FINAL == NULL, "Une finale nationale est déjà enregistrée.");
}
public function register()
{
global $DB, $YEAR;
$req = $DB->prepare("INSERT INTO `tournaments` (`name`, `size`, `place`, `price`, `description`,
`date_start`, `date_end`, `date_inscription`, `date_solutions`, `date_syntheses`, `final`, `year`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
$req->execute([$this->name, $this->size, $this->place, $this->price, $this->description, $this->date_start, $this->date_end,
"$this->date_inscription $this->time_inscription", "$this->date_solutions $this->time_solutions", "$this->date_syntheses $this->time_syntheses", $this->final ? 1 : 0, $YEAR]);
$this->tournament = Tournament::fromName($this->name);
/** @var User $organizer */
foreach ($this->organizers as $organizer) {
$this->tournament->addOrganizer($organizer);
Mailer::sendAddOrganizerForTournamentMail($organizer, $this->tournament);
}
}
}
require_once "server_files/views/ajouter_tournoi.php";

View File

@ -0,0 +1,19 @@
<?php
$token = $_GET["token"];
if (isset($token)) {
$result = $DB->query("SELECT `email` FROM `users` WHERE `confirm_email` = '$token' AND `year` = '$YEAR';");
if (($data = $result->fetch()) === FALSE)
$error_message = "Le jeton est invalide. Votre compte est peut-être déjà validé ?";
else {
$DB->exec("UPDATE `users` SET `confirm_email` = NULL WHERE `confirm_email` = '$token';");
$error_message = "Votre adresse mail a été validée ! Vous pouvez désormais vous connecter.";
}
}
else {
$error_message = "Il n'y a pas de compte à valider !";
}
require_once "server_files/views/header.php";
echo "<h2>$error_message</h2>";
require_once "server_files/views/footer.php";

View File

@ -0,0 +1,170 @@
<?php
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"]) && !isset($_SESSION["user_id"])) {
$logging_in_user = new LoggingInUser($_POST);
try {
$logging_in_user->makeVerifications();
$logging_in_user->login();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_POST["forgotten_password"]) && !isset($_SESSION["user_id"])) {
$recuperate_account = new RecuperateAccount($_POST);
try {
$recuperate_account->makeVerifications();
$recuperate_account->recuperateAccount();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_GET["reset_password"]) && isset($_GET["token"]) && !isset($_SESSION["user_id"])) {
$reset_password = new ResetPassword($_GET, $_POST);
try {
$reset_password->makeVerifications();
if (isset($_POST["password"]))
$reset_password->resetPassword();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_GET["confirmation-mail"]) && !isset($_SESSION["user_id"]))
sendConfirmEmail();
class LoggingInUser
{
public $email;
/** @var User $user */
public $user;
private $password;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
global $URL_BASE;
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide.");
$this->user = User::fromEmail($this->email);
ensure($this->user != null, "Le compte n'existe pas.");
ensure($this->user->checkPassword($this->password), "Le mot de passe est incorrect.");
if ($this->user->getConfirmEmailToken() != null) {
$_SESSION["confirm_email"] = $this->email;
throw new AssertionError("L'adresse mail n'a pas été validée. Veuillez vérifier votre boîte mail (surtout vos spams). "
. "<a href=\"$URL_BASE/connexion/confirmation-mail\">Cliquez ici pour renvoyer le mail de confirmation</a>.");
}
}
public function login()
{
$_SESSION["user_id"] = $this->user->getId();
loadUserValues();
}
}
class RecuperateAccount
{
public $email;
/** @var User $user */
public $user;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse email est invalide.");
$this->user = User::fromEmail($this->email);
ensure($this->user != null, "Le compte n'existe pas.");
}
public function recuperateAccount()
{
$token = genRandomPhrase(64);
$this->user->setForgottenPasswordToken($token);
Mailer::sendForgottenPasswordProcedureMail($this->user);
}
}
class ResetPassword
{
public $token;
/** @var User $user */
public $user;
private $password;
private $confirm_password;
public function __construct($data, $data2)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
foreach ($data2 as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
global $DB;
$data = $DB->query("SELECT `id` FROM `users` WHERE `forgotten_password` = '" . $this->token . "';")->fetch();
ensure($data !== false, "Il n'y a pas de compte à récupérer avec ce jeton.");
$this->user = User::fromId($data["id"]);
if ($this->password == null)
return;
ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents.");
ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères.");
}
public function resetPassword()
{
$this->user->setForgottenPasswordToken(null);
$this->user->setPassword($this->password);
Mailer::sendChangePasswordMail($this->user);
return false;
}
}
function sendConfirmEmail()
{
global $URL_BASE;
$email = htmlspecialchars($_SESSION["confirm_email"]);
if (!isset($email)) {
header("Location: $URL_BASE/connexion");
exit();
}
$user = User::fromEmail($email);
if ($user === null) {
unset($_SESSION["confirm_email"]);
header("Location: $URL_BASE/connexion");
exit();
}
Mailer::sendConfirmEmail($user);
return false;
}
require_once "server_files/views/connexion.php";

View File

@ -0,0 +1,8 @@
<?php
unset($_SESSION["user_id"]);
session_destroy();
require_once "server_files/views/header.php";
echo "<h2>Déconnexion réussie !</h2>";
require_once "server_files/views/footer.php";

View File

@ -0,0 +1,57 @@
<?php
if (!isset($_SESSION["user_id"]) || $_SESSION["role"] != Role::ORGANIZER && $_SESSION["role"] != Role::ADMIN)
require_once "server_files/403.php";
$trigram = htmlspecialchars($_GET["trigram"]);
$team = Team::fromTrigram($trigram);
$tournament = Tournament::fromId($team->getTournamentId());
if ($team === null)
require_once "server_files/404.php";
if (isset($_POST["validate"])) {
$team->setValidationStatus(ValidationStatus::VALIDATED);
}
if (isset($_POST["select"])) {
$team->selectForFinal(true);
$team->setValidationStatus(ValidationStatus::NOT_READY);
$sols = $tournament->getAllSolutions($team->getId());
/** @var Solution $sol */
foreach ($sols as $sol) {
$old_id = $sol->getFileId();
do
$id = genRandomPhrase(64);
while (file_exists("$LOCAL_PATH/files/$id"));
copy("$LOCAL_PATH/files/$old_id", "$LOCAL_PATH/files/$id");
$req = $DB->prepare("INSERT INTO `solutions`(`file_id`, `team`, `tournament`, `problem`) VALUES (?, ?, ?, ?);");
$req->execute([$id, $team->getId(), $FINAL->getId(), $sol->getFileId()]);
}
}
if (isset($_POST["download_zip"])) {
$final = isset($_POST["final"]);
$tournament_dest = $final ? $FINAL : $tournament;
$file_name = getZipFile(DocumentType::PARENTAL_CONSENT, $tournament_dest->getId(), $team->getId());
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"Documents de l'équipe " . $team->getTrigram() . ".zip\"");
header("Content-Length: " . strval(filesize($file_name)));
readfile($file_name);
exit();
}
$documents = $tournament->getAllDocuments($team->getId());
$documents_final = null;
if ($team->isSelectedForFinal())
$documents_final = $FINAL->getAllDocuments($team->getId());
require_once "server_files/views/equipe.php";

View File

@ -0,0 +1,3 @@
<?php
require_once "server_files/views/index.php";

View File

@ -0,0 +1,26 @@
<?php
if (!isset($_SESSION["role"]))
require_once "server_files/403.php";
$id = $_GET["id"];
$user = User::fromId($id);
if ($_SESSION["role"] != Role::ORGANIZER && $_SESSION["role"] != Role::ADMIN) {
if ($user->getId() != $_SESSION["user_id"] && ($user->getTeamId() == null || $user->getTeamId() != $_SESSION["user"]->getTeamId()))
require_once "server_files/403.php";
}
if ($user === null)
require_once "server_files/404.php";
$team = Team::fromId($user->getTeamId());
$tournaments = $user->getOrganizedTournaments();
if ($team != null) {
$documents = $user->getAllDocuments($team->getTournamentId());
if ($team->isSelectedForFinal())
$documents_final = $user->getAllDocuments($FINAL->getId());
}
require_once "server_files/views/informations.php";

View File

@ -0,0 +1,93 @@
<?php
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$user = new NewUser($_POST);
try {
$user->makeVerifications();
$user->register();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class NewUser
{
public $email;
public $first_name;
public $surname;
public $birth_date;
public $gender;
public $address = "";
public $postal_code;
public $city = "";
public $country;
public $phone_number;
public $role;
public $school;
public $class;
public $responsible_name;
public $responsible_phone;
public $responsible_email;
public $description;
public $confirm_email_token;
private $password;
private $confirm_password;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
}
public function makeVerifications()
{
global $YEAR;
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide.");
$this->email = strtolower($this->email);
ensure(!userExists($this->email), "Un compte existe déjà avec cette adresse e-mail.");
ensure(strlen($this->password) >= 8, "Le mot de passe doit comporter au moins 8 caractères.");
ensure($this->password == $this->confirm_password, "Les deux mots de passe sont différents.");
ensure($this->surname != "", "Le nom de famille est obligatoire.");
ensure($this->first_name != "", "Le prénom est obligatoire.");
ensure(dateWellFormed($this->birth_date), "La date de naissance est invalide.");
ensure($this->birth_date < $YEAR . "-01-01", "Vous devez être né.");
ensure($this->gender == "M" || $this->gender == "F", "Le sexe indiqué est invalide.");
ensure(preg_match("#^[0-9]{4}[0-9]?$#", $this->postal_code) && intval($this->postal_code) >= 01000 && intval($this->postal_code) <= 95999, "Le code postal est invalide.");
if ($this->country == "")
$this->country = "France";
ensure(strlen($this->phone_number) >= 10, "Le numéro de téléphone est invalide.");
$this->role = Role::fromName(strtoupper($this->role));
if ($this->role == Role::PARTICIPANT) {
$this->class = SchoolClass::fromName(strtoupper($this->class));
if ($this->birth_date > strval($YEAR - 18) . "04-01") {
ensure($this->responsible_name != "", "Veuillez spécifier un responsable légal.");
ensure(strlen($this->responsible_phone) >= 10, "Veuillez rentrer le numéro de téléphone de votre responsable légal.");
ensure(filter_var($this->responsible_email, FILTER_VALIDATE_EMAIL), "Veuillez spécifier un responsable légal.");
}
}
$this->confirm_email_token = genRandomPhrase(64);
}
public function register()
{
global $DB, $YEAR;
$req = $DB->prepare("INSERT INTO `users`(`email`, `pwd_hash`, `confirm_email`, `surname`, `first_name`, `birth_date`, `gender`,
`address`, `postal_code`, `city`, `country`, `phone_number`, `school`, `class`, `role`, `description`, `year`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);");
$req->execute([$this->email, password_hash($this->password, PASSWORD_BCRYPT), $this->confirm_email_token, $this->surname, $this->first_name, $this->birth_date, $this->gender, $this->address,
$this->postal_code, $this->city, $this->country, $this->phone_number, $this->school, SchoolClass::getName($this->class), Role::getName($this->role), $this->description, $YEAR]);
Mailer::sendRegisterMail($this);
}
}
require_once "server_files/views/inscription.php";

View File

@ -0,0 +1,152 @@
<?php
if (!isset($_SESSION["user_id"]))
require_once "server_files/403.php";
/** @var User $user */
$user = $_SESSION["user"];
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$my_account = new MyAccount($_POST);
try {
$my_account->makeVerifications();
$my_account->updateAccount();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_POST["submitted_password"])) {
$new_password = new NewPassword($_POST);
try {
$new_password->makeVerifications();
$new_password->updatePassword();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class MyAccount
{
public $email;
public $surname;
public $first_name;
public $birth_date;
public $gender;
public $address;
public $postal_code;
public $city;
public $country;
public $phone_number;
public $school;
public $class;
public $responsible_name;
public $responsible_phone;
public $responsible_email;
public $description;
private $user;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
$this->user = $_SESSION["user"];
$keys = ["email", "surname", "first_name", "birth_date", "gender", "address", "postal_code", "city", "country", "phone_number",
"school", "class", "responsible_name", "responsible_phone", "responsible_email", "description"];
if ($this->user->getRole() == Role::PARTICIPANT)
$this->class = SchoolClass::fromName($this->class);
foreach ($keys as $key)
$this->$key = $this->$key != null && $this->$key != "" ? $this->$key : $this->user->$key;
}
public function makeVerifications()
{
global $YEAR;
ensure(filter_var($this->email, FILTER_VALIDATE_EMAIL), "L'adresse e-mail entrée est invalide.");
$this->email = strtolower($this->email);
ensure($this->email == $this->user->getEmail() || !userExists($this->email), "Un compte existe déjà avec cette adresse e-mail.");
ensure(dateWellFormed($this->birth_date), "La date de naissance est invalide.");
ensure($this->birth_date < $YEAR . "-01-01", "Vous devez être né.");
ensure($this->gender == "M" || $this->gender == "F", "Le sexe indiqué est invalide.");
ensure(preg_match("#^[0-9]{4}[0-9]?$#", $this->postal_code) && intval($this->postal_code) >= 01000 && intval($this->postal_code) <= 95999, "Le code postal est invalide.");
ensure(strlen($this->phone_number) >= 10, "Le numéro de téléphone est invalide.");
if ($this->user->getRole() == Role::PARTICIPANT) {
if ($this->birth_date > strval($YEAR - 18) . "04-01") {
ensure($this->responsible_name != "", "Veuillez spécifier un responsable légal.");
ensure(strlen($this->responsible_phone) >= 10, "Veuillez rentrer le numéro de téléphone de votre responsable légal.");
ensure(filter_var($this->responsible_email, FILTER_VALIDATE_EMAIL), "Veuillez spécifier un responsable légal.");
}
}
}
public function updateAccount()
{
$this->user->setSurname($this->surname);
$this->user->setFirstName($this->first_name);
$this->user->setBirthDate($this->birth_date);
$this->user->setGender($this->gender);
$this->user->setAddress($this->address);
$this->user->setPostalCode($this->postal_code);
$this->user->setCity($this->city);
$this->user->setCountry($this->country);
$this->user->setPhoneNumber($this->phone_number);
$this->user->setSchool($this->school);
$this->user->setClass($this->class);
$this->user->setResponsibleName($this->responsible_name);
$this->user->setResponsiblePhone($this->responsible_phone);
$this->user->setResponsibleEmail($this->responsible_email);
$this->user->setDescription($this->description);
if ($this->email != $this->user->getEmail()) {
$this->user->setEmail($this->email);
$this->user->setConfirmEmailToken(genRandomPhrase(64));
Mailer::sendChangeEmailAddressMail($this->user);
}
}
}
class NewPassword
{
private $user;
private $old_password;
private $new_password;
private $confirm_password;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
$this->user = $_SESSION["user"];
}
public function makeVerifications()
{
ensure($this->user->checkPassword($this->old_password), "L'ancien mot de passe est incorrect.");
ensure(strlen($this->new_password) >= 8, "Le mot de passe doit comporter au moins 8 caractères.");
ensure($this->new_password == $this->confirm_password, "Les deux mots de passe sont différents.");
}
public function updatePassword()
{
$this->user->setPassword($this->new_password);
Mailer::sendChangePasswordMail($this->user);
}
}
require_once "server_files/views/mon_compte.php";

View File

@ -0,0 +1,141 @@
<?php
if (isset($_POST["leave_team"])) {
quitTeam();
exit();
}
$tournaments = Tournament::getAllTournaments(false, true);
$has_error = false;
$error_message = null;
if (isset($_POST["send_document"])) {
$send_document = new SendDocument();
try {
$send_document->makeVerifications();
$send_document->sendDocument();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_POST["team_edit"])) {
$my_team = new MyTeam($_POST);
try {
$my_team->makeVerifications();
$my_team->updateTeam();
}
catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
if (isset($_POST["request_validation"])) {
if (!canValidate($team, $tournament))
$error_message = "Votre équipe ne peut pas demander la validation : il manque soit des participants, soit des documents.";
else
$_SESSION["team"]->setValidationStatus(ValidationStatus::WAITING);
}
if (isset($_SESSION["user_id"]) && isset($_SESSION["team"]) && $_SESSION["team"] !== null) {
/**
* @var User $user
* @var Team $team
*/
$user = $_SESSION["user"];
$team = $_SESSION["team"];
$tournament = Tournament::fromId($team->getTournamentId());
$documents = $user->getAllDocuments($team->getTournamentId());
if ($team->isSelectedForFinal())
$documents_final = $user->getAllDocuments($FINAL->getId());
}
else
require_once "server_files/403.php";
class SendDocument
{
private $file;
private $type;
public function __construct()
{
$this->file = $_FILES["document"];
$this->type = strtoupper(htmlspecialchars($_POST["type"]));
}
public function makeVerifications()
{
global $LOCAL_PATH;
ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo.");
ensure(!$this->file["error"], "Une erreur est survenue.");
ensure(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]) == "application/pdf", "Le fichier doit être au format PDF.");
ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur.");
}
public function sendDocument()
{
global $LOCAL_PATH, $DB, $FINAL;
do
$id = genRandomPhrase(64);
while (file_exists("$LOCAL_PATH/files/$id"));
if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id"))
throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier.");
$req = $DB->prepare("INSERT INTO `documents`(`file_id`, `user`, `team`, `tournament`, `type`)
VALUES (?, ?, ?, ?, ?);");
$req->execute([$id, $_SESSION["user_id"], $_SESSION["team"]->getId(), $_SESSION["team"]->isSelectedForFinal() ? $FINAL->getId() : $_SESSION["team"]->getTournamentId(), $this->type]);
}
}
class MyTeam
{
public $name;
public $trigram;
public $tournament_id;
private $team;
private $tournament;
public function __construct($data)
{
foreach ($data as $key => $value)
$this->$key = htmlspecialchars($value);
$this->trigram = strtoupper($this->trigram);
$this->team = $_SESSION["team"];
$this->tournament = Tournament::fromId($this->tournament_id);
}
public function makeVerifications()
{
ensure($this->name != "" && $this->name != null, "Veuillez spécifier un nom d'équipe.");
ensure($this->name == $this->team->getName() || !teamExists($this->name), "Une équipe existe déjà avec ce nom.");
ensure(preg_match("#^[A-Z]{3}$#", $this->trigram), "Le trigramme n'est pas valide.");
ensure($this->trigram == $this->team->getTrigram() || !trigramExists($this->trigram), "Une équipe a déjà choisi ce trigramme.");
ensure($this->tournament != null, "Le tournoi indiqué n'existe pas.");
ensure(date("y-m-d H:i:s") <= $this->tournament->getInscriptionDate(), "Les inscriptions sont terminées.");
ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Votre équipe est déjà validée ou en cours de validation.");
}
public function updateTeam()
{
global $URL_BASE;
$this->team->setName($this->name);
$this->team->setTrigram($this->trigram);
$this->team->setTournamentId($this->tournament_id);
$_SESSION["tournament"] = $this->tournament;
header("Location: $URL_BASE/mon_equipe");
}
}
require_once "server_files/views/mon_equipe.php";

View File

@ -0,0 +1,66 @@
<?php
if (isset($_SESSION["team"]) || !isset($_SESSION["user"]) || ($_SESSION["role"] != Role::PARTICIPANT && $_SESSION["role"] != Role::ENCADRANT))
require_once "server_files/403.php";
$has_error = false;
$error_message = null;
if (isset($_POST["submitted"])) {
$join_team = new JoinTeam($_POST);
try {
$join_team->makeVerifications();
$join_team->joinTeam();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
class JoinTeam
{
private $access_code;
private $team;
private $min_null_index;
public function __construct($data)
{
$this->access_code = strtolower(htmlspecialchars($data["access_code"]));
$this->team = Team::fromAccessCode($this->access_code);
}
public function makeVerifications()
{
ensure(preg_match("#[a-z0-9]{6}#", $this->access_code), "Le code d'accès doit comporter 6 caractères alphanumériques.");
ensure($this->team != null, "Ce code d'accès est invalide.");
ensure($this->team->getValidationStatus() == ValidationStatus::NOT_READY, "Cette équipe est déjà validée ou en cours de validation, vous ne pouvez pas la rejoindre.");
for ($i = 1; $i <= $_SESSION["role"] == Role::PARTICIPANT ? 6 : 2; ++$i) {
if (($_SESSION["role"] == Role::PARTICIPANT ? $this->team->getParticipants()[$i - 1] : $this->team->getEncadrants()[$i - 1]) == NULL)
break;
}
$this->min_null_index = $i;
ensure($_SESSION["role"] == Role::PARTICIPANT && $this->min_null_index <= 6 || $_SESSION["role"] == Role::ENCADRANT && $this->min_null_index <= 2, "Il n'y a plus de place pour vous dans l'équipe.");
}
public function joinTeam()
{
$user = $_SESSION["user"];
$user->setTeamId($this->team->getId());
if ($_SESSION["role"] == Role::ENCADRANT)
$this->team->setEncadrant($this->min_null_index, $user->getId());
else
$this->team->setParticipant($this->min_null_index, $user->getId());
$_SESSION["team"] = $this->team;
$tournament = $_SESSION["tournament"] = Tournament::fromId($this->team->getTournamentId());
Mailer::sendJoinTeamMail($user, $this->team, $tournament);
}
}
require_once "server_files/views/rejoindre_equipe.php";

View File

@ -0,0 +1,72 @@
<?php
if (!isset($_SESSION["team"]))
require_once "server_files/403.php";
/**
* @var Team $team
* @var Tournament $tournament
*/
$team = $_SESSION["team"];
$tournament = Tournament::fromId($team->getTournamentId());
$has_error = false;
$error_message = null;
if (isset($_POST["send_solution"])) {
$save_solution = new SaveSolution();
try {
$save_solution->makeVerifications();
$save_solution->saveSolution();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
$solutions = $tournament->getAllSolutions($team->getId());
$solutions_final = null;
if ($team->isSelectedForFinal())
$solutions_final = $FINAL->getAllSolutions($team->getId());
class SaveSolution
{
private $problem;
private $file;
public function __construct()
{
$this->file = $_FILES["document"];
$this->problem = htmlspecialchars($_POST["problem"]);
}
public function makeVerifications()
{
global $LOCAL_PATH;
ensure(preg_match("#[1-9]#", $this->problem), "Le numéro du problème est invalide.");
ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo.");
ensure(!$this->file["error"], "Une erreur est survenue.");
ensure(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]) == "application/pdf", "Le fichier doit être au format PDF.");
ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur.");
}
public function saveSolution()
{
global $LOCAL_PATH, $DB, $team, $tournament, $FINAL;
do
$id = genRandomPhrase(64);
while (file_exists("$LOCAL_PATH/files/$id"));
if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id"))
throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier.");
$req = $DB->prepare("INSERT INTO `solutions`(`file_id`, `team`, `tournament`, `problem`) VALUES (?, ?, ?, ?);");
$req->execute([$id, $team->getId(), $team->isSelectedForFinal() ? $FINAL->getId() : $tournament->getId(), $this->problem]);
return false;
}
}
require_once "server_files/views/solutions.php";

View File

@ -0,0 +1,24 @@
<?php
if (!isset($_SESSION["role"]) || $_SESSION["role"] != Role::ADMIN && $_SESSION["role"] != Role::ORGANIZER)
require_once "server_files/403.php";
if (isset($_POST["download_zip"])) {
$id = $_POST["tournament"];
$tournament = Tournament::fromId($id);
$file_name = getZipFile(DocumentType::SOLUTION, $id);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"Solutions du tournoi de " . $tournament->getName() . ".zip\"");
header("Content-Length: " . strval(filesize($file_name)));
readfile($file_name);
exit();
}
$user = $_SESSION["user"];
$tournaments = $_SESSION["role"] == Role::ADMIN ? Tournament::getAllTournaments() : $user->getOrganizedTournaments();
require_once "server_files/views/solutions_orga.php";

View File

@ -0,0 +1,68 @@
<?php
if (!isset($_SESSION["team"]))
require_once "server_files/403.php";
/**
* @var Team $team
* @var Tournament $tournament
*/
$team = $_SESSION["team"];
$tournament = Tournament::fromId($team->getTournamentId());
if (isset($_POST["send_synthesis"])) {
$save_synthesis = new SaveSynthesis();
try {
$save_synthesis->makeVerifications();
$save_synthesis->saveSynthesis();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
$syntheses = $tournament->getAllSyntheses($team->getId());
$syntheses_final = null;
if ($team->isSelectedForFinal())
$syntheses_final = $FINAL->getAllSyntheses($team->getId());
class SaveSynthesis
{
private $dest;
private $file;
public function __construct()
{
$this->file = $_FILES["document"];
$this->dest = DestType::fromName(strtoupper(htmlspecialchars($_POST["problem"])));
}
public function makeVerifications()
{
global $LOCAL_PATH;
ensure($this->dest != DestType::DEFENSEUR, "Le destinataire est invalide.");
ensure($this->file["size"] <= 2e6, "Le fichier doit peser moins que 2 Mo.");
ensure(!$this->file["error"], "Une erreur est survenue.");
ensure(finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file["tmp_name"]) == "application/pdf", "Le fichier doit être au format PDF.");
ensure(is_dir("$LOCAL_PATH/files") || mkdir("$LOCAL_PATH/files"), "Un problème est survenue dans l'envoi du fichier. Veuillez contacter l'administrateur du serveur.");
}
public function saveSynthesis()
{
global $LOCAL_PATH, $DB, $team, $tournament, $FINAL;
do
$id = genRandomPhrase(64);
while (file_exists("$LOCAL_PATH/files/$id"));
if (!rename($this->file["tmp_name"], "$LOCAL_PATH/files/$id"))
throw new AssertionError("Une erreur est survenue lors de l'envoi du fichier.");
$req = $DB->prepare("INSERT INTO `syntheses`(`file_id`, `team`, `tournament`, `dest`) VALUES (?, ?, ?, ?);");
$req->execute([$id, $team->getId(), $team->isSelectedForFinal() ? $FINAL->getId() : $tournament->getId(), $this->dest]);
return false;
}
}
require_once "server_files/views/syntheses.php";

View File

@ -0,0 +1,22 @@
<?php if (!isset($_SESSION["role"]) || $_SESSION["role"] != Role::ADMIN && $_SESSION["role"] != Role::ORGANIZER)
require_once "server_files/403.php";
if (isset($_POST["download_zip"])) {
$id = $_POST["tournament"];
$tournament = Tournament::fromId($id);
$file_name = getZipFile(DocumentType::SYNTHESIS, $id);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=\"Notes de syntèses du tournoi de " . $tournament->getName() . ".zip\"");
header("Content-Length: " . filesize($file_name));
readfile($file_name);
exit();
}
$user = $_SESSION["user"];
$tournaments = $_SESSION["role"] == Role::ADMIN ? Tournament::getAllTournaments() : $user->getOrganizedTournaments();
require_once "server_files/views/syntheses_orga.php";

View File

@ -0,0 +1,125 @@
<?php
$tournament_name = htmlspecialchars($_GET["name"]);
$tournament = Tournament::fromName($tournament_name);
if ($tournament === null)
require_once "server_files/404.php";
if (isset($_GET["modifier"]) && $_SESSION["role"] != Role::ADMIN && !$tournament->organize($_SESSION["user_id"]))
require_once "server_files/403.php";
$has_error = false;
$error_message = null;
if (isset($_POST["edit_tournament"])) {
$update_tournament = new UpdateTournament($_POST);
try {
$update_tournament->makeVerifications();
$update_tournament->updateTournament();
} catch (AssertionError $e) {
$has_error = true;
$error_message = $e->getMessage();
}
}
$orgas = $tournament->getOrganizers();
$teams = $tournament->getAllTeams();
$orgas_response = $DB->query("SELECT `id`, `surname`, `first_name` FROM `users` WHERE (`role` = 'ORGANIZER' OR `role` = 'ADMIN') AND `year` = '$YEAR';");
class UpdateTournament
{
public $name;
public $organizers;
public $size;
public $place;
public $price;
public $date_start;
public $date_end;
public $date_inscription;
public $time_inscription;
public $date_solutions;
public $time_solutions;
public $date_syntheses;
public $time_syntheses;
public $description;
public $final;
public function __construct($data)
{
global $tournament;
foreach ($data as $key => $value)
$this->$key = ($key == "organizers" ? $value : htmlspecialchars($value));
if ($_SESSION["role"] != Role::ADMIN) {
$this->organizers = [];
/** @var User $organizer */
foreach ($tournament->getOrganizers() as $organizer)
$this->organizers[] = $organizer->getId();
}
}
public function makeVerifications()
{
global $tournament;
ensure($this->name != null && $this->name != "", "Le nom est invalide.");
ensure($this->name == $tournament->getName() || !tournamentExists($this->name), "Un tournoi existe déjà avec ce nom.");
ensure(sizeof($this->organizers) > 0, "Aucun organisateur n'a été choisi.");
$orgas = [];
foreach ($this->organizers as $orga_id) {
$orga = User::fromId($orga_id);
ensure($orga != null, "Un organisateur spécifié n'existe pas.");
ensure($orga->getRole() == Role::ORGANIZER || $orga->getRole() == Role::ADMIN, "Une personne indiquée ne peut pas organiser de tournoi.");
$orgas[] = $orga;
}
$this->organizers = $orgas;
ensure(preg_match("#[0-9]*#", $this->size), "Le nombre d'équipes indiqué n'est pas un nombre valide.");
$this->size = intval($this->size);
ensure($this->size >= 3 && $this->size <= 15, "Un tournoi doit avoir au moins 3 et au plus 15 équipes.");
ensure(preg_match("#[0-9]*#", $this->price), "Le tarif pour les participants n'est pas un entier valide.");
$this->price = intval($this->price);
ensure($this->price >= 0, "Le TFJM² ne va pas payer les élèves pour venir.");
ensure($this->price <= 50, "Soyons raisonnable sur le prix.");
ensure(dateWellFormed($this->date_start), "La date de début n'est pas valide.");
ensure(dateWellFormed($this->date_end), "La date de fin n'est pas valide.");
ensure(dateWellFormed($this->date_inscription . " " . $this->time_inscription), "La date de clôture des inscriptions n'est pas valide.");
ensure(dateWellFormed($this->date_solutions . " " . $this->time_solutions), "La date limite de remise des solutions n'est pas valide.");
ensure(dateWellFormed($this->date_syntheses . " " . $this->time_syntheses), "La date limite de remise des notes de synthèse n'est pas valide.");
}
public function updateTournament()
{
global $URL_BASE, $tournament;
$tournament->setName($this->name);
$tournament->setSize($this->size);
$tournament->setPlace($this->place);
$tournament->setPrice($this->price);
$tournament->setStartDate($this->date_start);
$tournament->setEndDate($this->date_end);
$tournament->setInscriptionDate("$this->date_inscription $this->time_inscription");
$tournament->setSolutionsDate("$this->date_solutions $this->time_solutions");
$tournament->setSynthesesDate("$this->date_syntheses $this->time_syntheses");
foreach ($this->organizers as $organizer) {
if (!$tournament->organize($organizer->getId()))
Mailer::sendAddOrganizerForTournamentMail($organizer, $tournament);
}
$tournament->clearOrganizers();
/** @var User $organizer */
foreach ($this->organizers as $organizer)
$tournament->addOrganizer($organizer);
header("Location: $URL_BASE/tournoi/" . $this->name);
exit();
}
}
require_once "server_files/views/tournoi.php";

View File

@ -0,0 +1,5 @@
<?php
$tournaments = Tournament::getAllTournaments();
require_once "server_files/views/tournois.php";

View File

@ -0,0 +1,78 @@
<?php
if (!isset($_GET["file_id"])) {
header("Location: $URL_BASE");
exit();
}
if (!isset($_SESSION["user_id"]))
require_once "server_files/403.php";
$id = htmlspecialchars($_GET["file_id"]);
$type = DocumentType::SOLUTION;
$file = Solution::fromId($id);
if ($file === null) {
$type = DocumentType::SYNTHESIS;
$file = Synthesis::fromId($id);
if ($file === null) {
$file = Document::fromId($id);
$type = DocumentType::PARENTAL_CONSENT;
}
}
if ($file !== null) {
$team = Team::fromId($file->getTeamId());
$tournament = Tournament::fromId($file->getTournamentId());
$trigram = $team->getTrigram();
if ($_SESSION["role"] == Role::ORGANIZER && !$tournament->organize($_SESSION["user_id"]))
require_once "server_files/403.php";
if ($type == DocumentType::SOLUTION) {
$problem = $file->getProblem();
$name = "Problème $problem $trigram.pdf";
if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && (!isset($_SESSION["team"]) || $_SESSION["team"]->getId() != $team->getId()))
require_once "server_files/403.php";
}
else if ($type == DocumentType::SYNTHESIS) {
$dest = $file->getDest();
$name = "Note de synthèse $trigram pour " . ($dest == DestType::OPPOSANT ? "l'opposant" : "le rapporteur") . ".pdf";
if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && (!isset($_SESSION["team"]) || $_SESSION["team"]->getId() != $team->getId()))
require_once "server_files/403.php";
}
else {
$user = User::fromId($file->getUserId());
$type = $file->getType();
if (($_SESSION["role"] == Role::PARTICIPANT || $_SESSION["role"] == Role::ENCADRANT) && $user->getId() != $_SESSION["user_id"])
require_once "server_files/403.php";
$surname = $user->getSurname();
$first_name = $user->getFirstName();
switch ($type) {
case DocumentType::PARENTAL_CONSENT:
$name = "Autorisation parentale";
break;
case DocumentType::PHOTO_CONSENT:
$name = "Autorisation de droit à l'image";
break;
case DocumentType::SANITARY_PLUG:
$name = "Fiche sanitaire";
break;
}
$name .= " de $first_name $surname.pdf";
}
}
else
require_once "server_files/404.php";
header("Content-Type: application/pdf");
header("Content-Disposition: inline; filename=\"$name\"");
readfile("$LOCAL_PATH/files/$id");
exit();