From ca052b2f5d2e6d08631e4a058d07a8449cd9a56b Mon Sep 17 00:00:00 2001
From: nicrausaz <n.crausaz99@gmail.com>
Date: Thu, 11 Oct 2018 10:35:23 +0200
Subject: [PATCH] Working

---
 canapEPFL/cible.php                         | 74 ++++++++++-----------
 canapEPFL/helpers.php                       | 33 ++++-----
 canapEPFL/models/PersonnalData.php          | 16 ++++-
 canapEPFL/models/PersonnalDataValidator.php | 24 +++++++
 canapEPFL/script.js                         | 21 +++---
 canapEPFL/templates/confirmationText.php    |  3 -
 canapEPFL/templates/head.php                |  6 +-
 7 files changed, 102 insertions(+), 75 deletions(-)

diff --git a/canapEPFL/cible.php b/canapEPFL/cible.php
index be2b3a2..dc2acfe 100644
--- a/canapEPFL/cible.php
+++ b/canapEPFL/cible.php
@@ -1,47 +1,45 @@
 <!doctype html>
 <html lang="fr">
     <head>
-         <?php
-            include("templates/head.php");
-            include('templates/isPostulationOpen.php');
-            require_once("helpers.php");
-            require_once("models/PersonnalData.php");
-            require_once("models/PersonnalDataValidator.php");
-         ?>
-         <title>Confirmation</title>
+      <?php
+        include("templates/head.php");
+        include('templates/isPostulationOpen.php');
+        require_once("helpers.php");
+        require_once("models/PersonnalData.php");
+        require_once("models/PersonnalDataValidator.php");
+      ?>
+      <title>Postulation Apprentis | Confirmation</title>
     </head>
     <body>
-    <div class="page-style">
-        <?php
-            include('templates/header.php');
-            //Init personnalData with postedData
-            $candidateData = new PersonnalData($_POST);
-            //Init dataValidator
-            $validator = new PersonnalDataValidator($candidateData);
+    <?php
+      include('templates/header.php');
+      // Init personnalData with postedData
+      $candidateData = new PersonnalData($_POST, $_FILES);
+      // Init dataValidator
+      $validator = new PersonnalDataValidator($candidateData);
 
-            if($validator->isValid()){
-                //Create folders
-                createCandidateFolders($candidateData);
-                //Upload files
-                $candidateData = uploadAllFiles($candidateData->getPaths()["pathAnnexes"], $_FILES, $candidateData);
-                //Create JSON file and upload it
-                $encodedJson = (json_encode($candidateData,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
-                file_put_contents($candidateData->getPaths()["pathInfos"].'/informations.json', $encodedJson);
-                //Send mails
+      if($validator->isValid()){
+        // Create folders
+        createCandidateFolders($candidateData);
+        // Upload files
+        $candidateData = uploadAllFiles($candidateData->getPaths()["pathAnnexes"], $candidateData->tmp_fichiers, $candidateData);
+        // Create JSON file and upload it
+        $encodedJson = (json_encode($candidateData,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
+        file_put_contents($candidateData->getPaths()["pathInfos"].'/informations.json', $encodedJson);
+        // Send mails
 
-                // mailToResp($candidateData->prenomApprenti, $candidateData->nomApprenti, $candidateData->formation);
-                mailToApprenti($candidateData->mailApprenti, $candidateData->formation);
-                // kill session
-                $_SESSION['formError'] = false;
-                //unset($_SESSION['postedForm']);
-                include("templates/confirmationText.php");
-            }else{
-                $_SESSION['formError'] = true;
-                $_SESSION['postedForm'] = $_POST;
-                $_SESSION['files'] = $_FILES;
-                include("templates/errorText.php");
-            }
-        ?>
-        </div>
+        // mailToResp($candidateData->prenomApprenti, $candidateData->nomApprenti, $candidateData->formation);
+        mailToApprenti($candidateData->mailApprenti, $candidateData->formation);
+        // kill session
+        $_SESSION['formError'] = false;
+        // unset($_SESSION['postedForm']);
+        include("templates/confirmationText.php");
+      } else {
+        $_SESSION['formError'] = true;
+        $_SESSION['postedForm'] = $_POST;
+        $_SESSION['files'] = $_FILES;
+        include("templates/errorText.php");
+      }
+    ?>
     </body>
 </html>
\ No newline at end of file
diff --git a/canapEPFL/helpers.php b/canapEPFL/helpers.php
index a22c93a..3d6341e 100644
--- a/canapEPFL/helpers.php
+++ b/canapEPFL/helpers.php
@@ -5,7 +5,7 @@ function mailToResp($surname, $name, $job){
 }
 
 //vire les accents et remplace caractere non alphanumeric par '-'
-function checkChars($toCheck){
+function checkChars ($toCheck) {
     $toCheck = strtr($toCheck,
     'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
     'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
@@ -20,18 +20,9 @@ function mailToApprenti($to, $job){
 
 function uploadFile(&$candidateData, $pathAnnexes, $file, $name){
     $extension = strtolower(strrchr($file['name'], '.'));
-    $validExt = ['.pdf', '.jpeg', '.png', '.jpg'];
-    $filename = $name . $extension;
-
-    if(!in_array($extension, $validExt)){
-        $erreur = "uploadError";
-    }
-
-    if(!isset($erreur)){
-        $filename = checkChars($filename);
-        move_uploaded_file($file['tmp_name'], $pathAnnexes . $filename);
-        $candidateData->fichiers[$name] = $filename;
-    }
+    $file['name'] = $name . $extension;
+    move_uploaded_file($file['tmp_name'], $pathAnnexes . $file['name']);
+    $candidateData->fichiers[$name] = $file['name'];
 }
 
 //Crée le dossier principal est ses 2 sous-dossiers
@@ -50,21 +41,23 @@ function uploadAllFiles($pathAnnexes, $postedFiles, $candidateData){
     uploadFile($candidateData, $pathAnnexes, $postedFiles['idCard'], "carte-identite");
     uploadFile($candidateData, $pathAnnexes, $postedFiles['cv'], "curriculum-vitae");
     uploadFile($candidateData, $pathAnnexes, $postedFiles['lettre'], "lettre-motivation");
-    
-    for($i=1; $i<=9; $i++){
-        if(array_key_exists('certifs'.$i, $postedFiles)){
-            if(!($postedFiles['certifs'.$i]['name'] == "")) {
+
+    for ($i = 1; $i <= 9; $i++){
+        if (array_key_exists('certifs'.$i, $postedFiles)){
+            if (!($postedFiles['certifs'.$i]['name'] == "")) {
                 uploadFile($candidateData, $pathAnnexes, $postedFiles['certifs'.$i], "annexe".$i);
             }
         }
     }
-    
-    if($candidateData->formation=="polyMecanicien"){
+
+    if($candidateData->formation=="polyMecanicien" && isset($postedFiles['gimch'])){
         uploadFile($candidateData, $pathAnnexes, $postedFiles['gimch'], "certificat-gimch");
     }
-    if($candidateData->formation=="informaticien"){
+    if($candidateData->formation=="informaticien" && isset($postedFiles['griTestInput'])){
         uploadFile($candidateData, $pathAnnexes, $postedFiles['griTestInput'], "certificat-gri");
     }
+
+    unset($candidateData->tmp_fichiers);
     return $candidateData;
 }
 ?>
\ No newline at end of file
diff --git a/canapEPFL/models/PersonnalData.php b/canapEPFL/models/PersonnalData.php
index 6e0872f..b4f799a 100644
--- a/canapEPFL/models/PersonnalData.php
+++ b/canapEPFL/models/PersonnalData.php
@@ -46,10 +46,11 @@ class PersonnalData {
     public $anneeCandidature = "";
     public $datePostulation = "";
     public $fichiers = [];
+    public $tmp_fichiers = [];
 
-    public function __construct($postedData){
+    public function __construct($postedData, $postedFiles) {
         $this->dateNow = date('Y-m-d_H-i-s');
-        //Rempli les infos
+        // Rempli les infos
         $this->postedData = $postedData;
         $this->formation = $postedData['job'];
         $this->lieu = $postedData['lieu'];
@@ -81,6 +82,7 @@ class PersonnalData {
         $this->setDejacand();
         $this->anneeFinScolarite = $postedData['anneeFin'];
         $this->datePostulation = date('j-n-o--'.'h:i:s');
+        $this->tmp_fichiers = $this->setFiles($postedFiles);
     }
 
     private function setRepresentants(){
@@ -129,6 +131,16 @@ class PersonnalData {
         }
     }
 
+    private function setFiles ($postedFiles) {
+        // Clear empty files
+        foreach ($postedFiles as $key => $file) {
+            if ($file['error'] != 0) {
+                unset($postedFiles[$key]);
+            }
+        }
+        return $postedFiles;
+    }
+
     public function getPaths(){
         $folderName = $this->dateNow."_".$this->mailApprenti;
         $path = $this->rootpath.$this->formations[$this->formation].'/'.$folderName.'/';
diff --git a/canapEPFL/models/PersonnalDataValidator.php b/canapEPFL/models/PersonnalDataValidator.php
index e41648b..17b4274 100644
--- a/canapEPFL/models/PersonnalDataValidator.php
+++ b/canapEPFL/models/PersonnalDataValidator.php
@@ -23,6 +23,7 @@ class PersonnalDataValidator {
         $this->isFormationValid();
         $this->isEcoleValid();
         $this->anneeFinScolariteValid();
+        $this->filesValid();
 
         return count($this->errors) === 0;
     }
@@ -126,5 +127,28 @@ class PersonnalDataValidator {
             }
         }
     }
+    private function filesValid () {
+        $filesToCheck = $this->personnalData->fichiers;
+        $validExt = ['.pdf', '.jpeg', '.png', '.jpg'];
+        $requiredKeys = ['photo', 'idCard', 'cv', 'lettre', 'certifs1'];
+
+        foreach($filesToCheck as $key => $file) {
+            // Pour les fichiers obligatoire
+            if (in_array($file['name'], $requiredKeys)) {
+                // si fichier non fourni
+                if (!$file['error'] == 0) {
+                    $this->errors['fichiers'] = 'Fichier(s) non fourni(s)';
+                }
+            }
+
+            // Check les formats
+            if ($file['name'] != "") {
+                $extension = strtolower(strrchr($file['name'], '.'));
+                if(!in_array($extension, $validExt)){
+                    $this->errors['fichiers'] = 'Format de fichier(s) non valable(s)';
+                }
+            }
+        }
+    }
 }
 ?>
\ No newline at end of file
diff --git a/canapEPFL/script.js b/canapEPFL/script.js
index 3db8c3d..d99432b 100644
--- a/canapEPFL/script.js
+++ b/canapEPFL/script.js
@@ -13,17 +13,18 @@ $(document).ready(function () {
 });
 
 function checkDate() {
-    var birthdate = moment(document.getElementById("birthApp").value, "DD/MM/YYYY")._d;
-    var cur = new Date();
-    var diff = cur - birthdate; // This is the difference in milliseconds
-    var age = Math.floor(diff / 31536000000); // Divide by 1000*60*60*24*365
+    // TODO: fix
+    // var birthdate = moment(document.getElementById("birthApp").value, "DD/MM/YYYY")._d;
+    // var cur = new Date();
+    // var diff = cur - birthdate; // This is the difference in milliseconds
+    // var age = Math.floor(diff / 31536000000); // Divide by 1000*60*60*24*365
 
-    if (age <= 12 || birthdate.getFullYear() < 1910 || age > 60) {
-        document.getElementById('errorMsg').innerHTML = '<p class ="errorMsgs">Date invalide';
-    }
-    else {
-        document.getElementById('errorMsg').innerHTML = '';
-    }
+    // if (age <= 12 || birthdate.getFullYear() < 1910 || age > 60) {
+    //     document.getElementById('errorMsg').innerHTML = '<p class="errorMsgs">Date invalide';
+    // }
+    // else {
+    //     document.getElementById('errorMsg').innerHTML = '';
+    // }
 }
 
 function initDateChecker() {
diff --git a/canapEPFL/templates/confirmationText.php b/canapEPFL/templates/confirmationText.php
index 20ce404..2ca1573 100644
--- a/canapEPFL/templates/confirmationText.php
+++ b/canapEPFL/templates/confirmationText.php
@@ -1,6 +1,3 @@
-
-
-
 <main id="main" role="main" class="content container-grid">
   <p>Votre demande à bien été enregistrée, vous allez bientôt recevoir un e-mail confirmant votre postulation.</p>
   <button type="button" class="btn btn-primary btn-sm mt-3 mb-2" id="retourHome">Retour à l'acceuil</button>
diff --git a/canapEPFL/templates/head.php b/canapEPFL/templates/head.php
index 29a7aab..589bac5 100644
--- a/canapEPFL/templates/head.php
+++ b/canapEPFL/templates/head.php
@@ -11,7 +11,9 @@
 <style>.error { color: red!important; }</style>
 <noscript>Veuillez Activer JavaScript pour utiliser le service de postulation</noscript>
 <?php
-  ini_set("display_errors",0);
-  error_reporting(0);
+  // ini_set("display_errors", 0);
+  // error_reporting(0);
+  ini_set("display_errors", 1);
+  error_reporting(E_ALL);
   session_start();
 ?>
\ No newline at end of file
-- 
GitLab