Compare commits

..

1 commit

Author SHA1 Message Date
39a2e8f707 Mettre à jour 'televerser.php'
Ajout et modification de champs
2024-01-27 12:08:01 +01:00
43 changed files with 929 additions and 11086 deletions

View file

@ -1,4 +0,0 @@
<?php
$page = str_replace(".php","",basename($_SERVER['SCRIPT_FILENAME']));
?>
<script type="text/javascript" src="js/<?=$page?>.js"></script>

View file

@ -1,13 +0,0 @@
<?php
//header("Content-Security-Policy: default-src 'self'; connect-src 'self'; script-src 'self'; img-src 'self'; font-src 'self'; media-src 'self'; frame-src 'self'; sandbox allow-forms; object-src 'none'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; worker-src 'none'; manifest-src : 'none'; prefetch-src : 'none'; navigate-to 'self';")
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php
$page = str_replace(".php","",basename($_SERVER['SCRIPT_FILENAME']));
?>
<title><?=$titre_page?></title>
<link rel="stylesheet" href="css/<?=$page?>.css">
</head>

171
api.md Normal file
View file

@ -0,0 +1,171 @@
# API PHP
Ce document décrit le comportement de l'api utilisée par le site
## Endpoints
### Authentification
- **Endpoint:** `auth.php?auth`
- **Description:** Authentifie l'utilisateur et initialise une session.
- **Méthode HTTP:** GET
- **Réponse JSON:**
```json
{
"status": 1,
"msg": "Authentification réussie."
}
```
En cas d'erreur :
```json
{
"status": 0,
"msg": "Erreur pendant le traitement de la requête."
}
### Déconnexion
- **Endpoint:** `auth.php?unauth`
- **Description:** Déconnecte l'utilisateur en mettant fin à la session.
- **Méthode HTTP:** GET
- **Réponse JSON:**
```json
{
"status": 1,
"msg": "Déconnexion réussie."
}
```
### Test d'authentification
- **Endpoint:** `auth.php?test_auth`
- **Description:** Vérifie si l'utilisateur est authentifié.
- **Méthode HTTP:** GET
- **Réponse JSON:**
- Si l'utilisateur est authentifié :
```json
{
"status": 1,
"msg": "Utilisateur bien authentifié."
}
```
- Si l'utilisateur n'est pas authentifié :
```json
{
"status": 4,
"msg": "Utilisateur non authentifié."
}
```
## Statuts de réponse
- **Status 1 :** Requête valide.
- **Status 0 :** Erreur pendant le traitement de la requête.
- **Status 2 :** Requête invalide.
- **Status 3 :** Session expirée.
- **Status 4 :** Utilisateur non authentifié, requête interdite.
## Gestion des sessions
Le fichier `session_verif.php` est inclus pour la gestion des sessions. Assurez-vous qu'il est présent et correctement configuré.
---
**Remarque :** Ce document est une documentation basique. Assurez-vous d'ajuster et d'améliorer la sécurité en fonction des besoins spécifiques de votre application.
## upload de plusieurs fichiers :
```javascript
async function uploadMultiple(donneesFormulaires) {
try {
const reponse = await fetch("https://example.com/api", {
method: "POST",
body: donneesFormulaires,
});
const resultat = await reponse.json();
console.log("Réussite :", resultat);
} catch (erreur) {
console.error("Erreur :", erreur);
}
}
const docs = document.querySelector('input[type="file"][multiple]');
const donneesFormulaires = new FormData();
donneesFormulaires.append("title", "documents");
for (const [i, doc] of Array.from(docs.files).entries()) {
donneesFormulaires.append(`doc_${i}`, doc);
}
uploadMultiple(donneesFormulaires);
```
## upload de données json
```javascript
async function postJSON(donnees) {
try {
const reponse = await fetch("https://example.com/profile", {
method: "POST", // ou 'PUT'
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(donnees),
});
const resultat = await reponse.json();
console.log("Réussite :", resultat);
} catch (erreur) {
console.error("Erreur :", erreur);
}
}
const donnees = { login: "Jean Biche" };
postJSON(donnees);
```
## récupérer des documents
``` javascript
async function fetchImage() {
try {
const response = await fetch("flowers.jpg");
if (!response.ok) {
throw new Error("La réponse n'est pas OK");
}
const myBlob = await response.blob();
monImage.src = URL.createObjectURL(myBlob);
} catch (error) {
console.error("Un problème est survenu lors de la récupération :", error);
}
}
```
[source](https://developer.mozilla.org/fr/docs/Web/API/Fetch_API/Using_Fetch)
## récupérer des données
``` javascript
async function test_auth(){
resp = await fetch("/annales/api.php?test_auth");
data = await resp.json();
document.getElementById("user_status").innerText = data["msg"];
}
async function unauthenticate_user(){
resp = await fetch("/annales/api.php?unauth");
data = await resp.json();
if(data.status == 1){
document.getElementById("user_status").innerText = data["msg"];
}
}
```

247
api.php
View file

@ -11,13 +11,10 @@
*/
include("session_verif.php");
include("bdd.php");
include('php-csrf.php');
include_once("utils/sendmail.php");
include_once("utils/token.php");
include_once("utils/inputs.php");
$csrf = new CSRF();
@ -39,31 +36,49 @@
$endpoint = explode("?",array_pop($url_parts))[0];
switch($endpoint){
case 'auth':
try{
$_SESSION["utilisateur_authentifie"] = true;
session_regenerate_id(true);
$_SESSION["heure_debut"] = time();
echo(json_encode(["status"=>"1","msg"=>"Authentification réussie."]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
case 'unauth':
$_SESSION["utilisateur_authentifie"] = false;
echo json_encode(["status"=>"1","msg"=>"Déconnection réussie."]);
session_destroy();
session_abort();
break;
case 'test_auth':
if($_SESSION["utilisateur_authentifie"] == true){
echo(json_encode(["status"=> "1","msg"=> "Utilisateur bien authentifié."]));
}else{
echo(json_encode(["status"=> "4","msg"=> "Utilisateur non authentifié."]));
}
break;
case 'rechercher':
if(isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1)){
// Exemple URL: /api.php/chercher?req=math&duree=30&themes=algebre,geometrie
$query = isset($_GET["req"]) ? $_GET["req"] : "";
$length = isset($_GET["duree"]) ? $_GET["duree"] : "";
$themes = isset($_GET["themes"]) ? explode(",", $_GET["themes"]) : [];
$tout_les_insa = isset($_GET["tout_les_insa"]) ? true : false;
//print_r($_GET);
try {
$results = RechercheExercices($query, $length, $themes,$tout_les_insa);
echo json_encode(["status" => "1", "resultats" => $results]);
} catch (Exception $e) {
echo json_encode(["status" => "0", "msg" => $e->getMessage()]);
}
// Exemple URL: /api.php/chercher?req=math&duree=30&themes=algebre,geometrie
}else{
echo json_encode(["status" => "1", "resultats" => []]);
$query = isset($_GET["req"]) ? $_GET["req"] : "";
$length = isset($_GET["duree"]) ? $_GET["duree"] : "";
$themes = isset($_GET["themes"]) ? explode(",", $_GET["themes"]) : [];
//print_r($_GET);
try {
$results = RechercheExercices($query, $length, $themes);
echo json_encode(["status" => "1", "resultats" => $results]);
} catch (Exception $e) {
echo json_encode(["status" => "0", "msg" => $e->getMessage()]);
}
break;
case 'decomposer_ensemble':
@ -137,44 +152,16 @@
case "generer_chronologie":
try{
if(isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1)){
$res = generer_chronologie();
echo(json_encode(["status"=>"1","resultats"=>$res]));
try{
$res = generer_chronologie();
echo(json_encode(["status"=>"1","resultats"=>$res]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
}else{
echo(json_encode(["status"=>"1","resultats"=>[]]));
}
break;
case "verification_inscription":
$succes = isset($_GET["token"]);
if(!$succes){
return $succes;
}
$token = htmlspecialchars($_GET["token"]);
$succes = verifier_utilisateur($token);
if($succes){
header("Location: /utilisateur_valide.php");
//echo( json_encode(["status"=> 1,"msg"=> "Utilisateur verifié !" ]) );
}else{
echo( json_encode(["status"=> "0","msg"=> "Une erreur est survenue lors de votre vérification ou vous avez essayé de modifier le contenu de la requête :/" ]) );
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
default:
@ -192,141 +179,53 @@
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$user_auth = isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1);
$admin_auth = $user_auth && isset($_SESSION["admin"]) && ($_SESSION["admin"] == 1);
verifier_session();
switch(array_pop($url_parts)){
case "aj_doc":
if($user_auth){
/*if(!$csrf->validate($context='televersement',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant ou invalide. ( contenu du champ : ".$_POST["jeton-csrf"]." )"]) );
break;
}*/
try{
ajouter_doc($_POST);
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
}else{
if(!$csrf->validate($context='televersement',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant.".$_POST["jeton-csrf"]]) );
break;
}
try{
ajouter_doc($_POST);
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
case "valider_ensemble":
if($admin_auth){
if(!$csrf->validate($context='valider_ensemble',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant.".$_POST["jeton-csrf"]]) );
break;
}
try{
valider_ensemble($_POST["ensemble_id"]);
echo(json_encode(["status"=>"1","msg"=>"Ensemble validé."]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
if(!$csrf->validate($context='valider_ensemble',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant.".$_POST["jeton-csrf"]]) );
break;
}
try{
valider_ensemble($_POST["ensemble_id"]);
echo(json_encode(["status"=>"1","msg"=>"Ensemble validé."]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
case "supprimer_ensemble":
if($admin_auth){
if(!$csrf->validate($context='supprimer_ensemble',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant." ]) );
break;
}
try{
supprimer_ensemble($_POST["ensemble_id"]);
echo(json_encode(["status"=>"1","msg"=>"Ensemble supprimé."]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
}
break;
case "connection":
if(!$csrf->validate($context='connection',$_POST["jeton-csrf"])){
if(!$csrf->validate($context='supprimer_ensemble',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant." ]) );
break;
}
$username = $_POST['username'];
$password = $_POST['password'];
$succes = connecter_utilisateur(htmlspecialchars($username),$password);
if($succes){
echo( json_encode(["status"=> "1","msg"=> "Utilisateur connecté !" ]) );
}else{
echo( json_encode(["status"=> "0","msg"=> "Utilisateur inconnu, non vérifié par mel ou informations d'identification erronées." ]) );
try{
supprimer_ensemble($_POST["ensemble_id"]);
echo(json_encode(["status"=>"1","msg"=>"Ensemble supprimé."]));
}catch(Exception $e){
echo( json_encode(["status"=> "0","msg"=> $e->getMessage() ]) );
}
break;
case "deconnection":
if(!$csrf->validate($context='deconnection',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant." ]) );
break;
}
session_destroy();
echo( json_encode(["status"=> "1","msg"=> "Utilisateur déconnecté !" ]) );
break;
case "inscription":
if(!$csrf->validate($context='inscription',$_POST["jeton-csrf"])){
echo( json_encode(["status"=> "2","msg"=>"jeton csrf manquant." ]) );
break;
}
$username = $_POST['username'];
$password = $_POST['password'];
$nom_insa = $_POST['nom_insa'];
$username = assainir_et_valider_mel($username);
if($username == "[ERREUR_MEL_MALSAINT]"){
echo(json_encode(["status"=> "2","msg"=> "Votre adresse mel n'a pas passé les filtres de sécurité :/ ( MOUAHAHAHAHA )" ]));
break;
}
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$token = inscription_utilisateur(htmlspecialchars($username),$password_hash,$nom_insa);
$succes = $token != "[ERREUR]";
if($succes){
$mailtest = new Mail();
$mailtest->setContent(
"Inscription sur Arch'INSA",
"https://annales.insat.fr/api.php/verification_inscription?token=".$token,
"Salut Salut !!",
"La validation du compte permettra de vous connecter et de publier du contenu sur Arch'INSA :D",
);
if(!$mailtest->send($username, "Eh toi là !")) {
echo $mailtest->getError(); //si le mail n'a pas été envoyé
$succes = false;
}
}
if($succes){
echo( json_encode(["status"=> 1,"msg"=> "Pour finaliser l'inscription et pouvoir vous connecter, veuillez valider votre compte via le mel que nous vous avons envoyé :)" ]) );
}else{
echo( json_encode(["status"=> 0,"msg"=> "Une erreur est survenue lors de votre inscription ou vous avez essayé de modifier le contenu de la requête :/" ]) );
}
break;
default:
echo(json_encode(["status"=> "2","msg"=> "Opération inconnue."]));
}
@ -334,4 +233,4 @@
exit;
}
?>

252
bdd.php
View file

@ -2,22 +2,14 @@
include("test_creds.php");
include_once("utils/token.php");
$conn = new mysqli($servername, $db_username, $db_password,$dbname);
$conn = new mysqli($servername, $username, $password,$dbname);
$uploadDir = 'archives/';
// le type de document est classifié entre 0 et n dans l'ensemble des entiers naturels
$max_val_type = 3;
/*
1 : texte
2 : image
3 : pdf
0 : non supporté
-1 : erreur
*/
// Liste des extensions autorisées pour les images
$image_extensions = [
@ -40,16 +32,14 @@ $pdf_extensions = ['pdf'];
$presentation_extensions = ['ppt', 'pptx','odp','pptm','ppsx'];
// pour les fonctions speciales comme les quiz html...
// ATTENTION ! NE PAS INCLURE PHP GRAND FOU QUE VOUS ETES
$ext_speciales = ["html","sh","txt","adb","ads","py","ipynb","c","cpp","rs","go","asm","js","java","md"];
$ext_speciales = ["html"];
// Fusionner les listes en une seule liste
$ext_autorisees = array_merge($image_extensions, $pdf_extensions, $presentation_extensions,$ext_speciales);
function check_ext($filename) {
global $ext_autorisees;
$extension = pathinfo($filename, PATHINFO_EXTENSION);
return in_array(strtolower($extension), $ext_autorisees);
return in_array(strtolower($extension), $GLOBALS["ext_autorisees"]);
}
@ -63,15 +53,18 @@ function ajouter_doc($request){
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ensembles (commentaire_auteur,corrige_inclu,date_conception,id_auteur) VALUES(?,?,?,?)";
$sql = "INSERT INTO ensembles (commentaire_auteur,corrige_inclu,date_conception) VALUES(?,?,?)";
try{
$stm = $conn->prepare($sql);
$request['commentaire_auteur'] = htmlentities($request["commentaire_auteur"]);
print_r($request);
$request['commentaire_auteur'] = htmlspecialchars($request["commentaire_auteur"]);
$request["corrige_inclu"] = boolval($request["corrige_inclu"]);
$request["date_conception"] = htmlentities($request["date_conception"]);
$stm->bind_param("sisi",$request['commentaire_auteur'],$request["corrige_inclu"],$request["date_conception"],$_SESSION["user_id"]);
$request["date_conception"] = htmlspecialchars($request["date_conception"]);
$stm->bind_param("sis",$request['commentaire_auteur'],$request["corrige_inclu"],$request["date_conception"]);
echo "test2";
$stm->execute();
echo "test3";
//$conn->execute_query($sql,array(htmlspecialchars($request['commentaire_auteur']),boolval($request["corrige_inclu"])));
saveFilesFromPost($request,mysqli_insert_id($conn));
@ -95,24 +88,19 @@ function saveFilesFromPost($postData,$id_ensemble) {
// Iterate through each file in the $_FILES array
$safe_type = intval($postData['type']);
$i = 0;
//var_dump($_FILES);
var_dump($_FILES);
foreach ($_FILES as $file) {
$safe_type = checkFileTypeSecure($file['tmp_name']);
// Extract file information
if (isset($file['name'])){
$fileName = htmlspecialchars($file['name']);
// Create a unique filename to avoid overwriting existing files
$uniqueFileName = uniqid() . '_' . $fileName;
// le dernier check est pour autoriser l'upload de fichiers html aux admins
if(!check_ext($fileName) || $safe_type == 0 || ($safe_type == 5 && !$_SESSION["admin"])){
echo(json_encode(["status"=>"0","msg"=>"le fichier '$fileName' n'a pas passé les filtres de contenu. ( dommaaaaggee :c )"]));
if(!check_ext($fileName)){
echo(json_encode(["status"=>"0","msg"=>"Error saving file '$uniqueFileName'"]));
exit;
}
@ -121,7 +109,8 @@ function saveFilesFromPost($postData,$id_ensemble) {
print_r($file);
}
// Create a unique filename to avoid overwriting existing files
$uniqueFileName = uniqid() . '_' . $fileName;
// Define the path to save the file
$filePath = $GLOBALS['uploadDir'] . $uniqueFileName;
@ -132,12 +121,14 @@ function saveFilesFromPost($postData,$id_ensemble) {
// Save the file
$f = fopen($file['tmp_name'],"r");
//echo fread($f,filesize($file['tmp_name']));
echo fread($f,filesize($file['tmp_name']));
fclose($f);
if (!move_uploaded_file($file['tmp_name'], $filePath)) {
echo(json_encode(["status"=>"0","msg"=>"Error saving file to '$filePath'"]));
if (move_uploaded_file($file['tmp_name'], $filePath)) {
echo(json_encode(["status"=>"1","msg" =>"File '$uniqueFileName' has been saved successfully."]));
} else {
echo(json_encode(["status"=>"0","msg"=>"Error saving file '$uniqueFileName'"]));
exit;
}
@ -199,7 +190,7 @@ function saveFilesFromPost($postData,$id_ensemble) {
$row = mysqli_fetch_assoc($result);
$id_theme = $row["id"];
}else{
//echo("creation d'un theme");
echo("creation d'un theme");
$sql = "INSERT INTO themes (name) VALUES(?)";
$conn->execute_query($sql,array($theme));
@ -210,7 +201,7 @@ function saveFilesFromPost($postData,$id_ensemble) {
// ensuite, on enregistre les qui lui sont associés
$sql= 'INSERT INTO exercices_themes (exercice_id,ensemble_id,theme_id) VALUES(?,?,?)';
$result = $conn->execute_query($sql,array($id_exo,$id_ensemble,$id_theme));
//echo("enregistrement d'un exercice");
echo("enregistrement d'un exercice");
}
}
@ -223,7 +214,6 @@ function saveFilesFromPost($postData,$id_ensemble) {
}
echo(json_encode(["status"=>"1","msg" =>"Files has/have been saved successfully."]));
} else {
@ -232,86 +222,67 @@ function saveFilesFromPost($postData,$id_ensemble) {
}
}
function RechercheExercices($query, $length, $tags, $tout_les_insa)
function RechercheExercices($query, $length, $tags)
{
global $conn;
// Start with the base SQL query
$sql = "SELECT * FROM documents AS d INNER JOIN ensembles AS e ON d.ensemble_id = e.id JOIN users as u ON u.id=e.id_auteur WHERE e.valide=TRUE";
// Build the SQL query based on the search parameters
$sql = "SELECT * FROM documents AS d INNER JOIN ensembles AS e ON d.ensemble_id = e.id WHERE e.valide=TRUE ";
// Array to hold the parameters
$params = [];
$types = ""; // Types for the bind_param function
$conditions = [];
// Handle the INSA restriction
if (!$tout_les_insa) {
$sql .= " AND u.nom_insa = ?";
$params[] = $_SESSION["nom_insa"];
$types .= "s"; // Assuming nom_insa is a string
}
// Handle the search query
if (!empty($query)) {
$query_words = preg_split("/\s+/", htmlspecialchars($query));
// va essayer de retrouver tout les mots de la requête dans le titre
$query = htmlspecialchars($query);
$query_words = preg_split("[ ]",$query);
foreach ($query_words as $word) {
$sql .= " AND titre LIKE ?";
$params[] = "%$word%";
$types .= "s";
$conditions[] = "AND titre LIKE '%$word%'";
}
}
// Handle the length filter
if (!empty($length)) {
$sql .= " AND duree = ?";
$params[] = $length;
$types .= "i"; // Assuming duree is an integer
$conditions[] = "duree = $length";
}
// Handle the tags filter
if (!empty($tags)) {
foreach ($tags as $tag) {
$tagConditions = array_map(function ($tag) {
$tag = htmlspecialchars($tag);
$sql .= " AND EXISTS (SELECT * FROM exercices_themes AS et INNER JOIN themes AS t ON et.exercice_id = t.id WHERE et.theme_id = t.id AND t.name = ?)";
$params[] = $tag;
$types .= "s";
}
return "EXISTS (SELECT * FROM exercices_themes AS et INNER JOIN themes AS t ON et.exercice_id = t.id WHERE et.theme_id = t.id AND t.name = '$tag')";
}, $tags);
$conditions[] = implode(" AND ", $tagConditions);
}
// Prepare the SQL statement
$stmt = $conn->prepare($sql);
if ($stmt === false) {
throw new Exception("Error preparing the query: " . $conn->error);
}
// Bind the parameters dynamically
if (!empty($params)) {
$stmt->bind_param($types, ...$params);
}
$sql .= implode(" AND ", $conditions);
//echo $sql;
// Execute the query
if (!$stmt->execute()) {
throw new Exception("Error executing the search query: " . $stmt->error);
$result = $conn->query($sql);
if (!$result) {
throw new Exception("Error executing search query: " . $conn->error);
}
// Fetch the results
$result = $stmt->get_result();
$exercises = [];
while ($row = $result->fetch_assoc()) {
$exercises[] = $row;
}
// Clean up
$stmt->close();
$conn->close();
return $exercises;
}
}
function valider_ensemble($ensembleId) {
$sql = "UPDATE ensembles SET valide = 1 WHERE id = $ensembleId";
@ -349,11 +320,12 @@ function generer_chronologie(){
global $conn;
// on va choper les 10 derniers trucs televerses par les gens
$sql = "SELECT * FROM ensembles WHERE valide=1 ORDER BY date_televersement DESC LIMIT 10";
$sql = "SELECT * FROM ensembles WHERE valide=1 ORDER BY date_televersement DESC ";
$res = $conn->execute_query($sql);
$i = 0;
$ensembles = array();
while (($ens = $res->fetch_assoc())){
while (($ens = $res->fetch_assoc()) && $i < 10){
array_push($ensembles,$ens);
@ -363,7 +335,7 @@ function generer_chronologie(){
// on rajoute le chemin vers chaque document présent dans l'ensemble
$resultat_complet = array();
foreach($ensembles as $ens){
$sql = "SELECT titre,upload_path,ensemble_id,type FROM documents WHERE ensemble_id=?";
$sql = "SELECT titre,upload_path,ensemble_id FROM documents WHERE ensemble_id=?";
$res = $conn->execute_query($sql,array($ens["id"]));
$ens["documents"] = array();
while($doc = $res->fetch_assoc()){
@ -378,122 +350,4 @@ function generer_chronologie(){
return $resultat_complet;
}
function connecter_utilisateur($username,$password){
global $conn;
$ret = false;
$stmt = $conn->prepare("SELECT id,password_hash,admin,nom_insa FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id,$password_hash,$admin,$nom_insa);
$ret = $stmt->fetch();
if (password_verify($password, $password_hash)) {
$_SESSION["utilisateur_authentifie"] = true;
$_SESSION["username"] = $username;
$_SESSION["admin"] = $admin;
$_SESSION["nom_insa"] = $nom_insa;
$_SESSION["user_id"] = $id;
$ret = true;
}
}
$stmt->close();
if($ret){
$ret=utilisateur_est_verifie($id);
}
return $ret;
}
function inscription_utilisateur($username,$password_hash,$nom_insa){
global $conn;
if(!in_array($nom_insa,["insa_toulouse","insa_lyon","insa_rennes","insa_cvl","insa_hdf","insa_rouen","insa_strasbourg","insa_hdf"])){
$ret = 0;
return $ret;
}
$stmt = $conn->prepare("INSERT INTO users (username, password_hash,nom_insa) VALUES (?, ?,?)");
$stmt->bind_param("sss", $username, $password_hash,$nom_insa);
$ret = $stmt->execute();
$stmt->close();
$tok = new Token();
$user_id = mysqli_insert_id($conn);
$tok->Add($user_id);
/*
if($ret){
// met le statut de l'utilisateur à connecté pour lui eviter de se connecter just après l'inscription
$_SESSION["utilisateur_authentifie"] = true;
$_SESSION["username"] = $username;
$_SESSION["admin"] = 0;
$_SESSION["nom_insa"] = $nom_insa;
$_SESSION["user_id"] = $conn->insert_id;
}*/
if($ret){
return $tok->getToken($user_id);
}else{
return "[ERREUR]";
}
}
function verifier_utilisateur($token){
global $conn;
$ret = false;
$t_instance = new Token();
$user_id = $t_instance->getUserID($token);
if($t_instance->isValid($user_id, $token) && $user_id != -1) {
$t_instance->delete($user_id, $token);
$stmt = $conn->prepare("UPDATE users SET verifie=? WHERE id = ?");
$val=1;
$stmt->bind_param("ss",$val,$user_id);
$ret = $stmt->execute();
$stmt->close();
}
return $ret;
}
function utilisateur_est_verifie($user_id){
global $conn;
$stmt = $conn->prepare("SELECT verifie FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->store_result();
$ret = $stmt->num_rows > 0;
$verif = 0;
if($ret){
$stmt->bind_result($verif);
$ret = $stmt->fetch();
$stmt->close();
}
return $ret && ($verif == 1);
}
?>

View file

@ -1,55 +0,0 @@
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="fr">
<?php
$titre_page = "Connection sur Arch'INSA";
include "_partials/_head.php";
include('php-csrf.php');
$csrf = new CSRF();
?>
<body>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
</div>
<div class="formulaire">
<input class="champ" id="username-input" type="text" name="username" placeholder="Nom d'utilisateur" required>
<input class="champ" id="password-input" type="password" name="password" placeholder="Mot de passe" required>
<button class="submit-button color-red-tr" onclick="connection()">Se connecter</button>
</div>
<div class="ascii-art">
⢀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠙⠻⢶⣄⡀⠀⠀⠀⢀⣤⠶⠛⠛⡇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣇⠀⠀⣙⣿⣦⣤⣴⣿⣁⠀⠀⣸⠇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣡⣾⣿⣿⣿⣿⣿⣿⣿⣷⣌⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣷⣄⡈⢻⣿⡟⢁⣠⣾⣿⣦⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿⣿⣿⠘⣿⠃⣿⣿⣿⣿⡏⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠈⠛⣰⠿⣆⠛⠁⠀⡀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣦⠀⠘⠛⠋⠀⣴⣿⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣶⣾⣿⣿⣿⣿⡇⠀⠀⠀⢸⣿⣏⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠀⠀⠀⠾⢿⣿⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⣿⣿⣿⣿⣿⣿⡿⠟⠋⣁⣠⣤⣤⡶⠶⠶⣤⣄⠈⠀⠀⠀⠀⠀⠀
⠀⠀⠀⢰⣿⣿⣮⣉⣉⣉⣤⣴⣶⣿⣿⣋⡥⠄⠀⠀⠀⠀⠉⢻⣄⠀⠀⠀⠀⠀
⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣋⣁⣤⣀⣀⣤⣤⣤⣤⣄⣿⡄⠀⠀⠀⠀
⠀⠀⠀⠀⠙⠿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠋⠉⠁⠀⠀⠀⠀⠈⠛⠃⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
</div>
</body>
<?php
echo $csrf->script($context='connection', $name='jeton_csrf', $declaration='var', $time2Live=-1, $max_hashes=5);
include "_partials/_footer.php";
?>
</html>

View file

@ -1,123 +0,0 @@
.gros-titre{
font-size: larger;
font-weight: bolder;
}
.centre-vertical{
margin-top: auto;
margin-bottom: auto;
}
.centre-horizontal{
margin: auto;
justify-content: center;
}
.centre-txt{
text-align: center;
}
.etaler{
width: 100%;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.button{
margin-top: 10px;
width: fit-content;
padding-top: 1%;
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
border-radius: 5px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.color-green-tr{
background-color: rgba(71, 224, 54, 0.482);
border-color: rgba(71, 224, 54, 0.482);
}
.barre-recherche{
margin-top: 10px;
width: 80vw;
max-width: 800px;
border-radius: 15px;
border-width: 5px;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
background-color: rgba(224, 54, 54, 0.482);
padding: 20px;
}
.champ{
margin-left: auto;
margin-right: auto;
display: block;
font-size: larger;
margin-top: 1vw;
}
.champ-titre{
font-size: larger;
margin-top: 1vw;
}
.formulaire{
margin-top: 5vw;
width: 50vw;
margin-left: 25vw;
margin-right: 25vw;
}
.submit-button{
margin-top: 5vh;
width: fit-content;
padding-top: 5%;
padding-left: 5%;
padding-right: 5%;
padding-bottom: 5%;
border-radius: 5px;
font-weight:bolder;
font-size: xx-large;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
margin-left: auto;
margin-right: auto;
display: block;
}
.ascii-art {
text-align: center;
margin-left: auto;
margin-right: auto;
font-size: 20px;
font-family: monospace;
white-space: pre;
}

View file

@ -1,115 +0,0 @@
.gros-titre{
font-size: larger;
font-weight: bolder;
}
.centre-vertical{
margin-top: auto;
margin-bottom: auto;
}
.centre-horizontal{
margin: auto;
justify-content: center;
}
.centre-txt{
text-align: center;
}
.etaler{
width: 100%;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.button{
margin-top: 10px;
width: fit-content;
padding-top: 1%;
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
border-radius: 5px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.color-green-tr{
background-color: rgba(71, 224, 54, 0.482);
border-color: rgba(71, 224, 54, 0.482);
}
.barre-recherche{
margin-top: 10px;
width: 80vw;
max-width: 800px;
border-radius: 15px;
border-width: 5px;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
background-color: rgba(224, 54, 54, 0.482);
padding: 20px;
}
.champ{
margin-left: auto;
margin-right: auto;
display: block;
font-size: larger;
margin-top: 1vw;
}
.champ-titre{
font-size: larger;
margin-top: 1vw;
}
.formulaire{
margin-top: 5vw;
width: 50vw;
margin-left: 25vw;
margin-right: 25vw;
}
.submit-button{
margin-top: 5vh;
width: fit-content;
padding-top: 5%;
padding-left: 5%;
padding-right: 5%;
padding-bottom: 5%;
border-radius: 5px;
font-weight:bolder;
font-size: xx-large;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
margin-left: auto;
margin-right: auto;
display: block;
}

View file

@ -1,177 +0,0 @@
@media only screen and (orientation: portrait){
.gros-titre{
width: 90vw;
overflow-x: hidden;
font-weight: bolder;
font-size: small;
}
}
@media only screen and (min-width: 1000px){
.gros-titre {
font-size: larger;
font-weight: bolder;
}
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
th,
td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
font-weight: bold;
color: #333;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:hover {
background-color: #ddd;
}
/* Add some spacing around the table */
#data-container {
padding: 20px;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.centre-txt{
text-align: center;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.centre-horizontal{
margin: auto;
justify-content: center;
}
.card {
background-color: #f6f3f3;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
padding: 20px;
}
.card img {
width: 100%;
height: auto;
margin-bottom: 10px;
border-radius: 7px;
}
.card textarea{
width: 100%;
height: 100vh;
margin-bottom: 10px;
border-radius: 7px;
}
.card embed{
width: 100%;
height: 50vh;
margin-bottom: 10px;
}
.card iframe {
width: 100%;
height: 50vh;
}
.card video {
width: 100%;
height: auto;
}
.card div {
margin-bottom: 10px;
line-height: 1.5;
}
.card ul {
padding-left: 20px;
margin-bottom: 10px;
}
.card a{
width: fit-content;
grid-column: auto;
}
/* Styles pour les titres importants */
.title {
font-size: 20px;
font-weight: bold;
color: #333;
margin-top: 10px;
}
/* Styles pour le texte principal */
.main-text {
margin-top: 10px;
font-size: 16px;
color: #555;
}
/* Styles pour les liens */
.lien {
color: #007bff;
text-decoration: none;
padding: 10px;
background-color: rgba(224, 54, 54, 0.482);
border-bottom: 2px solid rgba(224, 54, 54, 0.482);
border-radius: 5px;
margin-bottom: 30px;
}
.lien:hover {
text-decoration: underline;
}
/* Styles pour les informations secondaires */
.secondary-text {
margin-top: 10px;
font-size: 14px;
color: #777;
}

View file

@ -1,258 +0,0 @@
@media only screen and (orientation: portrait){
/* For mobile phones: */
.floating-action-btn{
width: auto;
text-align: left;
border-radius: 5px;
border-width: 2px;
font-weight:bolder;
text-decoration: none;
color: black;
background-color: rgba(224, 54, 54, 0.482);
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
position: fixed;
bottom: 2vh;
margin-top: 50vh;
right: 1vw;
padding-left: 10px;
padding-right: 10px;
padding-bottom: 9px;
}
.gros-titre{
width: 90vw;
overflow-x: hidden;
font-weight: bolder;
font-size: small;
}
.ligne-boutons{
display: grid;
}
.ligne-boutons #lien{
grid-row: auto;
}
.card{
width: 85vw;
}
}
@media only screen and (min-width: 1000px) {
/* For desktop: */
.floating-action-btn{
position: fixed;
margin-left:1%;
padding: 10px;
padding-top: 0px;
width: fit-content;
text-align: left;
border-radius: 5px;
border-width: 2px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
right: 1vw;
padding-left: 10px;
padding-right: 10px;
padding-bottom: 9px;
bottom:2vh;
}
.gros-titre{
font-size: larger;
font-weight: bolder;
}
.card {
width: 70vw;
}
}
.centre-vertical{
margin-top: auto;
margin-bottom: auto;
}
.centre-horizontal{
margin: auto;
justify-content: center;
display: flex;
}
.centre-txt{
text-align: center;
}
.etaler{
width: 100%;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.button{
margin-top: 10px;
width: fit-content;
padding-top: 1%;
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
border-radius: 5px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.barre-recherche{
margin-top: 10px;
width: 80vw;
max-width: 800px;
border-radius: 15px;
border-width: 5px;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
background-color: rgba(224, 54, 54, 0.482);
padding: 20px;
}
#recherche_input{
width: 80vw;
max-width: 800px;
}
.champ{
border-radius: 3px;
border: 0px;
background-color: transparent;
font-size: larger;
width: fit-content;
}
.champ:focus{
outline: none;
}
.card {
background-color: #f6f3f3;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
padding: 20px;
}
.card img {
width: 100%;
height: auto;
margin-bottom: 10px;
border-radius: 7px;
}
.card textarea{
width: 100%;
height: 100vh;
margin-bottom: 10px;
border-radius: 7px;
}
.card embed{
width: 100%;
height: 50vh;
margin-bottom: 10px;
}
.card iframe {
width: 100%;
height: 50vh;
}
.card video {
width: 100%;
height: auto;
}
.card div {
margin-bottom: 10px;
line-height: 1.5;
}
.card ul {
padding-left: 20px;
margin-bottom: 10px;
}
.card a{
width: fit-content;
grid-column: auto;
}
/* Styles pour les liens */
.lien {
color: #007bff;
text-decoration: none;
padding: 10px;
background-color: rgba(224, 54, 54, 0.482);
border-bottom: 2px solid rgba(224, 54, 54, 0.482);
border-radius: 5px;
margin-bottom: 30px;
margin-left: 2vw;
margin-top: 2vh;
}
.lien:hover {
text-decoration: underline;
}
/* Styles pour les informations secondaires */
.secondary-text {
font-size: 14px;
color: #777;
}
#recherche_input{
height: 4vw;
}
.checkbox{
height: 20px;
width: 20px;
}
.ascii-art {
font-family: monospace;
white-space: pre;
}
textarea{
width: 40vw;
height: 40vh;
}

View file

@ -1,135 +0,0 @@
.gros-titre{
font-size: larger;
font-weight: bolder;
}
.centre-vertical{
margin-top: auto;
margin-bottom: auto;
}
.centre-horizontal{
margin: auto;
justify-content: center;
}
.centre-txt{
text-align: center;
}
.etaler{
width: 100%;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.button{
margin-top: 10px;
width: fit-content;
padding-top: 1%;
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
border-radius: 5px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.color-green-tr{
background-color: rgba(71, 224, 54, 0.482);
border-color: rgba(71, 224, 54, 0.482);
}
.barre-recherche{
margin-top: 10px;
width: 80vw;
max-width: 800px;
border-radius: 15px;
border-width: 5px;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
background-color: rgba(224, 54, 54, 0.482);
padding: 20px;
}
.champ{
margin-left: auto;
margin-right: auto;
display: block;
font-size: larger;
margin-top: 1vw;
}
.champ-titre{
font-size: larger;
margin-top: 1vw;
}
.formulaire{
margin-top: 5vw;
width: 50vw;
margin-left: 25vw;
margin-right: 25vw;
}
.input-details-exo{
z-index: 1000;
position: relative;
font-size: larger;
margin-top: 1vw;
}
.submit-button{
margin-top: 5vh;
width: fit-content;
padding-top: 5%;
padding-left: 5%;
padding-right: 5%;
padding-bottom: 5%;
border-radius: 5px;
font-weight:bolder;
font-size: xx-large;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
margin-left: auto;
margin-right: auto;
display: block;
}
.label-input{
margin-left: auto;
margin-right: auto;
font-size: larger;
margin-top: 1vw;
}
.ascii-art {
text-align: center;
margin-left: auto;
margin-right: auto;
font-size: 20px;
font-family: monospace;
white-space: pre;
}

View file

@ -1,151 +0,0 @@
@media (hover: none) {
/* For mobile phones: */
.floating-action-btn{
/*position: fixed;
bottom: 30vh;
margin-left:5%;
padding: 10px;
padding-top: 0px;
width: fit-content;
text-align: left;
border-radius: 5px;
border-width: 2px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;*/
visibility: hidden;
}
}
@media only screen and (min-width: 1000px) {
/* For desktop: */
.floating-action-btn{
position: fixed;
bottom: 5%;
margin-left:1%;
padding: 10px;
padding-top: 0px;
width: fit-content;
text-align: left;
border-radius: 5px;
border-width: 2px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
}
.gros-titre{
font-size: larger;
font-weight: bolder;
}
.centre-vertical{
margin-top: auto;
margin-bottom: auto;
}
.centre-horizontal{
margin: auto;
justify-content: center;
}
.centre-txt{
text-align: center;
}
.etaler{
width: 100%;
}
.bulle-rouge{
width: fit-content;
padding-top: 5px;
padding-left: 5px;
padding-right: 5px;
padding-bottom: 5px;
background-color: rgba(255, 0, 0, 0.283);
border-radius: 5px;
border-width: 2px;
border-color: rgba(255, 0, 0, 0.283);
}
.button{
margin-top: 10px;
width: fit-content;
padding-top: 1%;
padding-left: 1%;
padding-right: 1%;
padding-bottom: 1%;
border-radius: 5px;
font-weight:bolder;
text-decoration: none;
color: black;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
border-top: 0px;
border-left: 0px;
border-right: 0px;
}
.color-red-tr{
background-color: rgba(224, 54, 54, 0.482);
border-color: rgba(224, 54, 54, 0.482);
}
.color-green-tr{
background-color: rgba(71, 224, 54, 0.482);
border-color: rgba(71, 224, 54, 0.482);
}
.barre-recherche{
margin-top: 10px;
width: 80vw;
max-width: 800px;
border-radius: 15px;
border-width: 5px;
border-bottom: 3px solid rgba(224, 54, 54, 0.482);
background-color: rgba(224, 54, 54, 0.482);
padding: 20px;
}
.champ{
font-size: larger;
margin-top: 1vw;
}
.champ-titre{
font-size: larger;
margin-top: 1vw;
}
.formulaire{
margin-top: 5vw;
width: 50vw;
margin-left: 25vw;
margin-right: 25vw;
}
.input-details-exo{
z-index: 1000;
position: relative;
font-size: larger;
margin-top: 1vw;
}
.ascii-art{
text-align: center;
margin-left: auto;
margin-right: auto;
font-size: 20px;
font-family: monospace;
white-space: pre;
}

View file

@ -1,34 +0,0 @@
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="fr">
<?php
$titre_page = "Déconnection d'Arch'INSA";
include "_partials/_head.php";
include('php-csrf.php');
$csrf = new CSRF();
?>
<body>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
</div>
<h2>Merci d'être passé sur Arch'INSA ! ~\_(^-^)_/~</h2>
</body>
<?php
echo $csrf->script($context='deconnection', $name='jeton_csrf', $declaration='var', $time2Live=-1, $max_hashes=5);
include "_partials/_footer.php";
?>
</html>

60
ens.php
View file

@ -1,23 +1,47 @@
<!DOCTYPE html>
<html lang="en">
<?php
$titre_page = "Ensemble de documents";
include "_partials/_head.php";
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ensemble de documents</title>
</head>
<body>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
</div>
<div id="data-container"></div>
</body>
<?php
include "_partials/_footer.php";
?>
<script>
/*
pour les docs afficher un truc du même acabit que la php :
if (strtolower($extension) === 'pdf'):
echo "<embed src=\"{$doc['upload_path']}\" type=\"application/pdf\" width=\"100%\" height=\"600px\" />";
elseif (in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif'])):
echo "<img src=\"{$doc['upload_path']}\">";
else:
echo "<p>Oups ! Je ne sais pas afficher ce document :/ (Rales autant que tu veux je men fous) </p>".$doc['upload_path'];
endif;
*/
// fetch l'api et afficher tout ce qu'elle nous rend
function querystring(key) {
var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r=[], m;
while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
return r;
}
async function gen_contenu(){
resp = await fetch("/annales/api.php/decomposer_ensemble?ensemble_id="+querystring("ensemble_id"));
data = await resp.json();
if(data["status"] == 1){
console.log(data);
}
}
</script>
</html>

View file

@ -1,146 +0,0 @@
<?php
session_start();
// Check if user is logged in and is an admin
if (!isset($_SESSION["utilisateur_authentifie"]) || $_SESSION["utilisateur_authentifie"] !== true || !$_SESSION["admin"]) {
header("Location: index.php");
exit;
}
// Database Connection
include("test_creds.php");
$mysqli = new mysqli($servername, $db_username, $db_password,$dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Handle Update for Ensembles
if (isset($_POST['update_ensemble'])) {
$id = $_POST['ensemble_id'];
$commentaire_auteur = $_POST['commentaire_auteur'];
$valide = isset($_POST['valide']) ? 1 : 0;
$corrige_inclu = isset($_POST['corrige_inclu']) ? 1 : 0;
$date_conception = $_POST['date_conception'];
$id_auteur = $_POST['id_auteur'];
$stmt = $mysqli->prepare("UPDATE ensembles SET commentaire_auteur = ?, valide = ?, corrige_inclu = ?, date_conception = ?, id_auteur = ? WHERE id = ?");
$stmt->bind_param('siisii', $commentaire_auteur, $valide, $corrige_inclu, $date_conception, $id_auteur, $id);
$stmt->execute();
$stmt->close();
}
// Handle Update for Documents
if (isset($_POST['update_document'])) {
$id = $_POST['document_id'];
$titre = $_POST['titre'];
$type = $_POST['type'];
$commentaire_auteur = $_POST['commentaire_auteur'];
echo var_dump($_POST);
$stmt = $mysqli->prepare("UPDATE documents SET titre = ?, type = ?, commentaire_auteur = ? WHERE id = ?");
$stmt->bind_param('sisi', $titre, $type, $commentaire_auteur, $id);
$stmt->execute();
$stmt->close();
}
// Handle Delete Document
if (isset($_GET['delete_document'])) {
$id = (int)$_GET['id'];
$path = $_GET['path'];
if (file_exists($path)) {
unlink($path); // Remove file
}
$stmt = $mysqli->prepare("DELETE FROM documents WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header("Location: dashboard.php");
}
// Fetch Ensembles
$ensembles = $mysqli->query("SELECT * FROM ensembles")->fetch_all(MYSQLI_ASSOC);
// Fetch Documents
$documents = $mysqli->query("SELECT * FROM documents")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>Ensembles & Documents Dashboard</title>
</head>
<body>
<h2>Manage Ensembles</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Commentaire Auteur</th>
<th>Valide</th>
<th>Corrige Inclu</th>
<th>Date Conception</th>
<th>Auteur ID</th>
<th>Action</th>
</tr>
<?php foreach ($ensembles as $ensemble): ?>
<tr>
<form method="POST">
<td><?php echo $ensemble['id']; ?></td>
<td><input type="text" name="commentaire_auteur" value="<?php echo $ensemble['commentaire_auteur']; ?>"></td>
<td><input type="checkbox" name="valide" <?php echo $ensemble['valide'] ? 'checked' : ''; ?>></td>
<td><input type="checkbox" name="corrige_inclu" <?php echo $ensemble['corrige_inclu'] ? 'checked' : ''; ?>></td>
<td><input type="text" name="date_conception" value="<?php echo $ensemble['date_conception']; ?>"></td>
<td><input type="number" name="id_auteur" value="<?php echo $ensemble['id_auteur']; ?>"></td>
<td>
<input type="hidden" name="ensemble_id" value="<?php echo $ensemble['id']; ?>">
<input type="submit" name="update_ensemble" value="Update">
</td>
</form>
</tr>
<?php endforeach; ?>
</table>
<h2>Manage Documents</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Titre</th>
<th>Type</th>
<th>Upload Path</th>
<th>Commentaire Auteur</th>
<th>Ensemble ID</th>
<th>Theme ID</th>
<th>Actions</th>
</tr>
<?php foreach ($documents as $document): ?>
<tr>
<form method="POST">
<td><?php echo $document['id']; ?></td>
<td><input type="text" name="titre" value="<?php echo $document['titre']; ?>"></td>
<td><input type="number" name="type" value="<?php echo $document['type']; ?>"></td>
<td><?php echo $document['upload_path']; ?></td>
<td><input type="text" name="commentaire_auteur" value="<?php echo $document['commentaire_auteur']; ?>"></td>
<td><input type="number" name="ensemble_id" value="<?php echo $document['ensemble_id']; ?>"></td>
<td><input type="number" name="theme_id" value="<?php echo $document['theme_id']; ?>"></td>
<td>
<input type="hidden" name="document_id" value="<?php echo $document['id']; ?>">
<input type="submit" name="update_document" value="Update">
<a href="?delete_document=1&id=<?php echo $document['id']; ?>&path=<?php echo $document['upload_path']; ?>" onclick="return confirm('Are you sure you want to delete this document?')">Delete</a>
</td>
</form>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

299
index.php
View file

@ -1,139 +1,212 @@
<!DOCTYPE html>
<html lang="en">
<?php
$titre_page = "Arch'INSA";
include "_partials/_head.php";
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php
session_start();
?>
<a href="javascript:authenticate_user();">connection</a>
<a href="javascript:unauthenticate_user();">déconnection</a>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
<div id="user_status">
</div>
</div>
<h4>Comme vous pouvez le constater, on cherche quelqu'un pour le design (html + css) du site :D club.info@amicale-insat.fr</h4>
<form id="recherche_form">
<input type="text" id="recherche_input" placeholder="Rechercher une fiche, annale ...">
<input type="text" id="themes_input" placeholder="themes (appuyez sur la touche entrée entre chaque thèmes)">
<input type="number" id="duree_input" placeholder="durée en minutes">
</form>
<?php
if(isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1)){
?>
<a href="deconnection.php" class="button color-red-tr" id="btn-deconnection">Se déconnecter</a>
<?php
}else{
?>
<a href="inscription.php" class="button color-red-tr" id="btn-connection">S'inscrire</a>
<a href="connection.php" class="button color-red-tr" id="btn-connection">Se connecter</a>
<?php
<a href="televerser.php">Téléverser des documents</a>
<div id="liste_resultats">
</div>
</body>
<script>
async function test_auth(){
resp = await fetch("api.php/test_auth");
data = await resp.json();
document.getElementById("user_status").innerText = data["msg"];
}
// fonction de test, innutile en prod
async function authenticate_user(){
resp = await fetch("api.php/auth");
data = await resp.json();
console.log("test");
if(data.status == 1){
document.getElementById("user_status").innerText = data["msg"];
}
}
async function unauthenticate_user(){
resp = await fetch("api.php/unauth");
data = await resp.json();
if(data.status == 1){
document.getElementById("user_status").innerText = data["msg"];
}
}
if(isset($_SESSION["admin"]) && ($_SESSION["admin"] == 1)){
?>
<a href="validation.php" class="button color-red-tr" id="btn-validation">Validation des ensembles</a>
<a href="utilisateurs.php" class="button color-red-tr" id="btn-validation">Gestion des utilisateurs</a>
<a href="gestion_contenu.php" class="button color-red-tr" id="btn-validation">Gestion du contenu</a>
<?php
}?>
async function rechercher(){
var req = document.getElementById("recherche_input").value;
var themes = [];
Array.from(document.getElementsByClassName("theme")).forEach(function (el) {
// on encode en url pour pouvoir le passer dans la requete GET
themes.push(encodeURIComponent(el.innerText));
});
var duree =document.getElementById("duree_input").value
<br>
<br>
<div id="user_status">
<?php
if(isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1)){
?><h2>Salut <?= $_SESSION["username"] ?> !</h2><?php
}else{
?><h2>Vous n'êtes pas connecté !</h2><?php
}
?>
</div>
var url = "api.php/rechercher?req="+req;
if(themes.toString() != ""){
url = url +"&themes="+themes.toString();
}
if(duree != ""){
url = url +"duree="+duree;
<?php
if(isset($_SESSION["utilisateur_authentifie"]) && ($_SESSION["utilisateur_authentifie"] == 1)){
?>
<div class="barre-recherche centre-horizontal">
<form id="recherche_form">
<input class="champ" type="text" id="recherche_input" placeholder="Rechercher une fiche, annale ...">
<div hidden>
<label class="champ" for="tout-les-insa-switch">Activer la recherche sur tout les INSA</label>
<input class="champ checkbox" type="checkbox" id="tout_les_insa_switch">
</div>
<input hidden type="submit">
<input hidden class="champ" type="text" id="themes_input" placeholder="themes (appuyez sur la touche entrée entre chaque thèmes)">
<input hidden class="champ" type="number" id="duree_input" placeholder="durée en minutes">
</form>
</div>
<a href="televerser.php">
<div class="ascii-art color-red-tr floating-action-btn">
============================================
| _ |
| _| |_ |
| |_ _| Téléverser des documents |
| |_| |
============================================
</div></a>
<div class="centre-horizontal etaler">
<div id="liste_resultats" class="centre-txt">
</div>
<div>
<?php
}else{
?>
<div class="centre-horizontal">
<h1>Vous devez vous connecter/inscrire avant d'accéder à Archinsa</h1>
</div>
<br>
<div class="centre-horizontal">
<div class="ascii-art">
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠙⠻⢶⣄⡀⠀⠀⠀⢀⣤⠶⠛⠛⡇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣇⠀⠀⣙⣿⣦⣤⣴⣿⣁⠀⠀⣸⠇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣡⣾⣿⣿⣿⣿⣿⣿⣿⣷⣌⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣷⣄⡈⢻⣿⡟⢁⣠⣾⣿⣦⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿⣿⣿⠘⣿⠃⣿⣿⣿⣿⡏⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠈⠛⣰⠿⣆⠛⠁⠀⡀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣦⠀⠘⠛⠋⠀⣴⣿⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣶⣾⣿⣿⣿⣿⡇⠀⠀⠀⢸⣿⣏⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠀⠀⠀⠾⢿⣿⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⣿⣿⣿⣿⣿⣿⡿⠟⠋⣁⣠⣤⣤⡶⠶⠶⣤⣄⠈⠀⠀⠀⠀⠀⠀
⠀⠀⠀⢰⣿⣿⣮⣉⣉⣉⣤⣴⣶⣿⣿⣋⡥⠄⠀⠀⠀⠀⠉⢻⣄⠀⠀⠀⠀⠀
⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣋⣁⣤⣀⣀⣤⣤⣤⣤⣄⣿⡄⠀⠀⠀⠀
⠀⠀⠀⠀⠙⠿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠋⠉⠁⠀⠀⠀⠀⠈⠛⠃
⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
</div>
</div>
<?php
}
?>
console.log(url);
</body>
<?php
include "_partials/_footer.php";
?>
resp = await fetch(url);
data = await resp.json();
// vide d'abord les éléments présents dans la liste sur la page
document.getElementById("liste_resultats").innerHTML = "";
if(data.status == 1){
data.resultats.forEach(doc => {
// on affiche le titre du résultat parce qu'on est pas des sauvages
let titre_ensemble;
titre_ensemble = document.createElement("h2");
titre_ensemble.innerText = doc.titre;
titre_ensemble.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
document.getElementById("liste_resultats").appendChild(titre_ensemble);
// images ou pdf ?
let ele;
if(doc.upload_path.toString().split(".").pop() == "pdf"){
ele = document.createElement("embed");
}else{
ele = document.createElement("img");
}
ele.src = doc.upload_path;
ele.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
document.getElementById("liste_resultats").appendChild(ele);
});
}
}
async function gen_chronologie(){
var url = "api.php/generer_chronologie";
console.log(url);
resp = await fetch(url);
data = await resp.json();
console.log(data);
// vide d'abord les éléments présents dans la liste sur la page
document.getElementById("liste_resultats").innerHTML = "";
// ensuite on ajoute un petit titre à la chronologie
let titre = document.createElement("h1");
titre.innerText = "Documents récemment publiés";
document.getElementById("liste_resultats").appendChild(titre);
// et on remplis avec ce que l'api a généré
if(data.status == 1){
data.resultats.forEach(ens => {
ens.documents.forEach(doc=>{
// on affiche le titre du résultat parce qu'on est pas des sauvages
let titre_ensemble;
titre_ensemble = document.createElement("h2");
titre_ensemble.innerText = doc.titre;
titre_ensemble.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
document.getElementById("liste_resultats").appendChild(titre_ensemble);
// fichiers spéciaux ?
let apercu;
let ext = doc.upload_path.toString().split(".").pop();
switch(ext){
case "pdf":
ele = document.createElement("embed");
break;
case "html":
ele = document.createElement("iframe");
ele.setAttribute("sandbox","allow-forms allow-modals allow-scripts");
break;
default:
ele = document.createElement("img");
break;
}
ele.src = doc.upload_path;
ele.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
document.getElementById("liste_resultats").appendChild(ele);
});
});
}
}
gen_chronologie();
test_auth();
document.getElementById("recherche_input").onkeydown =function(event) {
if (event.key === "Enter"){
rechercher();
}
}
document.getElementById("themes_input").onkeydown =function(event) {
if (event.key === "Enter"){
var theme = document.createElement("div");
theme.setAttribute("class","theme");
theme.innerText = document.getElementById("themes_input").value;
document.getElementById("recherche_form").appendChild(theme);
document.getElementById("themes_input").value = "";
}
}
</script>
</html>

View file

@ -3,7 +3,7 @@
include("test_creds.php");
// Create connection
$conn = new mysqli($servername, $db_username, $db_password, $dbname);
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
@ -12,22 +12,6 @@ if ($conn->connect_error) {
// Create tables
$sql = "
CREATE TABLE IF NOT EXISTS token(
id INT AUTO_INCREMENT PRIMARY KEY,
id_user INTEGER,
TOKEN VARCHAR(255),
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
nom_insa VARCHAR(25) NOT NULL,
admin BOOLEAN DEFAULT 0,
verifie BOOLEAN DEFAULT 0
);
CREATE TABLE IF NOT EXISTS themes (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
@ -39,9 +23,7 @@ $sql = "
valide BOOLEAN NOT NULL DEFAULT FALSE,
corrige_inclu BOOLEAN NOT NULL DEFAULT FALSE,
date_televersement DATETIME DEFAULT CURRENT_TIMESTAMP,
date_conception VARCHAR(10),
id_auteur INT,
FOREIGN KEY (id_auteur) REFERENCES users(id)
date_conception VARCHAR(9)
);
CREATE TABLE IF NOT EXISTS documents (
@ -78,6 +60,9 @@ $sql = "
FOREIGN KEY (theme_id) REFERENCES themes(id)
);
";
if ($conn->multi_query($sql) === TRUE) {

View file

@ -1,73 +0,0 @@
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<?php
$titre_page = "Inscription sur Arch'INSA";
include "_partials/_head.php";
include('php-csrf.php');
$csrf = new CSRF();
?>
<body>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
</div>
<div class="formulaire">
<input class="champ" id="username-input" type="text" name="username" placeholder="Ton adresse INSA" required>
<input class="champ" id="password-input" type="password" name="password" placeholder="Mot de passe" required>
<div hidden>
<h4 class=" centre-txt label-input" for="insa-input">Selectionne ton INSA</h4>
<select class="champ" id="insa-input" type="select" name="insa" required>
<option value="insa_toulouse">INSA Toulouse &lt;3</option>
<!--<option value="insa_lyon">INSA Lyon</option>
<option value="insa_rennes">INSA Rennes</option>
<option value="insa_cvl">INSA CVL</option>
<option value="insa_hdf">INSA HDF</option>
<option value="insa_rouen">INSA Rouen</option>
<option value="insa_strasbourg">INSA Strasbourg</option>
<option value="insa_hdf">INSA HDF</option>-->
</select>
</div>
<button class="submit-button color-red-tr" onclick="inscription()">S'inscrire !</button>
</div>
<div class="ascii-art">
⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠙⠻⢶⣄⡀⠀⠀⠀⢀⣤⠶⠛⠛⡇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣇⠀⠀⣙⣿⣦⣤⣴⣿⣁⠀⠀⣸⠇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣡⣾⣿⣿⣿⣿⣿⣿⣿⣷⣌⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣷⣄⡈⢻⣿⡟⢁⣠⣾⣿⣦⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿⣿⣿⠘⣿⠃⣿⣿⣿⣿⡏⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠈⠛⣰⠿⣆⠛⠁⠀⡀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣦⠀⠘⠛⠋⠀⣴⣿⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣶⣾⣿⣿⣿⣿⡇⠀⠀⠀⢸⣿⣏⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠀⠀⠀⠾⢿⣿⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⣿⣿⣿⣿⣿⣿⡿⠟⠋⣁⣠⣤⣤⡶⠶⠶⣤⣄⠈⠀⠀⠀⠀⠀⠀
⠀⠀⠀⢰⣿⣿⣮⣉⣉⣉⣤⣴⣶⣿⣿⣋⡥⠄⠀⠀⠀⠀⠉⢻⣄⠀⠀⠀⠀⠀
⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣋⣁⣤⣀⣀⣤⣤⣤⣤⣄⣿⡄⠀⠀⠀⠀
⠀⠀⠀⠀⠙⠿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠋⠉⠁⠀⠀⠀⠀⠈⠛⠃
⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
</div>
</body>
<?php
echo $csrf->script($context='inscription', $name='jeton_csrf', $declaration='var', $time2Live=-1, $max_hashes=5);
include "_partials/_footer.php";
?>
</html>

View file

@ -1,30 +0,0 @@
function connection(){
const formData = new FormData();
formData.append("username",document.getElementById("username-input").value);
formData.append("password",document.getElementById("password-input").value);
formData.append("jeton-csrf",jeton_csrf);
fetch('api.php/connection', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
//console.log(data);
switch(data.status){
case "1":
window.location.href = "index.php";
break;
default:
alert("Une erreur s'est produite lors de votre connection : "+data.msg);
break;
}
})
.catch(error => {
console.error('Error:', error);
});
}

View file

@ -1,28 +0,0 @@
function deconnection(){
const formData = new FormData();
formData.append("jeton-csrf",jeton_csrf);
fetch('api.php/deconnection', {
method: 'POST',
body:formData
})
.then(response => response.json())
.then(data => {
//console.log(data);
if(data.status == 1){
window.location.href = "index.php";
}else{
alert("Une erreur s'est produite lors de votre déconnection : "+data.msg);
}
})
.catch(error => {
console.error('Error:', error);
});
}
window.onload = function(){
deconnection();
}

159
js/ens.js
View file

@ -1,159 +0,0 @@
// fetch l'api et afficher tout ce qu'elle nous rend
function querystring(key) {
var re = new RegExp("(?:\\?|&)" + key + "=(.*?)(?=&|$)", "gi");
var r = [],
m;
while ((m = re.exec(document.location.search)) != null) r[r.length] = m[1];
return r;
}
async function gen_contenu() {
try {
const response = await fetch('api.php/decomposer_ensemble?ensemble_id=' + querystring("ensemble_id"));
const data = await response.json();
console.log(data);
const dataContainer = document.getElementById('data-container');
if (data.status === "1" && data.msg.documents.length > 0) {
// Ajout du contenu restant de la carte
const commentaireDiv = document.createElement('div');
commentaireDiv.classList.add('title');
commentaireDiv.textContent = `Commentaire Auteur: ${data.msg.commentaire_auteur || ''}`;
document.body.appendChild(commentaireDiv);
data.msg.documents.forEach(doc => {
// Création d'une carte (card)
const card = document.createElement('div');
card.classList.add('card');
// Construction du contenu de la carte
/*const idDiv = document.createElement('div');
idDiv.textContent = `ID: ${doc.id}`;
card.appendChild(idDiv);*/
const titreDiv = document.createElement('div');
titreDiv.classList.add('title');
titreDiv.textContent = `Titre: ${doc.titre}`;
card.appendChild(titreDiv);
/*const uploadPathDiv = document.createElement('div');
uploadPathDiv.textContent = `Upload Path: ${doc.upload_path}`;
card.appendChild(uploadPathDiv);*/
switch (doc.type) {
case 2: // image
const img = document.createElement('img');
img.src = doc.upload_path;
img.alt = doc.titre;
card.appendChild(img);
const imageLink = document.createElement('a');
imageLink.href = doc.upload_path;
imageLink.classList.add('lien');
imageLink.textContent = 'Voir image';
imageLink.target = '_blank';
card.appendChild(imageLink);
break;
case 3: // pdf
const embed = document.createElement('embed');
embed.src = doc.upload_path;
card.appendChild(embed);
const pdfLink = document.createElement('a');
pdfLink.href = doc.upload_path;
pdfLink.classList.add('lien');
pdfLink.textContent = 'Voir PDF en grand';
pdfLink.target = '_blank';
card.appendChild(pdfLink);
break;
case 4: // video
const video = document.createElement('video');
video.src = doc.upload_path;
video.controls = true;
card.appendChild(video);
break;
case 5:
const iframe = document.createElement('iframe');
iframe.src = doc.upload_path;
card.appendChild(iframe);
break;
case 1:
const textarea = document.createElement('textarea');
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', doc.upload_path, false);
xmlhttp.send();
text = xmlhttp.responseText;
textarea.value = text;
card.appendChild(textarea);
break;
default:
const unsupportedLink = document.createElement('a');
unsupportedLink.href = doc.upload_path;
unsupportedLink.classList.add('lien');
unsupportedLink.textContent = 'Type de fichier non supporté.';
unsupportedLink.target = '_blank';
card.appendChild(unsupportedLink);
break;
}
// Exercices
if (doc.exercices && doc.exercices.length > 0) {
const exercicesTitle = document.createElement('div');
exercicesTitle.classList.add('title');
exercicesTitle.textContent = 'Exercices:';
card.appendChild(exercicesTitle);
const exercicesList = document.createElement('ul');
doc.exercices.forEach(exercice => {
const exerciceItem = document.createElement('li');
exerciceItem.classList.add('main-text');
exerciceItem.textContent = `Exo n°${exercice.id} ${exercice.commentaire_auteur}, Durée: ${exercice.duree} min`;
exercicesList.appendChild(exerciceItem);
});
card.appendChild(exercicesList);
} else {
const noExercicesDiv = document.createElement('div');
noExercicesDiv.textContent = 'Pas de détails sur les exercices';
card.appendChild(noExercicesDiv);
}
// Ajout de la carte au conteneur principal
dataContainer.appendChild(card);
});
} else {
dataContainer.textContent = data.msg;
}
} catch (error) {
console.error(error);
}
}
document.addEventListener("DOMContentLoaded", (event)=>{
gen_contenu();
document.getElementById("titre").addEventListener("click", (event) => {
window.location.pathname = "/";
});
});

View file

@ -1,301 +0,0 @@
async function rechercher(){
var req = document.getElementById("recherche_input").value;
var themes = [];
Array.from(document.getElementsByClassName("theme")).forEach(function (el) {
// on encode en url pour pouvoir le passer dans la requete GET
themes.push(encodeURIComponent(el.innerText));
});
var duree =document.getElementById("duree_input").value
var url = "api.php/rechercher?req="+req;
if(themes.toString() != ""){
url = url +"&themes="+themes.toString();
}
if(duree != ""){
url = url +"&duree="+duree;
}
console.log(url);
var tout_les_insa_switch = document.getElementById("tout_les_insa_switch").checked;
if(tout_les_insa_switch){
url = url+"&tout_les_insa=1"
}
resp = await fetch(url);
data = await resp.json();
console.log(data);
// vide d'abord les éléments présents dans la liste sur la page
document.getElementById("liste_resultats").innerHTML = "";
// ensuite on ajoute un petit titre à la chronologie
let titre = document.createElement("h1");
titre.innerText = "Voilà les "+data.resultats.length+" résultats de ta recherche :";
document.getElementById("liste_resultats").appendChild(titre);
if(data.status == 1){
data.resultats.forEach(doc => {
const card = document.createElement('div');
card.classList.add('card');
// on affiche le titre du résultat parce qu'on est pas des sauvages
let titre_ensemble;
titre_ensemble = document.createElement("h2");
titre_ensemble.innerText = doc.titre;
titre_ensemble.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
card.appendChild(titre_ensemble);
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add("ligne-boutons");
// fichiers spéciaux ?
switch (doc.type) {
case 2: // image
const img = document.createElement('img');
img.src = doc.upload_path;
img.alt = doc.titre;
card.appendChild(img);
const imageLink = document.createElement('a');
imageLink.href = doc.upload_path;
imageLink.classList.add('lien');
imageLink.textContent = 'Voir image';
imageLink.target = '_blank';
card.appendChild(imageLink);
break;
case 3: // pdf
const embed = document.createElement('embed');
embed.src = doc.upload_path;
card.appendChild(embed);
const pdfLink = document.createElement('a');
pdfLink.href = doc.upload_path;
pdfLink.classList.add('lien');
pdfLink.textContent = 'Voir PDF en grand';
pdfLink.target = '_blank';
card.appendChild(pdfLink);
break;
case 4: // video
const video = document.createElement('video');
video.src = doc.upload_path;
video.controls = true;
card.appendChild(video);
break;
case 5:
const iframe = document.createElement('iframe');
iframe.src = doc.upload_path;
card.appendChild(iframe);
break;
case 1:
const textarea = document.createElement('textarea');
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', doc.upload_path, false);
xmlhttp.send();
text = xmlhttp.responseText;
textarea.value = text;
card.appendChild(textarea)
break;
default:
const unsupportedLink = document.createElement('a');
unsupportedLink.href = doc.upload_path;
unsupportedLink.classList.add('lien');
unsupportedLink.textContent = 'Type de fichier non supporté.';
unsupportedLink.target = '_blank';
buttonsDiv.appendChild(unsupportedLink);
break;
}
const ele = document.createElement("a");
ele.innerText = "Voir tous les pdf de cet ensemble";
ele.href = `ens.php?ensemble_id=${doc.ensemble_id}`;
ele.classList.add("lien");
buttonsDiv.appendChild(ele);
card.appendChild(buttonsDiv);
document.getElementById("liste_resultats").appendChild(card);
});
}
}
async function gen_chronologie(){
var url = "api.php/generer_chronologie";
console.log(url);
resp = await fetch(url);
data = await resp.json();
// vide d'abord les éléments présents dans la liste sur la page
document.getElementById("liste_resultats").innerHTML = "";
if(data.resultats.length > 0){
// ensuite on ajoute un petit titre à la chronologie
let titre = document.createElement("h1");
titre.innerText = "Documents récemment publiés";
document.getElementById("liste_resultats").appendChild(titre);
}else{
}
// et on remplis avec ce que l'api a généré
if(data.status == 1){
data.resultats.forEach(ens => {
ens.documents.forEach(doc=>{
const card = document.createElement('div');
card.classList.add('card');
// on affiche le titre du résultat parce qu'on est pas des sauvages
let titre_ensemble;
titre_ensemble = document.createElement("h2");
titre_ensemble.innerText = doc.titre;
titre_ensemble.setAttribute("onclick","document.location.href='ens.php?ensemble_id="+doc.ensemble_id.toString()+"'");
card.appendChild(titre_ensemble);
const buttonsDiv = document.createElement("div");
buttonsDiv.classList.add("ligne-boutons");
// fichiers spéciaux ?
switch (doc.type) {
case 2: // image
const img = document.createElement('img');
img.src = doc.upload_path;
img.alt = doc.titre;
card.appendChild(img);
const imageLink = document.createElement('a');
imageLink.href = doc.upload_path;
imageLink.classList.add('lien');
imageLink.textContent = 'Voir image';
imageLink.target = '_blank';
buttonsDiv.appendChild(imageLink);
break;
case 3: // pdf
const embed = document.createElement('embed');
embed.src = doc.upload_path;
card.appendChild(embed);
const pdfLink = document.createElement('a');
pdfLink.href = doc.upload_path;
pdfLink.classList.add('lien');
pdfLink.textContent = 'Voir PDF en grand';
pdfLink.target = '_blank';
buttonsDiv.appendChild(pdfLink);
break;
case 4: // video
const video = document.createElement('video');
video.src = doc.upload_path;
video.controls = true;
card.appendChild(video);
break;
case 5:
const iframe = document.createElement('iframe');
iframe.src = doc.upload_path;
card.appendChild(iframe);
break;
case 1:
const textarea = document.createElement('textarea');
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', doc.upload_path, false);
xmlhttp.send();
text = xmlhttp.responseText;
textarea.value = text;
card.appendChild(textarea)
break;
default:
const unsupportedLink = document.createElement('a');
unsupportedLink.href = doc.upload_path;
unsupportedLink.classList.add('lien');
unsupportedLink.textContent = 'Type de fichier non supporté.';
unsupportedLink.target = '_blank';
buttonsDiv.appendChild(unsupportedLink);
break;
}
const ele = document.createElement("a");
ele.innerText = "Voir tous les pdf de cet ensemble";
ele.href = `ens.php?ensemble_id=${doc.ensemble_id}`;
ele.classList.add("lien");
buttonsDiv.appendChild(ele);
card.appendChild(buttonsDiv);
document.getElementById("liste_resultats").appendChild(card);
});
});
}
}
document.addEventListener("DOMContentLoaded", (event)=>{
gen_chronologie();
document.getElementById("recherche_input").addEventListener("keydown", (event)=>{
if (event.key === "Enter"){
event.preventDefault();
rechercher();
}
});
document.getElementById("recherche_form").onsubmit = function(event){
event.preventDefault();
// faire tomber le clavier sur mobile
document.activeElement.blur();
rechercher();
}
document.getElementById("themes_input").onkeydown =function(event) {
if (event.key === "Enter"){
var theme = document.createElement("div");
theme.setAttribute("class","theme");
theme.innerText = document.getElementById("themes_input").value;
document.getElementById("recherche_form").appendChild(theme);
document.getElementById("themes_input").value = "";
}
}
document.getElementById("titre").addEventListener("click", (event) => {
window.location.pathname = "";
});
});

View file

@ -1,22 +0,0 @@
function inscription(){
const formData = new FormData();
formData.append("username",document.getElementById("username-input").value);
formData.append("password",document.getElementById("password-input").value);
console.log(document.getElementById("insa-input").value);
formData.append("nom_insa",document.getElementById("insa-input").value)
formData.append("jeton-csrf",jeton_csrf);
fetch('api.php/inscription', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
alert(data.msg);
})
.catch(error => {
console.error('Error:', error);
});
}

View file

@ -1,314 +0,0 @@
var camera_open = false;
var video;
// on utilise cette fonction pour prendre les infos qu'on veut et faire un titre
// bien propre pour la recherche dans le site
function concatener_titre_inputs() {
let inputs = document.querySelectorAll('.champ-titre');
let concatenatedString = '';
inputs.forEach(input => {
if (input.value.toString() != ""){
switch(input.id){
case "nb-cc":
concatenatedString += 'CC'+input.value +' ';
break;
case "nb-annee":
concatenatedString += input.value.toString()+'A' + ' ';
break;
default:
concatenatedString += input.value + ' ';
break;
}
}
});
// Remove trailing space
concatenatedString = concatenatedString.trim();
return concatenatedString;
}
function televerser_fichiers() {
const fileInput = document.getElementById('fileInput');
// Create FormData object to append files
const formData = new FormData();
formData.append("type",document.getElementById("select_type").value);
formData.append("titre",concatener_titre_inputs());
formData.append("commentaire_auteur",document.getElementById("commentaire_auteur").value);
formData.append("corrige_inclu",document.getElementById("corrige_checkbox").value);
formData.append("date_conception",document.getElementById("date_conception_input").value);
//let ex = [{duree:"10",themes:["algèbre","analyse"],commentaire_exo:"ceci est un commenataire"},{duree:"15",themes:["elec analogique"],commentaire_exo:""}];
var ex = [];
// details des exos pour les annales
if(formData.get("type") == "1"){
var details = document.getElementsByClassName("input-details-exo");
for(let i=0;i<details.length;i = i + 3){
ex.push({
duree:details[i].value,
themes:details[i+1].value.split(","),
commentaire_exo:details[i+2].value
})
}
}
formData.append("exercices",JSON.stringify(ex))
// Append each selected file to the FormData
let i = 0;
for (const file of fileInput.files) {
formData.append('fichier' + i, file);
i ++;
}
console.log(ex);
//csrf token
formData.append("jeton-csrf",jeton_csrf);
//alert(jeton_csrf);
// Append captured images as files to the FormData
const capturedImages = document.querySelectorAll('#selectedImages img');
i = 0;
capturedImages.forEach((img, index) => {
const imageDataUrl = img.src;
const blob = dataURLtoBlob(imageDataUrl);
const file = new File([blob], `camera_image_${index}.jpg`);
formData.append('fichier'+i, file);
i ++;
});
// Make a POST request using Fetch API
fetch('api.php/aj_doc', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
//console.log(data);
if(data.status == 1){
alert("le document a bien été envoyé ! Merci de votre participation :D")
}else{
alert("Une erreur s'est produite lors de l'envoi de votre fichier : "+data.msg);
}
})
.catch(error => {
console.error('Error:', error);
});
}
function ouvrir_camera() {
// test if camera is already open, in that case juste take a regular picture
if(camera_open){
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convert the canvas content to a data URL
const imageDataUrl = canvas.toDataURL('image/jpeg');
// Display the captured image
const img = document.createElement('img');
img.src = imageDataUrl;
img.style.maxWidth = '100px';
document.getElementById('selectedImages').appendChild(img);
return;
}
// Open the camera and take pictures
// You can use the MediaDevices API to access the camera
navigator.mediaDevices.getUserMedia({ video: true })
.then(mediaStream => {
video = document.createElement('video');
document.body.appendChild(video);
camera_open = true;
// Display the camera stream in a video element
video.srcObject = mediaStream;
video.play();
// Capture an image from the video stream
video.addEventListener('click', () => {
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convert the canvas content to a data URL
const imageDataUrl = canvas.toDataURL('image/jpeg');
// Display the captured image
const img = document.createElement('img');
img.src = imageDataUrl;
img.style.maxWidth = '100px';
document.getElementById('selectedImages').appendChild(img);
});
// POUR FERMER LA CAMERA :
// mediaStream.getTracks().forEach(track => track.stop());
})
.catch(error => {
console.error('Error accessing camera:', error);
});
}
function dataURLtoBlob(dataURL) {
const arr = dataURL.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
function ajouter_details_exo(){
duree = document.createElement("input");
duree.setAttribute("type","number");
duree.setAttribute("placeholder","Entrez la durée de l'exercice en minutes.")
// classe imortante pour itérer sur toutes les input
// dans le bon ordre et les associer aux exos dans la requête post
duree.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(duree);
themes = document.createElement("input");
themes.setAttribute("type","text");
themes.setAttribute("placeholder","Entrez les themes abordés par l'exercice séparés par une virgule.");
themes.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(themes);
comm = document.createElement("input");
comm.setAttribute("type","text");
comm.setAttribute("placeholder","Un ptit commentaire sur l'exo ?");
comm.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(comm);
// un peu de tendresse dans ce monde de brutes
br =document.createElement("br");
document.getElementById("exercices_details_wrapper").appendChild(br);
hr =document.createElement("hr");
document.getElementById("exercices_details_wrapper").appendChild(hr);
}
function mode_html(){
document.getElementById("exercices_details_wrapper").setAttribute("hidden",true);
document.getElementById("corrige_checkbox_wrapper").setAttribute("hidden",true);
document.getElementById("nb-cc").setAttribute("hidden",true);
}
function mode_fiche(){
document.getElementById("exercices_details_wrapper").setAttribute("hidden",true);
document.getElementById("corrige_checkbox_wrapper").setAttribute("hidden",true);
document.getElementById("nb-cc").setAttribute("hidden",true);
}
function mode_annale(){
document.getElementById("nb-cc").removeAttribute("hidden");
document.getElementById("corrige_checkbox_wrapper").removeAttribute("hidden");
document.getElementById("exercices_details_wrapper").removeAttribute("hidden");
}
function changer_mode(){
switch(document.getElementById("select_type").value){
// annale
case "1":
mode_annale();
break;
// fiche
case "2":
mode_fiche();
break;
// html personnalisé
case "3":
mode_html();
break;
}
}
function init_date(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear()-1; // pourquoi 2025 ?????
yyyy = parseInt(yyyy) + 1;
today = yyyy+"-"+mm+"-"+dd;
console.log(today);
document.getElementById("date_conception_input").setAttribute("value",today);
}
document.addEventListener("DOMContentLoaded", (event) => {
init_date();
document.getElementById("select_type").addEventListener("change", (event) => {
changer_mode();
});
document.getElementById("btn-soumettre").addEventListener("click", (event) => {
televerser_fichiers();
});
document.getElementById("btn-camera").addEventListener("click", (event) => {
ouvrir_camera();
});
document.getElementById("btn-details-exo").addEventListener("click", (event) => {
ajouter_details_exo();
});
document.getElementById("titre").addEventListener("click", (event) => {
window.location.pathname = "/";
});
});

View file

@ -1,74 +0,0 @@
function valider_ensemble(ensembleId) {
const formData = new FormData();
formData.append("jeton-csrf",jeton_valider_ensemble);
formData.append("ensemble_id",ensembleId);
fetch('api.php/valider_ensemble', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.status == 1) {
alert(data.msg)
}else{
alert(data.msg)
}
})
.catch(error => {
console.error('Error:', error);
});
}
function supprimer_ensemble(ensembleId) {
const formData = new FormData();
formData.append("jeton-csrf",jeton_supprimer_ensemble);
formData.append("ensemble_id",ensembleId);
fetch('api.php/supprimer_ensemble', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.status == 1) {
alert(data.msg)
document.location.reload();
}else{
alert(data.msg)
}
})
.catch(error => {
console.error('Error:', error);
});
}
document.addEventListener("DOMContentLoaded", (event) => {
let liens = document.getElementsByClassName('lien-valider-ens');
for (var i = 0; i < liens.length; i++) {
liens[i].addEventListener('click', function(event) {
event.preventDefault();
valider_ensemble(liens[i].getAttribute("id_ens"));
});
}
liens = document.getElementsByClassName('lien-supprimer-ens');
for (var i = 0; i < liens.length; i++) {
liens[i].addEventListener('click', function(event) {
event.preventDefault();
supprimer_ensemble(liens[i].getAttribute("id_ens"));
});
}
});

View file

@ -59,18 +59,15 @@ D'autres fonctionnalités seront ajoutées petit à petit. (si vous avez des sug
## TOUDOU :
> choisir un insa à l'inscription
> rajouter automatiquement l'insa de celui qui dépose un truc dans la table des ensembles
> mettre un switch pour activer une recherche sur tout les insa
### téléverser.php :
- ajouter un element "commentaire_doc_< i >" pour chaque document
- changer toutes les variables db avec $db_ devant
- rajouter des extensions en whitelist
- regex insa touloouse email inscription
- ssi le type est "annale" ajouter un element "commentaire_exo_< i >" pour chaque exercice déclaré dans chaque document
- Ajouter de même un champ "themes" qui porterons sur les thèmes abordés par l'exercice, possibilité d'en inscrire autant que l'on veut
- ajouter un champ "duree" pour chaque exercice
- tout pack dans un json à l'envoi :
``
let ex = [{duree:"10",themes:["algèbre","analyse"],commentaire_exo:"cci est un commenataire"},{duree:"15",themes:["elec analogique"],commentaire_exo:""}];
@ -78,3 +75,9 @@ let ex = [{duree:"10",themes:["algèbre","analyse"],commentaire_exo:"cci est un
``
- ssi le type est "annale" Ajouter une checkbox pour spécifier si l'ensemble de documents comprend un corrigé ou non identifiant : "corrige_inclu"
- dans le cas d'une fiche de révisions, on ajouter seulement un champ "themes"

View file

@ -1,2 +0,0 @@
User-agent : *
Disallow : /

19
session_verif.php Normal file
View file

@ -0,0 +1,19 @@
<?php
session_start();
function verifier_session(){
if(isset($_SESSION["utilisateur_authentifie"])){
// vérifie que la session ne dépasse pas 4h
if((time() - $_SESSION["heure_debut"]) > 3600*4){
session_destroy();
session_abort();
echo(json_encode(array("status"=> "3","msg"=>"Session expirée, veuillez vous reconnecter.")));
}
}else{
echo(json_encode(array("status"=> "0","msg"=> "Utilisateur non connecté.")));
exit;
}
}
?>

View file

@ -1,103 +1,312 @@
<!DOCTYPE html>
<html lang="en">
<?php
$titre_page = "Téléverser sur Arch'INSA";
include "_partials/_head.php";
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<?php
include("session_verif.php");
// Include the PHP-CSRF library
include('php-csrf.php');
session_start();
if (!isset($_SESSION["utilisateur_authentifie"]) || $_SESSION["utilisateur_authentifie"] !== true) {
header("Location: index.php");
exit;
}
verifier_session();
$csrf = new CSRF();
?>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
<!-- Input to choose files -->
</div>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="fileInput" multiple required>
<div class="formulaire">
<label for="select-type" class="champ" >Type de ressources</label>
<select id="select_type" class="champ" >
<option value="1" >Annale</option>
<option value="2" >Fiche de révision</option>
<br>
<select id="select_type" onchange="changer_mode()" required>
<option value="" disabled selected>Sélectionner le niveau</option>
<option value="1" >1A</option>
<option value="2" >2A</option>
<option value="3" >3A</option>
<option value="4" >4A</option>
<option value="5" >5A</option>
</select>
<!-- ne s'affiche qu'après avoir sélectionner le niveau -->
<select id="select_type" onchange="changer_mode()" hidden required>
<option value="" disabled selected>Sélectionner la matière</option>
<!-- options à chercher dans la bdd de ce niveau, avec possibilité de créer une nouvelle matière -->
</select>
<br>
<select id="select_type" onchange="changer_mode()" required>
<option value="" disabled selected>Sélectionner l'année scolaire</option>
<option value="1" >2019-2020</option>
<option value="2" >2020-2021</option>
<option value="3" >2021-2022</option>
<option value="4" >2022-2023</option>
<option value="5" >2023-2024</option>
</select>
<br>
<input type="text" placeholder="titre" id="titre" required></input>
<label for="titre">Utilisez un titre qui décrit bien l'archive.</label>
<br>
<select id="select_type" onchange="changer_mode()" required>
<option value="1" >annale</option>
<option value="2" >fiche_revision</option>
<option value="3" >HTML personnalisé</option>
</select>
<br>
<br>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" class="champ" id="fileInput" multiple>
<br>
<br>
<label for="titre-cours" class="champ" >Nom du cours</label>
<input type="text" class="champ-titre" placeholder="titre du cours" id="titre-cours" required></input>
<br>
<input type="text" placeholder="commentaires généraux sur l'ensemble des documents" id="commentaire_auteur"></input>
<br>
<div id="selectedImages"></div>
<label for="nb-cc" class="champ" >Numéro du CC</label>
<input type="number" class="champ-titre" placeholder="n° du CC" id="nb-cc" required></input>
<br>
<br>
<label for="nb-classe" class="champ" >Numéro de votre année (1A,2A...)</label>
<input type="number" max="5" min="1" class="champ-titre" placeholder="classe" id="nb-annee" required></input>
<br>
<br>
<label for="nom-spe" class="champ" >Nom de PO/Spécialité</label>
<input type="text" class="champ-titre" placeholder="classe" id="nom-spe" required></input>
<br>
<br>
<label for="commentaire_auteur" class="champ" >commentaires généraux sur l'ensemble des documents</label>
<input type="text" class="champ-titre" placeholder="commentaires généraux sur l'ensemble des documents" id="commentaire_auteur"></input>
<br>
<br>
<div id="selectedImages" class="champ"></div>
<div id="corrige_checkbox_wrapper">
<input type="checkbox" class="champ" id="corrige_checkbox">
<label for="corrige_checkbox" class="champ">Corrigé inclu</label>
<input type="checkbox" id="corrige_checkbox">
<label for="corrige_checkbox">Corrigé inclu</label>
</div>
<br>
<input type="date" id="date_conception_input" class="champ" >
<label for="date_conception_input" class="champ" >Date de conception du/des documents (Mettez juste la bonne année si vous ne savez pas) </label>
<br>
<input type="date" id="date_conception_input" required>
<label for="date_conception_input">Date de conception du/des documents (Mettez juste la bonne année si vous ne savez pas) </label>
<br>
<button type="button" onclick="uploadFiles()">Téléverser les fichiers</button>
</form>
<button type="button" id="btn-soumettre" class="champ button color-green-tr" >Téléverser les fichiers</button>
</form>
<br>
<br>
<div id="exercices_details_wrapper">
<button id="btn-details-exo" class="champ" >Ajouter les détails d'un exercice</button>
</div>
<div id="exercices_details_wrapper">
<button onclick="ajouter_details_exo()">Ajouter les détails d'un exercice</button>
</div>
<button onclick="openCamera()">Prendre des photos</button>
<script>
function uploadFiles() {
const fileInput = document.getElementById('fileInput');
// Create FormData object to append files
const formData = new FormData();
formData.append("type",document.getElementById("select_type").value);
formData.append("titre",document.getElementById("titre").value);
formData.append("commentaire_auteur",document.getElementById("commentaire_auteur").value);
formData.append("corrige_inclu",document.getElementById("corrige_checkbox").value);
formData.append("date_conception",document.getElementById("date_conception_input").value);
//let ex = [{duree:"10",themes:["algèbre","analyse"],commentaire_exo:"ceci est un commenataire"},{duree:"15",themes:["elec analogique"],commentaire_exo:""}];
var ex = [];
// details des exos pour les annales
if(formData.get("type") == "1"){
var details = document.getElementsByClassName("input-details-exo");
for(let i=0;i<details.length;i = i + 3){
ex.push({
duree:details[i].value,
themes:details[i+1].value.split(","),
commentaire_exo:details[i+2].value
})
}
}
formData.append("exercices",JSON.stringify(ex))
// Append each selected file to the FormData
let i = 0;
for (const file of fileInput.files) {
formData.append('fichier' + i, file);
i ++;
}
console.log(ex);
//csrf token
formData.append("jeton-csrf","<?=$csrf->string($context="televersement")?>");
// Append captured images as files to the FormData
const capturedImages = document.querySelectorAll('#selectedImages img');
i = 0;
capturedImages.forEach((img, index) => {
const imageDataUrl = img.src;
const blob = dataURLtoBlob(imageDataUrl);
const file = new File([blob], `camera_image_${index}.jpg`);
formData.append('fichier'+i, file);
i ++;
});
// Make a POST request using Fetch API
fetch('api.php/aj_doc', {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
console.log(data);
// Handle the response from the server
})
.catch(error => {
console.error('Error:', error);
});
}
function openCamera() {
// Open the camera and take pictures
// You can use the MediaDevices API to access the camera
navigator.mediaDevices.getUserMedia({ video: true })
.then(mediaStream => {
const video = document.createElement('video');
document.body.appendChild(video);
// Display the camera stream in a video element
video.srcObject = mediaStream;
video.play();
// Capture an image from the video stream
video.addEventListener('click', () => {
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
// Convert the canvas content to a data URL
const imageDataUrl = canvas.toDataURL('image/jpeg');
// Display the captured image
const img = document.createElement('img');
img.src = imageDataUrl;
img.style.maxWidth = '100px';
document.getElementById('selectedImages').appendChild(img);
});
// POUR FERMER LA CAMERA :
// mediaStream.getTracks().forEach(track => track.stop());
})
.catch(error => {
console.error('Error accessing camera:', error);
});
}
function dataURLtoBlob(dataURL) {
const arr = dataURL.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
function ajouter_details_exo(){
duree = document.createElement("input");
duree.setAttribute("type","number");
duree.setAttribute("placeholder","Entrez la durée de l'exercice en minutes.")
// classe imortante pour itérer sur toutes les input
// dans le bon ordre et les associer aux exos dans la requête post
duree.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(duree);
themes = document.createElement("input");
themes.setAttribute("type","text");
themes.setAttribute("placeholder","Entrez les themes abordés par l'exercice séparés par une virgule.");
themes.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(themes);
comm = document.createElement("input");
comm.setAttribute("type","text");
comm.setAttribute("placeholder","Un ptit commentaire sur l'exo ?");
comm.setAttribute("class","input-details-exo");
document.getElementById("exercices_details_wrapper").appendChild(comm);
// un peu de tendresse dans ce monde de brutes
br =document.createElement("br");
document.getElementById("exercices_details_wrapper").appendChild(br);
hr =document.createElement("hr");
document.getElementById("exercices_details_wrapper").appendChild(hr);
}
function mode_html(){
document.getElementById("exercices_details_wrapper").setAttribute("hidden",true);
document.getElementById("corrige_checkbox_wrapper").setAttribute("hidden",true);
}
function mode_fiche(){
document.getElementById("exercices_details_wrapper").setAttribute("hidden",true);
document.getElementById("corrige_checkbox_wrapper").setAttribute("hidden",true);
}
function mode_annale(){
document.getElementById("corrige_checkbox_wrapper").removeAttribute("hidden");
document.getElementById("exercices_details_wrapper").removeAttribute("hidden");
}
function changer_mode(){
switch(document.getElementById("select_type").value){
// annale
case "1":
mode_annale();
break;
// fiche
case "2":
mode_fiche();
break;
// html personnalisé
case "3":
mode_html();
break;
}
}
function init_date(){
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear()-1; // pourquoi 2025 ?????
yyyy = parseInt(yyyy) + 1;
today = yyyy+"-"+mm+"-"+dd;
console.log(today);
document.getElementById("date_conception_input").setAttribute("value",today);
}
document.addEventListener("DOMContentLoaded", (event) => {
init_date();
});
</script>
<button id="btn-camera" class="color-red-tr floating-action-btn" >
<pre> _
_| |_
|_ _| Prendre des photos
|_|
</pre></button>
</body>
<?php
echo $csrf->script($context='televersement', $name='jeton_csrf', $declaration='var', $time2Live=-1, $max_hashes=5);
include "_partials/_footer.php";
?>
</html>

View file

@ -1,31 +0,0 @@
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="fr">
<?php
$titre_page = "Validation de votre compte Arch'INSA";
include "_partials/_head.php";
?>
<body>
<div class="centre-horizontal bulle-rouge" id="titre">
<pre class="centre-txt gros-titre">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</pre>
</div>
<h1>Votre compte a bien été validé !!</h1>
<a hre="connection.php">Se connecter à Arch'INSA</a>
</body>
<?php
include "_partials/_footer.php";
?>
</html>

View file

@ -1,94 +0,0 @@
<?php
session_start();
include("test_creds.php");
// Check if user is logged in and is an admin
if (!isset($_SESSION["utilisateur_authentifie"]) || $_SESSION["utilisateur_authentifie"] !== true || !$_SESSION["admin"]) {
header("Location: index.php");
exit;
}
$conn = new mysqli($servername, $db_username, $db_password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$username = $_POST['username'];
$admin = isset($_POST['admin']) ? 1 : 0;
$stmt = $conn->prepare("UPDATE users SET username = ?, admin = ? WHERE id = ?");
$stmt->bind_param("sii", $username, $admin, $id);
$stmt->execute();
$stmt->close();
}
}
$result = $conn->query("SELECT id, username, admin FROM users");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin Page</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Liste des utilisateurs</h1>
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Admin</th>
<th>Actions</th>
</tr>
<?php while ($row = $result->fetch_assoc()): ?>
<tr>
<form method="post" action="utilisateurs.php">
<td><?php echo $row['id']; ?></td>
<td><input type="text" name="username" value="<?php echo $row['username']; ?>"></td>
<td><input type="checkbox" name="admin" <?php if ($row['admin']) echo "checked"; ?>></td>
<td>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button type="submit" name="update">Update</button>
<button type="submit" name="delete" onclick="return confirm('T\'es sur sur sur de le supprimer ? ');">Delete</button>
</td>
</form>
</tr>
<?php endwhile; ?>
</table>
</body>
</html>
<?php
$conn->close();
?>

View file

@ -1,135 +0,0 @@
<?php
function assainir_et_valider_mel($og_mel): string {
// Supprime les espaces en début et fin de chaîne
$mel = trim($og_mel);
// Assainit l'adresse e-mail en supprimant les caractères spéciaux
$mel = filter_var($mel, FILTER_SANITIZE_EMAIL);
// Vérifie si l'adresse e-mail est valide
$reg_pattern = "/^[a-zA-Z0-9._%+-]+@insa-toulouse\.fr$/";
if (filter_var($mel, FILTER_VALIDATE_EMAIL) && preg_match($mel,$reg_pattern)) {
return $mel; // Si valide, renvoie l'adresse e-mail assainie
} else {
return "[ERREUR_MEL_MALSAINT]"; // Sinon, renvoie un message d'erreur
}
}
function getFileSignature($filePath, $length = 8) {
// Open the file and read the first few bytes (file signature)
if ($file = fopen($filePath, 'rb')) {
$signature = fread($file, $length);
fclose($file);
return bin2hex($signature); // Return as hexadecimal string
}
return false;
}
function checkFileTypeSecure($filePath) {
if (!file_exists($filePath)) {
return -1; // File does not exist
}
// Get the file's signature (magic bytes)
$fileSignature = getFileSignature($filePath);
// Check for common signatures
$signatures = [
'text' => [
'txt' => 'efbbbf', // UTF-8 encoded text files (BOM)
],
'pdf' => [
'pdf' => '25504446', // PDF files always start with "%PDF" in hex
],
'image' => [
'jpeg0' => 'ffd8ffe0', // JPEG
'jpeg1' => 'ffd8ffe1', // JPEG but different you know they like to stand out (exif)
'jpeg2' => 'ffd8ffe2', // NO SHIT ??? (jfif or spiff)
'png' => '89504e47', // PNG
'gif' => '47494638', // GIF
'bmp' => '424d', // BMP
'webp' => '52494646', // WebP starts with "RIFF"
'tiff' => '49492a00' // TIFF
],
'video' => [
'mp4' => '00000018', // MP4
//'avi' => '52494646', // AVI starts with "RIFF" bah relou du coup c'est pareil que webp
'mkv' => '1a45dfa3', // MKV
'mov' => '00000014' // MOV
],
'html' => [
'html' => '3c68746d', // HTML documents start with "<html"
]
];
// Check against known file signatures
// Check for plain text
foreach ($signatures['text'] as $format => $signature) {
if (strpos($fileSignature, $signature) === 0) {
return 1; // Plain text file
}
}
// Check for PDF
foreach ($signatures['pdf'] as $format => $signature) {
if (strpos($fileSignature, $signature) === 0) {
return 3; // PDF file
}
}
// Check for images
foreach ($signatures['image'] as $format => $signature) {
if (strpos($fileSignature, $signature) === 0) {
return 2; // Image file
}
}
// Check for videos
foreach ($signatures['video'] as $format => $signature) {
if (strpos($fileSignature, $signature) === 0) {
return 4; // Video file
}
}
// Check for HTML documents
foreach ($signatures['html'] as $format => $signature) {
if (strpos($fileSignature, $signature) === 0) {
return 5; // HTML file
}
}
// brut text file that don't have BOM (magic byte)
if(is_utf8($filePath)){
return 1;
}
return 0; // Unknown or unsupported file type
}
function is_utf8_file($filePath) {
// Check if the file exists
if (!file_exists($filePath)) {
return false;
}
// Open the file for reading
$fileContents = file_get_contents($filePath);
if ($fileContents === false) {
return false; // Unable to read the file
}
// Check if the file content is valid UTF-8
return is_utf8($fileContents);
}
// Helper function to check if a string is valid UTF-8
function is_utf8($string) {
return mb_check_encoding($string, 'UTF-8');
}
?>

View file

@ -1,245 +0,0 @@
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2023 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
/**
* Configure PHPMailer with DSN string.
*
* @see https://en.wikipedia.org/wiki/Data_source_name
*
* @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
*/
class DSNConfigurator
{
/**
* Create new PHPMailer instance configured by DSN.
*
* @param string $dsn DSN
* @param bool $exceptions Should we throw external exceptions?
*
* @return PHPMailer
*/
public static function mailer($dsn, $exceptions = null)
{
static $configurator = null;
if (null === $configurator) {
$configurator = new DSNConfigurator();
}
return $configurator->configure(new PHPMailer($exceptions), $dsn);
}
/**
* Configure PHPMailer instance with DSN string.
*
* @param PHPMailer $mailer PHPMailer instance
* @param string $dsn DSN
*
* @return PHPMailer
*/
public function configure(PHPMailer $mailer, $dsn)
{
$config = $this->parseDSN($dsn);
$this->applyConfig($mailer, $config);
return $mailer;
}
/**
* Parse DSN string.
*
* @param string $dsn DSN
*
* @throws Exception If DSN is malformed
*
* @return array Configuration
*/
private function parseDSN($dsn)
{
$config = $this->parseUrl($dsn);
if (false === $config || !isset($config['scheme']) || !isset($config['host'])) {
throw new Exception('Malformed DSN');
}
if (isset($config['query'])) {
parse_str($config['query'], $config['query']);
}
return $config;
}
/**
* Apply configuration to mailer.
*
* @param PHPMailer $mailer PHPMailer instance
* @param array $config Configuration
*
* @throws Exception If scheme is invalid
*/
private function applyConfig(PHPMailer $mailer, $config)
{
switch ($config['scheme']) {
case 'mail':
$mailer->isMail();
break;
case 'sendmail':
$mailer->isSendmail();
break;
case 'qmail':
$mailer->isQmail();
break;
case 'smtp':
case 'smtps':
$mailer->isSMTP();
$this->configureSMTP($mailer, $config);
break;
default:
throw new Exception(
sprintf(
'Invalid scheme: "%s". Allowed values: "mail", "sendmail", "qmail", "smtp", "smtps".',
$config['scheme']
)
);
}
if (isset($config['query'])) {
$this->configureOptions($mailer, $config['query']);
}
}
/**
* Configure SMTP.
*
* @param PHPMailer $mailer PHPMailer instance
* @param array $config Configuration
*/
private function configureSMTP($mailer, $config)
{
$isSMTPS = 'smtps' === $config['scheme'];
if ($isSMTPS) {
$mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
}
$mailer->Host = $config['host'];
if (isset($config['port'])) {
$mailer->Port = $config['port'];
} elseif ($isSMTPS) {
$mailer->Port = SMTP::DEFAULT_SECURE_PORT;
}
$mailer->SMTPAuth = isset($config['user']) || isset($config['pass']);
if (isset($config['user'])) {
$mailer->Username = $config['user'];
}
if (isset($config['pass'])) {
$mailer->Password = $config['pass'];
}
}
/**
* Configure options.
*
* @param PHPMailer $mailer PHPMailer instance
* @param array $options Options
*
* @throws Exception If option is unknown
*/
private function configureOptions(PHPMailer $mailer, $options)
{
$allowedOptions = get_object_vars($mailer);
unset($allowedOptions['Mailer']);
unset($allowedOptions['SMTPAuth']);
unset($allowedOptions['Username']);
unset($allowedOptions['Password']);
unset($allowedOptions['Hostname']);
unset($allowedOptions['Port']);
unset($allowedOptions['ErrorInfo']);
$allowedOptions = \array_keys($allowedOptions);
foreach ($options as $key => $value) {
if (!in_array($key, $allowedOptions)) {
throw new Exception(
sprintf(
'Unknown option: "%s". Allowed values: "%s"',
$key,
implode('", "', $allowedOptions)
)
);
}
switch ($key) {
case 'AllowEmpty':
case 'SMTPAutoTLS':
case 'SMTPKeepAlive':
case 'SingleTo':
case 'UseSendmailOptions':
case 'do_verp':
case 'DKIM_copyHeaderFields':
$mailer->$key = (bool) $value;
break;
case 'Priority':
case 'SMTPDebug':
case 'WordWrap':
$mailer->$key = (int) $value;
break;
default:
$mailer->$key = $value;
break;
}
}
}
/**
* Parse a URL.
* Wrapper for the built-in parse_url function to work around a bug in PHP 5.5.
*
* @param string $url URL
*
* @return array|false
*/
protected function parseUrl($url)
{
if (\PHP_VERSION_ID >= 50600 || false === strpos($url, '?')) {
return parse_url($url);
}
$chunks = explode('?', $url);
if (is_array($chunks)) {
$result = parse_url($chunks[0]);
if (is_array($result)) {
$result['query'] = $chunks[1];
}
return $result;
}
return false;
}
}

View file

@ -1,40 +0,0 @@
<?php
/**
* PHPMailer Exception class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
/**
* PHPMailer exception handler.
*
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class Exception extends \Exception
{
/**
* Prettify error message output.
*
* @return string
*/
public function errorMessage()
{
return '<strong>' . htmlspecialchars($this->getMessage(), ENT_COMPAT | ENT_HTML401) . "</strong><br />\n";
}
}

View file

@ -1,139 +0,0 @@
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
use League\OAuth2\Client\Grant\RefreshToken;
use League\OAuth2\Client\Provider\AbstractProvider;
use League\OAuth2\Client\Token\AccessToken;
/**
* OAuth - OAuth2 authentication wrapper class.
* Uses the oauth2-client package from the League of Extraordinary Packages.
*
* @see https://oauth2-client.thephpleague.com
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
*/
class OAuth implements OAuthTokenProvider
{
/**
* An instance of the League OAuth Client Provider.
*
* @var AbstractProvider
*/
protected $provider;
/**
* The current OAuth access token.
*
* @var AccessToken
*/
protected $oauthToken;
/**
* The user's email address, usually used as the login ID
* and also the from address when sending email.
*
* @var string
*/
protected $oauthUserEmail = '';
/**
* The client secret, generated in the app definition of the service you're connecting to.
*
* @var string
*/
protected $oauthClientSecret = '';
/**
* The client ID, generated in the app definition of the service you're connecting to.
*
* @var string
*/
protected $oauthClientId = '';
/**
* The refresh token, used to obtain new AccessTokens.
*
* @var string
*/
protected $oauthRefreshToken = '';
/**
* OAuth constructor.
*
* @param array $options Associative array containing
* `provider`, `userName`, `clientSecret`, `clientId` and `refreshToken` elements
*/
public function __construct($options)
{
$this->provider = $options['provider'];
$this->oauthUserEmail = $options['userName'];
$this->oauthClientSecret = $options['clientSecret'];
$this->oauthClientId = $options['clientId'];
$this->oauthRefreshToken = $options['refreshToken'];
}
/**
* Get a new RefreshToken.
*
* @return RefreshToken
*/
protected function getGrant()
{
return new RefreshToken();
}
/**
* Get a new AccessToken.
*
* @return AccessToken
*/
protected function getToken()
{
return $this->provider->getAccessToken(
$this->getGrant(),
['refresh_token' => $this->oauthRefreshToken]
);
}
/**
* Generate a base64-encoded OAuth token.
*
* @return string
*/
public function getOauth64()
{
//Get a new token if it's not available or has expired
if (null === $this->oauthToken || $this->oauthToken->hasExpired()) {
$this->oauthToken = $this->getToken();
}
return base64_encode(
'user=' .
$this->oauthUserEmail .
"\001auth=Bearer " .
$this->oauthToken .
"\001\001"
);
}
}

View file

@ -1,44 +0,0 @@
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
/**
* OAuthTokenProvider - OAuth2 token provider interface.
* Provides base64 encoded OAuth2 auth strings for SMTP authentication.
*
* @see OAuth
* @see SMTP::authenticate()
*
* @author Peter Scopes (pdscopes)
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
*/
interface OAuthTokenProvider
{
/**
* Generate a base64-encoded OAuth token ensuring that the access token has not expired.
* The string to be base 64 encoded should be in the form:
* "user=<user_email_address>\001auth=Bearer <access_token>\001\001"
*
* @return string
*/
public function getOauth64();
}

File diff suppressed because it is too large Load diff

View file

@ -1,467 +0,0 @@
<?php
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2020 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
/**
* PHPMailer POP-Before-SMTP Authentication Class.
* Specifically for PHPMailer to use for RFC1939 POP-before-SMTP authentication.
* 1) This class does not support APOP authentication.
* 2) Opening and closing lots of POP3 connections can be quite slow. If you need
* to send a batch of emails then just perform the authentication once at the start,
* and then loop through your mail sending script. Providing this process doesn't
* take longer than the verification period lasts on your POP3 server, you should be fine.
* 3) This is really ancient technology; you should only need to use it to talk to very old systems.
* 4) This POP3 class is deliberately lightweight and incomplete, implementing just
* enough to do authentication.
* If you want a more complete class there are other POP3 classes for PHP available.
*
* @author Richard Davey (original author) <rich@corephp.co.uk>
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
*/
class POP3
{
/**
* The POP3 PHPMailer Version number.
*
* @var string
*/
const VERSION = '6.9.1';
/**
* Default POP3 port number.
*
* @var int
*/
const DEFAULT_PORT = 110;
/**
* Default timeout in seconds.
*
* @var int
*/
const DEFAULT_TIMEOUT = 30;
/**
* POP3 class debug output mode.
* Debug output level.
* Options:
* @see POP3::DEBUG_OFF: No output
* @see POP3::DEBUG_SERVER: Server messages, connection/server errors
* @see POP3::DEBUG_CLIENT: Client and Server messages, connection/server errors
*
* @var int
*/
public $do_debug = self::DEBUG_OFF;
/**
* POP3 mail server hostname.
*
* @var string
*/
public $host;
/**
* POP3 port number.
*
* @var int
*/
public $port;
/**
* POP3 Timeout Value in seconds.
*
* @var int
*/
public $tval;
/**
* POP3 username.
*
* @var string
*/
public $username;
/**
* POP3 password.
*
* @var string
*/
public $password;
/**
* Resource handle for the POP3 connection socket.
*
* @var resource
*/
protected $pop_conn;
/**
* Are we connected?
*
* @var bool
*/
protected $connected = false;
/**
* Error container.
*
* @var array
*/
protected $errors = [];
/**
* Line break constant.
*/
const LE = "\r\n";
/**
* Debug level for no output.
*
* @var int
*/
const DEBUG_OFF = 0;
/**
* Debug level to show server -> client messages
* also shows clients connection errors or errors from server
*
* @var int
*/
const DEBUG_SERVER = 1;
/**
* Debug level to show client -> server and server -> client messages.
*
* @var int
*/
const DEBUG_CLIENT = 2;
/**
* Simple static wrapper for all-in-one POP before SMTP.
*
* @param string $host The hostname to connect to
* @param int|bool $port The port number to connect to
* @param int|bool $timeout The timeout value
* @param string $username
* @param string $password
* @param int $debug_level
*
* @return bool
*/
public static function popBeforeSmtp(
$host,
$port = false,
$timeout = false,
$username = '',
$password = '',
$debug_level = 0
) {
$pop = new self();
return $pop->authorise($host, $port, $timeout, $username, $password, $debug_level);
}
/**
* Authenticate with a POP3 server.
* A connect, login, disconnect sequence
* appropriate for POP-before SMTP authorisation.
*
* @param string $host The hostname to connect to
* @param int|bool $port The port number to connect to
* @param int|bool $timeout The timeout value
* @param string $username
* @param string $password
* @param int $debug_level
*
* @return bool
*/
public function authorise($host, $port = false, $timeout = false, $username = '', $password = '', $debug_level = 0)
{
$this->host = $host;
//If no port value provided, use default
if (false === $port) {
$this->port = static::DEFAULT_PORT;
} else {
$this->port = (int) $port;
}
//If no timeout value provided, use default
if (false === $timeout) {
$this->tval = static::DEFAULT_TIMEOUT;
} else {
$this->tval = (int) $timeout;
}
$this->do_debug = $debug_level;
$this->username = $username;
$this->password = $password;
//Reset the error log
$this->errors = [];
//Connect
$result = $this->connect($this->host, $this->port, $this->tval);
if ($result) {
$login_result = $this->login($this->username, $this->password);
if ($login_result) {
$this->disconnect();
return true;
}
}
//We need to disconnect regardless of whether the login succeeded
$this->disconnect();
return false;
}
/**
* Connect to a POP3 server.
*
* @param string $host
* @param int|bool $port
* @param int $tval
*
* @return bool
*/
public function connect($host, $port = false, $tval = 30)
{
//Are we already connected?
if ($this->connected) {
return true;
}
//On Windows this will raise a PHP Warning error if the hostname doesn't exist.
//Rather than suppress it with @fsockopen, capture it cleanly instead
set_error_handler([$this, 'catchWarning']);
if (false === $port) {
$port = static::DEFAULT_PORT;
}
//Connect to the POP3 server
$errno = 0;
$errstr = '';
$this->pop_conn = fsockopen(
$host, //POP3 Host
$port, //Port #
$errno, //Error Number
$errstr, //Error Message
$tval
); //Timeout (seconds)
//Restore the error handler
restore_error_handler();
//Did we connect?
if (false === $this->pop_conn) {
//It would appear not...
$this->setError(
"Failed to connect to server $host on port $port. errno: $errno; errstr: $errstr"
);
return false;
}
//Increase the stream time-out
stream_set_timeout($this->pop_conn, $tval, 0);
//Get the POP3 server response
$pop3_response = $this->getResponse();
//Check for the +OK
if ($this->checkResponse($pop3_response)) {
//The connection is established and the POP3 server is talking
$this->connected = true;
return true;
}
return false;
}
/**
* Log in to the POP3 server.
* Does not support APOP (RFC 2828, 4949).
*
* @param string $username
* @param string $password
*
* @return bool
*/
public function login($username = '', $password = '')
{
if (!$this->connected) {
$this->setError('Not connected to POP3 server');
return false;
}
if (empty($username)) {
$username = $this->username;
}
if (empty($password)) {
$password = $this->password;
}
//Send the Username
$this->sendString("USER $username" . static::LE);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
//Send the Password
$this->sendString("PASS $password" . static::LE);
$pop3_response = $this->getResponse();
if ($this->checkResponse($pop3_response)) {
return true;
}
}
return false;
}
/**
* Disconnect from the POP3 server.
*/
public function disconnect()
{
// If could not connect at all, no need to disconnect
if ($this->pop_conn === false) {
return;
}
$this->sendString('QUIT' . static::LE);
// RFC 1939 shows POP3 server sending a +OK response to the QUIT command.
// Try to get it. Ignore any failures here.
try {
$this->getResponse();
} catch (Exception $e) {
//Do nothing
}
//The QUIT command may cause the daemon to exit, which will kill our connection
//So ignore errors here
try {
@fclose($this->pop_conn);
} catch (Exception $e) {
//Do nothing
}
// Clean up attributes.
$this->connected = false;
$this->pop_conn = false;
}
/**
* Get a response from the POP3 server.
*
* @param int $size The maximum number of bytes to retrieve
*
* @return string
*/
protected function getResponse($size = 128)
{
$response = fgets($this->pop_conn, $size);
if ($this->do_debug >= self::DEBUG_SERVER) {
echo 'Server -> Client: ', $response;
}
return $response;
}
/**
* Send raw data to the POP3 server.
*
* @param string $string
*
* @return int
*/
protected function sendString($string)
{
if ($this->pop_conn) {
if ($this->do_debug >= self::DEBUG_CLIENT) { //Show client messages when debug >= 2
echo 'Client -> Server: ', $string;
}
return fwrite($this->pop_conn, $string, strlen($string));
}
return 0;
}
/**
* Checks the POP3 server response.
* Looks for for +OK or -ERR.
*
* @param string $string
*
* @return bool
*/
protected function checkResponse($string)
{
if (strpos($string, '+OK') !== 0) {
$this->setError("Server reported an error: $string");
return false;
}
return true;
}
/**
* Add an error to the internal error store.
* Also display debug output if it's enabled.
*
* @param string $error
*/
protected function setError($error)
{
$this->errors[] = $error;
if ($this->do_debug >= self::DEBUG_SERVER) {
echo '<pre>';
foreach ($this->errors as $e) {
print_r($e);
}
echo '</pre>';
}
}
/**
* Get an array of error messages, if any.
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* POP3 connection error handler.
*
* @param int $errno
* @param string $errstr
* @param string $errfile
* @param int $errline
*/
protected function catchWarning($errno, $errstr, $errfile, $errline)
{
$this->setError(
'Connecting to the POP3 server raised a PHP warning:' .
"errno: $errno errstr: $errstr; errfile: $errfile; errline: $errline"
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arch'INSA</title>
<style>
.ascii-art {
font-family: monospace;
white-space: pre;
}
</style>
</head>
<body>
<h1>[titre]</h1>
<a href="[url_token]">Clickez ici pour valider votre compte !</a>
<p>[paragraphe]</p>
<div class="ascii-art">
__ ____ ___ _ _ /'/ ____ _ _ ___ __
/__\ ( _ \ / __)( )_( ) (_ _)( \( )/ __) /__\
/(__)\ ) /( (__ ) _ ( _)(_ ) ( \__ \ /(__)\
(__)(__)(_)\_) \___)(_) (_) (____)(_)\_)(___/(__)(__)
</div>
<div class="ascii-art">
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣾⠙⠻⢶⣄⡀⠀⠀⠀⢀⣤⠶⠛⠛⡇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣇⠀⠀⣙⣿⣦⣤⣴⣿⣁⠀⠀⣸⠇⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣡⣾⣿⣿⣿⣿⣿⣿⣿⣷⣌⠋⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣷⣄⡈⢻⣿⡟⢁⣠⣾⣿⣦⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿⣿⣿⠘⣿⠃⣿⣿⣿⣿⡏⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⠀⠈⠛⣰⠿⣆⠛⠁⠀⡀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣿⣦⠀⠘⠛⠋⠀⣴⣿⠁⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣶⣾⣿⣿⣿⣿⡇⠀⠀⠀⢸⣿⣏⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠀⠀⠀⠾⢿⣿⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⣠⣿⣿⣿⣿⣿⣿⡿⠟⠋⣁⣠⣤⣤⡶⠶⠶⣤⣄⠈⠀⠀⠀⠀⠀⠀
⠀⠀⠀⢰⣿⣿⣮⣉⣉⣉⣤⣴⣶⣿⣿⣋⡥⠄⠀⠀⠀⠀⠀⠉⢻⣄⠀⠀⠀⠀
⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣟⣋⣁⣤⣀⣀⣤⣤⣤⣤⣄⣿⡄⠀⠀⠀⠀
⠀⠀⠀⠀⠙⠿⣿⣿⣿⣿⣿⣿⣿⡿⠿⠛⠋⠉⠁⠀⠀⠀⠀⠈⠛⠃⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠉⠉⠉⠉⠉⠀⠀⠀⠀⠀
</div>
</body>
</html>

View file

@ -1,97 +0,0 @@
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once "phpmailer/Exception.php";
require_once "phpmailer/PHPMailer.php";
require_once "phpmailer/SMTP.php";
include("test_creds.php");
class Mail
{
private static $mail = NULL;
private static $error = "";
private function readFile($file)
{
$real_path = $file;
$file = fopen($real_path, "r") or die("Unable to open file!");;
$password = fgets($file);
fclose($file);
return trim($password);
}
public function __construct()
{
global $mel_id,$mel_adr,$mel_mdp;
try {
$this::$mail = new PHPMailer(true);
$this::$mail->isSMTP();
$this::$mail->Host = "smtp.insa-toulouse.fr";
$this::$mail->SMTPAuth = true;
$this::$mail->Username = $mel_id;
$this::$mail->Password = $mel_mdp;
$this::$mail->setFrom($mel_adr, 'Club Info INSA Toulouse');
$this::$mail->isHTML(true);
$this::$mail->Subject = 'Inscription sur Arch\'INSA';
$this::$mail->Body = 'Message vide.';
$this::$mail->CharSet = 'UTF-8';
} catch (Exception $e) {
null;
}
}
public function setContent(string $subject,string $url,string $titre,string $paragraphe)
{
try {
//sécu et encodage en UTF-8 (n'échappe pas les ')
$subject = mb_convert_encoding($subject, 'UTF-8', 'auto');
$this::$mail->Subject = htmlspecialchars($subject, ENT_NOQUOTES, 'UTF-8');
$template = file_get_contents("utils/phpmailer/template_mel.html");
$content = str_replace("[url_token]", $url, $template);
$content = str_replace("[titre]", $titre, $content);
$content = str_replace("[paragraphe]", $paragraphe, $content);
$this::$mail->Body = $content;
} catch (Exception $e) {
null;
}
}
public function send(string $mail_dest, string $name_dest): bool
{
try {
$mail_dest=htmlspecialchars($mail_dest);
$name_dest=htmlspecialchars($name_dest);
$this::$mail->addAddress($mail_dest, $name_dest);
$this::$mail->Port = 465;
$this::$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$this::$mail->send();
} catch (Exception $e) {
$this::$error=$this::$mail->ErrorInfo;
return false;
}
return true;
}
public function getError(): string
{
return $this::$error;
}
}
/*
echo "test d'envoi de mail (sans token) ...";
$mailtest = new Mail();
$mailtest->setContent("sujet du mail", "titre du mail", "<p>ceci est un test</p><p>ceci est une seconde ligne</p>");
if(!$mailtest->send("mougnibas@insa-toulouse.fr", "test")) {
echo $mailtest->getError(); //si le mail n'a pas été envoyé
} else {
echo "coul coul coul"; // si le mail a été envoyé
}
*/
?>

View file

@ -1,112 +0,0 @@
<?php
// Database connection parameters
include("test_creds.php");
class Token
{
private static $conn;
public function __construct()
{
global $servername,$db_username,$db_password,$dbname;
self::$conn = new mysqli($servername, $db_username, $db_password, $dbname);
// Check connection
if (self::$conn->connect_error) {
die("Connection failed: " . self::$conn->connect_error);
}
}
private function randomStr($str_len) : string
{
$random_str_tot = "";
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( $x = 0; $x < $str_len; $x++ ) {
$random_str= $chars[random_int(0, strlen($chars)-1)];
$random_str_tot = $random_str_tot.$random_str;
}
return $random_str_tot;
}
public function delete(int $id_user, string $token)
{
$token = htmlspecialchars($token);
$id_user = htmlspecialchars($id_user);
$deleteReq = self::$conn->prepare("DELETE FROM `token` WHERE `id_user` = ? AND `token` = ?");
$deleteReq->execute(array($id_user, $token));
}
public function isValid(int $id_user, string $token) : bool
{
$id_user = htmlspecialchars($id_user);
$token = htmlspecialchars($token);
$req = self::$conn->prepare("SELECT `TOKEN`, `create_time` FROM `token` WHERE `id_user` = ? AND `TOKEN` = ?");
$ret = $req->execute(array($id_user, $token));
if($ret){
$req->store_result();
$req->bind_result($dbToken,$createTime);
$req->fetch();
$createTime = strtotime($createTime);
$currentTime = time();
$oneDayInSeconds = 86400; // 1 jour = 86400 s
$ret = $currentTime - $createTime <= $oneDayInSeconds;
if(!$ret){
// OLD TOKEN (+ d'un jour donc expiré)
$deleteReq = self::$conn->prepare("DELETE FROM `token` WHERE `id_user` = ?");
$deleteReq->execute(array($id_user));
}
}
return $ret;
}
public function Add(int $id_user) : string
{
$id_user = (int) htmlspecialchars($id_user);
$token = $this->randomStr(50);
// supprimer les anciens token
$deleteReq = self::$conn->prepare("DELETE FROM `token` WHERE `id_user` = ?");
$deleteReq->execute(array($id_user));
$req = self::$conn->prepare("INSERT INTO `token`(`id_user`, `TOKEN`, `create_time`) VALUES(?, ?, ?)");
$req->execute(array($id_user, $token, date("Y-m-d H:i:s", time())));
return $token;
}
public function getUserID(string $token) : int
{
$token = htmlspecialchars($token);
$req = self::$conn->prepare("SELECT `id_user` FROM `token` WHERE `TOKEN` = ?");
$req->execute(array($token));
$req->store_result();
$req->bind_result($id_user);
$res = $req->fetch();
if ($res) {
return $id_user;
} else {
return -1;
}
}
public function getToken(string $user_id) : string
{
$req = self::$conn->prepare("SELECT `TOKEN` FROM `token` WHERE `id_user` = ?");
$req->execute(array($user_id));
$req->store_result();
$req->bind_result($token);
$res = $req->fetch();
if ($res) {
return $token;
} else {
return -1;
}
}
}
?>

View file

@ -6,18 +6,18 @@ session_start();
$csrf = new CSRF();
// Check if user is logged in and is an admin
if (!isset($_SESSION["utilisateur_authentifie"]) || $_SESSION["utilisateur_authentifie"] !== true || !$_SESSION["admin"]) {
header("Location: index.php");
exit;
}
include("session_verif.php");
// Include your database connection code here
include("test_creds.php");
$conn = new mysqli($servername, $db_username, $db_password,$dbname);
$conn = new mysqli($servername, $username, $password,$dbname);
// Function to fetch and display documents
function generer_chronologie() {
function displayDocuments() {
global $conn;
@ -37,8 +37,8 @@ function generer_chronologie() {
if (($row["ensemble_id"] != $ens_id) && ($ens_id != -1) ) {
echo "<p><a href='#' onclick='valider_ensemble({$ens_id})' class='lien-valider-ens'>Valider l'ensemble</a></p>";
echo "<p><a href='#' onclick='supprimer_ensemble({$ens_id})' class='lien-supp-ens'>Supprimer l'ensemble</a></p>";
echo "<p><a href='#' onclick='valider_ensemble({$ens_id})'>Valider l'ensemble</a></p>";
echo "<p><a href='#' onclick='supprimer_ensemble({$ens_id})'>Supprimer l'ensemble</a></p>";
echo "</div>";
$ens_id = $row["ensemble_id"];
}
@ -54,84 +54,99 @@ function generer_chronologie() {
echo "<p>Upload Path: {$row['upload_path']}</p>";
echo "<p>Ensemble ID: {$row['ensemble_id']}</p>";
generateFileHTML($row);
$extension = pathinfo($row['upload_path'], PATHINFO_EXTENSION);
if (strtolower($extension) === 'pdf'):
echo "<embed src=\"{$row['upload_path']}\" type=\"application/pdf\" width=\"100%\" height=\"600px\" />";
elseif (in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif'])):
echo "<img src=\"{$row['upload_path']}\">";
elseif (strtolower($extension) == "html"):
echo("<iframe src=\"{$row['upload_path']}\"></iframe>");
else:
echo "<p>Unsupported file type</p>".$row['upload_path'];
endif;
echo "<p>Theme ID: {$row['theme_id']}</p>";
}
// complète le formulaire du dernier ensemble itéré
echo "<p><a href='#' onclick='valider_ensemble({$ens_id})' class='lien-valider-ens' id_ens='$ens_id' >Valider l'ensemble</a></p>";
echo "<p><a href='#' onclick='supprimer_ensemble({$ens_id})' class='lien-supp-ens' id_ens='$ens_id'>Supprimer l'ensemble</a></p>";
echo "<p><a href='#' onclick='valider_ensemble({$ens_id})'>Valider l'ensemble</a></p>";
echo "<p><a href='#' onclick='supprimer_ensemble({$ens_id})'>Supprimer l'ensemble</a></p>";
echo "</div>";
}
// Function to handle different file types and generate HTML dynamically
function generateFileHTML($row) {
// Simulating the switch-case equivalent in PHP using a switch on doc.type
$doc_type = $row['type']; // Assuming 'type' is the same as doc.type in JS
switch ($doc_type) {
case 2: // Image
// Create image element
echo "<img src=\"{$row['upload_path']}\" alt=\"{$row['titre']}\" />";
// Create link to view image
echo "<a href=\"{$row['upload_path']}\" class=\"lien\" target=\"_blank\">Voir image</a>";
break;
case 3: // PDF
// Create embed for PDF
echo "<embed src=\"{$row['upload_path']}\" type=\"application/pdf\" width=\"100%\" height=\"600px\" />";
// Create link to view PDF
echo "<a href=\"{$row['upload_path']}\" class=\"lien\" target=\"_blank\">Voir PDF en grand</a>";
break;
case 4: // Video
// Create video element with controls
echo "<video src=\"{$row['upload_path']}\" controls></video>";
break;
case 5: // HTML
// Create iframe for HTML document
echo "<iframe src=\"{$row['upload_path']}\" width=\"100%\" height=\"600px\"></iframe>";
break;
case 1: // Plain Text
// Fetch content via PHP file_get_contents
$text = file_get_contents($row['upload_path']);
echo "<textarea readonly style=\"width: 100%; height: 200px;\">$text</textarea>";
break;
default:
// Unsupported file type, create link
echo "<a href=\"{$row['upload_path']}\" class=\"lien\" target=\"_blank\">Type de fichier non supporté.</a>";
break;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<?php
$titre_page = "Validation des documents";
include "_partials/_head.php";
?>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Validation des documents</title>
<!-- Include your CSS styles here -->
</head>
<body>
<h2>Validation des documents</h2>
<?php generer_chronologie(); ?>
<!-- Display documents -->
<?php displayDocuments(); ?>
<script>
function valider_ensemble(ensembleId) {
const formData = new FormData();
formData.append("jeton-csrf","<?=$csrf->string($context="valider_ensemble")?>");
formData.append("ensemble_id",ensembleId);
fetch('api.php/valider_ensemble', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.status == 1) {
alert(data.msg)
}else{
alert(data.msg)
}
})
.catch(error => {
console.error('Error:', error);
});
}
function supprimer_ensemble(ensembleId) {
const formData = new FormData();
formData.append("jeton-csrf","<?=$csrf->string($context="supprimer_ensemble")?>");
formData.append("ensemble_id",ensembleId);
fetch('api.php/supprimer_ensemble', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
if (data.status == 1) {
alert(data.msg)
document.location.reload();
}else{
alert(data.msg)
}
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
</body>
<?php
echo $csrf->script($context='supprimer_ensemble', $name='jeton_supprimer_ensemble', $declaration='var', $time2Live=-1, $max_hashes=5);
echo $csrf->script($context='valider_ensemble', $name='jeton_valider_ensemble', $declaration='var', $time2Live=-1, $max_hashes=5);
include "_partials/_footer.php";
?>
</html>