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', '/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', '/profil', 'UserControler','profil');
$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', '/validlogin', 'VisitorControler','validlogin');
$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', '/supFav/[i:id]', 'UserControler','supFav');
$router->map('GET|POST', '/changedata', 'UserControler','changedata');
@ -69,7 +75,7 @@ Class FrontControler{
$action = $match['name'];
//Si existe, on lappelle
//If exist
if(!$this->ifExisteAction($action)){
$dVueEreur[] = "Action introuvable";
$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 {
// Check if the action exists in the 'admin' action list
if( in_array($action , $this->listAction['admin']) ||
// Check if the action exists in the 'user' action list
in_array($action , $this->listAction['user']) ||
// Check if the action exists in the 'visitor' action list
in_array($action , $this->listAction['visitor']) ) {
return true;
}
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 {
if( in_array($action , $this->listAction['admin']) && $_SESSION["role"] == 'admin') return true;
elseif( in_array($action , $this->listAction['user']) && ($_SESSION["role"] == 'admin' || $_SESSION["role"] == 'user') ) return true;
elseif(in_array($action , $this->listAction['visitor']) && ($_SESSION["role"] == 'admin'|| $_SESSION["role"] == 'user'|| $_SESSION["role"] == 'visitor')) return true;
// Check if the action exists in the 'admin' action list and the user is an admin
if( in_array($action , $this->listAction['admin']) && $_SESSION["role"] == 'admin'){
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;
}
/**
* 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){
global $vues;
// Display the first error message in the array, if it exists
echo "{$dVueErreur[0]}";
// Include and render the error view from the `$vues` global array
require_once $vues['erreur'];
}

@ -45,27 +45,43 @@ class UserControler {
$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() {
global $vues;
// Retrieve the username details of the currently logged-in user from the session.
$p = $this->uMod->getUsername($_SESSION["user"]);
// Retrieve a list of all images from the image model.
$listImg = $this->iMod->getAllImg() ;
// Pour les messages d'erreur
$error_message = null;
// Check if there is an error message stored in the session.
if (isset($_SESSION['error_message'])) {
// Retrieve the 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']);
}
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(){
global $racine;
// Retrieve the ID of the quote from the POST request.
$id = $_POST['idQuote'];
// Create a new comment using validated input data.
$this->cMod->createComment(Verification::verifChar($_POST['content']),
Verification::verifChar($_POST['idQuote']),
$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) {
global $vues;
// Retrieve the ID of the currently logged-in user using their username from the session.
$userId = $this->uMod->getIdByUsername($_SESSION["user"]);
// Fetch the list of favorite quotes for the user.
$favorites = $this->qMod->getFavorites($userId);
require_once $vues['favorite'];
}
/**
* Logs the user out by clearing their session data and redirecting them to the homepage.
*
* @return void
*/
public function unlog(){
global $racine;
// Clear all session variables
session_unset();
// Destroy the current session.
session_destroy();
// Reset the session array to ensure no lingering data remains.
$_SESSION = array();
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){
global $vues;
// Retrieve the quiz ID from the arguments.
$id=$args['id'];
// Get the total number of questions in the quiz.
$nb_questions = $this->getNumberOfQuestion($id);
$action = $_REQUEST['action'] ?? null;
// Handle different actions during the quiz.
switch ($action) {
// Check the user's answer.
case 'canswer':
// If the answer is correct, update the score in the session.
if ($this->CorrectAnswer())
$_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);
break;
default:
switch($id)
{
// If the quiz ID is null, handle the error case
case null:
// page erreur
break;
// For a valid quiz ID, display the current question.
default:
$_SESSION['score'] = Verification::verifChar($_SESSION['score'] ?? 0);
$this->showQuestion($id, Verification::verifChar($_SESSION['no_question'] ?? 0));
@ -118,41 +165,63 @@ class UserControler {
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
* Manages the progression of a quiz by updating the user's current question index.
* If the quiz is completed, it triggers the end quiz process. Otherwise, it redirects
* 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{
global $racine;
// Retrieve the current score from the session.
$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);
// Check if the user has completed the quiz.
if ($_SESSION['no_question'] >= $total_questions) {
// Reset the question index to 0 for a new quiz attempt.
$_SESSION['no_question'] = 0;
$this->endQuiz($id_quiz, $score);
// Reset the score for the next attempt or session.
$_SESSION['score'] = 0;
}
else header("Location: ".$racine."/quiz/$id_quiz"); ///~kekentin/WF/WF-Website
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
/**
* Handles the end of the quiz, including checking if a next quiz exists
* and loading the appropriate view for the quiz completion.
*
* @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{
global $vues,$co;
// Create a new QuizGateway and QuizModel to interact with the database.
$gw = new QuizGateway($co);
$mdl = new QuizModel($gw);
// Check if a next quiz exists
if ($mdl->getQuiz($id_quiz + 1)){
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{
// Retrieve the user's selected answers from the POST request.
$answera = Verification::verifChar($_POST['answera'] ?? null);
$answerb = Verification::verifChar($_POST['answerb'] ?? null);
$answerc = Verification::verifChar($_POST['answerc'] ?? null);
@ -161,6 +230,7 @@ class UserControler {
$id= null;
$answer = null;
// Check which answer option the user selected and extract the answer and ID.
if ($answera) {
$answer = explode('-', $answera)[0];
$id = (int) explode('-', $answera)[1];
@ -174,51 +244,104 @@ class UserControler {
$answer = explode('-', $answerd)[0];
$id = (int) explode('-', $answerd)[1];
}
// Retrieve the correct answer for the question from the model.
$res = $this->mdl->getQuestion($id);
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{
global $co;
// Instantiate the QuizQuestionGateway to interact with the database.
$gw = new QuizQuestionGateway($co);
// Instantiate the QuizQuestionModel to handle the business logic.
$mdl = new QuizQuestionModel($gw);
// Retrieve all questions for the specified quiz ID and return them as an array.
return $mdl->getAllQuestionByQuiz($id, $co);
}
/**
* @throws RuntimeError
* @throws SyntaxError
* @throws LoaderError
* Displays a specific question from the quiz based on the provided quiz ID and question number.
*
* 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{
global $vues,$twig;
// Retrieve all questions for the specified quiz using GetQuestion method.
$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];
// Get the ID of the selected question for further processing if needed.
$idquestion = $question->getIdQuestion();
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{
global $co;
$gw = new QuizGateway($co);
// Instantiate the QuizModel to handle the business logic of fetching quiz data.
$mdl = new QuizModel($gw);
// Fetch the quiz by ID and return the total number of questions for that quiz.
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){
global $racine;
// Retrieve the quote ID from the provided arguments. Default to 1 if not provided.
$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);
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){
global $racine;
// Retrieve the quote ID from the provided arguments. Default to 1 if not provided.
$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);
header("Location:". $racine ."/quote/$id");
}
@ -226,10 +349,23 @@ class UserControler {
// ===================== 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{
global $vues, $racine;
// Check if the form has been submitted.
if ($_POST)
{
// Retrieve the submitted data from the form.
$newImage = $_POST['image'] ?? null;
$newPseudo = $_POST['pseudo'] ?? null;
$newEmail = $_POST['email'] ?? null;
@ -237,66 +373,106 @@ class UserControler {
$newMdpFirst = $_POST['passwdFirst'] ?? null;
$newMdpSecond = $_POST['passwdSecond'] ?? null;
if($newPseudo){//Modif le pseudo
// If a new pseudo is provided, update the username.
if($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->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);
}
else if($newImage){//Modif l'image
// If a new image is provided, update the profile image.
else if($newImage){
$this->updateImg($newImage);
}
}
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){
$user = $this-> uMod->setUsername($_SESSION['user'], $newPseudo);
// Check if the username was updated successfully
if($user == $newPseudo){
// Update the session with the new username
$_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";
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){
$user = $this-> uMod->setEmail($_SESSION['user'], $newEmail);
if($user == $_SESSION['user']){ // si email incorrect, renvoie le nom de l'utilisateur de la session
// Check if the email was successfully updated
if($user == $_SESSION['user']){
// If the email is invalid, set an error message and redirect
$_SESSION['error_message'] = "L'email n'est pas valide";
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){
// Check if the old password is provided
if(!$oldPasswd){
$_SESSION['error_message'] = "Veuillez taper votre ancien mot de passe";
header("Location: ". $racine."/profil");
}
// Check if the old password matches the one in the database
else if(!$this->uMod->isPassWd($_SESSION['user'], $oldPasswd)){
$_SESSION['error_message'] = "Votre ancien mot de passe est incorrect";
header("Location: ". $racine."/profil");
}
else{
// Check if the new passwords match
if($newMdpFirst == $newMdpSecond){
// Generate a new hashed password
$option = ['cost' => 12];
$newPassWd = password_hash($newMdpFirst, PASSWORD_BCRYPT, $option);
// Update the password in the database
$user = $this-> uMod->setPassWd($_SESSION['user'], $newPassWd);
}
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){
// Update the user's image in the database
$user = $this->uMod->setImage($_SESSION['user'],$newImage);
}
@ -317,47 +504,64 @@ class UserControler {
// ===================== SUBMIT FUNCTION =====================
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
* Displays the form for submitting a new quote.
*
* 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{
global $vues;
$p = $this->caMod->getAllPerso();
// Fetch all available characters and sources for the submission form
$p = $this->caMod->getAllCharacters();
$s = $this->srcMod->getAllSources();
require_once $vues['submitQuote'];
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
/**
* Processes the quote submission form and validates the character and source.
*
* 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{
global $co;
// Check if there is a POST request (form submission)
if ($_POST)
{
// Retrieve form data
$content = $_POST['content'] ?? null;
$character = $_POST['character'] ?? null;
$source = $_POST['src'] ?? null;
//$img = $_POST['img'] ?? null;
// Initialize an array to store errors
$errors = [null, null];
// Fetch the character from the database by its ID
$gw = new CharacterGateway($co);
$mdl = new CharacterModel($gw);
$character = $mdl -> getCharacterById($character);
// Fetch the source from the database by its ID
$gw = new SourceGateway($co);
$mdl = new SourceModel($gw);
$source = $mdl -> getSourceById($source);
// Validate character and source
if (!$character)
$errors[0] = "Personnage inexistant";
if (!$source)
$errors[1] = "Source inexistante";
// If there are any errors, reload the form and pass error messages
if ($errors[0] || $errors[1])
{
global $twig;
@ -365,30 +569,39 @@ class UserControler {
exit();
}
// If everything is valid, return the data as an array
$gw = new QuoteGateway($co);
$mdl = new QuoteModel($gw);
// Insert the new quote in the database
$mdl -> insert4User($content, '/imgPath', 'fr', $this -> getIdOfUser(), $source->getIdSource(), $character->getIdCharacter());
return [$content, $_POST['character'], $_POST['src']];
}
// If there is no POST request, return null
return null;
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
* Handles the validation of a quote submission form.
*
* 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
{
// Check if both the source and character are set to 'other'
if($_POST['src'] == 'other' && $_POST['character'] == 'other'){
global $vues;
$src = true;
$char = true;
$src = true; // Indicate an issue with the source field
$char = true; // Indicate an issue with the character field
require_once $vues['create'];
exit();
}
// If the source is 'other' but the character is not
elseif($_POST['src'] == 'other'){
global $vues;
$src = true;
@ -396,6 +609,7 @@ class UserControler {
require_once $vues['create'];
exit();
}
// If the character is 'other' but the source is not
elseif($_POST['character'] == 'other'){
global $vues;
$src = false;
@ -403,8 +617,12 @@ class UserControler {
require_once $vues['create'];
exit();
}
if($_POST)
// If a valid POST request is present
if($_POST){
$recap = $this -> toSubmit();
}
// If the submission is valid, process the recap
if ($recap)
{
$this -> recapSubmitQuote($recap);
@ -416,15 +634,33 @@ class UserControler {
// ===================== SUBMIT QUOTE FUNCTION =====================
/**
* @throws RuntimeError
* @throws SyntaxError
* @throws LoaderError
* Handles the rendering of the recap page for a submitted quote.
*
* 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{
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{
if (isset($_SESSION['user']))
{
@ -432,26 +668,49 @@ class UserControler {
$gw = new UserGateway($co);
$mdl = new UserModel($gw);
// Retrieve the user object by username and return its ID
return $mdl -> getUsername($_SESSION['user']) -> getId();
}
// Return null if no user is logged in
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(){
global $vues;
var_dump($_POST);
$error = [];
// Handle form submission for both source and character
if($_POST['req'] == "both"){
$src = true;
$char = true;
}
// Handle form submission for source only
elseif($_POST['req'] == "src"){
$src = true;
$char = false;
// Define allowed source types
$type = array("Movie","Serie","VideoGame","Anime");
// Validate title of the source
if(Verification::verifNotNull($_POST["titre"])){
$_POST["titre"] = Verification::verifChar($_POST["titre"]);
// Check if the source already exists
if($this->srcMod->existSource($_POST["titre"],$_POST["type"])){
$error[] = "La source existe déja";
}
@ -459,10 +718,13 @@ class UserControler {
else{
$error[] = "Le titre doit être définit";
}
// Validate the date of the source
if(Verification::verifNotNull($_POST["date"])){
$src = true;
$char = false;
$_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() )){
$error[] = "La date est invalide";
}
@ -470,8 +732,11 @@ class UserControler {
else{
$error[] = "La date doit être définit";
}
// Validate the date of the source
if(Verification::verifNotNull($_POST["type"])){
$_POST["type"] = Verification::verifChar($_POST["type"]);
// Check if the source already exists
if(!in_array($_POST["type"],$type)){
$error[] = "Le type indiquer est inexistant";
}
@ -487,11 +752,13 @@ class UserControler {
}
}
// If there are no errors, proceed with the creation
if($error == []){
if($_POST['req'] == "both"){
}
elseif($_POST['req'] == "src"){
// Create the new source
$this->srcMod->createSource($_POST["titre"], $_POST["date"], $_POST["type"]);
}
elseif($_POST['req'] == "char"){
@ -499,8 +766,8 @@ class UserControler {
}
}
else{
// If errors exist, return to the creation view and display the errors
require_once($vues["create"]);
var_dump($error);
}
}
@ -508,37 +775,70 @@ class UserControler {
// ===================== 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(){
$this->uMod->deleteAllCommentary($_SESSION["user"]); // Delete all commentary
$this->uMod->deleteAllFavorite($_SESSION["user"]); // Delete all favorite
// Delete all comments associated with the user's account
$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"]);
// Log the user out by clearing the session
$this->unlog();
}
// ===================== 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) {
// Génère les données du message
// Subject of the email
$sujet = "What The Fantasy - Changement d'Email";
// Path to the image to be embedded in the email
$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()));
//Instancie les headers
$headers = "From: noreply@whatTheFantasy.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/related; boundary=\"$boundary\"\r\n";
// Set up the headers for the email
$headers = "From: noreply@whatTheFantasy.com\r\n";
$headers .= "MIME-Version: 1.0\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 .= "Content-Type: text/html; charset=UTF-8\r\n";
$corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
// Ajoute le message HTML
// HTML content of the email
$corpsMessage .= "<html>
<body>
<img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
@ -549,23 +849,24 @@ class UserControler {
</body>
</html>\r\n";
// Ajoute l'image en pièce jointe
// Add the image as an attachment to the email
$corpsMessage .= "--$boundary\r\n";
$corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n";
$corpsMessage .= "Content-Transfer-Encoding: base64\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
if ($imageContent === false) {
return "Impossible de charger l'image spécifiée.";
}
$corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n";
$corpsMessage .= "--$boundary--";// Fin du corps de l'email
// End of the email message
$corpsMessage .= "--$boundary--";
mail($email, $sujet, $corpsMessage, $headers);// Envoi de l'email
// Send the email to the specified address
mail($email, $sujet, $corpsMessage, $headers);
}
}

@ -42,83 +42,121 @@ Class VisitorControler {
$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(){
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');
// Fetch a list of suggestions in French
$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'];
}
/**
* 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){
global $vues;
global $vues;// Access the global variable containing paths to view files.
$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);
// Fetch the quote's details using its ID.
$q = $this->qMod->searchId($id);
// Retrieve all comments associated with the quote.
$c = $this->cMod->getComment($id);
// Include the 'quote' view, passing the fetched data for rendering.
require_once $vues['quote'];
}
/**
* Displays the user's list of favorite items by rendering the favorite view.
*
* @return void
*/
public function favorite() {
global $vues;
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){
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'] ?? ""));
// Validate and retrieve the 'search' parameter from the POST request, defaulting to NULL if not set.
$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);
require_once $vues['search'];
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
* Displays the login page by rendering the login view.
*
* @return void
*/
public function login()
{
global $vues;
require_once $vues['login'];
//global $twig;
//echo $twig->render("login.html.twig");
//$this -> toLogIn();
}
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
* Displays the signin page by rendering the signin view.
*
* @return void
*/
public function signin(): void
{
global $vues;
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
{
global $vues,$racine;
// Check if the form has been submitted via POST.
if ($_POST)
{
$pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
@ -126,18 +164,22 @@ Class VisitorControler {
$user = $this -> uMod -> getUsername($pseudo);
// Check if the user exists in the database.
if ($user)
{
// Verify the provided password matches the stored hashed password.
if (password_verify($mdp, $user->getPassword()))
{
$_SESSION['user'] = Verification::verifChar($pseudo);
$_SESSION['role'] = 'user';
// Redirect the user to the home page upon successful login.
header("Location: ". $racine);
exit();
}else
{
global $twig;
$errors = "Identifiant ou mot de passe incorrect";
// Redisplay the login page with the error message.
require_once $vues['login'];
exit();
}
@ -146,40 +188,47 @@ Class VisitorControler {
{
global $twig;
$errors = "Identifiant ou mot de passe incorrect";
// Redisplay the login page with the error message
require_once $vues['login'];
exit();
}
}
}
/**
* @throws RuntimeError
* @throws SyntaxError
* @throws LoaderError
* Handles the user registration process, validating input, checking for duplicate users/emails,
* inserting a new user into the database, and initiating a session upon successful registration.
*
* @return void
*/
public function validsignin() : void
{
global $vues,$racine;
// Check if the form has been submitted via POST.
if ($_POST) {
// Validate and sanitize the input fields from the POST request.
$pseudo = Verification::verifChar($_POST['pseudo'] ?? null);
$email = Verification::verifChar($_POST['email'] ?? null);
$mdp = Verification::verifChar($_POST['mdp'] ?? null);
$cmdp = Verification::verifChar($_POST['cmdp'] ?? null);
// Check if the passwords match.
if ($mdp != $cmdp) {
$errors[2] = "Mots de passe incorrects";
require_once $vues['signin'];
exit();
}
// Hash the password securely with bcrypt and a cost factor of 12.
$option = ['cost' => 12];
$hmdp = password_hash($mdp, PASSWORD_BCRYPT, $option);
// Check if the username or email is already in use.
$isUserAlreadyUsed = $this -> uMod -> getUsername($pseudo);
$isEmailAlreadyUsed = $this -> uMod -> getEmail($email);
// Handle cases where the username or email is already taken.
if ($isUserAlreadyUsed and !$isEmailAlreadyUsed) {
$errors[0] = "Pseudo déjà utilisé";
require_once $vues['signin'];
@ -196,8 +245,11 @@ Class VisitorControler {
require_once $vues['signin'];
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);
@ -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) {
// Génère les données du message
// Subject of the email
$sujet = "What The Fantasy - Création de compte";
// Path to the image file to be embedded in the email
$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()));
//Instancie les headers
// Initialize email headers
$headers = "From: noreply@whatTheFantasy.com\r\n";
$headers .= "MIME-Version: 1.0\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 .= "Content-Type: text/html; charset=UTF-8\r\n";
$corpsMessage .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
// Ajoute le message HTML
// Add the HTML message content
$corpsMessage .= "<html>
<body>
<img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
@ -242,24 +302,25 @@ Class VisitorControler {
</body>
</html>\r\n";
// Ajoute l'image en pièce jointe
// Add the embedded image as a related part
$corpsMessage .= "--$boundary\r\n";
$corpsMessage .= "Content-Type: image/jpeg; name=\"image.jpg\"\r\n";
$corpsMessage .= "Content-Transfer-Encoding: base64\r\n";
$corpsMessage .= "Content-ID: <image1>\r\n\r\n";
$imageContent = file_get_contents($urlImage);// Lecture et encodage de l'image en base64
// Read and encode the image file
$imageContent = file_get_contents($urlImage);
if ($imageContent === false) {
return "Impossible de charger l'image spécifiée.";
}
// Encode and add the image content
$corpsMessage .= chunk_split(base64_encode($imageContent)) . "\r\n";
// End the email body with the closing boundary
$corpsMessage .= "--$boundary--";// Fin du corps de l'email
mail($email, $sujet, $corpsMessage, $headers);// Envoi de l'email
// Send the email
mail($email, $sujet, $corpsMessage, $headers);
}
}
Loading…
Cancel
Save