merge userControler

documentation
kevin.modejar 3 months ago
commit 06a68268e2

@ -37,17 +37,23 @@ Class FrontControler{
*/ */
// Route mapping using the router object
// Each route is associated with an HTTP method (GET|POST), a URL path, a controller, and a method within that controller.
//Visitor routes
$router->map('GET|POST', '/quote/[i:idQuote]', 'VisitorControler','quote'); $router->map('GET|POST', '/quote/[i:idQuote]', 'VisitorControler','quote');
$router->map('GET|POST', '/addComment', 'UserControler','addComment');
$router->map('GET|POST', '/quiz/[i:id]', 'UserControler','quiz');
$router->map('GET|POST', '/favorite', 'UserControler','favorite');
$router->map('GET|POST', '/search', 'VisitorControler','search'); $router->map('GET|POST', '/search', 'VisitorControler','search');
$router->map('GET|POST', '/profil', 'UserControler','profil');
$router->map('GET|POST', '/login', 'VisitorControler','login'); $router->map('GET|POST', '/login', 'VisitorControler','login');
$router->map('GET|POST', '/unlog', 'UserControler','unlog');
$router->map('GET|POST', '/signin', 'VisitorControler','signin'); $router->map('GET|POST', '/signin', 'VisitorControler','signin');
$router->map('GET|POST', '/validlogin', 'VisitorControler','validlogin'); $router->map('GET|POST', '/validlogin', 'VisitorControler','validlogin');
$router->map('GET|POST', '/validsignin', 'VisitorControler','validsignin'); $router->map('GET|POST', '/validsignin', 'VisitorControler','validsignin');
//User routes
$router->map('GET|POST', '/addComment', 'UserControler','addComment');
$router->map('GET|POST', '/quiz/[i:id]', 'UserControler','quiz');
$router->map('GET|POST', '/favorite', 'UserControler','favorite');
$router->map('GET|POST', '/profil', 'UserControler','profil');
$router->map('GET|POST', '/unlog', 'UserControler','unlog');
$router->map('GET|POST', '/addFav/[i:id]', 'UserControler','addFav'); $router->map('GET|POST', '/addFav/[i:id]', 'UserControler','addFav');
$router->map('GET|POST', '/supFav/[i:id]', 'UserControler','supFav'); $router->map('GET|POST', '/supFav/[i:id]', 'UserControler','supFav');
$router->map('GET|POST', '/changedata', 'UserControler','changedata'); $router->map('GET|POST', '/changedata', 'UserControler','changedata');
@ -69,7 +75,7 @@ Class FrontControler{
$action = $match['name']; $action = $match['name'];
//Si existe, on lappelle //If exist
if(!$this->ifExisteAction($action)){ if(!$this->ifExisteAction($action)){
$dVueEreur[] = "Action introuvable"; $dVueEreur[] = "Action introuvable";
$this->vueErreur($dVueEreur); $this->vueErreur($dVueEreur);
@ -95,26 +101,62 @@ Class FrontControler{
} }
/**
* Checks if a given action exists within the predefined lists of actions
* for admin, user, or visitor roles.
*
* @param string $action The action to check.
* @return bool True if the action exists in any of the lists; otherwise, false.
*/
private function ifExisteAction(string $action):bool { private function ifExisteAction(string $action):bool {
// Check if the action exists in the 'admin' action list
if( in_array($action , $this->listAction['admin']) || if( in_array($action , $this->listAction['admin']) ||
// Check if the action exists in the 'user' action list
in_array($action , $this->listAction['user']) || in_array($action , $this->listAction['user']) ||
// Check if the action exists in the 'visitor' action list
in_array($action , $this->listAction['visitor']) ) { in_array($action , $this->listAction['visitor']) ) {
return true; return true;
} }
return false; return false;
} }
/**
* Verifies if the current user has the rights to perform a given action
* based on their role (admin, user, or visitor) and the predefined lists of actions.
*
* @param string $action The action to verify.
* @return bool True if the user has the rights to perform the action; otherwise, false.
*/
private function verifDroit(string $action):bool { private function verifDroit(string $action):bool {
if( in_array($action , $this->listAction['admin']) && $_SESSION["role"] == 'admin') return true; // Check if the action exists in the 'admin' action list and the user is an admin
elseif( in_array($action , $this->listAction['user']) && ($_SESSION["role"] == 'admin' || $_SESSION["role"] == 'user') ) return true; if( in_array($action , $this->listAction['admin']) && $_SESSION["role"] == 'admin'){
elseif(in_array($action , $this->listAction['visitor']) && ($_SESSION["role"] == 'admin'|| $_SESSION["role"] == 'user'|| $_SESSION["role"] == 'visitor')) return true; return true;
}
// Check if the action exists in the 'user' action list and the user is an admin or a user
elseif( in_array($action , $this->listAction['user']) && ($_SESSION["role"] == 'admin' || $_SESSION["role"] == 'user') ) {
return true;
}
// Check if the action exists in the 'visitor' action list and the user is an admin, user, or visitor
elseif(in_array($action , $this->listAction['visitor']) && ($_SESSION["role"] == 'admin'|| $_SESSION["role"] == 'user'|| $_SESSION["role"] == 'visitor')) {
return true;
}
return false; return false;
} }
/**
* Handles the display of errors by rendering an error view and optionally displaying
* the first error message from the provided error array.
*
* @param array $dVueErreur An array of error messages to be displayed.
* @return void
*/
private function vueErreur(array $dVueErreur){ private function vueErreur(array $dVueErreur){
global $vues; global $vues;
// Display the first error message in the array, if it exists
echo "{$dVueErreur[0]}"; echo "{$dVueErreur[0]}";
// Include and render the error view from the `$vues` global array
require_once $vues['erreur']; require_once $vues['erreur'];
} }

@ -45,27 +45,43 @@ class UserControler {
$this->iMod = new ImageModel(new ImageGateway($co)); $this->iMod = new ImageModel(new ImageGateway($co));
} }
/**
* Displays the user's profile page.
* Retrieves user details and a list of images, and handles error messages if present.
*
* @return void
*/
public function profil() { public function profil() {
global $vues; global $vues;
// Retrieve the username details of the currently logged-in user from the session.
$p = $this->uMod->getUsername($_SESSION["user"]); $p = $this->uMod->getUsername($_SESSION["user"]);
// Retrieve a list of all images from the image model.
$listImg = $this->iMod->getAllImg() ; $listImg = $this->iMod->getAllImg() ;
// Pour les messages d'erreur
$error_message = null; $error_message = null;
// Check if there is an error message stored in the session.
if (isset($_SESSION['error_message'])) { if (isset($_SESSION['error_message'])) {
// Retrieve the error message
$error_message = $_SESSION['error_message']; $error_message = $_SESSION['error_message'];
// Supprimer le message d'erreur après l'avoir lu // Remove the error message from the session
unset($_SESSION['error_message']); unset($_SESSION['error_message']);
} }
require_once $vues['profil']; require_once $vues['profil'];
} }
/**
* Adds a new comment to a specific quote.
* Validates input data, creates the comment, and redirects the user back to the quote page.
*
* @return void
*/
public function addComment(){ public function addComment(){
global $racine; global $racine;
// Retrieve the ID of the quote from the POST request.
$id = $_POST['idQuote']; $id = $_POST['idQuote'];
// Create a new comment using validated input data.
$this->cMod->createComment(Verification::verifChar($_POST['content']), $this->cMod->createComment(Verification::verifChar($_POST['content']),
Verification::verifChar($_POST['idQuote']), Verification::verifChar($_POST['idQuote']),
$this->uMod->getIdByUsername(Verification::verifChar($_SESSION['user']))); $this->uMod->getIdByUsername(Verification::verifChar($_SESSION['user'])));
@ -73,42 +89,73 @@ class UserControler {
} }
/**
* Displays the user's list of favorite quotes.
* Retrieves the user's ID from the session, fetches their favorites, and loads the favorites view.
*
* @param array $args Optional arguments passed to the method (not currently used).
* @return void
*/
public function favorite(array $args) { public function favorite(array $args) {
global $vues; global $vues;
// Retrieve the ID of the currently logged-in user using their username from the session.
$userId = $this->uMod->getIdByUsername($_SESSION["user"]); $userId = $this->uMod->getIdByUsername($_SESSION["user"]);
// Fetch the list of favorite quotes for the user.
$favorites = $this->qMod->getFavorites($userId); $favorites = $this->qMod->getFavorites($userId);
require_once $vues['favorite']; require_once $vues['favorite'];
} }
/**
* Logs the user out by clearing their session data and redirecting them to the homepage.
*
* @return void
*/
public function unlog(){ public function unlog(){
global $racine; global $racine;
// Clear all session variables
session_unset(); session_unset();
// Destroy the current session.
session_destroy(); session_destroy();
// Reset the session array to ensure no lingering data remains.
$_SESSION = array(); $_SESSION = array();
header("Location:".$racine); header("Location:".$racine);
} }
/**
* Handles the quiz functionality, including displaying questions, processing answers,
* and managing user progress and scores.
*
* @param array $args An array of arguments, expected to include 'id' for the quiz ID.
* @return void
*/
public function quiz(array $args){ public function quiz(array $args){
global $vues; global $vues;
// Retrieve the quiz ID from the arguments.
$id=$args['id']; $id=$args['id'];
// Get the total number of questions in the quiz.
$nb_questions = $this->getNumberOfQuestion($id); $nb_questions = $this->getNumberOfQuestion($id);
$action = $_REQUEST['action'] ?? null; $action = $_REQUEST['action'] ?? null;
// Handle different actions during the quiz.
switch ($action) { switch ($action) {
// Check the user's answer.
case 'canswer': case 'canswer':
// If the answer is correct, update the score in the session.
if ($this->CorrectAnswer()) if ($this->CorrectAnswer())
$_SESSION['score'] = Verification::verifChar( isset( $_SESSION['score']) ? ($_SESSION['score'] + 1) : 1 ) ; $_SESSION['score'] = Verification::verifChar( isset( $_SESSION['score']) ? ($_SESSION['score'] + 1) : 1 ) ;
// Continue the quiz with the next question or finish if it's the last question.
$this->continueQuiz($id, $nb_questions); $this->continueQuiz($id, $nb_questions);
break; break;
default: default:
switch($id) switch($id)
{ {
// If the quiz ID is null, handle the error case
case null: case null:
// page erreur
break; break;
// For a valid quiz ID, display the current question.
default: default:
$_SESSION['score'] = Verification::verifChar($_SESSION['score'] ?? 0); $_SESSION['score'] = Verification::verifChar($_SESSION['score'] ?? 0);
$this->showQuestion($id, Verification::verifChar($_SESSION['no_question'] ?? 0)); $this->showQuestion($id, Verification::verifChar($_SESSION['no_question'] ?? 0));
@ -118,41 +165,63 @@ class UserControler {
} }
/** /**
* @throws SyntaxError * Manages the progression of a quiz by updating the user's current question index.
* @throws RuntimeError * If the quiz is completed, it triggers the end quiz process. Otherwise, it redirects
* @throws LoaderError * to the next question.
*
* @param int $id_quiz The ID of the quiz.
* @param int $total_questions The total number of questions in the quiz.
* @return void
*/ */
public function continueQuiz(int $id_quiz, int $total_questions) : void{ public function continueQuiz(int $id_quiz, int $total_questions) : void{
global $racine; global $racine;
// Retrieve the current score from the session.
$score = $_SESSION['score']; $score = $_SESSION['score'];
// Update the question index in the session, incrementing by 1 or initializing to 1.
$_SESSION['no_question'] = Verification::verifChar( isset($_SESSION['no_question']) ? ($_SESSION['no_question'] + 1) : 1); $_SESSION['no_question'] = Verification::verifChar( isset($_SESSION['no_question']) ? ($_SESSION['no_question'] + 1) : 1);
// Check if the user has completed the quiz.
if ($_SESSION['no_question'] >= $total_questions) { if ($_SESSION['no_question'] >= $total_questions) {
// Reset the question index to 0 for a new quiz attempt.
$_SESSION['no_question'] = 0; $_SESSION['no_question'] = 0;
$this->endQuiz($id_quiz, $score); $this->endQuiz($id_quiz, $score);
// Reset the score for the next attempt or session.
$_SESSION['score'] = 0; $_SESSION['score'] = 0;
} }
else header("Location: ".$racine."/quiz/$id_quiz"); ///~kekentin/WF/WF-Website else header("Location: ".$racine."/quiz/$id_quiz"); ///~kekentin/WF/WF-Website
} }
/** /**
* @throws SyntaxError * Handles the end of the quiz, including checking if a next quiz exists
* @throws RuntimeError * and loading the appropriate view for the quiz completion.
* @throws LoaderError *
* @param int $id_quiz The ID of the current quiz.
* @param int $score The score the user achieved in the quiz.
* @return void
*/ */
public function endQuiz(int $id_quiz, int $score) : void{ public function endQuiz(int $id_quiz, int $score) : void{
global $vues,$co; global $vues,$co;
// Create a new QuizGateway and QuizModel to interact with the database.
$gw = new QuizGateway($co); $gw = new QuizGateway($co);
$mdl = new QuizModel($gw); $mdl = new QuizModel($gw);
// Check if a next quiz exists
if ($mdl->getQuiz($id_quiz + 1)){ if ($mdl->getQuiz($id_quiz + 1)){
require_once $vues['endQuiz']; require_once $vues['endQuiz'];
} }
require_once $vues['endQuiz']; require_once $vues['endQuiz'];
} }
/**
* Validates the user's answer to a quiz question by checking the submitted
* answers against the correct answer stored in the database.
*
* @return bool Returns true if the user's answer is correct, false otherwise.
*/
public function CorrectAnswer() : bool{ public function CorrectAnswer() : bool{
// Retrieve the user's selected answers from the POST request.
$answera = Verification::verifChar($_POST['answera'] ?? null); $answera = Verification::verifChar($_POST['answera'] ?? null);
$answerb = Verification::verifChar($_POST['answerb'] ?? null); $answerb = Verification::verifChar($_POST['answerb'] ?? null);
$answerc = Verification::verifChar($_POST['answerc'] ?? null); $answerc = Verification::verifChar($_POST['answerc'] ?? null);
@ -161,6 +230,7 @@ class UserControler {
$id= null; $id= null;
$answer = null; $answer = null;
// Check which answer option the user selected and extract the answer and ID.
if ($answera) { if ($answera) {
$answer = explode('-', $answera)[0]; $answer = explode('-', $answera)[0];
$id = (int) explode('-', $answera)[1]; $id = (int) explode('-', $answera)[1];
@ -174,51 +244,104 @@ class UserControler {
$answer = explode('-', $answerd)[0]; $answer = explode('-', $answerd)[0];
$id = (int) explode('-', $answerd)[1]; $id = (int) explode('-', $answerd)[1];
} }
// Retrieve the correct answer for the question from the model.
$res = $this->mdl->getQuestion($id); $res = $this->mdl->getQuestion($id);
return $answer == $res->getCanswer(); return $answer == $res->getCanswer();
} }
/**
* Retrieves all questions for a specific quiz identified by its ID.
*
* This function interacts with the QuizQuestionModel to fetch all the questions
* related to a specific quiz from the database.
*
* @param int $id The ID of the quiz for which to retrieve the questions.
* @return array An array of questions associated with the given quiz ID.
*/
public function GetQuestion(int $id): array{ public function GetQuestion(int $id): array{
global $co; global $co;
// Instantiate the QuizQuestionGateway to interact with the database.
$gw = new QuizQuestionGateway($co); $gw = new QuizQuestionGateway($co);
// Instantiate the QuizQuestionModel to handle the business logic.
$mdl = new QuizQuestionModel($gw); $mdl = new QuizQuestionModel($gw);
// Retrieve all questions for the specified quiz ID and return them as an array.
return $mdl->getAllQuestionByQuiz($id, $co); return $mdl->getAllQuestionByQuiz($id, $co);
} }
/** /**
* @throws RuntimeError * Displays a specific question from the quiz based on the provided quiz ID and question number.
* @throws SyntaxError *
* @throws LoaderError * This method retrieves the questions for a specific quiz and selects a particular question
* based on the question number (`$num`). It then passes the question data to the view for rendering.
*
* @param int $id The ID of the quiz to retrieve questions for.
* @param int $num The index of the question to display.
* @return void
*/ */
public function showQuestion(int $id, int $num) : void{ public function showQuestion(int $id, int $num) : void{
global $vues,$twig; global $vues,$twig;
// Retrieve all questions for the specified quiz using GetQuestion method.
$q = $this->GetQuestion($id); $q = $this->GetQuestion($id);
// Select the question based on the question number ($num). If the question number is out of bounds, use the first question.
$question = $q[$num] ?? $q[0]; $question = $q[$num] ?? $q[0];
// Get the ID of the selected question for further processing if needed.
$idquestion = $question->getIdQuestion(); $idquestion = $question->getIdQuestion();
require_once $vues['quiz']; require_once $vues['quiz'];
//echo $twig->render('quiz.html.twig', ['question' => $question,'id'=>$idquestion]);
} }
/**
* Retrieves the total number of questions for a specific quiz identified by its ID.
*
* This method uses the `QuizModel` to fetch the quiz data and returns the total number of questions
* associated with the specified quiz ID.
*
* @param int $id The ID of the quiz for which to retrieve the number of questions.
* @return int The total number of questions in the quiz.
*/
public function getNumberOfQuestion(int $id) : int{ public function getNumberOfQuestion(int $id) : int{
global $co; global $co;
$gw = new QuizGateway($co); $gw = new QuizGateway($co);
// Instantiate the QuizModel to handle the business logic of fetching quiz data.
$mdl = new QuizModel($gw); $mdl = new QuizModel($gw);
// Fetch the quiz by ID and return the total number of questions for that quiz.
return $mdl->getQuiz($id)->getNbQuestions(); return $mdl->getQuiz($id)->getNbQuestions();
} }
/**
* Adds a quote to the user's list of favorites.
*
* This method takes the ID of a quote, verifies the user, and then adds the specified quote
* to the user's list of favorites in the database. After that, it redirects the user back to
* the page displaying the quote.
*
* @param array $arg The arguments passed to the method, typically containing the quote ID.
* @return void
*/
public function addFav(array $arg){ public function addFav(array $arg){
global $racine; global $racine;
// Retrieve the quote ID from the provided arguments. Default to 1 if not provided.
$id= $arg['id'] ?? 1; $id= $arg['id'] ?? 1;
// Add the quote to the user's favorites by calling the addFavorite method from UserModel.
$this->uMod->addFavorite(Verification::verifChar($_SESSION["user"]),$id); $this->uMod->addFavorite(Verification::verifChar($_SESSION["user"]),$id);
header("Location:" . $racine . "/quote/$id"); header("Location:" . $racine . "/quote/$id");
} }
/**
* Removes a quote from the user's list of favorites.
*
* This method takes the ID of a quote, verifies the user, and then removes the specified quote
* from the user's list of favorites in the database. After that, it redirects the user back to
* the page displaying the quote.
*
* @param array $arg The arguments passed to the method, typically containing the quote ID.
* @return void
*/
public function supFav(array $arg){ public function supFav(array $arg){
global $racine; global $racine;
// Retrieve the quote ID from the provided arguments. Default to 1 if not provided.
$id= $arg['id'] ?? 1; $id= $arg['id'] ?? 1;
// Remove the quote from the user's favorites by calling the supFavorite method from UserModel.
$this->uMod->supFavorite(Verification::verifChar($_SESSION["user"]),$id); $this->uMod->supFavorite(Verification::verifChar($_SESSION["user"]),$id);
header("Location:". $racine ."/quote/$id"); header("Location:". $racine ."/quote/$id");
} }
@ -226,10 +349,23 @@ class UserControler {
// ===================== UPDATE DATA USER FUNCTION ===================== // ===================== UPDATE DATA USER FUNCTION =====================
/**
* Handles the updating of user data such as username, email, password, or profile image.
*
* This method processes the user's input from a form submission, which could include changes
* to the user's username, email, password, or profile image. Based on the provided input,
* the appropriate update function is called (e.g., `updatePseudo`, `updateEmail`, etc.).
* After updating the data, the user is redirected to their profile page.
*
* @return void
*/
public function changedata() : void{ public function changedata() : void{
global $vues, $racine; global $vues, $racine;
// Check if the form has been submitted.
if ($_POST) if ($_POST)
{ {
// Retrieve the submitted data from the form.
$newImage = $_POST['image'] ?? null; $newImage = $_POST['image'] ?? null;
$newPseudo = $_POST['pseudo'] ?? null; $newPseudo = $_POST['pseudo'] ?? null;
$newEmail = $_POST['email'] ?? null; $newEmail = $_POST['email'] ?? null;
@ -237,66 +373,106 @@ class UserControler {
$newMdpFirst = $_POST['passwdFirst'] ?? null; $newMdpFirst = $_POST['passwdFirst'] ?? null;
$newMdpSecond = $_POST['passwdSecond'] ?? null; $newMdpSecond = $_POST['passwdSecond'] ?? null;
// If a new pseudo is provided, update the username.
if($newPseudo){//Modif le pseudo if($newPseudo){
$this->updatePseudo($newPseudo); $this->updatePseudo($newPseudo);
} }
else if($newEmail){//Modif l'email // If a new email is provided, update the email and send a confirmation email.
else if($newEmail){
$this->updateEmail($newEmail); $this->updateEmail($newEmail);
$this->sendEmailChangeLogin($newEmail); //Envoie un email confirmant le changement d'email $this->sendEmailChangeLogin($newEmail); // Send a confirmation email for the email change.
} }
else if($newMdpFirst && $newMdpSecond){ //Modif le mot de passe // If new password fields are provided, validate and update the password.
else if($newMdpFirst && $newMdpSecond){
$this->updatePassWd($oldPasswd, $newMdpFirst,$newMdpSecond); $this->updatePassWd($oldPasswd, $newMdpFirst,$newMdpSecond);
} }
else if($newImage){//Modif l'image // If a new image is provided, update the profile image.
else if($newImage){
$this->updateImg($newImage); $this->updateImg($newImage);
} }
} }
header("Location: ". $racine."/profil"); header("Location: ". $racine."/profil");
} }
/**
* Updates the user's username (pseudo).
*
* This method attempts to update the user's username in the database. If the new username is
* valid and available, it updates the session with the new username. If the username is
* invalid or already taken, an error message is set in the session, and the user is redirected
* back to their profile page.
*
* @param string $newPseudo The new username (pseudo) to set.
* @return void
*/
public function updatePseudo(string $newPseudo){ public function updatePseudo(string $newPseudo){
$user = $this-> uMod->setUsername($_SESSION['user'], $newPseudo); $user = $this-> uMod->setUsername($_SESSION['user'], $newPseudo);
// Check if the username was updated successfully
if($user == $newPseudo){ if($user == $newPseudo){
// Update the session with the new username
$_SESSION['user'] = $newPseudo; $_SESSION['user'] = $newPseudo;
} }
else{ // pseudo invalide // If the username is invalid or already taken, set an error message
else{
$_SESSION['error_message'] = $newPseudo . " n'est pas valide ou non libre"; $_SESSION['error_message'] = $newPseudo . " n'est pas valide ou non libre";
header("Location: ". $racine."/profil"); header("Location: ". $racine."/profil");
} }
} }
/**
* Updates the user's email address.
*
* This method attempts to update the user's email address in the database. If the new email
* is invalid or cannot be updated, an error message is set in the session, and the user is
* redirected back to their profile page.
*
* @param string $newEmail The new email address to set.
* @return void
*/
public function updateEmail(string $newEmail){ public function updateEmail(string $newEmail){
$user = $this-> uMod->setEmail($_SESSION['user'], $newEmail); $user = $this-> uMod->setEmail($_SESSION['user'], $newEmail);
// Check if the email was successfully updated
if($user == $_SESSION['user']){ // si email incorrect, renvoie le nom de l'utilisateur de la session if($user == $_SESSION['user']){
// If the email is invalid, set an error message and redirect
$_SESSION['error_message'] = "L'email n'est pas valide"; $_SESSION['error_message'] = "L'email n'est pas valide";
header("Location: ". $racine."/profil"); header("Location: ". $racine."/profil");
} }
} }
/**
* Updates the user's password after verifying the old password and new password confirmation.
*
* This method checks if the old password is correct, ensures that the new passwords match,
* and then updates the password in the database. If any validation fails, an error message
* is set in the session, and the user is redirected back to their profile page.
*
* @param string $oldPasswd The user's old password.
* @param string $newMdpFirst The user's new password (first entry).
* @param string $newMdpSecond The user's new password (second entry for confirmation).
* @return void
*/
public function updatePassWd(string $oldPasswd, string $newMdpFirst, string $newMdpSecond){ public function updatePassWd(string $oldPasswd, string $newMdpFirst, string $newMdpSecond){
// Check if the old password is provided
if(!$oldPasswd){ if(!$oldPasswd){
$_SESSION['error_message'] = "Veuillez taper votre ancien mot de passe"; $_SESSION['error_message'] = "Veuillez taper votre ancien mot de passe";
header("Location: ". $racine."/profil"); header("Location: ". $racine."/profil");
} }
// Check if the old password matches the one in the database
else if(!$this->uMod->isPassWd($_SESSION['user'], $oldPasswd)){ else if(!$this->uMod->isPassWd($_SESSION['user'], $oldPasswd)){
$_SESSION['error_message'] = "Votre ancien mot de passe est incorrect"; $_SESSION['error_message'] = "Votre ancien mot de passe est incorrect";
header("Location: ". $racine."/profil"); header("Location: ". $racine."/profil");
} }
else{ else{
// Check if the new passwords match
if($newMdpFirst == $newMdpSecond){ if($newMdpFirst == $newMdpSecond){
// Generate a new hashed password
$option = ['cost' => 12]; $option = ['cost' => 12];
$newPassWd = password_hash($newMdpFirst, PASSWORD_BCRYPT, $option); $newPassWd = password_hash($newMdpFirst, PASSWORD_BCRYPT, $option);
// Update the password in the database
$user = $this-> uMod->setPassWd($_SESSION['user'], $newPassWd); $user = $this-> uMod->setPassWd($_SESSION['user'], $newPassWd);
} }
else{ else{
@ -306,7 +482,18 @@ class UserControler {
} }
} }
/**
* Updates the user's profile image.
*
* This method updates the user's profile image by calling the `setImage` method
* from the user model. It is assumed that the new image is valid and already uploaded
* to the server or provided in the correct format (e.g., a URL or image path).
*
* @param string $newImage The new image URL or path to be set as the user's profile picture.
* @return void
*/
public function updateImg(string $newImage){ public function updateImg(string $newImage){
// Update the user's image in the database
$user = $this->uMod->setImage($_SESSION['user'],$newImage); $user = $this->uMod->setImage($_SESSION['user'],$newImage);
} }
@ -317,47 +504,64 @@ class UserControler {
// ===================== SUBMIT FUNCTION ===================== // ===================== SUBMIT FUNCTION =====================
/** /**
* @throws SyntaxError * Displays the form for submitting a new quote.
* @throws RuntimeError *
* @throws LoaderError * This method retrieves all available characters and sources from the database
* and then displays the form for submitting a new quote. The data is passed to the
* view where the user can enter the quote details, such as the quote text, character,
* and source.
*
* @return void
*/ */
public function submit() : void{ public function submit() : void{
global $vues; global $vues;
$p = $this->caMod->getAllPerso(); // Fetch all available characters and sources for the submission form
$p = $this->caMod->getAllCharacters();
$s = $this->srcMod->getAllSources(); $s = $this->srcMod->getAllSources();
require_once $vues['submitQuote']; require_once $vues['submitQuote'];
} }
/** /**
* @throws SyntaxError * Processes the quote submission form and validates the character and source.
* @throws RuntimeError *
* @throws LoaderError * This method retrieves the data submitted by the user via POST, checks if the character and source
* exist in the database, and returns the valid data if everything is correct. If there are errors, it
* reloads the submission form and displays error messages.
*
* @return ?array Returns the form data (content, character ID, source ID) if valid, or null if no data.
*/ */
public function toSubmit() : ?array{ public function toSubmit() : ?array{
global $co; global $co;
// Check if there is a POST request (form submission)
if ($_POST) if ($_POST)
{ {
// Retrieve form data
$content = $_POST['content'] ?? null; $content = $_POST['content'] ?? null;
$character = $_POST['character'] ?? null; $character = $_POST['character'] ?? null;
$source = $_POST['src'] ?? null; $source = $_POST['src'] ?? null;
//$img = $_POST['img'] ?? null;
// Initialize an array to store errors
$errors = [null, null]; $errors = [null, null];
// Fetch the character from the database by its ID
$gw = new CharacterGateway($co); $gw = new CharacterGateway($co);
$mdl = new CharacterModel($gw); $mdl = new CharacterModel($gw);
$character = $mdl -> getCharacterById($character); $character = $mdl -> getCharacterById($character);
// Fetch the source from the database by its ID
$gw = new SourceGateway($co); $gw = new SourceGateway($co);
$mdl = new SourceModel($gw); $mdl = new SourceModel($gw);
$source = $mdl -> getSourceById($source); $source = $mdl -> getSourceById($source);
// Validate character and source
if (!$character) if (!$character)
$errors[0] = "Personnage inexistant"; $errors[0] = "Personnage inexistant";
if (!$source) if (!$source)
$errors[1] = "Source inexistante"; $errors[1] = "Source inexistante";
// If there are any errors, reload the form and pass error messages
if ($errors[0] || $errors[1]) if ($errors[0] || $errors[1])
{ {
global $twig; global $twig;
@ -365,30 +569,39 @@ class UserControler {
exit(); exit();
} }
// If everything is valid, return the data as an array
$gw = new QuoteGateway($co); $gw = new QuoteGateway($co);
$mdl = new QuoteModel($gw); $mdl = new QuoteModel($gw);
// Insert the new quote in the database
$mdl -> insert4User($content, '/imgPath', 'fr', $this -> getIdOfUser(), $source->getIdSource(), $character->getIdCharacter()); $mdl -> insert4User($content, '/imgPath', 'fr', $this -> getIdOfUser(), $source->getIdSource(), $character->getIdCharacter());
return [$content, $_POST['character'], $_POST['src']]; return [$content, $_POST['character'], $_POST['src']];
} }
// If there is no POST request, return null
return null; return null;
} }
/** /**
* @throws SyntaxError * Handles the validation of a quote submission form.
* @throws RuntimeError *
* @throws LoaderError * This method checks if both the 'character' and 'source' fields are set to 'other',
* and ensures the user is prompted to fill in valid custom values. If any fields are set to 'other',
* it will reload the form with a corresponding error message. Otherwise, it processes the valid submission.
*
* @return void
*/ */
public function validsubmit() : void public function validsubmit() : void
{ {
// Check if both the source and character are set to 'other'
if($_POST['src'] == 'other' && $_POST['character'] == 'other'){ if($_POST['src'] == 'other' && $_POST['character'] == 'other'){
global $vues; global $vues;
$src = true; $src = true; // Indicate an issue with the source field
$char = true; $char = true; // Indicate an issue with the character field
require_once $vues['create']; require_once $vues['create'];
exit(); exit();
} }
// If the source is 'other' but the character is not
elseif($_POST['src'] == 'other'){ elseif($_POST['src'] == 'other'){
global $vues; global $vues;
$src = true; $src = true;
@ -396,6 +609,7 @@ class UserControler {
require_once $vues['create']; require_once $vues['create'];
exit(); exit();
} }
// If the character is 'other' but the source is not
elseif($_POST['character'] == 'other'){ elseif($_POST['character'] == 'other'){
global $vues; global $vues;
$src = false; $src = false;
@ -403,8 +617,12 @@ class UserControler {
require_once $vues['create']; require_once $vues['create'];
exit(); exit();
} }
if($_POST) // If a valid POST request is present
if($_POST){
$recap = $this -> toSubmit(); $recap = $this -> toSubmit();
}
// If the submission is valid, process the recap
if ($recap) if ($recap)
{ {
$this -> recapSubmitQuote($recap); $this -> recapSubmitQuote($recap);
@ -416,15 +634,33 @@ class UserControler {
// ===================== SUBMIT QUOTE FUNCTION ===================== // ===================== SUBMIT QUOTE FUNCTION =====================
/** /**
* @throws RuntimeError * Handles the rendering of the recap page for a submitted quote.
* @throws SyntaxError *
* @throws LoaderError * This method takes the recap array (content, character, and source of a quote) and
* passes it to the Twig template engine to render the recap page.
*
* @param ?array $recap The recap array containing the content, character, and source details.
* If null, no rendering will occur.
* @return void
*/ */
public function recapSubmitQuote(?array $recap) : void{ public function recapSubmitQuote(?array $recap) : void{
global $twig; global $twig;
echo $twig -> render("recapSubmitQuote.html.twig", ['content' => $recap[0], 'character' => $recap[1], 'source' => $recap[2]]); // Render the recap page using the provided data
echo $twig -> render("recapSubmitQuote.html.twig", [
'content' => $recap[0],
'character' => $recap[1],
'source' => $recap[2]]);
} }
/**
* Retrieves the ID of the currently logged-in user.
*
* This method checks if a user is logged in by verifying the session. If a user is logged in,
* it retrieves the user's ID from the database using the `UserModel`. If no user is logged in, it returns `null`.
*
* @return ?int The ID of the logged-in user if one exists, otherwise `null`.
*/
public function getIdOfUser() : ?int{ public function getIdOfUser() : ?int{
if (isset($_SESSION['user'])) if (isset($_SESSION['user']))
{ {
@ -432,26 +668,49 @@ class UserControler {
$gw = new UserGateway($co); $gw = new UserGateway($co);
$mdl = new UserModel($gw); $mdl = new UserModel($gw);
// Retrieve the user object by username and return its ID
return $mdl -> getUsername($_SESSION['user']) -> getId(); return $mdl -> getUsername($_SESSION['user']) -> getId();
} }
// Return null if no user is logged in
return null; return null;
} }
/**
* Handles the creation of a new source or character based on the form submission.
*
* This method processes a form submission to either create a new source or character, depending on the value of `$_POST['req']`.
* It performs various validation checks to ensure the input is valid and ensures the source or character does not already exist in the system.
* If any errors occur during the validation, they are added to the `$error` array, and the user is shown the error messages.
*
* The method supports three types of submissions:
* - "both": which might imply both a source and character are being submitted.
* - "src": submission of a new source (e.g., movie, game, etc.).
* - "char": submission of a new character.
*
* The method uses the `Verification` class for validation and interacts with the `srcMod` model to manage sources.
*
* @return void
*/
public function add(){ public function add(){
global $vues; global $vues;
var_dump($_POST);
$error = []; $error = [];
// Handle form submission for both source and character
if($_POST['req'] == "both"){ if($_POST['req'] == "both"){
$src = true; $src = true;
$char = true; $char = true;
} }
// Handle form submission for source only
elseif($_POST['req'] == "src"){ elseif($_POST['req'] == "src"){
$src = true; $src = true;
$char = false; $char = false;
// Define allowed source types
$type = array("Movie","Serie","VideoGame","Anime"); $type = array("Movie","Serie","VideoGame","Anime");
// Validate title of the source
if(Verification::verifNotNull($_POST["titre"])){ if(Verification::verifNotNull($_POST["titre"])){
$_POST["titre"] = Verification::verifChar($_POST["titre"]); $_POST["titre"] = Verification::verifChar($_POST["titre"]);
// Check if the source already exists
if($this->srcMod->existSource($_POST["titre"],$_POST["type"])){ if($this->srcMod->existSource($_POST["titre"],$_POST["type"])){
$error[] = "La source existe déja"; $error[] = "La source existe déja";
} }
@ -459,10 +718,13 @@ class UserControler {
else{ else{
$error[] = "Le titre doit être définit"; $error[] = "Le titre doit être définit";
} }
// Validate the date of the source
if(Verification::verifNotNull($_POST["date"])){ if(Verification::verifNotNull($_POST["date"])){
$src = true; $src = true;
$char = false; $char = false;
$_POST["date"] = Verification::verifChar($_POST["date"]); $_POST["date"] = Verification::verifChar($_POST["date"]);
// Validate that the date is within a reasonable range
if(intval($_POST["date"],10) < 1850 or intval($_POST["date"],10) > date( "Y", time() )){ if(intval($_POST["date"],10) < 1850 or intval($_POST["date"],10) > date( "Y", time() )){
$error[] = "La date est invalide"; $error[] = "La date est invalide";
} }
@ -470,8 +732,11 @@ class UserControler {
else{ else{
$error[] = "La date doit être définit"; $error[] = "La date doit être définit";
} }
// Validate the date of the source
if(Verification::verifNotNull($_POST["type"])){ if(Verification::verifNotNull($_POST["type"])){
$_POST["type"] = Verification::verifChar($_POST["type"]); $_POST["type"] = Verification::verifChar($_POST["type"]);
// Check if the source already exists
if(!in_array($_POST["type"],$type)){ if(!in_array($_POST["type"],$type)){
$error[] = "Le type indiquer est inexistant"; $error[] = "Le type indiquer est inexistant";
} }
@ -487,11 +752,13 @@ class UserControler {
} }
} }
// If there are no errors, proceed with the creation
if($error == []){ if($error == []){
if($_POST['req'] == "both"){ if($_POST['req'] == "both"){
} }
elseif($_POST['req'] == "src"){ elseif($_POST['req'] == "src"){
// Create the new source
$this->srcMod->createSource($_POST["titre"], $_POST["date"], $_POST["type"]); $this->srcMod->createSource($_POST["titre"], $_POST["date"], $_POST["type"]);
} }
elseif($_POST['req'] == "char"){ elseif($_POST['req'] == "char"){
@ -499,8 +766,8 @@ class UserControler {
} }
} }
else{ else{
// If errors exist, return to the creation view and display the errors
require_once($vues["create"]); require_once($vues["create"]);
var_dump($error);
} }
} }
@ -508,37 +775,70 @@ class UserControler {
// ===================== DELETE ACCOUNT FUNCTION ===================== // ===================== DELETE ACCOUNT FUNCTION =====================
/**
* Deletes a user's account and all associated data.
*
* This method performs the complete deletion of a user's account by first removing all comments and favorites associated
* with the user, followed by the deletion of the user's account itself from the database.
* After the account deletion, the user is logged out, and their session is destroyed.
*
* @return void
*/
public function deleteAccount(){ public function deleteAccount(){
$this->uMod->deleteAllCommentary($_SESSION["user"]); // Delete all commentary // Delete all comments associated with the user's account
$this->uMod->deleteAllFavorite($_SESSION["user"]); // Delete all favorite $this->uMod->deleteAllCommentary($_SESSION["user"]);
// Delete all favorites associated with the user's account
$this->uMod->deleteAllFavorite($_SESSION["user"]);
// Delete the user's account from the system
$this->uMod->deleteAccount($_SESSION["user"]); $this->uMod->deleteAccount($_SESSION["user"]);
// Log the user out by clearing the session
$this->unlog(); $this->unlog();
} }
// ===================== EMAIL FUNCTION ===================== // ===================== EMAIL FUNCTION =====================
/**
* Sends a confirmation email to the user notifying them about a change in their email address.
*
* This method constructs an email with HTML content and an embedded image, informing the user that their email
* address has been changed successfully. It uses PHP's `mail` function to send the email with the new email address
* provided as the content of the email.
*
* The email includes the following details:
* - A subject ("What The Fantasy - Changement d'Email").
* - A message body with an embedded image (Banner image) and the updated email address.
*
* The email is sent using the "noreply@whatTheFantasy.com" address as the sender.
*
* @param string $email The new email address of the user.
* @return void
*/
public function sendEmailChangeLogin(string $email) { public function sendEmailChangeLogin(string $email) {
// Génère les données du message // Subject of the email
$sujet = "What The Fantasy - Changement d'Email"; $sujet = "What The Fantasy - Changement d'Email";
// Path to the image to be embedded in the email
$urlImage = "public/images/Baneer.png"; $urlImage = "public/images/Baneer.png";
// Génère une frontière unique pour l'email // Generate a unique boundary for the email to separate parts
$boundary = "-----=" . md5(uniqid(mt_rand())); $boundary = "-----=" . md5(uniqid(mt_rand()));
//Instancie les headers // Set up the headers for the email
$headers = "From: noreply@whatTheFantasy.com\r\n"; $headers = "From: noreply@whatTheFantasy.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"; $headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n"; $headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n";
// Corps de l'email HTML avec l'image intégrée // Email body with embedded image
$corpsMessage = "--$boundary\r\n"; $corpsMessage = "--$boundary\r\n";
$corpsMessage .= "Content-Type: text/html; charset=UTF-8\r\n"; $corpsMessage .= "Content-Type: text/html; charset=UTF-8\r\n";
$corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n"; $corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
// Ajoute le message HTML // HTML content of the email
$corpsMessage .= "<html> $corpsMessage .= "<html>
<body> <body>
<img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" /> <img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
@ -549,23 +849,24 @@ class UserControler {
</body> </body>
</html>\r\n"; </html>\r\n";
// Ajoute l'image en pièce jointe // Add the image as an attachment to the email
$corpsMessage .= "--$boundary\r\n"; $corpsMessage .= "--$boundary\r\n";
$corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n"; $corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n";
$corpsMessage .= "Content-Transfer-Encoding: base64\r\n"; $corpsMessage .= "Content-Transfer-Encoding: base64\r\n";
$corpsMessage .= "Content-ID: <image1>\r\n\r\n"; $corpsMessage .= "Content-ID: <image1>\r\n\r\n";
// Read the image content and encode it in base64
$imageContent = file_get_contents($urlImage);// Lecture et encodage de l'image en base64 $imageContent = file_get_contents($urlImage);// Lecture et encodage de l'image en base64
if ($imageContent === false) { if ($imageContent === false) {
return "Impossible de charger l'image spécifiée."; return "Impossible de charger l'image spécifiée.";
} }
$corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n"; $corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n";
// End of the email message
$corpsMessage .= "--$boundary--";// Fin du corps de l'email $corpsMessage .= "--$boundary--";
// Send the email to the specified address
mail($email, $sujet, $corpsMessage, $headers);// Envoi de l'email mail($email, $sujet, $corpsMessage, $headers);
} }
} }

@ -42,83 +42,121 @@ Class VisitorControler {
$this->uMod = new UserModel(new UserGateway($co)); $this->uMod = new UserModel(new UserGateway($co));
} }
/**
* Handles the display of the homepage (accueil) by fetching the quote of the day
* and suggestions, then passing them to the appropriate view.
*
* @return void
*/
public function accueil(){ public function accueil(){
global $vues; global $vues;// Access the global variable containing the paths to view files.
// Récupérer la citation du jour via AccueilGateway // Fetch the quote of the day in French
$citationDuJour = $this->qMod->getQuoteOfTheDay('fr'); $citationDuJour = $this->qMod->getQuoteOfTheDay('fr');
// Fetch a list of suggestions in French
$suggestions = $this->qMod->getSuggest(0, 'fr'); $suggestions = $this->qMod->getSuggest(0, 'fr');
// Passer les données à la vue // Pass the fetched data to the "accueil" view for rendering.
require_once $vues['accueil']; require_once $vues['accueil'];
} }
/**
* Displays the details of a specific quote, including its favorite status,
* associated comments, and the quote's content itself.
*
* @param array $arg An associative array containing route parameters, such as the 'idQuote'.
* @return void
*/
public function quote(array $arg){ public function quote(array $arg){
global $vues; global $vues;// Access the global variable containing paths to view files.
$id= $arg['idQuote'] ?? 1; $id= $arg['idQuote'] ?? 1;
// Check if the quote is marked as a favorite for the logged-in user.
$f = $this->uMod->isFavorite($_SESSION["user"],$id); $f = $this->uMod->isFavorite($_SESSION["user"],$id);
// Fetch the quote's details using its ID.
$q = $this->qMod->searchId($id); $q = $this->qMod->searchId($id);
// Retrieve all comments associated with the quote.
$c = $this->cMod->getComment($id); $c = $this->cMod->getComment($id);
// Include the 'quote' view, passing the fetched data for rendering.
require_once $vues['quote']; require_once $vues['quote'];
} }
/**
* Displays the user's list of favorite items by rendering the favorite view.
*
* @return void
*/
public function favorite() { public function favorite() {
global $vues; global $vues;
require_once $vues['favorite']; require_once $vues['favorite'];
} }
/**
* Handles the search functionality by processing input parameters,
* validating them, and passing the results to the search view.
*
* @param array $arg An associative array containing route parameters, such as filters ('filtre').
* @return void
*/
public function search(array $arg){ public function search(array $arg){
global $vues; global $vues;
// Validate and retrieve the 'type' parameter from the POST request, defaulting to an empty string if not set.
$type = ( Verification::verifChar( $_POST['type'] ?? "")); $type = ( Verification::verifChar( $_POST['type'] ?? ""));
// Validate and retrieve the 'search' parameter from the POST request, defaulting to NULL if not set.
$search = ( Verification::verifChar( $_POST['search'] ?? NULL)); $search = ( Verification::verifChar( $_POST['search'] ?? NULL));
$filtre = ( Verification::verifArrayChar( $arg['filtre'] ?? []));
// Validate and retrieve the 'filtre' parameter from the route arguments, defaulting to an empty array if not set.
$filtre = ( Verification::verifArrayChar( $arg['filtre'] ?? []));
// Perform the search using the validated parameters.
$tq=$this->sMod->searchQuote($type,$search,$filtre); $tq=$this->sMod->searchQuote($type,$search,$filtre);
require_once $vues['search']; require_once $vues['search'];
} }
/** /**
* @throws SyntaxError * Displays the login page by rendering the login view.
* @throws RuntimeError *
* @throws LoaderError * @return void
*/ */
public function login() public function login()
{ {
global $vues; global $vues;
require_once $vues['login']; require_once $vues['login'];
//global $twig;
//echo $twig->render("login.html.twig");
//$this -> toLogIn();
} }
/** /**
* @throws SyntaxError * Displays the signin page by rendering the signin view.
* @throws RuntimeError *
* @throws LoaderError * @return void
*/ */
public function signin(): void public function signin(): void
{ {
global $vues; global $vues;
require_once $vues['signin']; require_once $vues['signin'];
//global $twig;
//echo $twig->render("login.html.twig");
//$this -> signin();
} }
/**
* Validates user login credentials and initiates a session for authenticated users.
* Redirects to the home page upon successful login, or redisplays the login page with errors otherwise.
*
* @return void
*/
public function validlogin() : void public function validlogin() : void
{ {
global $vues,$racine; global $vues,$racine;
// Check if the form has been submitted via POST.
if ($_POST) if ($_POST)
{ {
$pseudo = Verification::verifChar($_POST['pseudo'] ?? null); $pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
@ -126,18 +164,22 @@ Class VisitorControler {
$user = $this -> uMod -> getUsername($pseudo); $user = $this -> uMod -> getUsername($pseudo);
// Check if the user exists in the database.
if ($user) if ($user)
{ {
// Verify the provided password matches the stored hashed password.
if (password_verify($mdp, $user->getPassword())) if (password_verify($mdp, $user->getPassword()))
{ {
$_SESSION['user'] = Verification::verifChar($pseudo); $_SESSION['user'] = Verification::verifChar($pseudo);
$_SESSION['role'] = 'user'; $_SESSION['role'] = 'user';
// Redirect the user to the home page upon successful login.
header("Location: ". $racine); header("Location: ". $racine);
exit(); exit();
}else }else
{ {
global $twig; global $twig;
$errors = "Identifiant ou mot de passe incorrect"; $errors = "Identifiant ou mot de passe incorrect";
// Redisplay the login page with the error message.
require_once $vues['login']; require_once $vues['login'];
exit(); exit();
} }
@ -146,40 +188,47 @@ Class VisitorControler {
{ {
global $twig; global $twig;
$errors = "Identifiant ou mot de passe incorrect"; $errors = "Identifiant ou mot de passe incorrect";
// Redisplay the login page with the error message
require_once $vues['login']; require_once $vues['login'];
exit(); exit();
} }
} }
} }
/** /**
* @throws RuntimeError * Handles the user registration process, validating input, checking for duplicate users/emails,
* @throws SyntaxError * inserting a new user into the database, and initiating a session upon successful registration.
* @throws LoaderError *
* @return void
*/ */
public function validsignin() : void public function validsignin() : void
{ {
global $vues,$racine; global $vues,$racine;
// Check if the form has been submitted via POST.
if ($_POST) { if ($_POST) {
// Validate and sanitize the input fields from the POST request.
$pseudo = Verification::verifChar($_POST['pseudo'] ?? null); $pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
$email = Verification::verifChar($_POST['email'] ?? null); $email = Verification::verifChar($_POST['email'] ?? null);
$mdp = Verification::verifChar($_POST['mdp'] ?? null); $mdp = Verification::verifChar($_POST['mdp'] ?? null);
$cmdp = Verification::verifChar($_POST['cmdp'] ?? null); $cmdp = Verification::verifChar($_POST['cmdp'] ?? null);
// Check if the passwords match.
if ($mdp != $cmdp) { if ($mdp != $cmdp) {
$errors[2] = "Mots de passe incorrects"; $errors[2] = "Mots de passe incorrects";
require_once $vues['signin']; require_once $vues['signin'];
exit(); exit();
} }
// Hash the password securely with bcrypt and a cost factor of 12.
$option = ['cost' => 12]; $option = ['cost' => 12];
$hmdp = password_hash($mdp, PASSWORD_BCRYPT, $option); $hmdp = password_hash($mdp, PASSWORD_BCRYPT, $option);
// Check if the username or email is already in use.
$isUserAlreadyUsed = $this -> uMod -> getUsername($pseudo); $isUserAlreadyUsed = $this -> uMod -> getUsername($pseudo);
$isEmailAlreadyUsed = $this -> uMod -> getEmail($email); $isEmailAlreadyUsed = $this -> uMod -> getEmail($email);
// Handle cases where the username or email is already taken.
if ($isUserAlreadyUsed and !$isEmailAlreadyUsed) { if ($isUserAlreadyUsed and !$isEmailAlreadyUsed) {
$errors[0] = "Pseudo déjà utilisé"; $errors[0] = "Pseudo déjà utilisé";
require_once $vues['signin']; require_once $vues['signin'];
@ -196,8 +245,11 @@ Class VisitorControler {
require_once $vues['signin']; require_once $vues['signin'];
exit(); exit();
} }
else echo $this->uMod->insertUser($pseudo, $email, $hmdp); else{
// Insert the new user into the database.
echo $this->uMod->insertUser($pseudo, $email, $hmdp);
}
// Send a confirmation email to the user after successful registration.
$this->sendEmailSubmit($email, $pseudo); $this->sendEmailSubmit($email, $pseudo);
@ -208,28 +260,36 @@ Class VisitorControler {
} }
} }
/**
* Sends a confirmation email to the user after account creation.
* Includes an HTML message with an embedded image.
*
* @param string $email The recipient's email address.
* @param string $pseudo The recipient's username.
* @return string|null Returns an error message if the image cannot be loaded, otherwise null.
*/
function sendEmailSubmit(string $email, string $pseudo) { function sendEmailSubmit(string $email, string $pseudo) {
// Génère les données du message // Subject of the email
$sujet = "What The Fantasy - Création de compte"; $sujet = "What The Fantasy - Création de compte";
// Path to the image file to be embedded in the email
$urlImage = "public/images/Baneer.png"; $urlImage = "public/images/Baneer.png";
// Génère une frontière unique pour l'email // Generate a unique boundary for separating parts of the email
$boundary = "-----=" . md5(uniqid(mt_rand())); $boundary = "-----=" . md5(uniqid(mt_rand()));
//Instancie les headers // Initialize email headers
$headers = "From: noreply@whatTheFantasy.com\r\n"; $headers = "From: noreply@whatTheFantasy.com\r\n";
$headers .= "MIME-Version: 1.0\r\n"; $headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n"; $headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n";
// Corps de l'email HTML avec l'image intégrée // Start building the email body
$corpsMessage = "--$boundary\r\n"; $corpsMessage = "--$boundary\r\n";
$corpsMessage .= "Content-Type: text/html; charset=UTF-8\r\n"; $corpsMessage .= "Content-Type: text/html; charset=UTF-8\r\n";
$corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n"; $corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
// Ajoute le message HTML // Add the HTML message content
$corpsMessage .= "<html> $corpsMessage .= "<html>
<body> <body>
<img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" /> <img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
@ -242,24 +302,25 @@ Class VisitorControler {
</body> </body>
</html>\r\n"; </html>\r\n";
// Ajoute l'image en pièce jointe // Add the embedded image as a related part
$corpsMessage .= "--$boundary\r\n"; $corpsMessage .= "--$boundary\r\n";
$corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n"; $corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n";
$corpsMessage .= "Content-Transfer-Encoding: base64\r\n"; $corpsMessage .= "Content-Transfer-Encoding: base64\r\n";
$corpsMessage .= "Content-ID: <image1>\r\n\r\n"; $corpsMessage .= "Content-ID: <image1>\r\n\r\n";
// Read and encode the image file
$imageContent = file_get_contents($urlImage);// Lecture et encodage de l'image en base64 $imageContent = file_get_contents($urlImage);
if ($imageContent === false) { if ($imageContent === false) {
return "Impossible de charger l'image spécifiée."; return "Impossible de charger l'image spécifiée.";
} }
// Encode and add the image content
$corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n"; $corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n";
// End the email body with the closing boundary
$corpsMessage .= "--$boundary--";// Fin du corps de l'email $corpsMessage .= "--$boundary--";// Fin du corps de l'email
// Send the email
mail($email, $sujet, $corpsMessage, $headers);// Envoi de l'email mail($email, $sujet, $corpsMessage, $headers);
} }
} }
Loading…
Cancel
Save