You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WF-Website/src/Controleur/VisitorControler.php

326 lines
11 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace Controleur;
use Model\QuoteModel;
use Model\CommentaryModel;
use Gateway\Connection;
use Gateway\QuoteGateway;
use Gateway\CommentaryGateway;
use Model\SearchModel;
use Gateway\UserGateway;
use Model\UserModel;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Verification\Verification;
Class VisitorControler {
private QuoteModel $qMod;
private CommentaryModel $cMod;
private SearchModel $sMod;
private UserGateway $gw;
private UserModel $uMod;
private array $errors;
/**
* @throws SyntaxError
* @throws RuntimeError
* @throws LoaderError
*/
public function __construct() {
global $co;
$this->qMod = new QuoteModel(new QuoteGateway($co));
$this->cMod = new CommentaryModel(new CommentaryGateway($co));
$this->sMod = new SearchModel(new QuoteGateway($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(){
global $vues;// Access the global variable containing the paths to view files.
// 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');
// 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;// 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));
// 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'];
}
/**
* Displays the login page by rendering the login view.
*
* @return void
*/
public function login()
{
global $vues;
require_once $vues['login'];
}
/**
* Displays the signin page by rendering the signin view.
*
* @return void
*/
public function signin(): void
{
global $vues;
require_once $vues['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);
$mdp = Verification::verifChar($_POST['mdp'] ?? null);
$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();
}
}
else
{
global $twig;
$errors = "Identifiant ou mot de passe incorrect";
// Redisplay the login page with the error message
require_once $vues['login'];
exit();
}
}
}
/**
* 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'];
exit();
}
else if ($isEmailAlreadyUsed and !$isUserAlreadyUsed) {
$errors[1] = "Email déjà utilisé";
require_once $vues['signin'];
exit();
}
else if ($isEmailAlreadyUsed and $isUserAlreadyUsed) {
$errors[0] = "Pseudo déjà utilisé";
$errors[1] = "Email déjà utilisé";
require_once $vues['signin'];
exit();
}
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);
$_SESSION["role"] = Verification::verifChar('user');
$_SESSION["user"] = Verification::verifChar($pseudo);
header("Location: ". $racine);
}
}
/**
* 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) {
// 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";
// Generate a unique boundary for separating parts of the email
$boundary = "-----=" . md5(uniqid(mt_rand()));
// 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";
// 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";
// Add the HTML message content
$corpsMessage .= "<html>
<body>
<img src=\"cid:image1\" alt=\"Image\" style=\"width: 1200px; height: auto;\" />
<p>Bonjour $pseudo,</p>
<p>Merci de vous être inscrit sur notre site What The Fantasy. Cest avec grande joie que nous vous accueillons au sein de notre confrérie, pour découvrir ensemble...
</p>
<p>À bientôt !</p>
<p>L'équipe du site</p>
</body>
</html>\r\n";
// 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";
// 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
// Send the email
mail($email, $sujet, $corpsMessage, $headers);
}
}