ça marche bordel

This commit is contained in:
thaaoblues 2023-11-03 22:22:27 +01:00
parent 02b2a1946e
commit 53e45aeb0d
5 changed files with 86 additions and 54 deletions

View file

@ -63,10 +63,10 @@
$query = isset($_GET["req"]) ? $_GET["req"] : "";
$length = isset($_GET["duree"]) ? $_GET["duree"] : "";
$tags = isset($_GET["duree"]) ? explode(",", $_GET["tags"]) : [];
$themes = isset($_GET["duree"]) ? explode(",", $_GET["themes"]) : [];
try {
$results = searchExercises($query, $length, $tags);
$results = searchExercises($query, $length, $themes);
echo json_encode(["status" => "1", "results" => $results]);
} catch (Exception $e) {
echo json_encode(["status" => "0", "msg" => $e->getMessage()]);

54
bdd.php
View file

@ -1,12 +1,16 @@
<?php
include("annales/test_creds.php");
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "archivinsa";
include("test_creds.php");
$conn = new mysqli($servername, $username, $password,$dbname);
// /!\ A CHANGER EN PROD /!\
$uploadDir = '/opt/lampp/htdocs/annales/archives/';
// le type de document est classifié entre 0 et n dans l'ensemble des entiers naturels
$max_val_type = 2;
// Liste des extensions autorisées pour les images
$image_extensions = [
@ -29,7 +33,7 @@ $pdf_extensions = ['pdf'];
$presentation_extensions = ['ppt', 'pptx','odp','pptm','ppsx'];
// Fusionner les listes en une seule liste
$ext_autorisees = array_merge($imageExtensions, $pdfExtensions, $presentationExtensions);
$ext_autorisees = array_merge($image_extensions, $pdf_extensions, $presentation_extensions);
function check_ext($filename) {
$extension = pathinfo($filename, PATHINFO_EXTENSION);
@ -39,33 +43,36 @@ function check_ext($filename) {
function ajouter_doc($request){
$conn = new mysqli($GLOBALS["servername"], $GLOBALS["username"], $GLOBALS["password"], $GLOBALS["dbname"]);
global $conn;
print_r($request);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ensemble (commentaire_auteur) VALUES(\"\")";
$sql = "INSERT INTO ensemble (commentaire_auteur) VALUES(\"".htmlspecialchars($request['commentaire_auteur'])."\")";
try{
$conn->execute_query($sql);
saveFilesFromPost($request,mysqli_insert_id($conn),$conn);
saveFilesFromPost($request,mysqli_insert_id($conn));
}catch(Exception $e){
echo(json_encode(["status"=>"0","msg"=>$e]));
echo(json_encode(["status"=>"0","msg"=>$e->getMessage()]));
}
}
function saveFilesFromPost($postData,$id_ensemble,$conn) {
function saveFilesFromPost($postData,$id_ensemble) {
global $conn;
// Check if the $_POST variable is set and contains files
echo(print_r($_FILES,true));
if (isset($_FILES['fichiers']) && is_array($_FILES['fichiers'])) {
// Directory to save the files
// /!\ A CHANGER EN PROD /!\
$uploadDir = '/opt/lampp/htdocs/annales/archives/';
if (isset($_FILES) && is_array($_FILES)) {
// Iterate through each file in the $_FILES array
@ -87,7 +94,7 @@ function saveFilesFromPost($postData,$id_ensemble,$conn) {
$uniqueFileName = uniqid() . '_' . htmlspecialchars($fileName);
// Define the path to save the file
$filePath = $uploadDir . $uniqueFileName;
$filePath = $GLOBALS['uploadDir'] . $uniqueFileName;
//echo($filePath."\n");
@ -106,15 +113,22 @@ function saveFilesFromPost($postData,$id_ensemble,$conn) {
try{
//update the database
$safe_titre = htmlspecialchars($postData['titre']);
$safe_type = htmlspecialchars($postData['type']);
$safe_type = intval($postData['type']);
global $max_val_type;
if ($safe_type < 1|| $safe_type > $max_val_type) {
echo(json_encode(['status'=> '2','msg'=>"Le type de document spécifié n'existe pas."]));
exit;
}
// pour tester, pas implémenté les commentaires globaux ni les themes
$sql="INSERT INTO documents (titre,type,upload_path,commentaire_auteur,ensemble_id) VALUES(?,?,?,?,?)";
$conn->execute_query($sql, array("titre"=> $safe_titre,"type"=>$safe_type,"upload_path"=> $uploadDir,"commentaire_auteur"=>"","ensemble_id"=>$id_ensemble));
$conn->execute_query($sql,array($safe_titre,$safe_type,$filePath,"",$id_ensemble));
}catch(Exception $e){
echo(json_encode(['status'=> '0','msg'=>$e]));
exit;
echo(json_encode(['status'=> '0','msg'=>$e->getMessage()]));
//exit;
}
}

View file

@ -1,9 +1,6 @@
<?php
// Database connection parameters
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "archivinsa";
include("test_creds.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
@ -22,7 +19,8 @@ $sql = "
CREATE TABLE IF NOT EXISTS ensemble (
id INT AUTO_INCREMENT PRIMARY KEY,
commentaire_auteur TEXT
commentaire_auteur TEXT,
valide BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE TABLE IF NOT EXISTS documents (

View file

@ -36,7 +36,7 @@ D'autres fonctionnalités seront ajoutées petit à petit. (si vous avez des sug
|--------------------|---------------|------------------------------------------|
| id | INT | AUTO_INCREMENT |
| commentaire_auteur | TEXT | |
| valide | BOOLEAN | NOT NULL |
### Table: documents
| Column | Type | Constraints |

View file

@ -14,12 +14,15 @@
<input type="text" placeholder="titre" id="titre"></input>
<select id="select_type">
<option value="annale">annale</option>
<option value="fiche_revision">fiche_revision</option>
<option value="1">annale</option>
<option value="2">fiche_revision</option>
</select>
<button type="button" onclick="uploadFiles()">Upload File</button>
<input type="text" placeholder="commentaires généraux sur l'ensemble des documents" id="commentaire_auteur"></input>
<div id="selectedImages"></div>
<button type="button" onclick="uploadFiles()">Téléverser les fichiers</button>
</form>
<!-- Button to open the camera -->
@ -36,12 +39,27 @@ function uploadFiles() {
formData.append("type",document.getElementById("select_type").value);
formData.append("titre",document.getElementById("titre").value);
formData.append("commentaire_auteur",document.getElementById("commentaire_auteur").value);
// Append each selected file to the FormData
let i = 0;
for (const file of fileInput.files) {
formData.append('fichiers', file);
formData.append('fichier' + i, file);
i ++;
}
// 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',
@ -80,34 +98,36 @@ function openCamera() {
// Convert the canvas content to a data URL
const imageDataUrl = canvas.toDataURL('image/jpeg');
// Close the camera stream
mediaStream.getTracks().forEach(track => track.stop());
// Make a POST request to upload the image
fetch('api.php/aj_doc', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fichiers: [{ name: 'camera_image.jpg', data: imageDataUrl.split(',')[1] }]
})
})
.then(response => response.text())
.then(data => {
console.log(data);
// Handle the response from the server
})
.catch(error => {
console.error('Error:', error);
});
// 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 });
}
</script>
</body>