ç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"] : ""; $query = isset($_GET["req"]) ? $_GET["req"] : "";
$length = isset($_GET["duree"]) ? $_GET["duree"] : ""; $length = isset($_GET["duree"]) ? $_GET["duree"] : "";
$tags = isset($_GET["duree"]) ? explode(",", $_GET["tags"]) : []; $themes = isset($_GET["duree"]) ? explode(",", $_GET["themes"]) : [];
try { try {
$results = searchExercises($query, $length, $tags); $results = searchExercises($query, $length, $themes);
echo json_encode(["status" => "1", "results" => $results]); echo json_encode(["status" => "1", "results" => $results]);
} catch (Exception $e) { } catch (Exception $e) {
echo json_encode(["status" => "0", "msg" => $e->getMessage()]); echo json_encode(["status" => "0", "msg" => $e->getMessage()]);

54
bdd.php
View file

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

View file

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

View file

@ -14,12 +14,15 @@
<input type="text" placeholder="titre" id="titre"></input> <input type="text" placeholder="titre" id="titre"></input>
<select id="select_type"> <select id="select_type">
<option value="annale">annale</option> <option value="1">annale</option>
<option value="fiche_revision">fiche_revision</option> <option value="2">fiche_revision</option>
</select> </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> </form>
<!-- Button to open the camera --> <!-- Button to open the camera -->
@ -36,12 +39,27 @@ function uploadFiles() {
formData.append("type",document.getElementById("select_type").value); formData.append("type",document.getElementById("select_type").value);
formData.append("titre",document.getElementById("titre").value); formData.append("titre",document.getElementById("titre").value);
formData.append("commentaire_auteur",document.getElementById("commentaire_auteur").value);
// Append each selected file to the FormData // Append each selected file to the FormData
let i = 0;
for (const file of fileInput.files) { 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 // Make a POST request using Fetch API
fetch('api.php/aj_doc', { fetch('api.php/aj_doc', {
method: 'POST', method: 'POST',
@ -80,34 +98,36 @@ function openCamera() {
// Convert the canvas content to a data URL // Convert the canvas content to a data URL
const imageDataUrl = canvas.toDataURL('image/jpeg'); const imageDataUrl = canvas.toDataURL('image/jpeg');
// Close the camera stream // Display the captured image
mediaStream.getTracks().forEach(track => track.stop()); 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());
// 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);
});
});
}) })
.catch(error => { .catch(error => {
console.error('Error accessing camera:', 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> </script>
</body> </body>