Compare commits

...

6 Commits

@ -115,6 +115,8 @@ function editFieldPassWd(id) {
inputNewPass.focus();// Mettre le focus sur le premier champ de saisie
}
function editFieldImage(id,path) {
var pElement = document.getElementById('imagePost');

@ -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);
//$mdl -> insert4User($content, '/imgPath', 'fr', $this -> getIdOfUser(), $source->getIdSource(), $character->getIdCharacter());
// 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";
// End of the email message
$corpsMessage .= "--$boundary--";
$corpsMessage .= "--$boundary--";// Fin du corps de l'email
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);
}
}

@ -3,14 +3,14 @@ namespace Entity;
class CharacterEntity
{
// Properties
private int $id_character;
private string $name;
private string $img_path;
/**
* Constructor
*
* @param int $id_character
* @param string $name
* @param string $img_path
@ -23,6 +23,8 @@ class CharacterEntity
}
/**
* Get the character ID
*
* @return int
*/
public function getIdCharacter(): int
@ -31,6 +33,8 @@ class CharacterEntity
}
/**
* Set the character ID
*
* @param int $id_character
*/
public function setIdCharacter(int $id_character): void
@ -39,6 +43,8 @@ class CharacterEntity
}
/**
* Get the character name
*
* @return string
*/
public function getName(): string
@ -47,6 +53,8 @@ class CharacterEntity
}
/**
* Set the character name
*
* @param string $name
*/
public function setName(string $name): void
@ -55,6 +63,8 @@ class CharacterEntity
}
/**
* Get the image path
*
* @return string
*/
public function getImgPath(): string
@ -63,12 +73,12 @@ class CharacterEntity
}
/**
* Set the image path
*
* @param string $img_path
*/
public function setImgPath(string $img_path): void
{
$this->img_path = $img_path;
}
}

@ -13,6 +13,8 @@ class CommentaryEntity {
* @param int $id_comment
* @param string $comment
* @param string $date
* @param string $user
* @param string $img
*/
public function __construct(int $id_comment, string $comment, string $date, string $user, string $img)
{
@ -82,7 +84,7 @@ class CommentaryEntity {
/**
* @param string $user
*/
public function setUser(int $user): void
public function setUser(string $user): void
{
$this->user = $user;
}
@ -98,7 +100,7 @@ class CommentaryEntity {
/**
* @param string $img
*/
public function setImg(int $img): void
public function setImg(string $img): void
{
$this->img = $img;
}

@ -3,10 +3,12 @@ namespace Entity;
class FavoriteEntity
{
private int $id_user;
private int $id_quote;
private int $id_user; // ID of the user
private int $id_quote; // ID of the quote
/**
* Constructor to initialize the FavoriteEntity with user ID and quote ID
*
* @param int $id_user
* @param int $id_quote
*/
@ -17,6 +19,8 @@ class FavoriteEntity
}
/**
* Get the user ID
*
* @return int
*/
public function getIdUser(): int
@ -25,6 +29,8 @@ class FavoriteEntity
}
/**
* Set the user ID
*
* @param int $id_user
*/
public function setIdUser(int $id_user): void
@ -33,6 +39,8 @@ class FavoriteEntity
}
/**
* Get the quote ID
*
* @return int
*/
public function getIdQuote(): int
@ -41,13 +49,12 @@ class FavoriteEntity
}
/**
* Set the quote ID
*
* @param int $id_quote
*/
public function setIdQuote(int $id_quote): void
{
$this->id_quote = $id_quote;
}
}

@ -3,13 +3,14 @@ namespace Entity;
class ImageEntity
{
private int $idImg;
private string $imgPath;
private int $idImg; // ID of the image
private string $imgPath; // Path to the image file
/**
* @param int $idImg
* @param string $imgPath
* @param string $isImgProfile
* Constructor for ImageEntity
*
* @param int $idImg ID of the image
* @param string $imgPath Path to the image file
*/
public function __construct(int $idImg, string $imgPath)
{
@ -17,25 +18,43 @@ class ImageEntity
$this->imgPath = $imgPath;
}
/**
* Get the ID of the image
*
* @return int
*/
public function getIdImg(): int
{
return $this->idImg;
}
/**
* Set the ID of the image
*
* @param int $idImg
*/
public function setIdImg(int $idImg): void
{
$this->idImg = $idImg;
}
/**
* Get the path to the image file
*
* @return string
*/
public function getImgPath(): string
{
return $this->imgPath;
}
/**
* Set the path to the image file
*
* @param string $imgPath
*/
public function setImgPath(string $imgPath): void
{
$this->imgPath = $imgPath;
}
}

@ -1,148 +1,175 @@
<?php
namespace Entity;
namespace Entity;
class QuestionEntity
{
private int $id_question;
private string $question;
private string $answerA;
private string $answerB;
private string $answerC;
private string $answerD;
private string $cAnswer;
/**
* Constructor to initialize the QuestionEntity object.
*
* @param int $id_question The ID of the question.
* @param string $question The question text.
* @param string $answerA The text for answer A.
* @param string $answerB The text for answer B.
* @param string $answerC The text for answer C.
* @param string $answerD The text for answer D.
* @param string $cAnswer The correct answer.
*/
public function __construct(int $id_question, string $question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer)
{
$this->id_question = $id_question;
$this->question = $question;
$this->answerA = $answerA;
$this->answerB = $answerB;
$this->answerC = $answerC;
$this->answerD = $answerD;
$this->cAnswer = $cAnswer;
}
/**
* Get the ID of the question.
*
* @return int The ID of the question.
*/
public function getIdQuestion(): int
{
return $this->id_question;
}
/**
* Set the ID of the question.
*
* @param int $id_question The ID of the question.
*/
public function setIdQuestion(int $id_question): void
{
$this->id_question = $id_question;
}
/**
* Get the question text.
*
* @return string The question text.
*/
public function getQuestion(): string
{
return $this->question;
}
/**
* Set the question text.
*
* @param string $question The question text.
*/
public function setQuestion(string $question): void
{
$this->question = $question;
}
/**
* Get the text for answer A.
*
* @return string The text for answer A.
*/
public function getAnswerA(): string
{
return $this->answerA;
}
/**
* Set the text for answer A.
*
* @param string $answerA The text for answer A.
*/
public function setAnswerA(string $answerA): void
{
$this->answerA = $answerA;
}
class QuestionEntity
/**
* Get the text for answer B.
*
* @return string The text for answer B.
*/
public function getAnswerB(): string
{
private int $id_question;
private string $question;
private string $answerA;
private string $answerB;
private string $answerC;
private string $answerD;
private string $cAnswer;
/**
* @param int $id_question
* @param string $question
* @param string $answerA
* @param string $answerB
* @param string $answerC
* @param string $answerD
* @param string $cAnswer
*/
public function __construct(int $id_question, string $question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer)
{
$this->id_question = $id_question;
$this->question = $question;
$this->answerA = $answerA;
$this->answerB = $answerB;
$this->answerC = $answerC;
$this->answerD = $answerD;
$this->cAnswer = $cAnswer;
}
/**
* @return int
*/
public function getIdQuestion(): int
{
return $this->id_question;
}
/**
* @param int $id_question
*/
public function setIdQuestion(int $id_question): void
{
$this->id_question = $id_question;
}
/**
* @return string
*/
public function getQuestion(): string
{
return $this->question;
}
/**
* @param string $question
*/
public function setQuestion(string $question): void
{
$this->question = $question;
}
/**
* @return string
*/
public function getAnswerA(): string
{
return $this->answerA;
}
/**
* @param string $answerA
*/
public function setAnswerA(string $answerA): void
{
$this->answerA = $answerA;
}
/**
* @return string
*/
public function getAnswerB(): string
{
return $this->answerB;
}
/**
* @param string $answerB
*/
public function setAnswerB(string $answerB): void
{
$this->answerB = $answerB;
}
/**
* @return string
*/
public function getAnswerC(): string
{
return $this->answerC;
}
/**
* @param string $answerC
*/
public function setAnswerC(string $answerC): void
{
$this->answerC = $answerC;
}
/**
* @return string
*/
public function getAnswerD(): string
{
return $this->answerD;
}
/**
* @param string $answerD
*/
public function setAnswerD(string $answerD): void
{
$this->answerD = $answerD;
}
/**
* @return string
*/
public function getCAnswer(): string
{
return $this->cAnswer;
}
/**
* @param string $cAnswer
*/
public function setCAnswer(string $cAnswer): void
{
$this->cAnswer = $cAnswer;
}
return $this->answerB;
}
/**
* Set the text for answer B.
*
* @param string $answerB The text for answer B.
*/
public function setAnswerB(string $answerB): void
{
$this->answerB = $answerB;
}
/**
* Get the text for answer C.
*
* @return string The text for answer C.
*/
public function getAnswerC(): string
{
return $this->answerC;
}
/**
* Set the text for answer C.
*
* @param string $answerC The text for answer C.
*/
public function setAnswerC(string $answerC): void
{
$this->answerC = $answerC;
}
/**
* Get the text for answer D.
*
* @return string The text for answer D.
*/
public function getAnswerD(): string
{
return $this->answerD;
}
/**
* Set the text for answer D.
*
* @param string $answerD The text for answer D.
*/
public function setAnswerD(string $answerD): void
{
$this->answerD = $answerD;
}
/**
* Get the correct answer.
*
* @return string The correct answer.
*/
public function getCAnswer(): string
{
return $this->cAnswer;
}
/**
* Set the correct answer.
*
* @param string $cAnswer The correct answer.
*/
public function setCAnswer(string $cAnswer): void
{
$this->cAnswer = $cAnswer;
}
}

@ -3,14 +3,15 @@ namespace Entity;
class QuizEntity
{
private int $id_quiz;
private int $nb_questions;
// Properties
private int $id_quiz; // ID of the quiz
private int $nb_questions; // Number of questions in the quiz
/**
* @param int $id_quiz
* @param int $nb_questions
* Constructor
*
* @param int $id_quiz ID of the quiz
* @param int $nb_questions Number of questions in the quiz
*/
public function __construct(int $id_quiz, int $nb_questions)
{
@ -19,6 +20,8 @@ class QuizEntity
}
/**
* Get the ID of the quiz
*
* @return int
*/
public function getIdQuiz(): int
@ -27,6 +30,8 @@ class QuizEntity
}
/**
* Set the ID of the quiz
*
* @param int $id_quiz
*/
public function setIdQuiz(int $id_quiz): void
@ -35,6 +40,8 @@ class QuizEntity
}
/**
* Get the number of questions in the quiz
*
* @return int
*/
public function getNbQuestions(): int
@ -43,14 +50,12 @@ class QuizEntity
}
/**
* Set the number of questions in the quiz
*
* @param int $nb_questions
*/
public function setNbQuestions(int $nb_questions): void
{
$this->nb_questions = $nb_questions;
}
}

@ -1,15 +1,16 @@
<?php
namespace Entity;
class QuizQuestionEntity
{
private int $id_question;
private int $id_quiz;
private int $id_question; // ID of the question
private int $id_quiz; // ID of the quiz
/**
* @param int $id_question
* @param int $id_quiz
* Constructor to initialize the QuizQuestionEntity
*
* @param int $id_question ID of the question
* @param int $id_quiz ID of the quiz
*/
public function __construct(int $id_question, int $id_quiz)
{
@ -18,7 +19,9 @@ class QuizQuestionEntity
}
/**
* @return int
* Get the ID of the question
*
* @return int ID of the question
*/
public function getIdQuestion(): int
{
@ -26,7 +29,9 @@ class QuizQuestionEntity
}
/**
* @param int $id_question
* Set the ID of the question
*
* @param int $id_question ID of the question
*/
public function setIdQuestion(int $id_question): void
{
@ -34,7 +39,9 @@ class QuizQuestionEntity
}
/**
* @return int
* Get the ID of the quiz
*
* @return int ID of the quiz
*/
public function getIdQuiz(): int
{
@ -42,13 +49,12 @@ class QuizQuestionEntity
}
/**
* @param int $id_quiz
* Set the ID of the quiz
*
* @param int $id_quiz ID of the quiz
*/
public function setIdQuiz(int $id_quiz): void
{
$this->id_quiz = $id_quiz;
}
}

@ -3,13 +3,29 @@
class Quote{
// Represents the unique identifier for the quote
private int $id;
// The content of the quote
private string $content;
// The characteristic or attribute associated with the quote
private string $carac;
// The file path to the image associated with the quote
private string $imgPath;
// The title source of the quote
private string $titleSrc;
// The date source of the quote
private string $dateSrc;
// The number of likes the quote has received
private int $like;
// The language of the quote
private string $langue;
/**

@ -3,67 +3,111 @@ namespace Entity;
class ResultsEntity
{
// Property to store the quiz ID
private int $idQuiz;
// Property to store the user ID
private int $idUser;
// Property to store the number of points
private int $nbPts;
// Property to store the time
private int $time;
/**
* Constructor to initialize the properties
*
* @param int $idQuiz The ID of the quiz
* @param int $idUser The ID of the user
* @param int $time The time taken
* @param int $nbPts The number of points
*/
public function __construct(int $idQuiz, int $idUser, int $time, int $nbPts)
{
$this->idQuiz = $idQuiz;
$this->idUser = $idUser;
$this->time = $time;
$this->nbPts = $nbPts;
}
/**
* Get the user ID
*
* @return int The ID of the user
*/
public function getIdUser(): int
{
return $this->idUser;
}
/**
* Set the user ID
*
* @param int $idUser The ID of the user
*/
public function setIdUser(int $idUser): void
{
$this->idUser = $idUser;
}
/**
* Get the quiz ID
*
* @return int The ID of the quiz
*/
public function getIdQuiz(): int
{
return $this->idQuiz;
}
/**
* Set the quiz ID
*
* @param int $idQuiz The ID of the quiz
*/
public function setIdQuiz(int $idQuiz): void
{
$this->idQuiz = $idQuiz;
}
/**
* Get the time taken
*
* @return int The time taken
*/
public function getTime(): int
{
return $this->time;
}
/**
* Set the time taken
*
* @param int $time The time taken
*/
public function setTime(int $time): void
{
$this->time = $time;
}
/**
* Get the number of points
*
* @return int The number of points
*/
public function getNbPts(): int
{
return $this->nbPts;
}
public function setNbPts(int $nbPts): void
{
$this->nbPts = $nbPts;
}
private int $idUser;
private int $nbPts;
private int $time;
/**
* @param int $idQuiz
* @param int $idUser
* @param int $time
* @param int $nbPts
* Set the number of points
*
* @param int $nbPts The number of points
*/
public function __construct(int $idQuiz, int $idUser, int $time, int $nbPts)
public function setNbPts(int $nbPts): void
{
$this -> idQuiz = $idQuiz;
$this -> idUser = $idUser;
$this -> time = $time;
$this -> nbPts = $nbPts;
$this->nbPts = $nbPts;
}
}

@ -5,28 +5,33 @@ use Enum\TypeSourceEnum;
class SourceEntity
{
private int $id_source;
private int $id_source; // ID of the source
private string $title;
private string $title; // Title of the source
private string $date;
private string $date; // Date of the source
private TypeSourceEnum $type;
private TypeSourceEnum $type; // Type of the source
/**
* Constructor to initialize the SourceEntity object
*
* @param int $id_source
* @param string $title
* @param string $date
* @param TypeSourceEnum $type
*/
public function __construct(int $id_source, string $title, string $date, TypeSourceEnum $type)
{
$this->id_source = $id_source;
$this->title = $title;
$this->date = $date;
//$this->type = $type;
//$this->type = $type; // Uncomment this line to initialize the type
}
/**
* Get the ID of the source
*
* @return int
*/
public function getIdSource(): int
@ -35,6 +40,8 @@ class SourceEntity
}
/**
* Set the ID of the source
*
* @param int $id_source
*/
public function setIdSource(int $id_source): void
@ -43,6 +50,8 @@ class SourceEntity
}
/**
* Get the title of the source
*
* @return string
*/
public function getTitle(): string
@ -51,6 +60,8 @@ class SourceEntity
}
/**
* Set the title of the source
*
* @param string $title
*/
public function setTitle(string $title): void
@ -59,6 +70,8 @@ class SourceEntity
}
/**
* Get the date of the source
*
* @return string
*/
public function getDate(): string
@ -67,6 +80,8 @@ class SourceEntity
}
/**
* Set the date of the source
*
* @param string $date
*/
public function setDate(string $date): void
@ -74,17 +89,23 @@ class SourceEntity
$this->date = $date;
}
/**
* Get the type of the source
*
* @return TypeSourceEnum
*/
public function getType(): TypeSourceEnum
{
return $this->type;
}
/**
* Set the type of the source
*
* @param TypeSourceEnum $type
*/
public function setType(TypeSourceEnum $type): void
{
$this->type = $type;
}
}

@ -8,61 +8,142 @@ use PDO;
class CharacterGateway extends Gateway
{
public function create(int $id_character, string $name , string $img_char) : bool
/**
* Creates a new character record in the database.
*
* This method inserts a new character into the `caracter` table using the provided character
* ID, name, and image path.
*
* @param int $id_character The unique ID for the character.
* @param string $name The name of the character.
* @param string $img_char The path to the character's image.
*
* @return bool Returns `true` if the character was successfully created,
* or `false` if the insertion failed (e.g., due to a database error).
*/
public function create(int $id_character, string $name, string $img_char) : bool
{
$query = "
INSERT INTO caracter
VALUES(:id_caracter, :caracter, :id_img)
";
// SQL query to insert a new character into the "caracter" table
$query = "INSERT INTO caracter
VALUES(:id_caracter, :caracter, :id_img)";
return $this -> co -> executeQuery($query, [
// Execute the query with the provided parameters
return $this->co->executeQuery($query, [
'id_caracter' => array($id_character, PDO::PARAM_INT),
'caracter' => array($name, PDO::PARAM_STR),
'id_img' => array($img_char, PDO::PARAM_STR)
]);
}
/**
* Finds a character by its ID in the database.
*
* This method retrieves a character from the `caracter` table by its unique character ID.
*
* @param int $id The unique ID of the character to retrieve.
*
* @return array Returns an array containing the character data if found, or an empty array if no matching character is found.
*/
public function findById(int $id) : array
{
// SQL query to select a character by its unique ID
$query = "SELECT * FROM caracter WHERE id_caracter = :id_c";
$this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]);
return $this -> co -> getResults();
// Execute the query with the provided character ID
$this->co->executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]);
// Return the results (array of matching character data)
return $this->co->getResults();
}
/**
* Finds a character by its name in the database.
*
* This method retrieves a character from the `caracter` table by its name.
*
* @param string $name The name of the character to retrieve.
*
* @return array Returns an array containing the character data if found, or an empty array if no matching character is found.
*/
public function findByName(string $name) : array
{
// SQL query to select a character by its name
$query = "SELECT * FROM caracter WHERE caracter = :n";
$this -> co -> executeQuery($query, ["n" => array($name, PDO::PARAM_STR)]);
return $this -> co -> getResults();
// Execute the query with the provided character name
$this->co->executeQuery($query, ["n" => array($name, PDO::PARAM_STR)]);
// Return the results (array of matching character data)
return $this->co->getResults();
}
/**
* Retrieves all characters from the database.
*
* This method fetches all rows from the `caracter` table, ordering them by the character name (`caracter`) in ascending order.
*
* @return array Returns an array of all characters. Each character is represented as an associative array with column names as keys.
*/
public function findAll() : array
{
// SQL query to retrieve all characters from the 'caracter' table, ordered by character name in ascending order
$query = "SELECT * FROM caracter ORDER BY caracter ASC";
$this -> co -> executeQuery($query);
return $this -> co -> getResults();
// Execute the query
$this->co->executeQuery($query);
// Return the results, which is an array of all character records
return $this->co->getResults();
}
/**
* Deletes a character from the database by its ID.
*
* This method removes a character from the `caracter` table based on the provided character ID (`id_caracter`).
* It executes a DELETE SQL query to remove the record from the database.
*
* @param int $id The ID of the character to be deleted.
*
* @return bool Returns `true` if the deletion was successful, `false` otherwise.
*/
public function delete(int $id) : bool
{
// SQL query to delete a character from the 'caracter' table by character ID
$query = "DELETE FROM caracter WHERE id_caracter = :id_c";
// Execute the query using the provided character ID, binding the parameter to an integer
return $this -> co -> executeQuery($query, ["id_c" => array($id, PDO::PARAM_INT)]);
}
/**
* Updates the details of a character in the database.
*
* This method updates a character's name and associated image in the `caracter` table
* based on the provided character ID (`id_caracter`).
*
* @param int $id_char The ID of the character to be updated.
* @param string $name The new name for the character.
* @param string $img_char The new image path for the character.
*
* @return bool Returns `true` if the update was successful, `false` otherwise.
*/
public function update(int $id_char, string $name, string $img_char) : bool
{
$query = "
UPDATE caracter
// SQL query to update the character's name and image based on character ID
$query = "UPDATE caracter
SET caracter = :n, id_img = :i
WHERE id_caracter = :id_c
";
WHERE id_caracter = :id_c";
// Execute the query, binding the parameters for character ID, name, and image path
return $this -> co -> executeQuery($query, [
"id_c" => array($id_char, PDO::PARAM_INT),
"caracter" => array($name, PDO::PARAM_STR),
"i" => array($img_char, PDO::PARAM_STR)
]);
}
}

@ -4,70 +4,205 @@ use PDO;
class CommentaryGateway extends Gateway{
public function firstIdComment():int{
$query = "Select id_comment from Commentary;";
$this -> co -> executeQuery($query);
$res = $this -> co -> getResults();
/**
* Finds the first available ID for a new comment in the Commentary table.
*
* This method retrieves all existing comment IDs from the Commentary table, determines the first unused ID,
* and returns it. If there are no comments in the table, it returns `1` as the starting ID.
*
* @return int The first available ID for a new comment.
*/
public function firstIdComment(): int
{
// Define the query to fetch all comment IDs from the Commentary table
$query = "SELECT id_comment FROM Commentary;";
// Execute the query and fetch the results
$this->co->executeQuery($query);
$res = $this->co->getResults();
// Initialize an array to store existing comment IDs
$tab = null;
foreach($res as $r){
// Populate the array with IDs from the result set
foreach ($res as $r) {
$tab[] = $r["id_comment"];
}
if($tab == null){
// If no comments exist, return 1 as the starting ID
if ($tab == null) {
return 1;
}
$id=1;
while(in_array($id,$tab)){$id=$id+1;}
// Initialize the ID counter
$id = 1;
// Increment the ID until a gap is found (i.e., an ID that is not in the array)
while (in_array($id, $tab)) {
$id = $id + 1;
}
// Return the first available ID
return $id;
}
public function create(string $comment ,string $idUser, int $idQuote) :bool {
$id=$this->firstIdComment();
$query="INSERT INTO Commentary(quote,users,datec,comment,id_comment) VALUES(:idQuote, :idUser , CURRENT_DATE,:comment ,:idComment)";
return $this -> co -> executeQuery($query, array(
/**
* Creates a new comment in the database.
*
* This method inserts a new comment for a given quote and user into the `Commentary` table.
* It automatically generates a unique comment ID by calling the `firstIdComment()` method.
*
* @param string $comment The text content of the comment.
* @param string $idUser The ID of the user who is posting the comment.
* @param int $idQuote The ID of the quote that the comment is associated with.
*
* @return bool `true` if the comment was successfully created, `false` otherwise.
*/
public function create(string $comment, string $idUser, int $idQuote): bool
{
// Get the first available comment ID using the firstIdComment method
$id = $this->firstIdComment();
// Prepare the SQL query to insert a new comment
$query = "INSERT INTO Commentary(quote, users, datec, comment, id_comment)
VALUES(:idQuote, :idUser, CURRENT_DATE, :comment, :idComment)";
// Execute the query with the provided parameters
return $this->co->executeQuery($query, array(
"comment" => array($comment, PDO::PARAM_STR),
"idUser" => array($idUser, PDO::PARAM_STR),
"idQuote" => array($idQuote, PDO::PARAM_INT),
"idComment" => array($id, PDO::PARAM_INT)));
"idComment" => array($id, PDO::PARAM_INT)
));
}
public function findById(int $id) : array {
$query="SELECT * FROM Commentary WHERE id_comment = :id_comment";
$this -> co -> executeQuery($query, array("id_comment" => $id));
return $res = $this -> co -> getResults();
/**
* Retrieves a commentary by its unique ID.
*
* This method queries the `Commentary` table to find a comment by its `id_comment`.
* It returns an array containing the details of the comment if found.
*
* @param int $id The unique ID of the comment to retrieve.
*
* @return array An array containing the commentary details (or an empty array if no comment is found).
*/
public function findById(int $id): array
{
// SQL query to find the commentary by its unique ID
$query = "SELECT *
FROM Commentary
WHERE id_comment = :id_comment";
// Execute the query with the provided comment ID as a parameter
$this->co->executeQuery($query, array("id_comment" => $id));
// Return the results from the query execution
return $this->co->getResults();
}
public function findByQuote(int $id) : array{
$query="SELECT c.id_comment, c.dateC, c.comment, u.username, i.imgPath FROM Commentary c JOIN Users u ON u.id_user = c.users JOIN Image i ON i.id_img = u.img WHERE quote = :idQuote ORDER BY c.datec DESC";
$this -> co -> executeQuery($query, array("idQuote" => array($id,PDO::PARAM_STR)));
return $res = $this -> co -> getResults();
/**
* Retrieves all comments associated with a specific quote.
*
* This method queries the `Commentary`, `Users`, and `Image` tables to find all comments related
* to a specific quote, and returns the details of each comment, including the commenter's username,
* the commenter's profile image path, and the comment itself, ordered by date in descending order.
*
* @param int $id The ID of the quote for which comments are being retrieved.
*
* @return array An array containing the details of all comments associated with the specified quote.
* Each entry includes the comment ID, comment date, content, username, and profile image path.
*/
public function findByQuote(int $id): array
{
// SQL query to retrieve comments for a specific quote, joining with the Users and Image tables
$query = "SELECT c.id_comment, c.dateC, c.comment, u.username, i.imgPath
FROM Commentary c
JOIN Users u ON u.id_user = c.users
JOIN Image i ON i.id_img = u.img
WHERE quote = :idQuote
ORDER BY c.datec DESC";
// Execute the query with the provided quote ID as a parameter
$this->co->executeQuery($query, array("idQuote" => array($id, PDO::PARAM_STR)));
// Return the results from the query execution
return $this->co->getResults();
}
public function findAll() : array {
$query="SELECT * FROM Commentary";
$this -> co -> executeQuery($query);
return $res = $this -> co -> getResults();
}
public function delete(int $id) : bool {
$query="DELETE FROM Commentary WHERE id_comment = :id_comment";
return $this -> co -> executeQuery($query, array("id_comment" => $id));
/**
* Retrieves all comments from the database.
*
* This method executes a query to fetch all records from the `Commentary` table,
* and returns the details of each comment stored in the database.
*
* @return array An array containing all the comments in the `Commentary` table.
* Each entry includes details of the comment, such as the comment's ID,
* creation date, content, user who made the comment, and the quote associated with it.
*/
public function findAll() : array
{
// SQL query to retrieve all comments from the `Commentary` table
$query = "SELECT * FROM Commentary";
// Execute the query
$this->co->executeQuery($query);
// Return the results from the query execution
return $this->co->getResults();
}
public function update(commentaryEntity $c) : bool {
$query="UPDATE Commentary SET comment = :comment WHERE id_comment = :id_comment";
/**
* Deletes a comment from the database.
*
* This method executes a query to delete a specific comment from the `Commentary` table
* based on the provided comment ID. It will remove the comment with the given ID if it exists.
*
* @param int $id The ID of the comment to be deleted.
*
* @return bool Returns `true` if the comment was successfully deleted,
* or `false` if the deletion failed (e.g., if the comment ID was not found).
*/
public function delete(int $id) : bool
{
// SQL query to delete a comment with the specified ID
$query = "DELETE FROM Commentary
WHERE id_comment = :id_comment";
// Execute the query and return the result
return $this->co->executeQuery($query, array("id_comment" => $id));
}
return $this -> co -> executeQuery($query, array(
"comment" => array($c->getComment(),PDO::PARAM_STR),
"id_comment" => array($c->getIdComment(),PDO::PARAM_INT))
);
/**
* Updates a comment in the database.
*
* This method executes a query to update the `comment` field of a specific comment in the
* `Commentary` table based on the provided `commentaryEntity` object. It will update the
* comment with the given ID if it exists.
*
* @param commentaryEntity $c The commentary entity containing the new comment content and comment ID.
*
* @return bool Returns `true` if the comment was successfully updated,
* or `false` if the update failed (e.g., if the comment ID was not found).
*/
public function update(commentaryEntity $c) : bool
{
// SQL query to update the comment based on its ID
$query = "UPDATE Commentary
SET comment = :comment
WHERE id_comment = :id_comment";
// Execute the query with the parameters from the commentary entity object
return $this->co->executeQuery($query, array(
"comment" => array($c->getComment(), PDO::PARAM_STR),
"id_comment" => array($c->getIdComment(), PDO::PARAM_INT)
));
}
}
?>

@ -6,66 +6,139 @@ use PDO;
class FavoriteGateway extends Gateway
{
/**
* Adds a new favorite entry to the `Favorite` table.
*
* This method inserts a record into the `Favorite` table, linking a user (`idUser`) with
* a specific quote (`idQuote`). It assumes that the `Favorite` table has two columns:
* - `user` (foreign key referencing the user's ID)
* - `quote` (foreign key referencing the quote's ID)
*
* @param int $idUser The ID of the user who is marking the quote as a favorite.
* Must correspond to an existing user in the database.
* @param int $idQuote The ID of the quote being marked as a favorite.
* Must correspond to an existing quote in the database.
*
* @return bool Returns `true` if the query was successfully executed, indicating the favorite
* was added. Returns `false` if the query execution failed.
*/
public function createFavoriteGateway(int $idUser, int $idQuote) : bool
{
$query = "
INSERT INTO Favorite
VALUES (:user, :quote)
";
// Define the SQL query to insert a new favorite entry
$query = "INSERT INTO Favorite
VALUES (:user, :quote)";
return $this -> co -> executeQuery($query, [
// Execute the query using the provided database connection and return the result
return $this->co->executeQuery($query, [
'user' => array($idUser, PDO::PARAM_INT),
'quote' => array($idQuote, PDO::PARAM_INT)
]);
}
/**
* Retrieves a specific favorite entry from the `Favorite` table.
*
* This method fetches a record from the `Favorite` table based on the provided user ID (`idUser`)
* and quote ID (`idQuote`). If the favorite exists, it returns the corresponding data as an array.
*
* @param int $idUser The ID of the user who favorited the quote. This must reference a valid user in the database.
* @param int $idQuote The ID of the quote that is favorited. This must reference a valid quote in the database.
*
* @return array Returns an associative array containing the favorite record if it exists.
* If no matching record is found, an empty array is returned.
*/
public function findFavoriteById(int $idUser, int $idQuote) : array
{
$query = "
SELECT * FROM Favorite
WHERE user_f = :user AND quote_f = :quote
";
// Define the SQL query to fetch the favorite record
$query = "SELECT * FROM Favorite
WHERE user_f = :user AND quote_f = :quote";
$this -> co -> executeQuery($query, [
// Execute the query using the provided database connection
$this->co->executeQuery($query, [
'user' => array($idUser, PDO::PARAM_INT),
'quote' => array($idQuote, PDO::PARAM_INT)
]);
return $this -> co -> getResults();
// Return the query results as an array
return $this->co->getResults();
}
/**
* Retrieves all favorites for a specific user from the `Favorite` table.
*
* This method fetches all records from the `Favorite` table where the `user_f` column
* matches the provided user ID. It allows retrieving all quotes favorited by a specific user.
*
* @param int $idUser The ID of the user whose favorites are being retrieved. This must reference a valid user in the database.
*
* @return array Returns an array of associative arrays, where each entry represents a favorite record.
* If the user has no favorites, an empty array is returned.
*/
public function findFavoriteByUser(int $idUser) : array
{
$query = "
SELECT * FROM Favorite
WHERE user_f = :user
";
// Define the SQL query to fetch all favorites for the user
$query = "SELECT * FROM Favorite
WHERE user_f = :user";
$this -> co -> executeQuery($query, ['user' => array($idUser, PDO::PARAM_INT)]);
// Execute the query using the provided database connection
$this->co->executeQuery($query, ['user' => array($idUser, PDO::PARAM_INT)]);
return $this -> co -> getResults();
// Return the query results as an array
return $this->co->getResults();
}
/**
* Retrieves all records from the `Favorite` table.
*
* This method fetches all the favorite records in the database, returning an array of
* all user-quote associations stored in the `Favorite` table.
*
* Use this method to get a global view of all user favorites, which can be useful for
* administrative tasks or debugging.
*
* @return array Returns an array of associative arrays where each entry represents a favorite record.
* If there are no records in the table, an empty array is returned.
*/
public function findAllFavorite() : array
{
// Define the SQL query to fetch all favorite records
$query = "SELECT * FROM Favorite";
$this -> co -> executeQuery($query);
// Execute the query using the provided database connection
$this->co->executeQuery($query);
return $this -> co -> getResults();
// Return the results of the query as an array
return $this->co->getResults();
}
/**
* Deletes a specific favorite record from the `Favorite` table.
*
* This method removes the association between a user and a quote in the `Favorite` table
* by matching the provided user ID and quote ID. It is typically used to allow users
* to unfavorite quotes or to clean up favorites.
*
* @param int $idUser The ID of the user whose favorite record is to be deleted. This must reference a valid user in the database.
* @param int $idQuote The ID of the quote to be removed from the user's favorites. This must reference a valid quote in the database.
*
* @return bool Returns `true` if the deletion query was executed successfully, otherwise `false`.
*/
public function deleteFavoriteGateway(int $idUser, int $idQuote) : bool
{
$query = "
DELETE FROM Favorite
WHERE user_f = :user AND quote_f = :quote
";
// Define the SQL query to delete a favorite record matching user ID and quote ID
$query = "DELETE FROM Favorite
WHERE user_f = :user AND quote_f = :quote";
return $this -> co -> executeQuery($query, [
// Execute the query with the provided parameters
return $this->co->executeQuery($query, [
'user' => array($idUser, PDO::PARAM_INT),
'quote' => array($idQuote, PDO::PARAM_INT)
]);
}
}

@ -6,61 +6,146 @@ use PDO;
class ImageGateway extends Gateway
{
/**
* Inserts a new image entry into the `Image` table in the database.
*
* This method executes an SQL query to insert a new record into the `Image` table with the specified image ID
* and image path. It uses the provided database connection to perform the insertion operation.
*
* The image data inserted includes:
* - The image ID (`idImg`).
* - The path to the image file (`imgPath`).
*
* **Note**: This method assumes that the `Image` table exists with at least the `id_img` and `img_path` columns.
*
* @param int $idImg The unique identifier for the image.
* @param string $imgPath The file path to the image (including the filename).
*
* @return bool Returns `true` if the query was successfully executed, `false` if there was an error.
*/
public function createImgGateway(int $idImg, string $imgPath) : bool
{
$query = "
INSERT INTO Image
VALUES (:id_img, :img_path)
";
// Define the SQL query to insert a new image record
$query = "INSERT INTO Image
VALUES (:id_img, :img_path)";
return $this -> co -> executeQuery($query, [
'id_img' => array($idImg, PDO::PARAM_INT),
'img_path' => array($imgPath, PDO::PARAM_STR),
// Execute the query using the provided database connection and parameterized values
return $this->co->executeQuery($query, [
'id_img' => array($idImg, PDO::PARAM_INT), // Bind the image ID as an integer
'img_path' => array($imgPath, PDO::PARAM_STR), // Bind the image path as a string
]);
}
/**
* Finds an image record from the `Image` table by its ID.
*
* This method executes a SQL query to retrieve the image record corresponding to the provided image ID (`$idImg`).
* The method returns all columns of the matching image from the `Image` table.
*
* **Note**: This method assumes that the `Image` table exists with at least the `id_img` and `img_path` columns.
*
* @param int $idImg The unique identifier for the image to retrieve.
*
* @return array Returns an associative array of the image record. The array contains key-value pairs where
* each key is a column name and the value is the corresponding column value from the `Image` table.
* If no matching record is found, it returns an empty array.
*/
public function findImgById(int $idImg) : array
{
$query = "
SELECT * FROM Image
WHERE id_img = :id_img
";
// Define the SQL query to select an image by its ID
$query = "SELECT * FROM Image
WHERE id_img = :id_img";
$this -> co -> executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]);
// Execute the query using the provided database connection and parameterized values
$this->co->executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]);
return $this -> co -> getResults();
// Return the results of the query execution
return $this->co->getResults();
}
/**
* Retrieves all image records from the `Image` table.
*
* This method executes a SQL query to fetch all records from the `Image` table
* and returns the results as an associative array. Each record corresponds to one image.
*
* **Note**: This method assumes that the `Image` table exists with appropriate columns,
* such as `id_img` and `img_path`.
*
* @return array Returns an array of associative arrays, where each associative array represents
* a single image record from the `Image` table. Each key in the associative array
* corresponds to a column name, and the value is the respective column value.
* If no records are found, returns an empty array.
*/
public function findAllImg() : array
{
$query = "
SELECT * FROM Image
";
// Define the SQL query to retrieve all image records
$query = "SELECT * FROM Image";
$this -> co -> executeQuery($query);
// Execute the query using the provided database connection
$this->co->executeQuery($query);
return $this -> co -> getResults();
// Return the results of the query execution
return $this->co->getResults();
}
/**
* Deletes an image record from the `Image` table based on the provided ID.
*
* This method executes a SQL query to delete a specific image record from the database,
* identified by its unique `id_img`.
*
* **Note**: This method assumes that the `Image` table exists and the `id_img` column
* is used as the primary key or a unique identifier for each image.
*
* @param int $idImg The ID of the image to be deleted from the `Image` table.
* Must be a valid integer corresponding to an existing image record.
*
* @return bool Returns `true` if the query was successfully executed, indicating the image
* record was deleted. Returns `false` if the query failed.
*/
public function deleteImgGateway(int $idImg) : bool
{
$query = "
DELETE FROM Image
WHERE id_img = :id_img
";
// Define the SQL query to delete an image record based on its ID
$query = "DELETE FROM Image
WHERE id_img = :id_img";
return $this -> co -> executeQuery($query, ['id_img' => array($idImg, PDO::PARAM_INT)]);
// Execute the query using the provided database connection and return the result
return $this->co->executeQuery($query, [
'id_img' => array($idImg, PDO::PARAM_INT)
]);
}
/**
* Updates the path of an image in the `Image` table based on the provided image ID.
*
* This method executes a SQL query to update the `imgPath` column for a specific image
* identified by its unique `id_img`. It assumes the `Image` table exists and contains
* the columns `id_image` and `imgPath`.
*
* @param int $idImg The ID of the image to be updated. Must correspond to an existing
* record in the `Image` table.
* @param string $imgPath The new path for the image. Must be a valid string representing
* the location of the image file.
*
* @return bool Returns `true` if the query was successfully executed, indicating that the
* image path was updated. Returns `false` if the query execution failed.
*/
public function updateImgGateway(int $idImg, string $imgPath) : bool
{
$query = "
UPDATE Image
// Define the SQL query to update the image path based on the image ID
$query = "UPDATE Image
SET imgPath = :img_path
WHERE id_image = :id_img
";
WHERE id_image = :id_img";
return $this -> co -> executeQuery($query, [
// Execute the query using the provided database connection and return the result
return $this->co->executeQuery($query, [
'id_img' => array($idImg, PDO::PARAM_INT),
'img_path' => array($imgPath, PDO::PARAM_STR)
]);

@ -6,96 +6,196 @@ use PDO;
class QuestionGateway extends Gateway
{
/**
* Creates a new question entry in the database.
*
* This method inserts a new question into the `Question` table, including the question text,
* multiple choice answers (A, B, C, D), and the correct answer.
*
* @param int $id_question The unique ID of the question.
* @param string $question The question text.
* @param string $answerA The first multiple choice answer.
* @param string $answerB The second multiple choice answer.
* @param string $answerC The third multiple choice answer.
* @param string $answerD The fourth multiple choice answer.
* @param string $cAnswer The correct answer among the options (A, B, C, D).
*
* @return bool Returns `true` if the question was successfully created, `false` otherwise.
*/
public function create(int $id_question, string $question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer): bool
{
$query = "
INSERT INTO Question
VALUES (:id_q, :question, :answerA, :answerB, :answerC, :answerD, :cAnswer)
";
// SQL query to insert a new question with its answers and correct answer
$query = "INSERT INTO Question
VALUES (:id_q, :question, :answerA, :answerB, :answerC, :answerD, :cAnswer)";
// Execute the query, binding the parameters securely to prevent SQL injection
return $this -> co -> executeQuery($query, [
array('id_q' => $id_question, PDO::PARAM_INT),
array('question' => $question, PDO::PARAM_STR),
array('answerA' => $answerA, PDO::PARAM_STR),
array('answerB' => $answerB, PDO::PARAM_STR),
array('answerC' => $answerC, PDO::PARAM_STR),
array('answerD' => $answerD, PDO::PARAM_STR),
array('cAnswer' => $cAnswer, PDO::PARAM_STR),
'id_q' => array($id_question, PDO::PARAM_INT),
'question' => array($question, PDO::PARAM_STR),
'answerA' => array($answerA, PDO::PARAM_STR),
'answerB' => array($answerB, PDO::PARAM_STR),
'answerC' => array($answerC, PDO::PARAM_STR),
'answerD' => array($answerD, PDO::PARAM_STR),
'cAnswer' => array($cAnswer, PDO::PARAM_STR),
]);
}
/**
* Retrieves a question by its ID from the database.
*
* This method queries the `Question` table to find the question with the specified ID
* and returns all its details, including the question text, possible answers, and the correct answer.
*
* @param int $id The unique ID of the question to be retrieved.
*
* @return array An associative array containing the details of the question (if found).
* The keys correspond to the column names in the `Question` table.
* Returns an empty array if the question is not found.
*/
public function findById(int $id) : array
{
$query = "SELECT * FROM Question WHERE id_question = :id_q";
// SQL query to select the question with the specified ID
$query = "SELECT *
FROM Question
WHERE id_question = :id_q";
// Execute the query, binding the parameter securely to prevent SQL injection
$this -> co -> executeQuery($query, ['id_q' => array($id, PDO::PARAM_INT)]);
// Retrieve and return the results as an associative array
return $this -> co -> getResults();
}
/**
* Updates the text of a question in the database.
*
* This method modifies the `question` field of a specific question in the `Question` table,
* identified by its unique ID.
*
* @param int $id_q The unique ID of the question to be updated.
* @param string $newQuestion The new text to replace the current question text.
*
* @return bool Returns `true` if the query was successfully executed, or `false` otherwise.
*/
public function updateText(int $id_q, string $newQuestion) : bool
{
$query = "
UPDATE Question
// SQL query to update the question text for a specific ID
$query = "UPDATE Question
SET question = :question
WHERE id_question = :id_q
";
WHERE id_question = :id_q";
// Execute the query with bound parameters
return $this -> co -> executeQuery($query, [
'id_q' => array($id_q, PDO::PARAM_INT),
'question' => array($newQuestion, PDO::PARAM_STR)
'id_q' => array($id_q, PDO::PARAM_INT), // Bind the ID of the question
'question' => array($newQuestion, PDO::PARAM_STR) // Bind the new question text
]);
}
/**
* Updates the answers for a specific question in the database.
*
* This method modifies the answer options (`answerA`, `answerB`, `answerC`, `answerD`)
* and the correct answer (`cAnswer`) of a specific question identified by its unique ID.
*
* @param int $id_q The unique ID of the question to be updated.
* @param string $newA The new value for the first answer option (A).
* @param string $newB The new value for the second answer option (B).
* @param string $newC The new value for the third answer option (C).
* @param string $newD The new value for the fourth answer option (D).
* @param string $newCorrect The new correct answer.
*
* @return bool Returns `true` if the query was successfully executed, or `false` otherwise.
*/
public function updateAnswers(int $id_q, string $newA, string $newB, string $newC, string $newD, string $newCorrect): bool
{
$query = "
UPDATE Question
// SQL query to update the answers and the correct answer for a specific question
$query = "UPDATE Question
SET answerA = :answerA, answerB = :answerB,
answerC = :answerC, answerD = :answerD, cAnswer = :cAnswer
WHERE id_question = :id_q
";
WHERE id_question = :id_q";
// Execute the query with bound parameters
return $this -> co -> executeQuery($query, [
'id_q' => array($id_q, PDO::PARAM_INT),
'answerA' => array($newA, PDO::PARAM_STR),
'answerB' => array($newB, PDO::PARAM_STR),
'answerC' => array($newC, PDO::PARAM_STR),
'answerD' => array($newD, PDO::PARAM_STR),
'cAnswer' => array($newCorrect, PDO::PARAM_STR)
'id_q' => array($id_q, PDO::PARAM_INT), // Bind the ID of the question
'answerA' => array($newA, PDO::PARAM_STR), // Bind the new answer A
'answerB' => array($newB, PDO::PARAM_STR), // Bind the new answer B
'answerC' => array($newC, PDO::PARAM_STR), // Bind the new answer C
'answerD' => array($newD, PDO::PARAM_STR), // Bind the new answer D
'cAnswer' => array($newCorrect, PDO::PARAM_STR) // Bind the new correct answer
]);
}
/**
* Deletes a question from the database by its ID
* Deletes a question from the database.
*
* This method removes a specific question from the `Question` table based on its unique ID.
*
* @param int $id The unique ID of the question to be deleted.
*
* @param int $id The ID of the question
* @return bool
* @return bool Returns `true` if the query was successfully executed, or `false` otherwise.
*/
public function delete(int $id) : bool
{
$query = "DELETE FROM Question WHERE id_question = :id_q";
// SQL query to delete a question by its ID
$query = "DELETE FROM Question
WHERE id_question = :id_q";
return $this -> co -> executeQuery($query, ['id_q' => array($id, PDO::PARAM_INT)]);
// Execute the query with the provided ID
return $this -> co -> executeQuery($query, [
'id_q' => array($id, PDO::PARAM_INT) // Bind the ID parameter to the query
]);
}
/**
* Retrieves all quizzes from the database
* Retrieves all questions from the database.
*
* @return QuestionEntity[] An array of `Question` objects
* This method fetches all records from the `Question` table, returning an array
* of questions with their associated details.
*
* @return array Returns an array containing all the questions. Each question is represented
* as an associative array with keys corresponding to the table columns.
*/
public function findAll() : array
{
// SQL query to select all questions
$query = "SELECT * FROM Question";
// Execute the query
$this -> co -> executeQuery($query);
// Return all results as an array
return $this -> co -> getResults();
}
/**
* Retrieves a random question from the database.
*
* This method selects one random record from the `Question` table.
*
* @return array Returns an array containing the details of a randomly selected question.
* The result is an associative array with keys corresponding to the table columns.
*/
public function findRdmQuestion() : array
{
$query = "SELECT * FROM Question ORDER BY RANDOM() LIMIT 1";
// SQL query to fetch a random question
$query = "SELECT *
FROM Question
ORDER BY RANDOM()
LIMIT 1";
// Execute the query
$this -> co -> executeQuery($query);
// Return the randomly selected question
return $this -> co -> getResults();
}
}

@ -8,37 +8,98 @@ use PDO;
class QuizGateway extends Gateway
{
/**
* Creates a new quiz in the database.
*
* This method inserts a new record into the `Quiz` table, specifying the quiz ID
* and the number of questions in the quiz.
*
* @param int $id_quiz The unique ID of the quiz.
* @param int $nb_questions The total number of questions in the quiz.
*
* @return bool Returns `true` if the query was successfully executed, or `false` otherwise.
*/
public function create(int $id_quiz, int $nb_questions) : bool
{
$query = "
INSERT INTO Quiz
VALUES (:id_q, :nb_q)
";
// SQL query to insert a new quiz into the Quiz table
$query = "INSERT INTO Quiz
VALUES (:id_q, :nb_q)";
// Execute the query with bound parameters
return $this -> co -> executeQuery($query, [
':id_q' => array($id_quiz, PDO::PARAM_INT),
':nb_q' => array($nb_questions, PDO::PARAM_INT)
':id_q' => array($id_quiz, PDO::PARAM_INT), // Bind the quiz ID
':nb_q' => array($nb_questions, PDO::PARAM_INT) // Bind the number of questions
]);
}
/**
* Retrieves a quiz from the database by its ID.
*
* This method fetches a single quiz record from the `Quiz` table, identified by its unique ID.
*
* @param int $id The unique ID of the quiz to retrieve.
*
* @return array Returns an associative array representing the quiz, with keys corresponding
* to the table columns. If no quiz is found, returns an empty array.
*/
public function findQuizById(int $id) : array
{
$query = "SELECT * FROM Quiz WHERE id_quiz = :id_q";
$this -> co -> executeQuery($query, [':id_q' => array($id, PDO::PARAM_INT)]);
// SQL query to fetch a quiz by its ID
$query = "SELECT *
FROM Quiz
WHERE id_quiz = :id_q";
// Execute the query with the bound ID parameter
$this -> co -> executeQuery($query, [
':id_q' => array($id, PDO::PARAM_INT) // Bind the quiz ID
]);
// Return the result as an array
return $this -> co -> getResults();
}
/**
* Deletes a quiz from the database by its ID.
*
* This method removes a specific quiz from the `Quiz` table, identified by its unique ID.
*
* @param int $id The unique ID of the quiz to be deleted.
*
* @return bool Returns `true` if the query was successfully executed, or `false` otherwise.
*/
public function delete(int $id) : bool
{
$query = "DELETE FROM Quiz WHERE id_quiz = :id_q";
return $this -> co -> executeQuery($query, [':id_q' => array($id, PDO::PARAM_INT)]);
// SQL query to delete a quiz by its ID
$query = "DELETE FROM Quiz
WHERE id_quiz = :id_q";
// Execute the query with the provided ID parameter
return $this -> co -> executeQuery($query, [
':id_q' => array($id, PDO::PARAM_INT) // Bind the quiz ID
]);
}
/**
* Retrieves all quizzes from the database.
*
* This method fetches all records from the `Quiz` table, returning an array of results.
*
* @return array Returns an array containing all quizzes. Each quiz is represented as an associative array with its columns as keys.
*/
public function findAll() : array
{
// SQL query to select all records from the Quiz table
$query = "SELECT * FROM Quiz";
// Execute the query to fetch all quiz records
$this -> co -> executeQuery($query);
// Return the results retrieved from the database
return $this -> co -> getResults();
}
}

@ -6,62 +6,26 @@ use PDO;
class QuizQuestionGateway extends Gateway
{
public function createQuizQuestionGateway(int $idQuiz, int $idQuestion): bool
{
$query = "
INSERT INTO Quiz_Question
VALUES (:id_quiz, :id_question)
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_question' => array($idQuestion, PDO::PARAM_INT)
]);
}
public function findQuizQuestionById(int $idQuiz, int $idQuestion) : array
{
$query = "
SELECT * FROM Quiz_Question
WHERE quiz = :id_quiz AND question_qq = :id_question
";
$this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_question' => array($idQuestion, PDO::PARAM_INT)
]);
return $this -> co -> getResults();
}
/**
* Retrieves the questions associated with a specific quiz.
*
* This method fetches all records from the `Quiz_Question` table that are linked to a specific quiz by its ID.
*
* @param int $idQuiz The ID of the quiz for which the questions are to be retrieved.
*
* @return array Returns an array of questions linked to the provided quiz ID. Each question is represented as an associative array with its columns as keys.
*/
public function findQuestionsFromQuiz(int $idQuiz) : array
{
$query = "
SELECT * FROM Quiz_Question
WHERE quiz = :id_quiz
";
// SQL query to select all records from the Quiz_Question table where the quiz ID matches the given ID
$query = "SELECT * FROM Quiz_Question
WHERE quiz = :id_quiz";
// Execute the query with the provided quiz ID
$this -> co -> executeQuery($query, ['id_quiz' => array($idQuiz, PDO::PARAM_INT)]);
// Return the results retrieved from the database
return $this -> co -> getResults();
}
public function deleteQuizQuestionGateway(int $idQuiz, int $idQuestion) : bool
{
$query = "
DELETE FROM Quiz_Question
WHERE quiz = :id_quiz AND question_qq = :id_question
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_question' => array($idQuestion, PDO::PARAM_INT)
]);
}
# To do :
# Method that deletes all questions related to a quiz
}

@ -5,87 +5,139 @@ use PDOException;
Class QuoteGateway extends Gateway{
public function searchQuote(string $quote,int $numpage,string $language):array{
$query="SELECT q.id_quote, q.content, q.id_caracter, c.img_char, s.title, s.date, q.likes, q.langue
/**
* Searches for quotes that match the given criteria (quote content, language, and pagination).
*
* This method retrieves quotes from the `Quote` table that match a specified search term (`$quote`),
* belong to the specified language (`$language`), and are marked as valid. It also supports pagination.
*
* @param string $quote The search term to match within the content of the quotes.
* @param int $numpage The page number to retrieve, used for pagination. This number is used to calculate
* the offset in the query to return results for that specific page.
* @param string $language The language of the quotes to retrieve.
*
* @return array Returns an array of quotes matching the search criteria. Each quote is represented
* as an associative array with column names as keys.
*/
public function searchQuote(string $quote, int $numpage, string $language) : array
{
// SQL query to search for quotes with pagination and language filtering
$query = "SELECT q.id_quote, q.content, q.id_caracter, c.img_char, s.title, s.date, q.likes, q.langue
FROM Quote q
JOIN Source s ON s.id_source = q.id_source
WHERE content LIKE '%:quote%' AND is_valid = true AND langue = :langue
LIMIT 20 OFFSET :page*20;";
$this->co->executeQuery($query,array(':quote' => array($quote,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR)));
// Execute the query with the provided parameters
$this->co->executeQuery($query, [
':quote' => array($quote, PDO::PARAM_STR),
':page' => array($numpage, PDO::PARAM_INT),
':langue' => array($language, PDO::PARAM_STR)
]);
// Return the search results
return $this->co->getResults();
}
public function searchSource(string $source,int $numpage,string $language):array{
//recherche par source
$query="SELECT q.id_quote, q.content, c.character, c.img_path, s.title, s.date, q.likes, q.langue
/**
* Searches for a quote by its unique ID.
*
* This method retrieves a quote from the `Quote` table based on its ID (`$id`). It joins related tables
* (`Caracter`, `Source`, and `Image`) to fetch additional information such as character name, image path,
* source title, and the number of likes, only for valid quotes.
*
* @param string $id The unique identifier of the quote to retrieve.
*
* @return array Returns an associative array of the quote's details including content, character, image path,
* source title, date, likes, and language.
*/
public function searchId(string $id): array
{
// SQL query to search for a quote by its ID with related tables for additional information
$query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.character
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
WHERE s.title LIKE '%:source%' AND q.is_valid = true AND langue = :langue
LIMIT 20 OFFSET :page*20;";
$this->co->executeQuery($query,array(':source' => array($source,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR)));
$result=$this->co->getResults();
return $result;
}
JOIN Image i ON c.id_img = i.id_img
WHERE q.id_quote = :id AND q.isvalide = true;";
public function searchPers(string $Carac,int $numpage,string $language):array{
// Execute the query with the provided quote ID
$this->co->executeQuery($query, [':id' => array($id, PDO::PARAM_STR)]);
//recherche par personnage
$query="SELECT q.id_quote, q.content, c.character, c.img_path, s.title, s.date, q.likes, q.langue
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.character
JOIN Source s ON s.id_source = q.id_source
WHERE c.character LIKE '%:pers%' AND q.is_valid = true AND langue = :langue
LIMIT 20 OFFSET :page*20;";
$this->co->executeQuery($query,array(':pers' => array($Pers,PDO::PARAM_STR),':page' => array($numpage,PDO::PARAM_INT),':langue' => array($language,PDO::PARAM_STR)));
$result=$this->co->getResults();
return $result;
// Return the result set
return $this->co->getResults();
}
public function searchId(string $id):array{
//recherche par id
$query="SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue
/**
* Searches for quotes based on a search term and filter type.
*
* This method allows you to search for quotes by a specific criterion, such as character name (`personnage`),
* source title (`titre`), or the content of the quote itself. It joins related tables (`Caracter`, `Source`, and `Image`)
* to retrieve additional information such as the character's name, image, source title, and likes. The search is case-insensitive.
*
* @param string|null $type The type of search. Can be:
* - `personnage` to search by character name.
* - `titre` to search by source title.
* - `null` or any other value to search by quote content.
* If not provided or invalid, it defaults to searching by content.
*
* @param string|null $search The search term to look for in the chosen field (`personnage`, `titre`, or `content`).
* This parameter can be `null`, which will result in no filtering.
*
* @param array $filtre (Unused in this method, included for compatibility)
*
* @return array Returns an associative array of quotes matching the search criteria, including content, character name,
* image path, source title, date, likes, and language.
*/
public function search(?string $type, ?string $search, array $filtre): array
{
// Start building the query
$query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE q.id_quote = :id AND q.isvalide = true;";
$this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR)));
$result=$this->co->getResults();
return $result;
}
public function search(?string $type,?string $search,array $filtre):array{
$query="SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dates, q.likes, q.langue
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE lower(";
if($type=='personnage'){
$query = $query . "c.caracter) LIKE lower('%" . $search . "%')";
WHERE lower()";
// Build the condition based on the $type parameter
if ($type == 'personnage') {
// Search by character name
$query .= "c.caracter) LIKE lower('%" . $search . "%')";
} elseif ($type == 'titre') {
// Search by source title
$query .= "s.title) LIKE lower('%" . $search . "%')";
} else {
// Default to searching by quote content
$query .= "q.content) LIKE lower('%" . $search . "%')";
}
elseif($type=='titre'){
$query = $query . "s.title) LIKE lower('%" . $search . "%')";
}
else{
$query = $query . "q.content) LIKE lower('%" . $search . "%')";
}
/* Categorie a rajouter
foreach($filtre as $fil){
$query = $query . " AND " . $fil
}*/
$this->co->executeQuery($query,array());
// Execute the query
$this->co->executeQuery($query, array());
$result=$this->co->getResults();
// Get the results and return them
$result = $this->co->getResults();
return $result;
}
public function getQuoteOfTheDay(string $language): array {
/**
* Retrieves the quote of the day in the specified language.
*
* This method retrieves the quote of the day from the `DailyQuote` table, including associated information such as
* the character's name, image, source title, and the number of likes. The quote is filtered by its validity (`isValide = true`)
* and the language (`$language`). Only one quote is returned, and the most recent valid quote is chosen.
*
* @param string $language The language of the quote to retrieve (e.g., "English", "French", etc.).
*
* @return array Returns an associative array of the quote's details, including the quote content, character,
* character image path, source title, source date, likes, and language. If no result is found,
* an empty array is returned.
*/
public function getQuoteOfTheDay(string $language): array
{
// SQL query to retrieve the quote of the day in the specified language
$query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue
FROM DailyQuote dq
JOIN Quote q ON dq.citation_id = q.id_quote
@ -95,11 +147,16 @@ Class QuoteGateway extends Gateway{
WHERE q.isValide = true AND q.langue = :language
ORDER BY q.id_quote DESC
LIMIT 1;";
try {
// Execute the query with the provided language parameter
$this->co->executeQuery($query, [':language' => [$language, PDO::PARAM_STR]]);
// Get the results and return the first (and only) result if available
$result = $this->co->getResults();
return $result[0] ?? [];
return $result[0] ?? []; // Return the first result or an empty array if no result is found
} catch (PDOException $e) {
// In case of a database error, catch the exception and display an error message
echo "Erreur dans getQuoteOfTheDay: " . $e->getMessage();
return [];
}
@ -107,145 +164,141 @@ Class QuoteGateway extends Gateway{
/**
* Retrieves a list of quote suggestions in the specified language with pagination.
*
* This method fetches a random selection of quotes that are marked as valid (`isValide = true`) in the specified language.
* The quotes are paginated, returning a set of 20 quotes per page, with each call providing a different set of suggestions
* due to the random ordering.
*
* @param int $numpage The page number for pagination. This value is used to calculate the offset for the query.
* Each page contains 20 quotes.
*
* @param string $language The language of the quotes to retrieve (e.g., "English", "French", etc.).
*
* @return array Returns an array of quotes, each with its content, associated character, character's image path,
* source title, source date, number of likes, and language. If no results are found, an empty array is returned.
*/
public function getSuggestions(int $numpage, string $language): array {
// SQL query to retrieve random quote suggestions based on the specified language and pagination
$query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE q.isValide = true AND q.langue = :language
ORDER BY RANDOM()
LIMIT 20 OFFSET :offset;";
FROM Quote q
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE q.isValide = true AND q.langue = :language
ORDER BY RANDOM()
LIMIT 20 OFFSET :offset;";
// Execute the query with the provided language and offset for pagination
$this->co->executeQuery($query, [
':language' => [$language, PDO::PARAM_STR],
':offset' => [$numpage * 20, PDO::PARAM_INT]
':offset' => [$numpage * 20, PDO::PARAM_INT] // Calculate the offset for pagination
]);
// Return the result set (quotes)
return $this->co->getResults();
}
/**
* Retrieves a list of quotes marked as favorites by a specific user.
*
* This method fetches the quotes that are marked as favorites by the user, along with relevant information such as
* the character's name, image path, source title, and number of likes. It uses the `Favorite` table to identify the quotes
* favorited by the specified user.
*
* @param string $userId The ID of the user whose favorite quotes are to be retrieved.
*
* @return array Returns an array of quotes that are marked as favorites by the user, each with its content,
* associated character, character's image path, source title, source date, likes, and language.
* If no favorites are found, an empty array is returned.
*/
public function getFavorites(string $userId): array {
// SQL query to retrieve the list of favorite quotes for a specific user
$query = "SELECT q.id_quote, q.content, c.caracter, i.imgPath, s.title, s.dateS, q.likes, q.langue
FROM Favorite f
JOIN Quote q ON f.quote = q.id_quote
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE f.users = :userId";
FROM Favorite f
JOIN Quote q ON f.quote = q.id_quote
JOIN Caracter c ON c.id_caracter = q.id_caracter
JOIN Source s ON s.id_source = q.id_source
JOIN Image i ON c.id_img = i.id_img
WHERE f.users = :userId;";
try {
// Execute the query with the provided user ID
$this->co->executeQuery($query, [
':userId' => [$userId, PDO::PARAM_STR]
]);
// Return the results (favorites)
return $this->co->getResults();
} catch (PDOException $e) {
// In case of a database error, catch the exception and display an error message
echo "Erreur dans getFavorites: " . $e->getMessage();
return [];
}
}
public function autoincrement() : int
/**
* Retrieves the next available auto-incremented quote ID.
*
* This method retrieves the next available `id_quote` by selecting the maximum `id_quote` in the `Quote` table and
* incrementing it by 1. This value can be used to set the `id_quote` for a new quote being inserted into the database.
*
* @return int Returns the next available quote ID (the maximum `id_quote` value + 1). If no quotes exist yet, it returns 1.
*/
public function autoincrement(): int
{
$query = "SELECT Max(id_quote) + 1 as id FROM Quote;";
// SQL query to retrieve the next available quote ID by selecting the maximum id_quote and adding 1
$query = "SELECT Max(id_quote) + 1 as id
FROM Quote;";
// Execute the query to get the maximum id_quote value
$this->co->executeQuery($query);
return ($this -> co ->getResults())[0]['id'];
// Return the next available id (the result of the query), or 1 if no quotes are found
return ($this->co->getResults())[0]['id'];
}
/**
* Inserts a new quote into the Quote table, associated with a user, source, and character.
*
* This method inserts a new quote into the `Quote` table, setting various attributes like the content, language,
* image path, the user who created the quote, the source of the quote, and the character associated with the quote.
* The method automatically generates a new quote ID by using the `autoincrement` function, ensuring a unique ID
* for each new quote.
*
* @param string $content The content of the quote to be inserted.
* @param string $img_path The path to the image associated with the quote.
* @param string $langage The language of the quote (e.g., "English", "French").
* @param int $user The ID of the user who created the quote.
* @param int $source The ID of the source of the quote (e.g., book, movie).
* @param int $character The ID of the character associated with the quote.
*
* @return bool Returns true if the query executed successfully, false otherwise.
*/
public function insert4User(string $content, string $img_path, string $langage, int $user, int $source, int $character) : bool
{
$query = "
INSERT INTO Quote (id_quote, content, langue, reason, id_source, id_caracter, id_user_verif, img_path)
VALUES (:id, :content, :langage, :reason, :source, :character, :user, :img_path)
";
// SQL query to insert a new quote into the database
$query = "INSERT INTO Quote (id_quote, content, langue, reason, id_source, id_caracter, id_user_verif, img_path)
VALUES (:id, :content, :langage, :reason, :source, :character, :user, :img_path)";
// Execute the query with the provided parameters
return $this->co->executeQuery($query, [
':id' => array($this->autoincrement(), PDO::PARAM_INT),
':content' => array($content, PDO::PARAM_STR),
':img_path' => array($img_path, PDO::PARAM_STR),
':langage' => array($langage, PDO::PARAM_STR),
':user' => array($user, PDO::PARAM_INT),
':reason' => array('À vérifier', PDO::PARAM_STR),
':source' => array($source, PDO::PARAM_STR),
':character' => array($character, PDO::PARAM_STR)
':id' => array($this->autoincrement(), PDO::PARAM_INT), // Generate the next available quote ID
':content' => array($content, PDO::PARAM_STR), // Content of the quote
':img_path' => array($img_path, PDO::PARAM_STR), // Path to the image associated with the quote
':langage' => array($langage, PDO::PARAM_STR), // Language of the quote
':user' => array($user, PDO::PARAM_INT), // User ID who created the quote
':reason' => array('À vérifier', PDO::PARAM_STR), // Default value for the quote verification status
':source' => array($source, PDO::PARAM_STR), // Source ID (book, movie, etc.)
':character' => array($character, PDO::PARAM_STR) // Character ID associated with the quote
]);
}
//======================== PARTI ADMIN ========================
//Probablement à déplacer dans un autre fichier
public function getQuoteIsValide():array{
//obtenir les quotes en attentes de validation par l'admin
$query = 'SELECT * FROM Quote WHERE isValid=:bool';
$this->co->executeQuery($query,array(':bool' => array(false, PDO::PARAM_BOOL)));
return $this->co->getResults();
}
public function validQuote(int $id){
//Valider la quote par l'admin
$query ='UPDATE Quote SET isValid=:newValide WHERE id_Quote=:id';
$this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_INT)));
}
public function invalidQuote(int $id){
//Invalide la quote par l'admin (suppression)
$query ='DELETE FROM Quote WHERE id_Quote=:id';
$this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_INT)));
}
public function updateContent(int $id, string $newContent):array{
//Update le contexte de quote passé en paramètre
$queryUpdate = 'UPDATE Quote SET content=:newContent WHERE id_quote=:idQuote';
$this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newContent'=> array($newContent, PDO::PARAM_STR)));
//Renvoie le nouveau contexte de quote
$queryReponse = 'SELECT content FROM Quote WHERE id_quote=:idQuote';
$this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR)));
return $this->co->getResults();
}
public function updateTimeCode(int $id, string $newTimeCode):array{
//Update le time code de quote passé en paramètre
$queryUpdate = 'UPDATE Quote SET timecode=:newTimeCode WHERE id_quote=:idQuote';
$this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newTimeCode'=> array($newTimeCode, PDO::PARAM_STR)));
//Renvoie le nouveau contexte de quote
$queryReponse = 'SELECT timecode FROM Quote WHERE id_quote=:idQuote';
$this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR)));
return $this->co->getResults();
}
public function updateDate(int $id, int $newDate):array{
//Update la date de quote passé en paramètre
$queryUpdate = 'UPDATE Source SET dateSource =:newdate WHERE idSource = (SELECT idSource FROM Quote WHERE idQuote =:idQuote)';
$this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newDate'=> array($newDate, PDO::PARAM_INT)));
//Renvoie la nouvelle date de quote
$queryReponse = 'SELECT s.dateSource FROM Source s, Quote q WHERE id_quote=:idQuote AND s.idSource = q.idSource';
$this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR)));
return $this->co->getResults();
}
public function updateTitle(int $id, string $newTitle):array{
//Update le titre de l'oeuvre de quote passé en paramètre
$queryUpdate = 'UPDATE Source SET title =:newTitle WHERE idSource = (SELECT idSource FROM Quote WHERE idQuote =:idQuote)';
$this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newTitle'=> array($newTitle, PDO::PARAM_STR)));
//Renvoie le nouveau titre de quote
$queryReponse = 'SELECT s.title FROM Source s, Quote q WHERE id_quote=:idQuote AND s.idSource = q.idSource';
$this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR)));
return $this->co->getResults();
}
public function updateNameCharacter(int $id, string $newNameCharacter):array{
//Update le personnage de l'oeuvre de quote passé en paramètre
$queryUpdate = 'UPDATE Character SET name =:newNameCharacter WHERE idCharacter = (SELECT idCharacter FROM Quote WHERE idQuote =:idQuote)';
$this->co->executeQuery($queryUpdate, array(':idQuote'=>array($id, PDO::PARAM_STR), ':newNameCharacter'=> array($newNameCharacter, PDO::PARAM_STR)));
//Renvoie le nouveau personnage de quote
$queryReponse = 'SELECT c.title FROM Character c, Quote q WHERE id_quote=:idQuote AND c.idCharacter = q.idCharacter';
$this->co->executeQuery($queryReponse, array(':idQuote'=>array($id, PDO::PARAM_STR)));
return $this->co->getResults();
}
}
?>

@ -1,125 +0,0 @@
<?php
namespace Gateway;
use PDO;
class ResultsGateway extends Gateway
{
public function createResultsGateway(int $idQuiz, int $idUser, int $nbPts, int $time) : bool
{
$query = "
INSERT INTO Results
VALUES (:id_quiz, :id_user, :nb_pts, :time)
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_user' => array($idUser, PDO::PARAM_INT),
'nb_pts' => array($nbPts, PDO::PARAM_INT),
'time' => array($time, PDO::PARAM_INT)
]);
}
public function findResultsByQuiz(int $idQuiz) : array
{
$query = "
SELECT * FROM Results
WHERE quiz_r = :id_quiz
";
$this -> co -> executeQuery($query, ['id_quiz' => array($idQuiz, PDO::PARAM_INT)]);
return $this -> co -> getResults();
}
public function findResultsByUser(int $idUser) : array
{
$query = "
SELECT * FROM Results
WHERE user_r = :id_user
";
$this -> co -> executeQuery($query, ['id_user' => array($idUser, PDO::PARAM_INT)]);
return $this -> co -> getResults();
}
public function findResultsById(int $idQuiz, int $idUser) : array
{
$query = "
SELECT * FROM Results
WHERE quiz_r = :id_quiz AND user_r = :id_user
";
$this -> co -> executeQuery($query, [
'id_user' => array($idUser, PDO::PARAM_INT),
'id_quiz' => array($idQuiz, PDO::PARAM_INT)
]);
return $this -> co -> getResults();
}
public function findAllResults() : array
{
$query = "SELECT * FROM Results";
$this -> co -> executeQuery($query);
return $this -> co -> getResults();
}
public function updateResults(int $idQuiz, int $idUser, ?int $score, ?int $time) : bool
{
if ($score && !$time)
{
$query = "
UPDATE Results
SET score = :score
WHERE quiz_r = :id_quiz AND user_r = :id_user
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_user' => array($idUser, PDO::PARAM_INT),
'score' => array($score, PDO::PARAM_INT)
]);
}
else if (!$score && $time)
{
$query = "
UPDATE Results
SET time = :time
WHERE quiz_r = :id_quiz AND user_r = :id_user
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_user' => array($idUser, PDO::PARAM_INT),
'time' => array($time, PDO::PARAM_INT)
]);
}
else
{
$query = "
UPDATE Results
SET score = :score AND time = :time
WHERE quiz_r = :id_quiz AND user_r = :id_user
";
return $this -> co -> executeQuery($query, [
'id_quiz' => array($idQuiz, PDO::PARAM_INT),
'id_user' => array($idUser, PDO::PARAM_INT),
'score' => array($score, PDO::PARAM_INT),
'time' => array($time, PDO::PARAM_INT)
]);
}
}
}

@ -6,79 +6,147 @@ use PDO;
class SourceGateway extends Gateway{
/**
* Inserts a new source into the Source table.
*
* This method inserts a new source into the `Source` table, setting attributes like the title and date of the source.
* It takes a `sourceEntity` object as an argument, which contains the data required for the insertion.
* The method assumes that the source entity is valid and contains the appropriate values for the title and date.
*
* @param sourceEntity $s The source entity object containing the source's title and date.
*
* @return bool Returns true if the query executed successfully, false otherwise.
*/
public function create(sourceEntity $s) : bool
{
$query = "
INSERT INTO Source
VALUES( :title, :date)
";
return $this -> co -> executeQuery($query, [
"title" => array($s->getTitle(), PDO::PARAM_STR),
"date" => array($s->getDate(), PDO::PARAM_STR),
#"type" => array($s->getType(), PDO::PARAM_STR)
// SQL query to insert a new source into the database
$query = "INSERT INTO Source
VALUES( :title, :date)";
// Execute the query with the parameters extracted from the source entity object
return $this->co->executeQuery($query, [
'title' => array($s->getTitle(), PDO::PARAM_STR), // The title of the source (e.g., book title, movie title)
'date' => array($s->getDate(), PDO::PARAM_STR), // The date of the source (e.g., publication date, release date)
// 'type' => array($s->getType(), PDO::PARAM_STR) // Optional: Add 'type' if needed (commented out for now)
]);
}
/**
* Retrieves a source by its ID from the Source table.
*
* This method fetches the details of a source from the `Source` table by its `id_source`.
* It executes a query to retrieve the source record that matches the provided ID.
* If a source is found with the given ID, the details of the source are returned as an associative array.
*
* @param int $id The ID of the source to be retrieved.
*
* @return array An associative array containing the details of the source, or an empty array if no source is found.
*/
public function findById(int $id) : array
{
$query = "SELECT * FROM Source WHERE id_source = :id";
// SQL query to select a source by its ID
$query = "SELECT *
FROM Source
WHERE id_source = :id";
$this -> co -> executeQuery($query, array("id" => array($id, PDO::PARAM_INT)));
return $res = $this -> co -> getResults();
// Execute the query with the provided ID
$this->co->executeQuery($query, array("id" => array($id, PDO::PARAM_INT)));
// Return the result of the query
return $res = $this->co->getResults();
}
/**
* Retrieves a source by its title from the Source table.
*
* This method fetches the details of a source from the `Source` table by its `title`.
* It executes a query to retrieve the source record that matches the provided title.
* If a source is found with the given title, the details of the source are returned as an associative array.
*
* @param string $t The title of the source to be retrieved.
*
* @return array An associative array containing the details of the source, or an empty array if no source is found.
*/
public function findByTitle(string $t) : array
{
$query = "SELECT * FROM Source WHERE title = :t";
$this -> co -> executeQuery($query, ["t" => array($t, PDO::PARAM_STR)]);
return $res = $this -> co -> getResults();
}
// SQL query to select a source by its title
$query = "SELECT *
FROM Source
WHERE title = :t";
public function findByDate(string $d) : array
{
$query = "SELECT * FROM Source WHERE dates = :d";
// Execute the query with the provided title
$this->co->executeQuery($query, ["t" => array($t, PDO::PARAM_STR)]);
$this -> co -> executeQuery($query, ["d" => array($d, PDO::PARAM_STR)]);
return $this -> co -> getResults();
// Return the result of the query
return $res = $this->co->getResults();
}
/*
public function findByType(TypeSourceEnum $type) : array
{
$query = "SELECT * FROM Source WHERE type = :t";
$this -> co -> executeQuery($query, ["t" => array($type, PDO::PARAM_STR)]);
return $this -> co -> getResults();
}
*/
/**
* Retrieves all sources from the Source table.
*
* This method fetches all records from the `Source` table, sorted by the `title` column in ascending order.
* It executes a query to retrieve all source records and returns them as an associative array.
*
* @return array An array of associative arrays, each containing the details of a source.
*/
public function findAll() : array
{
$query = "SELECT * FROM Source ORDER BY title ASC";
$this -> co -> executeQuery($query);
return $this -> co -> getResults();
// SQL query to select all sources from the Source table, ordered by title in ascending order
$query = "SELECT *
FROM Source
ORDER BY title ASC";
// Execute the query to fetch the results
$this->co->executeQuery($query);
// Return the result of the query
return $this->co->getResults();
}
/**
* Deletes a source record from the Source table by its ID.
*
* This method deletes the record from the `Source` table where the `id_source` matches the provided ID.
* It executes the DELETE SQL query to remove the source from the database.
*
* @param int $id The ID of the source to delete.
* @return bool True if the delete was successful, false otherwise.
*/
public function delete(int $id) : bool
{
$query = "DELETE FROM Source WHERE id_source = :id_s";
// SQL query to delete the source record with the given id_source
$query = "DELETE FROM Source
WHERE id_source = :id_s";
$this -> co -> executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]);
// Execute the query with the provided source ID
return $this->co->executeQuery($query, ["id_s" => array($id, PDO::PARAM_INT)]);
}
/**
* Updates an existing source record in the Source table.
*
* This method updates the `title` and `date` columns of the `Source` table for a given `id_source`.
* It executes the `UPDATE` SQL query to modify the record with the specified ID.
*
* @param sourceEntity $s The source entity containing the updated data (ID, title, and date).
* @return bool True if the update was successful, false otherwise.
*/
public function update(sourceEntity $s) : bool
{
$query = "
UPDATE Source
// SQL query to update the title and date of a source record with the given id_source
$query = "UPDATE Source
SET title = :t, date = :d
WHERE id_source = :id_s
";
WHERE id_source = :id_s";
// Execute the query with the provided source entity data
return $this->co->executeQuery($query, [
"id_s" => array($s -> getIdSource(), PDO::PARAM_INT),
"t" => array($s -> getTitle(), PDO::PARAM_STR),
"d" => array($s -> getDate(), PDO::PARAM_STR)
"id_s" => array($s->getIdSource(), PDO::PARAM_INT),
"t" => array($s->getTitle(), PDO::PARAM_STR),
"d" => array($s->getDate(), PDO::PARAM_STR)
]);
}
}

@ -4,44 +4,117 @@ use PDO;
Class UserGateway extends Gateway{
/**
* Gets the total number of users in the Users table.
*
* This method executes a `SELECT COUNT(*)` SQL query to count all the records in the `Users` table.
* It returns the count as an array.
*
* @return array An array containing the total number of users in the `Users` table.
*/
public function getNumberOfUsers() : array
{
// SQL query to count all users in the Users table
$query = "SELECT Count(*) FROM Users";
$this -> co -> executeQuery($query);
// Execute the query
$this->co->executeQuery($query);
return $this -> co -> getResults();
// Return the result of the query
return $this->co->getResults();
}
public function firstIdUser():int{
$query = "Select id_user from Users;";
$this -> co -> executeQuery($query);
$res = $this -> co -> getResults();
foreach($res as $r){
/**
* Finds the first available ID for a new user.
*
* This method fetches all existing user IDs from the `Users` table and
* returns the first integer ID that is not already in use.
*
* @return int The first available user ID.
*/
public function firstIdUser(): int
{
// SQL query to get all user IDs from the Users table
$query = "SELECT id_user FROM Users;";
// Execute the query to fetch all user IDs
$this->co->executeQuery($query);
$res = $this->co->getResults();
// Initialize an empty array to store the user IDs
foreach ($res as $r) {
$tab[] = $r["id_user"];
}
$id=1;
while(in_array($id,$tab)){$id=$id+1;}
// Start checking for the first available ID from 1
$id = 1;
while (in_array($id, $tab)) {
// If the ID already exists, increment and check again
$id = $id + 1;
}
// Return the first available ID
return $id;
}
public function randomImg():int{
$query = "SELECT id_img FROM image ORDER BY Random() LIMIT 1";
/**
* Fetches a random image ID from the `image` table.
*
* This method selects a random row from the `image` table using the SQL
* clause `ORDER BY RANDOM()` and returns the `id_img` of the randomly selected image.
*
* @return int The ID of a random image.
*/
public function randomImg(): int
{
// SQL query to select a random image ID
$query = "SELECT id_img
FROM image
ORDER BY RANDOM()
LIMIT 1";
// Execute the query
$this->co->executeQuery($query);
// Fetch the result
$res = $this->co->getResults();
// Return the ID of the randomly selected image
return $res[0][0];
}
public function insertUser(string $pseudo, string $email, string $password, bool $isAdmin, int $imgPrfl) : bool {
$id=$this->firstIdUser();
$idImg=$this->randomImg();
/**
* Inserts a new user into the `Users` table.
*
* This method first generates a new user ID, retrieves a random image ID,
* and inserts the provided user details (pseudo, email, password, profile image)
* into the `Users` table.
*
* @param string $pseudo The username (pseudo) of the new user.
* @param string $email The email address of the new user.
* @param string $password The password for the new user.
* @param bool $isAdmin Whether the user is an admin (not used in this query).
* @param int $imgPrfl The ID of the profile image for the new user (assigned randomly).
*
* @return bool Whether the insertion was successful.
*/
public function insertUser(string $pseudo, string $email, string $password, bool $isAdmin, int $imgPrfl): bool
{
// Get the next available user ID using the firstIdUser method
$id = $this->firstIdUser();
$query = "
INSERT INTO Users(id_user,username,email,password,creation,img)
VALUES (:id, :pseudo, :email, :password, CURRENT_DATE, :imgPrfl);
";
return $this -> co -> executeQuery($query, [
// Get a random image ID using the randomImg method
$idImg = $this->randomImg();
// SQL query to insert the new user into the Users table
$query = "INSERT INTO Users(id_user, username, email, password, creation, img)
VALUES (:id, :pseudo, :email, :password, CURRENT_DATE, :imgPrfl);";
// Execute the query with the provided data
return $this->co->executeQuery($query, [
":id" => [$id, PDO::PARAM_INT],
":pseudo" => [$pseudo, PDO::PARAM_STR],
":email" => [$email, PDO::PARAM_STR],
@ -50,187 +123,477 @@ Class UserGateway extends Gateway{
]);
}
public function delete(string $id) : bool{
// supretion user
$query='DELETE FROM Users WHERE id_user = :id;';
return $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR)));
/**
* Deletes a user from the `Users` table.
*
* This method takes a user ID (as a string) and removes the corresponding
* user from the `Users` table using the provided ID.
*
* @param string $id The ID of the user to be deleted.
* @return bool Whether the deletion was successful.
*/
public function delete(string $id): bool
{
// SQL query to delete a user from the Users table based on the user ID
$query = 'DELETE FROM Users
WHERE id_user = :id;';
// Execute the query with the provided user ID
return $this->co->executeQuery($query, [
':id' => [$id, PDO::PARAM_STR]
]);
}
public function inFavorite(string $username, int $idq):bool{
$query = 'SELECT count(*) FROM Favorite f JOIN Users u ON f.users = u.id_user WHERE u.username = :user AND f.quote = :id';
$this->co->executeQuery($query, array(':user'=>array($username, PDO::PARAM_STR),':id'=>array($idq, PDO::PARAM_INT)));
/**
* Checks if a quote is in the user's favorite list.
*
* This method checks if a specific quote, identified by its ID,
* is already marked as a favorite by a user, identified by their username.
*
* @param string $username The username of the user.
* @param int $idq The ID of the quote.
* @return bool True if the quote is in the user's favorite list, false otherwise.
*/
public function inFavorite(string $username, int $idq): bool
{
// SQL query to count the number of favorites for the given user and quote
$query = 'SELECT count(*)
FROM Favorite f
JOIN Users u ON f.users = u.id_user
WHERE u.username = :user AND f.quote = :id';
// Execute the query with the provided parameters (username and quote ID)
$this->co->executeQuery($query, array(
':user' => array($username, PDO::PARAM_STR),
':id' => array($idq, PDO::PARAM_INT)
));
// Fetch the results and check if count is greater than or equal to 1
$result = $this->co->getResults();
// Return true if the quote is in the favorites, otherwise false
return ($result[0]['count'] >= 1);
}
public function addFavorite(string $username, int $id){
$query = 'INSERT INTO Favorite VALUES ((SELECT id_user FROM Users WHERE username = :username), :id)';
$this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR), ':id' => array($id,PDO::PARAM_INT)));
/**
* Adds a quote to a user's favorite list and increments the like count for the quote.
*
* This method performs two actions:
* 1. Adds the quote (identified by its ID) to the user's favorite list.
* 2. Increments the number of likes for the given quote.
*
* @param string $username The username of the user who is adding the quote to their favorites.
* @param int $id The ID of the quote being added to the favorites.
*/
public function addFavorite(string $username, int $id)
{
// First query: Insert a new favorite for the user and the specified quote.
$query = 'INSERT INTO Favorite VALUES (
(SELECT id_user FROM Users WHERE username = :username),
:id
)';
// Execute the query to add the quote to the user's favorites
$this->co->executeQuery($query, array(
':username' => array($username, PDO::PARAM_STR),
':id' => array($id, PDO::PARAM_INT)
));
// Second query: Increment the likes for the given quote.
$query = 'UPDATE Quote SET likes = (likes + 1) WHERE id_quote = :id';
$this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT)));
// Execute the query to update the like count for the quote
$this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
}
public function supFavorite(string $username, int $id){
$query = 'SELECT id_user FROM Users WHERE username = :username';
$this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR)));
/**
* Removes a quote from a user's favorite list and decrements the like count for the quote.
*
* This method performs two actions:
* 1. Removes the specified quote from the user's favorites.
* 2. Decrements the number of likes for the given quote.
*
* @param string $username The username of the user who is removing the quote from their favorites.
* @param int $id The ID of the quote being removed from the favorites.
*/
public function supFavorite(string $username, int $id)
{
// First query: Get the user id based on the username.
$query = 'SELECT id_user
FROM Users
WHERE username = :username';
$this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
$result = $this->co->getResults()[0]['id_user'];
$query = 'DELETE FROM Favorite WHERE users = :user AND quote = :id;';
$this->co->executeQuery($query, array(':user' => array($result,PDO::PARAM_INT), ':id' => array($id,PDO::PARAM_INT)));
$query = 'UPDATE Quote SET likes = (likes - 1) WHERE id_quote = :id';
$this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT)));
// Second query: Delete the quote from the user's favorites.
$query = 'DELETE FROM Favorite
WHERE users = :user AND quote = :id;';
$this->co->executeQuery($query, array(':user' => array($result, PDO::PARAM_INT), ':id' => array($id, PDO::PARAM_INT)));
// Third query: Decrement the like count for the quote.
$query = 'UPDATE Quote
SET likes = (likes - 1)
WHERE id_quote = :id';
$this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
}
public function deleteAllCommentaryUser(string $user){
$query = 'DELETE FROM Commentary WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);';
$this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
// ===================== DELETE FUNCTION =====================
/**
* Deletes all commentaries made by a user.
*
* This method performs the following actions:
* 1. Finds all commentaries made by a specified user using their username.
* 2. Deletes all the commentaries associated with that user from the Commentary table.
*
* @param string $user The username of the user whose commentaries need to be deleted.
*/
public function deleteAllCommentaryUser(string $user)
{
// Query to delete all commentaries made by the user.
$query = 'DELETE FROM Commentary
WHERE users IN ( SELECT id_user
FROM Users
WHERE username = :user);';
// Execute the query with the provided username.
$this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR)));
}
public function deleteAllFavoriteUser(string $user){
$query = 'DELETE FROM Favorite WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);';
$this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
/**
* Deletes all favorites associated with a user.
*
* This method performs the following actions:
* 1. Finds all favorite quotes associated with the user using their username.
* 2. Deletes all the entries in the Favorite table where this user is marked as the owner.
*
* @param string $user The username of the user whose favorites need to be deleted.
*/
public function deleteAllFavoriteUser(string $user)
{
// Query to delete all favorites associated with the user.
$query = 'DELETE FROM Favorite
WHERE users IN ( SELECT id_user
FROM Users
WHERE username = :user);';
// Execute the query with the provided username.
$this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR)));
}
public function deleteUser(string $user){
$query = 'DELETE FROM Users WHERE username=:user;';
$this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
/**
* Deletes a user from the Users table based on their username.
*
* @param string $user The username of the user to be deleted.
*/
public function deleteUser(string $user)
{
// SQL query to delete the user from the Users table based on their username.
$query = 'DELETE FROM Users
WHERE username = :user;';
// Execute the query with the username parameter.
$this->co->executeQuery($query, array(':user' => array($user, PDO::PARAM_STR)));
}
// ===================== GET FUNCTION =====================
public function getFavorite(string $id):array{
/**
* Retrieves the favorite quotes of a user based on their user ID.
*
* @param string $id The ID of the user whose favorite quotes are to be fetched.
* @return array The list of favorite quotes of the user.
*/
public function getFavorite(string $id): array
{
// SQL query to retrieve all quotes that the user has marked as favorites.
$query = 'SELECT *
FROM Quote
WHERE id_quote IN (SELECT id_quote
FROM Favorite f JOIN Users u ON u.id_user = f.user_f
WHERE u.id_user = :id);';
//obtention favoris d'un user
$query='SELECT * FROM Quote WHERE id_quote IN (SELECT id_quote FROM Favorite f JOIN users u ON u.id_user = f.user_f WHERE u.id_user = :id);';
$this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR)));
$result=$this->co->getResults();
return $result;
}
// Execute the query with the user ID as a parameter.
$this->co->executeQuery($query, array(':id' => array($id, PDO::PARAM_STR)));
public function getIdUser(string $username):array{
$query = 'SELECT id_user FROM Users WHERE username=:username';
$this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR)));
// Get the results of the query and return them.
$result = $this->co->getResults();
return $result;
}
// ===================== FIND FUNCTION =====================
//obtenir les information d'un user
public function findDataUser(int $id):array{
$query = 'SELECT u.id_user , u.username , u.email , u.password , i.imgPath , u.creation FROM Users WHERE id_user=:idUser';
$this->co->executeQuery($query, array(':idUser'=>array($id, PDO::PARAM_STR)));
/**
* Retrieves the user ID based on the given username.
*
* @param string $username The username for which to retrieve the user ID.
* @return array The user ID corresponding to the given username.
*/
public function getIdUser(string $username): array
{
// SQL query to retrieve the user ID based on the username.
$query = 'SELECT id_user
FROM Users
WHERE username = :username';
// Execute the query with the provided username parameter.
$this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
// Get the results of the query and return them.
$result = $this->co->getResults();
return $result;
}
// obtenir les informations d'un user selon son pseudo
public function findUsername(string $username):array{
$query = 'SELECT * FROM Users u Join Image i on i.id_img=u.img WHERE username= :username';
$this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR)));
// ===================== FIND FUNCTION =====================
/**
* Retrieves user information including their image based on the username.
*
* @param string $username The username of the user whose details are to be fetched.
* @return array An array containing user details and image information.
*/
public function findUsername(string $username): array
{
// SQL query to retrieve user details and their associated image.
$query = 'SELECT * FROM Users u
JOIN Image i ON i.id_img = u.img
WHERE username = :username';
// Execute the query with the provided username as a parameter.
$this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
// Get the result of the query and return it.
return $this->co->getResults();
}
public function findEmail(string $email):array{
$query = 'SELECT * FROM Users WHERE email = :email';
$this->co->executeQuery($query, array(':email'=>array($email, PDO::PARAM_STR)));
/**
* Retrieves user information based on their email.
*
* @param string $email The email of the user whose details are to be fetched.
* @return array An array containing the user's details.
*/
public function findEmail(string $email): array
{
// SQL query to retrieve user details based on email.
$query = 'SELECT *
FROM Users
WHERE email = :email';
// Execute the query with the provided email as a parameter.
$this->co->executeQuery($query, array(':email' => array($email, PDO::PARAM_STR)));
// Get the result of the query and return it.
return $this->co->getResults();
}
// ===================== CHECK FUNCTION =====================
public function IsExisteUsername(string $username): bool {
$query = 'SELECT COUNT(*) as count FROM Users WHERE username = :username';
/**
* Checks if a username already exists in the database.
*
* @param string $username The username to check.
* @return bool Returns true if the username exists, false otherwise.
*/
public function IsExisteUsername(string $username): bool
{
// SQL query to check if the username exists in the "Users" table.
$query = 'SELECT COUNT(*) as count
FROM Users
WHERE username = :username';
// Execute the query, binding the provided username parameter.
$this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
// Get the query results.
$results = $this->co->getResults();
return $results[0]['count'] > 0; // retourne true si "count" > 0)
// Return true if the "count" is greater than 0, meaning the username exists.
return $results[0]['count'] > 0;
}
public function IsExisteEmail(string $email): bool {
$query = 'SELECT COUNT(*) as count FROM Users WHERE email = :email';
/**
* Checks if an email already exists in the database.
*
* @param string $email The email to check.
* @return bool Returns true if the email exists, false otherwise.
*/
public function IsExisteEmail(string $email): bool
{
// SQL query to check if the email exists in the "Users" table.
$query = 'SELECT COUNT(*) as count
FROM Users
WHERE email = :email';
// Execute the query, binding the provided email parameter.
$this->co->executeQuery($query, array(':email' => array($email, PDO::PARAM_STR)));
// Get the query results.
$results = $this->co->getResults();
return $results[0]['count'] > 0; // retourne true si "count" > 0)
// Return true if the "count" is greater than 0, meaning the email exists.
return $results[0]['count'] > 0;
}
/**
* Retrieves the password hash for a given username.
*
* @param string $username The username to search for.
* @return string|null The password hash if the username is found, null otherwise.
*/
public function getPasswordHash(string $username): ?string {
$query = 'SELECT password FROM Users WHERE username = :username';
// SQL query to retrieve the password hash for a given username.
$query = 'SELECT password
FROM Users
WHERE username = :username';
// Execute the query with the provided username as the parameter.
$this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
// Get the results of the query.
$results = $this->co->getResults();
// Si un utilisateur est trouvé, retourner le hash du mot de passe, sinon null
// If results are found, return the password hash, otherwise return null.
return $results ? $results[0]['password'] : null;
}
// ===================== UPDATE FUNCTION =====================
//Update Username
public function updateUsername(string $username, string $newUsername):array{
//Update le nom du user passé en paramètre
$queryUpdate = 'UPDATE Users SET username=:newUsername WHERE username=:username';
$this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newUsername'=> array($newUsername, PDO::PARAM_STR)));
// ===================== UPDATE FUNCTION =====================
//Renvoie le nouveau nom du user
/**
* Updates the username for a user.
*
* @param string $username The current username.
* @param string $newUsername The new username to set.
* @return array The result of the update, including the new username.
*/
public function updateUsername(string $username, string $newUsername): array {
// SQL query to update the username for the user with the current username
$queryUpdate = 'UPDATE Users
SET username=:newUsername
WHERE username=:username';
// Execute the update query with the provided parameters
$this->co->executeQuery($queryUpdate, array(
':username' => array($username, PDO::PARAM_STR),
':newUsername' => array($newUsername, PDO::PARAM_STR)
));
// SQL query to retrieve the updated username from the Users table
$queryReponse = 'SELECT username FROM Users WHERE username=:idUser';
$this->co->executeQuery($queryReponse, array(':idUser'=>array($newUsername, PDO::PARAM_STR)));
// Execute the query to fetch the updated username
$this->co->executeQuery($queryReponse, array(':idUser' => array($newUsername, PDO::PARAM_STR)));
// Return the result, which will contain the new username
return $this->co->getResults();
}
//Update Email
public function updateEmail(string $username, string $newEmail):array{
//Update le email du user passé en paramètre
$queryUpdate = 'UPDATE Users SET email=:newEmail WHERE username=:username';
$this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newEmail'=> array($newEmail, PDO::PARAM_STR)));
//Renvoie le nouveau email du user
/**
* Updates the email for a user based on their username.
*
* @param string $username The username of the user whose email will be updated.
* @param string $newEmail The new email to set for the user.
* @return array The result of the update, including the new email.
*/
public function updateEmail(string $username, string $newEmail): array {
// SQL query to update the email for the user with the specified username
$queryUpdate = 'UPDATE Users
SET email=:newEmail
WHERE username=:username';
// Execute the update query with the provided parameters (username and newEmail)
$this->co->executeQuery($queryUpdate, array(
':username' => array($username, PDO::PARAM_STR),
':newEmail' => array($newEmail, PDO::PARAM_STR)
));
// SQL query to retrieve the updated email from the Users table
$queryReponse = 'SELECT email FROM Users WHERE username=:username';
$this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR)));
// Execute the query to fetch the updated email
$this->co->executeQuery($queryReponse, array(':username' => array($username, PDO::PARAM_STR)));
// Return the result, which will contain the new email
return $this->co->getResults();
}
public function updateImg(string $username,string $newImage):array{
if($newImage==null){
/**
* Updates the profile image for a user based on their username.
*
* @param string $username The username of the user whose image will be updated.
* @param string|null $newImage The new image ID or `null` to use a random image.
* @return array The result of the update, including the new image ID.
*/
public function updateImg(string $username, string $newImage): array {
// Determine the image ID to use
if ($newImage == null) {
// If no image provided, use a random image ID
$id_image = $this->randomImg();
}
else if(is_int((int)$newImage)){
$id_image=(int)$newImage;
}
else{
} else if (is_int((int)$newImage)) {
// If a valid image ID is provided, use it
$id_image = (int)$newImage;
} else {
// If the provided value is not valid, use a random image ID
$id_image = $this->randomImg();
}
// SQL query to update the image for the user with the specified username
$query = 'UPDATE Users
SET img=:id_image
WHERE username=:username';
$this->co->executeQuery($query, array(
':username' => array($username, PDO::PARAM_STR),
':id_image' => array($id_image, PDO::PARAM_INT)
));
//Update l'image du user passé en paramètre
$query = 'UPDATE Users SET img=:id_image WHERE username=:username';
$this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':id_image'=> array($id_image, PDO::PARAM_INT)));
//Renvoie la nouvelle image du user
// SQL query to retrieve the updated image for the user
$queryReponse = 'SELECT img FROM Users WHERE username=:username';
$this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR)));
$this->co->executeQuery($queryReponse, array(':username' => array($username, PDO::PARAM_STR)));
// Return the result, which will contain the new image ID
return $this->co->getResults();
}
public function updatePasswd(string $username, string $newPassWd):void{
//Update le passwd du user passé en paramètre
$query = 'UPDATE Users SET password=:newPassWd WHERE username=:username';
$this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':newPassWd'=> array($newPassWd, PDO::PARAM_STR)));
}
public function emailWithUser(string $user):array{
$query = 'SELECT email FROM Users WHERE username = :user';
$this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
return $this->co->getResults();
/**
* Updates the password for a user based on their username.
*
* @param string $username The username of the user whose password will be updated.
* @param string $newPassWd The new password to set for the user.
*/
public function updatePasswd(string $username, string $newPassWd): void {
// SQL query to update the password for the user with the specified username
$query = 'UPDATE Users
SET password=:newPassWd
WHERE username=:username';
// Execute the query with the provided parameters (username and new password)
$this->co->executeQuery($query, array(
':username' => array($username, PDO::PARAM_STR),
':newPassWd' => array($newPassWd, PDO::PARAM_STR)
));
}
}
?>

@ -6,75 +6,94 @@ use Gateway\CharacterGateway;
use Gateway\Gateway;
class CharacterModel extends Model
{
class CharacterModel extends Model {
public function createCharacter(int $id_character, string $name , string $img_char) : bool
{
return $this -> gateway -> create($id_character, $name, $img_char);
/**
* Creates a character by calling the gateway's create method.
*
* @param int $id_character The unique identifier for the character.
* @param string $name The name of the character.
* @param string $img_char The file path of the image associated with the character.
*
* @return bool Returns true if the character was successfully created, otherwise false.
*/
public function createCharacter(int $id_character, string $name, string $img_char) : bool {
return $this->gateway->create($id_character, $name, $img_char);
}
public function getCharacterById(int $id_character) : ?CharacterEntity
{
$c = $this -> gateway -> findById($id_character);
if ($c)
/**
* Retrieves a character by its unique identifier.
*
* @param int $id_character The unique identifier of the character to retrieve.
*
* @return CharacterEntity|null Returns a CharacterEntity object if found, otherwise null.
*/
public function getCharacterById(int $id_character) : ?CharacterEntity {
// Attempt to find the character by ID using the gateway's findById method.
$c = $this->gateway->findById($id_character);
// If the character is found, create and return a new CharacterEntity object.
if ($c) {
return new CharacterEntity(
$c[0]['id_caracter'],
$c[0]['caracter'],
$c[0]['id_img']
$c[0]['id_caracter'], // Character ID
$c[0]['caracter'], // Character name
$c[0]['id_img'] // Image ID associated with the character
);
}
// If no character is found, return null.
return null;
}
public function getAllPerso() :array{
/**
* Retrieves all characters from the database and returns them as an array of CharacterEntity objects.
*
* @return CharacterEntity[] Returns an array of CharacterEntity objects representing all characters.
*/
public function getAllCharacters() : array {
// Fetch all characters using the gateway's findAll method.
$res = $this->gateway->findAll();
foreach($res as $c){
// Initialize an empty array to store the CharacterEntity objects.
$charac = [];
// Loop through each character in the result and create a CharacterEntity for each.
foreach ($res as $c) {
$charac[] = new CharacterEntity(
$c['id_caracter'],
$c['caracter'],
$c['id_img']
$c['id_caracter'], // Character ID
$c['caracter'], // Character name or description
$c['id_img'] // Image ID associated with the character
);
}
return $charac;
}
public function getCharacterByName(string $name) : ?CharacterEntity
{
$c = $this -> gateway -> findByName($name);
if ($c)
return new CharacterEntity(
$c[0]['id_caracter'],
$c[0]['caracter'],
$c[0]['id_img']
);
return null;
// Return the array of CharacterEntity objects.
return $charac;
}
public function getAllCharacters() : array
{
$c = $this -> gateway -> findAll();
$characters = [];
/**
* Retrieves a character by its name.
*
* @param string $name The name of the character to retrieve.
*
* @return CharacterEntity|null Returns a CharacterEntity object if a character with the given name is found, otherwise null.
*/
public function getCharacterByName(string $name) : ?CharacterEntity {
// Attempt to find the character by name using the gateway's findByName method.
$c = $this->gateway->findByName($name);
foreach ($c as $character)
{
$characters[] = new CharacterEntity(
$character['id_caracter'],
$character['caracter'],
$character['id_img']
// If the character is found, create and return a new CharacterEntity object.
if ($c) {
return new CharacterEntity(
$c[0]['id_caracter'], // Character ID
$c[0]['caracter'], // Character name or description
$c[0]['id_img'] // Image ID or path associated with the character
);
}
return $characters;
}
public function deleteCharacter(int $id_character) : bool
{
return $this -> gateway -> delete($id_character);
}
public function updateCharacter(int $id_character, string $name, string $img_char) : bool
{
return $this -> gateway -> update($id_character, $name, $img_char);
// If no character is found, return null.
return null;
}
}
?>

@ -1,45 +1,56 @@
<?php
namespace Model;
use Entity\CommentaryEntity;
use Gateway\CommentaryGateway;
use Gateway\Gateway;
class CommentaryModel extends Model {
/**
* Creates a new comment associated with a specific quote and user.
*
* @param string $comment The content of the comment.
* @param string $idQuote The identifier of the quote the comment is associated with.
* @param string $idUser The identifier of the user who is creating the comment.
*
* @return bool Returns true if the comment was successfully created, otherwise false.
*/
public function createComment(string $comment, string $idQuote, string $idUser): bool {
// Calls the gateway's create method to insert the new comment into the data source.
return $this->gateway->create($comment, $idUser, $idQuote);
}
/**
* Retrieves all comments associated with a specific quote.
*
* @param int $id The unique identifier of the quote.
*
* @return CommentaryEntity[] Returns an array of CommentaryEntity objects representing all the comments for the given quote.
*/
public function getComment(int $id): array {
// Initialize an empty array to store the comment objects.
$com = [];
// Fetch all comments related to the given quote ID using the gateway's findByQuote method.
$res = $this->gateway->findByQuote($id);
foreach ($res as $comments){
$com[] = new CommentaryEntity($comments["id_comment"], $comments["comment"], $comments["datec"], $comments["username"], $comments["imgpath"]);
}
return $com;
}
public function getComments(): array {
$res = $this->gateway->findAll();
// Loop through each comment in the result and create a CommentaryEntity object for each.
foreach ($res as $comments) {
$com[] = new CommentaryEntity($comments["id_comment"], $comments["comment"], $comments["date"]);
$com[] = new CommentaryEntity(
$comments["id_comment"], // Comment ID
$comments["comment"], // The content of the comment
$comments["datec"], // The date the comment was created
$comments["username"], // The username of the user who made the comment
$comments["imgpath"] // The image path associated with the user who made the comment
);
}
return $com;
}
public function deleteComment(int $id_comment): bool {
return $this -> gateway -> delete($id_comment);
}
public function updateComment(int $id_comment, string $comment): bool {
$c = $this -> getComment($id_comment);
if($c){
$c -> setComment($comment);
return $this->gateway -> update($c);
}
return false;
// Return the array of CommentaryEntity objects.
return $com;
}
}
?>

@ -1,65 +0,0 @@
<?php
namespace Model;
use Gateway\FavoriteGateway;
use Entity\FavoriteEntity;
use Gateway\Gateway;
class FavoriteModel extends Model
{
public function createFavoriteModel(int $idUser, int $idQuote) : bool
{
return $this -> gateway -> createFavoriteGateway($idUser, $idQuote);
}
public function getFavoriteById(int $idUser, int $idQuote) : ?FavoriteEntity
{
$res = $this -> gateway -> findFavoriteById($idUser, $idQuote);
if ($res)
{
return new FavoriteEntity (
$res[0]['user_f'],
$res[0]['quote_f'],
);
}
return null;
}
public function getFavoriteByUser(int $idUser) : array
{
$res = $this -> gateway -> findFavoriteByUser($idUser);
$favorites = [];
foreach ($res as $favorite)
{
$favorites = new FavoriteEntity (
$favorite['user_f'],
$favorite['quote_f']
);
}
return $favorites;
}
public function getAllFavorite() : array
{
$res = $this -> gateway -> findAllFavorite();
$favorites = [];
foreach ($res as $favorite)
{
$favorites = new FavoriteEntity (
$favorite['user_f'],
$favorite['quote_f']
);
}
return $favorites;
}
public function removeFavorite(int $idUser, int $idQuote) : bool
{
return $this -> gateway -> deleteFavoriteGateway($idUser, $idQuote);
}
}

@ -1,56 +1,37 @@
<?php
namespace Model;
use Entity\ImageEntity;
use Gateway\ImageGateway;
use Gateway\Gateway;
class ImageModel extends Model
{
public function createImgModel(int $idImg, string $imgPath) : bool
{
return $this -> gateway -> createImgGateway($idImg, $imgPath);
}
public function getImgById(int $idImg) : ?ImageEntity
{
$res = $this -> gateway -> findImgById($idImg);
if ($res)
{
return new ImageEntity(
$res[0]['id_img'],
$res[0]['imgpath']
);
}
return null;
}
public function getAllImg() : array
{
$res = $this -> gateway -> findAllImg();
/**
* Retrieves all images from the database.
*
* @return ImageEntity[] Returns an array of ImageEntity objects representing all the images.
*/
public function getAllImg() : array {
// Fetch all images using the gateway's findAllImg method.
$res = $this->gateway->findAllImg();
// Initialize an empty array to store the ImageEntity objects.
$images = [];
foreach ($res as $img)
{
// Loop through each image in the result and create an ImageEntity object for each.
foreach ($res as $img) {
$images[] = new ImageEntity(
$img['id_img'],
$img['imgpath']
$img['id_img'], // Image ID
$img['imgpath'] // Image path (location or URL of the image)
);
}
return $images;
}
public function deleteImgModel(int $idImg) : bool
{
return $this -> gateway -> deleteImgGateway($idImg);
}
public function updateImgModel(int $idImg, string $imgPath) : bool
{
return $this -> gateway -> updateImgGateway($idImg, $imgPath);
// Return the array of ImageEntity objects.
return $images;
}
}
?>

@ -1,12 +1,21 @@
<?php
namespace Model;
use Gateway\Gateway;
class Model
{
// The gateway instance responsible for interacting with the data source.
protected Gateway $gateway;
/**
* Constructor that initializes the Model with a Gateway instance.
*
* @param Gateway $gate The Gateway instance used to interact with the data source.
*/
public function __construct(Gateway $gate){
// Assign the provided Gateway instance to the model's gateway property.
$this->gateway = $gate;
}
}

@ -7,76 +7,60 @@ use Gateway\Gateway;
class QuestionModel extends Model
{
public function createQuestion(int $id_question, string $question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer): bool
{
return $this -> gateway -> create($id_question, $question, $answerA, $answerB, $answerC, $answerD, $cAnswer);
}
/**
* Retrieves a question by its unique identifier.
*
* @param int $id_question The unique identifier of the question to retrieve.
*
* @return QuestionEntity|null Returns a QuestionEntity object if found, otherwise null.
*/
public function getQuestion(int $id_question) : ?QuestionEntity {
// Attempt to find the question by its ID using the gateway's findById method.
$q = $this->gateway->findById($id_question);
public function getQuestion(int $id_question) : ?QuestionEntity
{
$q = $this -> gateway -> findById($id_question);
if ($q)
// If the question is found, create and return a new QuestionEntity object with the question details.
if ($q) {
return new QuestionEntity(
$q[0]['id_question'],
$q[0]['texte'],
$q[0]['answera'],
$q[0]['answerb'],
$q[0]['answerc'],
$q[0]['answerd'],
$q[0]['canswer']
$q[0]['id_question'], // Question ID
$q[0]['texte'], // The text/content of the question
$q[0]['answera'], // The first answer option
$q[0]['answerb'], // The second answer option
$q[0]['answerc'], // The third answer option
$q[0]['answerd'], // The fourth answer option
$q[0]['canswer'] // The correct answer
);
return null;
}
public function updateTextQuestion(int $id_question, string $question) : bool
{
return $this -> gateway -> updateText($id_question, $question);
}
public function updateAnswersQuestion(int $id_question, string $answerA, string $answerB, string $answerC, string $answerD, string $cAnswer): bool
{
return $this -> gateway -> updateAnswers($id_question, $answerA, $answerB, $answerC, $answerD, $cAnswer);
}
}
public function deleteQuestion(int $id_question) : bool
{
return $this -> gateway -> delete($id_question);
// If no question is found, return null.
return null;
}
public function getAllQuestions() : array
{
$q = $this -> gateway -> findAll();
$questions = [];
/**
* Retrieves a random question from the database.
*
* @return QuestionEntity|null Returns a QuestionEntity object if a random question is found, otherwise null.
*/
public function getRdmQuestion() : ?QuestionEntity {
// Fetch a random question using the gateway's findRdmQuestion method.
$q = $this->gateway->findRdmQuestion();
foreach ($q as $question) {
$questions[] = new QuestionEntity(
$question['id_question'],
$question['question'],
$question['answerA'],
$question['answerB'],
$question['answerC'],
$question['answerD'],
$question['cAnswer']
// If a random question is found, create and return a new QuestionEntity object with the question details.
if ($q) {
return new QuestionEntity(
$q['id_question'], // Question ID
$q['question'], // The text/content of the question
$q['answerA'], // The first answer option
$q['answerB'], // The second answer option
$q['answerC'], // The third answer option
$q['answerD'], // The fourth answer option
$q['cAnswer'] // The correct answer
);
}
return $questions;
}
public function getRdmQuestion() : ?QuestionEntity
{
$q = $this -> gateway -> findRdmQuestion();
if ($q)
return new QuestionEntity(
$q['id_question'],
$q['question'],
$q['answerA'],
$q['answerB'],
$q['answerC'],
$q['answerD'],
$q['cAnswer']
);
// If no random question is found, return null.
return null;
}
}
?>

@ -1,49 +1,60 @@
<?php
namespace Model;
use Entity\quizEntity;
use Gateway\QuizGateway;
use Gateway\Gateway;
class QuizModel extends Model{
public function createQuiz(int $id_quiz, int $nb_questions) : bool
{
return $this -> gateway -> create($id_quiz, $nb_questions);
}
class QuizModel extends Model{
public function getQuiz(int $id_quiz): ?quizEntity
{
$q = $this -> gateway -> findQuizById($id_quiz);
/**
* Retrieves a quiz by its unique identifier.
*
* @param int $id_quiz The unique identifier of the quiz to retrieve.
*
* @return quizEntity|null Returns a quizEntity object if found, otherwise null.
*/
public function getQuiz(int $id_quiz): ?quizEntity{
// Attempt to find the quiz by its ID using the gateway's findQuizById method.
$q = $this->gateway->findQuizById($id_quiz);
// If the quiz is found, create and return a new quizEntity object with the quiz details.
if ($q) {
return new quizEntity(
$q[0]['id_quiz'],
$q[0]['nb_quest']
$q[0]['id_quiz'], // Quiz ID
$q[0]['nb_quest'] // The number of questions in the quiz
);
}
return null;
}
public function deleteQuiz(int $id_quiz) : bool
{
return $this -> gateway -> delete($id_quiz);
// If no quiz is found, return null.
return null;
}
public function getAllQuiz() : array
{
$q = $this -> gateway -> findAll();
/**
* Retrieves all quizzes from the database.
*
* @return quizEntity[] Returns an array of quizEntity objects representing all the quizzes.
*/
public function getAllQuiz() : array{
// Fetch all quizzes using the gateway's findAll method.
$q = $this->gateway->findAll();
// Initialize an empty array to store the quiz objects.
$quizzes = [];
// Loop through each quiz in the result and create a quizEntity object for each.
foreach ($q as $quiz) {
$quizzes[] = new quizEntity(
$quiz['id_quiz'],
$quiz['nb_questions']
$quiz['id_quiz'], // Quiz ID
$quiz['nb_questions'] // The number of questions in the quiz
);
}
return $quizzes;
// Return the array of quizEntity objects.
return $quizzes;
}
}
?>

@ -14,59 +14,37 @@ use Gateway\Gateway;
class QuizQuestionModel extends Model
{
public function createQuizQuestion(int $idQuiz, int $idQuestion): bool
{
return $this->gateway->create($idQuiz,$idQuestion);
}
public function findQuizQuestionByIdQuiz(int $id): ?QuizQuestionEntity
{
$q = $this ->gateway->findQuizQuestionByIdQuiz($id);
if ($q) {
return new QuizQuestionEntity(
$q['idQuiz'],
$q['idQuestion'],
);
}
return null;
}
public function getAllQuestionByQuiz(int $id, Connection $co): array
{
/**
* Retrieves all questions associated with a specific quiz.
*
* @param int $id The unique identifier of the quiz.
* @param Connection $co The database connection to be used for querying.
*
* @return QuestionEntity[] Returns an array of QuestionEntity objects representing all the questions in the quiz.
*/
public function getAllQuestionByQuiz(int $id, Connection $co): array{
// Fetch all questions related to the given quiz ID using the gateway's findQuestionsFromQuiz method.
$q = $this->gateway->findQuestionsFromQuiz($id);
// Initialize an empty array to store the QuestionEntity objects.
$questions = [];
// Create a new QuestionGateway instance using the provided database connection.
$gateway = new QuestionGateway($co);
// Create a new QuestionModel instance, passing the QuestionGateway for data operations.
$qmdl = new QuestionModel($gateway);
foreach ($q as $question){
$questions [] = $qmdl->getQuestion($question[1]);
// Loop through each question in the result and retrieve its full details using the QuestionModel.
foreach ($q as $question) {
// Add the full QuestionEntity object for each question to the questions array.
$questions[] = $qmdl->getQuestion($question[1]);
}
// Return the array of QuestionEntity objects.
return $questions;
}
public function findAll(): array
{
$q = $this -> gateway -> findAll();
$quizzes = [];
foreach ($q as $quiz) {
$quizzes[] = new QuizQuestionEntity(
$quiz['idQuiz'],
$quiz['idQuestion']
);
}
return $quizzes;
}
public function deleteQuizQuestion(int $id): bool
{
return $this -> gateway -> delete($id);
}
}
?>

@ -1,4 +1,5 @@
<?php
namespace Model;
use Entity\Quote;
use Gateway\QuoteGateway;
@ -7,47 +8,154 @@
class QuoteModel extends Model
{
public function searchId(int $id): Quote{
/**
* Searches for a quote by its unique identifier.
*
* @param int $id The unique identifier of the quote to search for.
*
* @return Quote Returns a Quote object. If no quote is found, returns a default Quote with an ID of -1 and default values.
*/
public function searchId(int $id): Quote {
// Fetch the quote data by ID using the gateway's searchId method.
$res = $this->gateway->searchId($id);
if( count($res) == 0)
return new Quote(-1,"NULL","NULL","NULL","NULL","NULL",0,"Default");
else
return new Quote($res[0]["id_quote"],$res[0]["content"],$res[0]["caracter"],$res[0]["imgpath"],$res[0]["title"],$res[0]["dates"],$res[0]["likes"],$res[0]["langue"]);
// If no result is found, return a default Quote with an ID of -1 and placeholder values.
if (count($res) == 0) {
return new Quote(-1, "NULL", "NULL", "NULL", "NULL", "NULL", 0, "Default");
} else {
// Otherwise, return the Quote object populated with data from the search result.
return new Quote(
$res[0]["id_quote"], // Quote ID
$res[0]["content"], // Quote content
$res[0]["caracter"], // Character associated with the quote
$res[0]["imgpath"], // Image path (associated with the quote or character)
$res[0]["title"], // Title of the quote
$res[0]["dates"], // Date the quote was created
$res[0]["likes"], // Number of likes for the quote
$res[0]["langue"] // Language of the quote
);
}
}
public function getSuggest(int $numpage, string $language):array{
$res = $this->gateway->getSuggestions($numpage,$language);
$tabQ=[];
/**
* Retrieves suggestions for quotes based on the specified page number and language.
*
* @param int $numpage The page number for pagination.
* @param string $language The language to filter the suggestions by.
*
* @return Quote[] Returns an array of Quote objects representing the suggested quotes.
*/
public function getSuggest(int $numpage, string $language): array {
// Fetch suggestions from the gateway's getSuggestions method.
$res = $this->gateway->getSuggestions($numpage, $language);
foreach($res as $q ){
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"],0,150).'...' : $q["content"];
$tabQ[]= new Quote($q["id_quote"],$q["content"],$q["caracter"],$q["imgpath"],$q["title"],$q["dates"],$q["likes"],$q["langue"]) ;
// Initialize an empty array to store the resulting Quote objects.
$tabQ = [];
// Loop through the result set and create Quote objects.
foreach ($res as $q) {
// Truncate the content if it's longer than 153 characters, appending '...' if necessary.
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"], 0, 150) . '...' : $q["content"];
// Create a new Quote object and add it to the tabQ array.
$tabQ[] = new Quote(
$q["id_quote"], // Quote ID
$q["content"], // Truncated content of the quote
$q["caracter"], // Character associated with the quote
$q["imgpath"], // Image path related to the quote
$q["title"], // Title of the quote
$q["dates"], // Date the quote was created
$q["likes"], // Number of likes the quote has received
$q["langue"] // Language of the quote
);
}
// Return the array of Quote objects.
return $tabQ;
}
public function getQuoteOfTheDay(string $language):Quote{
/**
* Retrieves the quote of the day for a specified language.
*
* @param string $language The language to filter the quote of the day by.
*
* @return Quote Returns the Quote of the Day. If no quote is found, returns a default Quote with an ID of -1 and default values.
*/
public function getQuoteOfTheDay(string $language): Quote {
// Fetch the quote of the day from the gateway's getQuoteOfTheDay method.
$res = $this->gateway->getQuoteOfTheDay($language);
if( count($res) == 0)
return new Quote(-1,"NULL","NULL","NULL","NULL","NULL",0,"Default");
else
$res["content"] = (strlen($res["content"]) > 153) ? substr($res["content"],0,150).'...' : $res["content"];
return new Quote($res["id_quote"],$res["content"],$res["caracter"],$res["imgpath"],$res["title"],$res["dates"],$res["likes"],$res["langue"]) ;
// If no result is found, return a default Quote with an ID of -1 and placeholder values.
if (count($res) == 0) {
return new Quote(-1, "NULL", "NULL", "NULL", "NULL", "NULL", 0, "Default");
} else {
// Truncate the content if it's longer than 153 characters, appending '...' if necessary.
$res["content"] = (strlen($res["content"]) > 153) ? substr($res["content"], 0, 150) . '...' : $res["content"];
// Return the Quote object populated with data from the quote of the day.
return new Quote(
$res["id_quote"], // Quote ID
$res["content"], // Truncated content of the quote
$res["caracter"], // Character associated with the quote
$res["imgpath"], // Image path associated with the quote
$res["title"], // Title of the quote
$res["dates"], // Date the quote was created
$res["likes"], // Number of likes the quote has received
$res["langue"] // Language of the quote
);
}
}
/**
* Retrieves all favorite quotes for a specified user.
*
* @param string $userId The unique identifier of the user.
*
* @return Quote[] Returns an array of Quote objects representing the user's favorite quotes.
*/
public function getFavorites(string $userId): array {
// Fetch the user's favorite quotes from the gateway's getFavorites method.
$res = $this->gateway->getFavorites($userId);
$tabQ=[];
foreach($res as $q ){
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"],0,150).'...' : $q["content"];
$tabQ[]= new Quote($q["id_quote"],$q["content"],$q["caracter"],$q["imgpath"],$q["title"],$q["dates"],$q["likes"],$q["langue"]) ;
// Initialize an empty array to store the resulting Quote objects.
$tabQ = [];
// Loop through the result set and create Quote objects.
foreach ($res as $q) {
// Truncate the content if it's longer than 153 characters, appending '...' if necessary.
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"], 0, 150) . '...' : $q["content"];
// Create a new Quote object and add it to the tabQ array.
$tabQ[] = new Quote(
$q["id_quote"], // Quote ID
$q["content"], // Truncated content of the quote
$q["caracter"], // Character associated with the quote
$q["imgpath"], // Image path related to the quote
$q["title"], // Title of the quote
$q["dates"], // Date the quote was created
$q["likes"], // Number of likes the quote has received
$q["langue"] // Language of the quote
);
}
// Return the array of favorite Quote objects.
return $tabQ;
}
public function insert4User(string $content, string $img_path, string $langage, int $user, int $source, int $character) : bool
{
/**
* Inserts a new quote for a specific user.
*
* @param string $content The content of the quote.
* @param string $img_path The image path associated with the quote.
* @param string $langage The language of the quote.
* @param int $user The ID of the user associated with the quote.
* @param int $source The source of the quote (e.g., the origin of the quote or where it was sourced from).
* @param int $character The character associated with the quote.
*
* @return bool Returns true if the quote was successfully inserted, otherwise false.
*/
public function insert4User(string $content, string $img_path, string $langage, int $user, int $source, int $character): bool {
// Call the gateway's insert4User method to insert the new quote into the database.
return $this->gateway->insert4User($content, $img_path, $langage, $user, $source, $character);
}

@ -1,91 +0,0 @@
<?php
namespace Model;
use Entity\ResultsEntity;
use Gateway\ResultsGateway;
use Gateway\Gateway;
class ResultsModel extends Model
{
public function createResultsModel(int $idQuiz, int $idUser, int $score, int $time) : bool
{
return $this -> gateway -> createResultsGateway($idQuiz, $idUser, $score, $time);
}
public function getResultsByQuiz(int $idQuiz) : array
{
$res = $this -> gateway -> findResultsByQuiz($idQuiz);
$results = [];
foreach ($res as $result)
{
$results[] = new ResultsEntity (
$result['user_r'],
$result['quiz_r'],
$result['score'],
$result['time']
);
}
return $results;
}
public function getResultsByUser(int $idUser) : array
{
$res = $this -> gateway -> findResultsByUser($idUser);
$results = [];
foreach ($res as $result)
{
$results[] = new ResultsEntity (
$result['user_r'],
$result['quiz_r'],
$result['score'],
$result['time']
);
}
return $results;
}
public function getResultsById(int $idQuiz, int $idUser) : ?ResultsEntity
{
$res = $this -> gateway -> findResultsById($idQuiz, $idUser);
if ($res)
{
return new ResultsEntity (
$res['user_r'],
$res['quiz_r'],
$res['score'],
$res['time']
);
}
return null;
}
public function getAllResults() : array
{
$res = $this -> gateway -> findAllResults();
$results = [];
foreach ($res as $result)
{
$results[] = new ResultsEntity (
$result['user_r'],
$result['quiz_r'],
$result['score'],
$result['time']
);
}
return $results;
}
public function updateResultsModel(int $idQuiz, int $idUser, ?int $score, ?int $time) : bool
{
return $this -> gateway -> updateResults($idQuiz, $idUser, $score, $time);
}
}

@ -7,15 +7,41 @@
class SearchModel extends Model
{
public function searchQuote(?string $type,?string $search,array $filtre): array{
/**
* Searches for quotes based on specified filters and search criteria.
*
* @param string|null $type The type of quote to search for (optional).
* @param string|null $search The search term to filter quotes (optional).
* @param array $filtre Additional filters to refine the search (e.g., date range, category).
*
* @return Quote[] Returns an array of Quote objects that match the search criteria and filters.
*/
public function searchQuote(?string $type, ?string $search, array $filtre): array {
// Call the gateway's search method with the provided search criteria and filters.
$res = $this->gateway->search($type, $search, $filtre);
$res = $this->gateway->search($type,$search,$filtre);
$tabQ=[];
// Initialize an empty array to store the resulting Quote objects.
$tabQ = [];
foreach($res as $q ){
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"],0,150).'...' : $q["content"];
$tabQ[]= new Quote($q["id_quote"],$q["content"],$q["caracter"],$q["imgpath"],$q["title"],$q["dates"],$q["likes"],$q["langue"]) ;
// Loop through the search results.
foreach ($res as $q) {
// Truncate the quote content to 150 characters, adding '...' if it's too long.
$q["content"] = (strlen($q["content"]) > 153) ? substr($q["content"], 0, 150) . '...' : $q["content"];
// Create a new Quote object and add it to the tabQ array.
$tabQ[] = new Quote(
$q["id_quote"], // Quote ID
$q["content"], // The content of the quote (truncated if too long)
$q["caracter"], // The character associated with the quote
$q["imgpath"], // The image path associated with the quote (e.g., character image)
$q["title"], // The title of the quote
$q["dates"], // The date when the quote was made
$q["likes"], // The number of likes the quote has received
$q["langue"] // The language of the quote
);
}
// Return the array of Quote objects.
return $tabQ;
}
}

@ -1,112 +1,126 @@
<?php
namespace Model;
use Entity\SourceEntity;
use Enum\TypeSourceEnum;
class SourceModel extends Model
{
/**
* Creates a new source with the provided title, date, and type.
*
* @param string $title The title of the source.
* @param string $date The date associated with the source.
* @param TypeSourceEnum $type The type of the source (e.g., Movie, Book, etc.).
*
* @return bool Returns true if the source was successfully created, false otherwise.
*/
public function createSource(string $title, string $date, TypeSourceEnum $type) : bool
{
$q = new SourceEntity(-1,$title, $date, TypeSourceEnum::Movie/*$type*/);
return $this -> gateway -> create($q);
// Create a new SourceEntity with the given title, date, and type.
// Note: The type is hardcoded as "Movie" in this implementation.
$q = new SourceEntity(-1, $title, $date, TypeSourceEnum::Movie);
// Use the gateway to insert the new source and return the result.
return $this->gateway->create($q);
}
/**
* Retrieves a source by its unique identifier.
*
* @param int $id_source The unique identifier of the source.
*
* @return SourceEntity|null Returns a SourceEntity object if found, or null if no source is found with the given ID.
*/
public function getSourceById(int $id_source) : ?SourceEntity
{
$res = $this -> gateway -> findById($id_source);
if ($res)
return new sourceEntity(
$res[0]["id_source"],
$res[0]["title"],
$res[0]["dates"],
TypeSourceEnum::Movie//from($res[0]["type"])
// Fetch the source by ID using the gateway's findById method.
$res = $this->gateway->findById($id_source);
// If a source is found, return a SourceEntity object.
if ($res) {
return new SourceEntity(
$res[0]["id_source"], // Source ID
$res[0]["title"], // Title of the source
$res[0]["dates"], // Date associated with the source
TypeSourceEnum::Movie // Hardcoded to "Movie" type; you may consider dynamically mapping this
);
}
// Return null if no source is found.
return null;
}
/**
* Retrieves a source by its title.
*
* @param string $title The title of the source to search for.
*
* @return SourceEntity|null Returns a SourceEntity object if found, or null if no source is found with the given title.
*/
public function getSourceByTitle(string $title) : ?SourceEntity
{
// Fetch the source by title using the gateway's findByTitle method.
$res = $this->gateway->findByTitle($title);
if ($res)
return new sourceEntity(
$res[0]["id_source"],
$res[0]["title"],
$res[0]["dates"],
TypeSourceEnum::Movie//from($res[0]["type"])
);
return null;
}
public function getSourceByDate(string $date) : array
{
$res = $this->gateway->findByDate($date);
$src = [];
foreach ($res as $sources) {
$src[] = new sourceEntity(
$sources["id_source"],
$sources["title"],
$sources["dates"],
TypeSourceEnum::from($sources["type"])
// If a source is found, return a SourceEntity object.
if ($res) {
return new SourceEntity(
$res[0]["id_source"], // Source ID
$res[0]["title"], // Title of the source
$res[0]["dates"], // Date associated with the source
TypeSourceEnum::Movie // Hardcoded to "Movie" type; dynamic mapping could be considered
);
}
return $src;
}
public function getSourceByType(TypeSourceEnum $type) : array
{
$res = $this->gateway->findByType($type);
$src = [];
foreach ($res as $sources) {
$src[] = new sourceEntity(
$sources["id_source"],
$sources["title"],
$sources["dates"],
TypeSourceEnum::from($sources["type"])
);
}
return $src;
// Return null if no source is found.
return null;
}
/**
* Retrieves all sources from the database.
*
* @return SourceEntity[] Returns an array of SourceEntity objects representing all the sources.
*/
public function getAllSources() : array
{
$res = $this -> gateway -> findAll();
// Fetch all sources from the gateway's findAll method.
$res = $this->gateway->findAll();
// Initialize an empty array to store the SourceEntity objects.
$src = [];
// Loop through the result and create a SourceEntity object for each source.
foreach ($res as $sources) {
$src[] = new SourceEntity(
$sources["id_source"],
$sources["title"],
$sources["dates"],
TypeSourceEnum::Movie
//TypeSourceEnum::from($sources["type"])
$sources["id_source"], // Source ID
$sources["title"], // Title of the source
$sources["dates"], // Date associated with the source
TypeSourceEnum::Movie // Hardcoded to "Movie" type; you may consider dynamically mapping this
);
}
return $src;
}
public function deleteSource(int $id_source) : bool
{
return $this -> gateway -> delete($id_source);
// Return the array of SourceEntity objects.
return $src;
}
public function updateSource(int $id_source, string $title, string $date) : bool
/**
* Checks if a source with the given name and type exists.
*
* @param string $name The name of the source to check.
* @param string $type The type of the source to check (e.g., Movie, Book, etc.).
*
* @return bool Returns true if the source exists, false otherwise.
*/
public function existSource(string $name, string $type) : bool
{
$q = $this -> getSourceById($id_source);
// Retrieve the source by title using the getSourceByTitle method.
$q = $this->getSourceByTitle($name);
if ($q){
$q -> setTitle($title);
$q -> setDate($date);
return $this -> gateway -> update($q);
}
return false;
}
public function existSource(string $name, string $type) : bool{
$q = $this -> getSourceByTitle($name);
// Check if the source exists and return the result.
return isset($q[0]);
}
}
?>

@ -8,51 +8,55 @@
class UserModel extends Model
{
public function insertUser(string $username,string $email,string $passwd) : bool{
/*global $rep,$image;*/
return $this->gateway->insertUser( $username, $email, $passwd, false, 1);
/**
* Inserts a new user with the provided username, email, and password.
* The account is created with default settings (active and role 1).
*
* @param string $username The username for the new user.
* @param string $email The email address for the new user.
* @param string $passwd The password for the new user.
*
* @return bool Returns true if the user was successfully created, false otherwise.
*/
public function insertUser(string $username, string $email, string $passwd) : bool {
// Calls the gateway method to insert a new user with default settings.
return $this->gateway->insertUser($username, $email, $passwd, false, 1);
}
public function deleteUser(string $id) : bool{
/**
* Deletes a user by their ID.
*
* @param string $id The ID of the user to be deleted.
*
* @return bool Returns true if the user was successfully deleted, false otherwise.
*/
public function deleteUser(string $id) : bool {
// Calls the gateway method to delete the user by their ID.
return $this->gateway->delete($id);
}
// ===================== Get FUNCTION =====================
public function getNumberOfUsers() : int
{
/**
* Retrieves the total number of users in the system.
*
* @return int The total number of users.
*/
public function getNumberOfUsers() : int {
// Calls the gateway method to get the number of users and returns the count.
return $this->gateway->getNumberOfUsers()[0]['count'] ?? 0;
}
// public function getFavoriteUser(string $id) : array{
// $res[0] = array();
// $data = $this->gateway->getFavorite($id);
// foreach ($data as $favoris) {
// $res[0][] = new Quote();
// }
// }
public function getDataUser(int $id) : ?UserEntity {
$res = $this->gateway->findDataUser($id);
if ($res)
return new UserEntity(
$res[0]['id_user'],
$res[0]['username'],
$res[0]['password'],
$res[0]['email'],
$res[0]['img'],
$res[0]['creation']
);
return null;
}
public function getUsername(string $username) : ?UserEntity
{
/**
* Retrieves a user by their username.
*
* @param string $username The username of the user to retrieve.
*
* @return UserEntity|null Returns a UserEntity object if the user is found, or null if not.
*/
public function getUsername(string $username) : ?UserEntity {
// Fetches the user details using the gateway method findUsername.
$res = $this->gateway->findUsername($username);
// If the user is found, return a UserEntity object with the user's details.
if ($res)
return new UserEntity(
$res[0]['id_user'],
@ -62,12 +66,22 @@
$res[0]['imgpath'],
$res[0]['creation']
);
// Return null if no user is found.
return null;
}
public function getEmail(string $email) : ?UserEntity
{
/**
* Retrieves a user by their email.
*
* @param string $email The email of the user to retrieve.
*
* @return UserEntity|null Returns a UserEntity object if the user is found, or null if not.
*/
public function getEmail(string $email) : ?UserEntity {
// Fetches the user details using the gateway method findEmail.
$res = $this->gateway->findEmail($email);
// If the user is found, return a UserEntity object with the user's details.
if ($res)
return new UserEntity(
$res[0]['id_user'],
@ -77,115 +91,214 @@
$res[0]['img'],
$res[0]['creation']
);
// Return null if no user is found.
return null;
}
public function getIdByUsername(string $username){
/**
* Retrieves the user ID based on the username.
*
* @param string $username The username of the user.
*
* @return int The user ID.
*/
public function getIdByUsername(string $username) {
// Fetches the user ID using the gateway method getIdUser.
$res = $this->gateway->getIdUser($username);
return $res[0]['id_user'];
}
public function getEmailWithUser(string $user){
$res = $this->gateway->emailWithUser($user);
return $res[0]['email'];
}
// ===================== Bool FUNCTION =====================
public function IsExisteUsername(string $username):bool{
/**
* Checks if a given username already exists.
*
* @param string $username The username to check.
*
* @return bool Returns true if the username exists, false otherwise.
*/
public function IsExisteUsername(string $username) : bool {
// Checks if the username exists using the gateway method.
return $this->gateway->IsExisteUsername($username);
}
public function IsExisteEmail(string $email):bool{
/**
* Checks if a given email already exists.
*
* @param string $email The email to check.
*
* @return bool Returns true if the email exists, false otherwise.
*/
public function IsExisteEmail(string $email) : bool {
// Checks if the email exists using the gateway method.
return $this->gateway->IsExisteEmail($email);
}
public function isPassWd(string $username, string $passWd): bool {
/**
* Verifies if the provided password matches the stored password hash for the given username.
*
* @param string $username The username for the user.
* @param string $passWd The password to verify.
*
* @return bool Returns true if the password is correct, false otherwise.
*/
public function isPassWd(string $username, string $passWd) : bool {
// Fetches the stored password hash for the username.
$hash = $this->gateway->getPasswordHash($username);
// Verifies the password using password_verify.
return $hash !== null && password_verify($passWd, $hash);
}
public function isFavorite(?string $username, int $idq): bool {
if($_SESSION["user"] == NULL){
/**
* Checks if a quote is marked as a favorite by the current user.
*
* @param string|null $username The username of the user (can be null).
* @param int $idq The ID of the quote to check.
*
* @return bool Returns true if the quote is a favorite, false otherwise.
*/
public function isFavorite(?string $username, int $idq) : bool {
// If the user is not logged in (session is null), return false.
if ($_SESSION["user"] == NULL) {
return false;
}
else{
$res = $this->gateway->inFavorite($_SESSION["user"],$idq);
} else {
// Checks if the quote is in the user's favorites.
$res = $this->gateway->inFavorite($_SESSION["user"], $idq);
return $res;
}
}
// ===================== Set FUNCTION =====================
public function setUsername(string $username, string $newUsername): string {
if ($this->IsExisteUsername($newUsername)) {// Vérifier si le nouveau nom d'utilisateur existe déjà
return $username;// Retourne l'ancien nom d'utilisateur sans modification
/**
* Updates the username for a user.
*
* @param string $username The current username.
* @param string $newUsername The new username to set.
*
* @return string Returns the new username if it was successfully updated, or the current username if the new one already exists.
*/
public function setUsername(string $username, string $newUsername) : string {
// If the new username already exists, return the current username.
if ($this->IsExisteUsername($newUsername)) {
return $username;
}
$res = $this->gateway->updateUsername($username, $newUsername);// Sinon, mettre à jour le nom d'utilisateur
// Updates the username using the gateway method.
$res = $this->gateway->updateUsername($username, $newUsername);
// Retourner le nouveau nom d'utilisateur après modification
// If the update was successful, return the new username.
if (!empty($res) && isset($res[0]['username'])) {
return $res[0]['username'];
}
return $username; // En cas d'échec, retourne l'ancien nom d'utilisateur
// Return the original username if the update was unsuccessful.
return $username;
}
public function setEmail(string $username, string $newEmail){
/**
* Updates the email for a user.
*
* @param string $username The current username.
* @param string $newEmail The new email to set.
*
* @return string Returns the new email if it was successfully updated, or the current username if the new email already exists.
*/
public function setEmail(string $username, string $newEmail) {
// If the new email already exists, return the current username.
if ($this->IsExisteEmail($newEmail)) {
return $username;
}
$res = $this->gateway->updateEmail($username,$newEmail);
// Updates the email using the gateway method.
$res = $this->gateway->updateEmail($username, $newEmail);
// If the update was successful, return the new email.
if (!empty($res) && isset($res[0]['email'])) {
return $res[0]['email'];
}
return $username;// En cas d'échec, retourne l'ancien email
// Return the original username if the update was unsuccessful.
return $username;
}
public function setImage(string $username,string $newImage){
$res = $this->gateway->updateImg($username,$newImage);
/**
* Updates the profile image for a user.
*
* @param string $username The username of the user.
* @param string $newImage The new image path to set.
*
* @return array Returns an array with the new image path.
*/
public function setImage(string $username, string $newImage) {
// Updates the image path using the gateway method.
$res = $this->gateway->updateImg($username, $newImage);
// Returns the updated image path.
$src[] = $res[0]['img'];
return $src;
}
public function setPassWd(string $username, string $newPassWd):void{
$res = $this->gateway->updatePasswd($username,$newPassWd);
/**
* Updates the password for a user.
*
* @param string $username The username of the user.
* @param string $newPassWd The new password to set.
*/
public function setPassWd(string $username, string $newPassWd) : void {
// Updates the password using the gateway method.
$res = $this->gateway->updatePasswd($username, $newPassWd);
}
public function addFavorite(string $username, int $id){
$this->gateway->addFavorite($username,$id);
/**
* Adds a quote to the user's favorites.
*
* @param string $username The username of the user.
* @param int $id The ID of the quote to add.
*/
public function addFavorite(string $username, int $id) {
// Adds the quote to the user's favorites.
$this->gateway->addFavorite($username, $id);
}
public function supFavorite(string $username, int $id){
$this->gateway->supFavorite($username,$id);
/**
* Removes a quote from the user's favorites.
*
* @param string $username The username of the user.
* @param int $id The ID of the quote to remove.
*/
public function supFavorite(string $username, int $id) {
// Removes the quote from the user's favorites.
$this->gateway->supFavorite($username, $id);
}
// ===================== DELETE FUNCTION =====================
public function deleteAllCommentary(string $username){
/**
* Deletes all comments made by the specified user.
*
* @param string $username The username of the user.
*/
public function deleteAllCommentary(string $username) {
// Deletes all comments made by the user.
$this->gateway->deleteAllCommentaryUser($username);
}
public function deleteAllFavorite(string $username){
/**
* Deletes all favorite quotes of the specified user.
*
* @param string $username The username of the user.
*/
public function deleteAllFavorite(string $username) {
// Deletes all favorite quotes of the user.
$this->gateway->deleteAllFavoriteUser($username);
}
public function deleteAccount(string $username){
/**
* Deletes the user's account.
*
* @param string $username The username of the user to delete.
*/
public function deleteAccount(string $username) {
// Deletes the user's account.
$this->gateway->deleteUser($username);
}
}
?>

Loading…
Cancel
Save