/[openfoncier]/trunk/services/metier/consultationmanager.php
ViewVC logotype

Diff of /trunk/services/metier/consultationmanager.php

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 564 by mlimic, Wed Oct 31 12:23:19 2012 UTC revision 744 by fmichon, Mon Nov 19 11:52:29 2012 UTC
# Line 1  Line 1 
1  <?php  <?php
2    /**
3  /*   * Ce fichier permet de déclarer la classe ConsultationManager, qui effectue les
4   * Processes requests received via services which concern consultations (by   * traitements pour la ressource 'consultations'.
  * ERP or other services).  
  *  
  * @author Mirna Limic <[email protected]>  
  * Date: 18/10/2012  
5   *   *
6   * Follow-up:   * @package openfoncier
7   * Bugs:   * @version SVN : $Id$
8   */   */
9    
10    // Inclusion de la classe de base MetierManager
11    require_once("./metier/metiermanager.php");
12    
13  require_once ("./metier/metiermanager.php");  // Inclusion de la classe métier consultation
14    require_once("../obj/consultation.class.php");
15    
16    /**
17     * Cette classe hérite de la classe MetierManager. Elle permet d'effectuer des
18     * traitements pour la ressource 'consultations'. Le traitement permet de
19     * rendre un retour d'avis sur une consultation existante par un service
20     * interne à la mairie directement depuis son application.
21     *
22     * @todo XXX Traduire et commenter toutes les méthodes
23     */
24  class ConsultationManager extends MetierManager {  class ConsultationManager extends MetierManager {
       
25    
26      /*      /**
27       * Constructor.       * Constructeur
28       *       *
29       * Calls it's parent constructor to establish a DB connection       * @todo XXX Ajouter la description des attributs
30       * and initializes the instance variables       */
      */      
31      public function __construct() {      public function __construct() {
32    
33            // Appel du constructeur parent
34          parent::__construct();          parent::__construct();
35          $this->date_limite = null;  
36          $this->date_retour = null;          //
         $this->date_envoi = null;  
         $this->dossier_id = null;  
37          $this->decisions = null;          $this->decisions = null;
38            $this->metier_instance = null;
39            $this->filename_prefix = null;
40            $this->filename = null;
41    
42      }      }
43        
44            /**
45      /*       * Destructeur
46       * Destructor       */
      *  
      * Call's its parent's destructor.  
      */      
47      public function __destruct() {      public function __destruct() {
48    
49            // Appel du destructeur parent
50          parent::__destruct();          parent::__destruct();
     }  
51    
       
     /*  
      * Verifies that a date falls inside of a date interval  
      * @param string $date_str The string that should fall  
      * within the interval  
      * @param string $date_start_str The begining of the interval  
      * @param string $date_end_str The end of the interval  
      * @return book true if $date_str is found inside of the  
      * interval, false otherwise  
      */  
     private function dateValid($date_str, $date_start_str = null,  
                                $date_end_str = null) {  
         $dates_str = array($date_start_str, $date_end_str);  
         $dates = array();  
         for ($i = 0; $i < 2; $i++) {  
             if ($dates_str[$i] == null) {  
                 $dates[] = null;  
                 continue;  
             }  
             $d = explode('-', $dates_str[$i]);  
             $dates[] = strtotime($d[2].'-'.$d[1].'-'.$d[0]);  
         }  
         $d = explode('/', $date_str);  
         $date = strtotime(implode('-', $d));  
           
         if ($dates[0] && $date < $dates[0]) {  
             return false;  
         }  
         if ($dates[1] && $date > $dates[1]) {  
             return false;  
         }  
         return true;  
     }  
       
       
     /*  
      * Searches for the consultation in DB to extract dates  
      * and the ID of the dossier the consultation belongs to.  
      * @param string $id The discussion id  
      * @return string OK on success, KO otherwise  
      */  
     private function getDataFromDB($id) {  
         $sql = 'SELECT date_envoi, date_retour, date_limite, dossier FROM '.  
             'consultation WHERE consultation = '.$id;  
         $res = $this->db->query($sql);  
         if ($this->checkDBError($res, 'Erreur lors de recuperation des dates '.  
                 'de la consultation '.$id)) {  
             return $this->KO;  
         }  
         while ($row =& $res->fetchRow(DB_FETCHMODE_ORDERED)) {  
             $this->date_envoi = $row[0];;  
             $this->date_retour = $row[1];  
             $this->date_limite = $row[2];  
             $this->dossier_id = $row[3];  
         }  
           
         $res->free();  
         return $this->OK;  
52      }      }
53    
54        /**
     /*  
55       * Verifies that the date_retour received in the incomming data       * Verifies that the date_retour received in the incomming data
56       * is in the (date_envoi, date_limite) interval. Also, check that       * is in the (date_envoi, date_limite) interval. Also, check that
57       * there is no date_retour set for the consultation, as well as the       * there is no date_retour set for the consultation, as well as the
# Line 115  class ConsultationManager extends Metier Line 63  class ConsultationManager extends Metier
63       */           */    
64      private function checkDates($date_str, $id) {      private function checkDates($date_str, $id) {
65          // check that the consultation exists in DB          // check that the consultation exists in DB
66          if (!$this->date_limite) {          if (empty($this->metier_instance->valF['date_limite'])) {
67              $this->setMessage("La consultation ".$id." n'était pas trouvé");              $this->setMessage("La consultation ".$id." n'était pas trouvé");
68              return $this->BAD_DATA;              return $this->BAD_DATA;
69          }          }
70    
71          // check that the date_retour does not already exist          // check that the date_retour does not already exist
72          if (!empty($this->date_retour)) {          if (!empty($this->metier_instance->valF['date_retour'])) {
73              $this->setMessage("Le date de retour de la consultation ".$id.              $this->setMessage("Le date de retour de la consultation ".$id.
74                  " existe déjà");                  " existe déjà");
75              return $this->BAD_DATA;              return $this->BAD_DATA;
# Line 135  class ConsultationManager extends Metier Line 83  class ConsultationManager extends Metier
83              return $this->BAD_DATA;              return $this->BAD_DATA;
84          }          }
85                    
86          if (!$this->dateValid($date_str, $this->date_envoi, $this->date_limite)) {          if (!$this->dateInsideInterval($date_str,
87                        $this->metier_instance->valF['date_envoi'],
88                        $this->metier_instance->valF['date_limite'])) {
89              $this->setMessage("Le date de retour fourni pour la consultation ".              $this->setMessage("Le date de retour fourni pour la consultation ".
90                                $id." n'est pas entre le date d'envoi ".                                $id." n'est pas entre le date d'envoi ".
91                                "et le date limite de la demande de consultation");                                "et le date limite de la demande de consultation");
# Line 144  class ConsultationManager extends Metier Line 94  class ConsultationManager extends Metier
94          return $this->OK;          return $this->OK;
95      }      }
96    
97        /**
     /*  
98       * Verifies that the avis received in the incomming data corresponds       * Verifies that the avis received in the incomming data corresponds
99       * to one of the avis found in DB.       * to one of the avis found in DB.
100       * @param string $avis The avis recived in the request       * @param string $avis The avis recived in the request
# Line 154  class ConsultationManager extends Metier Line 103  class ConsultationManager extends Metier
103       */       */
104      private function avisValid($avis, $id) {      private function avisValid($avis, $id) {
105          // get all of the decisions possible from table avis_decision          // get all of the decisions possible from table avis_decision
106          $sql = "SELECT libelle, avis_consultation FROM avis_consultation";          $sql = "SELECT libelle, avis_consultation FROM ".DB_PREFIXE."avis_consultation";
107          $res = $this->db->query($sql);          $res = $this->db->query($sql);
108          if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.          if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.
109                  'possibles pendant traitement de la consultation '.$id)) {                  'possibles pendant traitement de la consultation '.$id)) {
# Line 170  class ConsultationManager extends Metier Line 119  class ConsultationManager extends Metier
119          // check that the decision received corresponds to a decision in DB          // check that the decision received corresponds to a decision in DB
120          if (!in_array($avis, array_keys($this->decisions))) {          if (!in_array($avis, array_keys($this->decisions))) {
121              $this->setMessage(              $this->setMessage(
122                  "L'avis de consultation reçu n'est pas trouvé dans la BD");                  "L'avis de consultation reçu n'est pas feasible");
123              return $this->KO;              return $this->KO;
124          }          }
125          return $this->OK;          return $this->OK;
126      }      }
127    
128            /**
     /*  
129       * Verifies that all the data concerning file to be stored (if any)       * Verifies that all the data concerning file to be stored (if any)
130       * are present in full or not present at all       * are present in full or not present at all
131       * @param mixed $data The data recived in the request       * @param mixed $data The data recived in the request
# Line 196  class ConsultationManager extends Metier Line 144  class ConsultationManager extends Metier
144          return $this->OK;          return $this->OK;
145      }      }
146    
147        /**
     /*  
      * Store the data recived in the request into a file on the  
      * local filesystem.  
      * @todo This function will need to be changed for the save to  
      * be on GED  
      * @param mixed $data The data received with the request  
      * @param string $id The consultation ID  
      * @return string OK on success, KO otherwise  
      */  
     private function storeDecisionFile(&$data, $id) {  
         if (isset($data['fichier_base64'])) {  
             $dir = dirname(__FILE__).'/../../trs/'.$this->dossier_id;  
               
             // if a file already exists by that name and it  
             // is not a directory, back out  
             if (file_exists($dir) && !is_dir($dir)) {  
                 $this->setMessage("Fichier d'avis ne peut pas être ".  
                 "enregistré pour la consultation ".$id);  
                 return $this->KO;                  
             }  
             // if a dirextory by that name exists, make sure it does  
             // not already contain an avis de consultation  
             if (file_exists($dir) && is_dir($dir)) {  
                 $dir_contents = trim(shell_exec('ls '.$dir));  
                 if (strpos($dir_contents, ' ') != false) {  
                     $dir_contents = explode(' ', $dir_contents);  
                 } else {  
                     $dir_contents = array($dir_contents);  
                 }  
                 foreach ($dir_contents as $filename) {  
                     if (strspn($filename, 'consultation_'.$id.'_', 0) > 0) {  
                         $this->setMessage("Un fichier d'avis existe déjà ".  
                         "pour la consultation ".$id);  
                         return $this->KO;  
                     }  
                 }  
             }  
             // if no file by that name exists, create the directory  
             if (!file_exists($dir)) {  
                 if (!mkdir($dir, 0775)) {  
                     $this->setMessage("Erreur dans la création de répertoire ".  
                     "pour la sauvegarde de l'avis de la consultation ".$id);  
                     return $this->KO;  
                 }  
             }  
   
               
             // store the file contents into the file named:  
             //      consultation_<ID>_<file_name_received>  
             $file_len = strlen($data['fichier_base64']);  
             $filename = $dir.'/consultation_'.$id.'_'.$data['nom_fichier'];  
             $file = fopen($filename, 'w');  
             if (!$file) {  
                 $this->setMessage("Echec en création de pointeur de fichier ".  
                     "pour la sauvegarde de l'avis de la consultation ".$id);  
                 return $this->KO;  
             }  
             // check that the number of bytes written is equal to the length  
             // of the data received  
             $num_written = fwrite($file, $data['fichier_base64'], $file_len);  
             if (!$num_written || $num_written != $file_len) {  
                 $this->setMessage("Sauvegarde de fichier d'avis pour la ".  
                 "consultation ".$id." a échouée");  
                 // remove the file  
                 //print '   $num_written:'.$num_written."\r\n";  
                 // the return value from shell can't be used for checking since  
                 // one can not know if the NULL returned is because there was no  
                 // output or because there was an error  
                 $ret = shell_exec("rm -f $filename 2>&1");  
                 //if ($ret == NULL) { // an error occured while deleting the file  
                 //    $msg = $this->getMessage();  
                 //    $this->setMessage($msg . ' Problème pendent la suppression '.  
                 //            'des données corrompues');  
                 //}  
                 return $this->KO;  
             }  
             fclose($file);  
         }  
         return $this->OK;  
     }  
       
     /*  
148       * Called when one of the external services sends its recommendation       * Called when one of the external services sends its recommendation
149       * as a responde to a demand issued by openfoncier.       * as a responde to a demand issued by openfoncier.
150       * @param mixed $data The array containing building number.       * @param mixed $data The array containing building number.
# Line 286  class ConsultationManager extends Metier Line 152  class ConsultationManager extends Metier
152       * @return bool 'OK'       * @return bool 'OK'
153       */       */
154      public function consultationDecision($data, $id) {      public function consultationDecision($data, $id) {
155                  
156          // get all of the dates for the consultation from DB          // get all of the dates for the consultation from DB
157          // and check the date received is ok with respect to the          // and check the date received is ok with respect to the
158          // time interval set by (date_envoi, date_limite)          // time interval set by (date_envoi, date_limite)
159          // equally extract the dossier ID while at it          // equally extract the dossier ID while at it
160          $res = $this->getDataFromDB($id);          $this->metier_instance = new consultation($id, $this->db, 0);
161          if ($res != $this->OK) {          
162              return $res;          // check that the consultation was found
163            if (isset($this->metier_instance->errors['db_debuginfo'])
164                && !empty($consultation->errors['db_debuginfo'])) {
165                $this->setMessage("Erreur lors de recuperation de la ".
166                            "consultation $id");
167                return $this->KO;
168          }          }
169                    
170          // check that the date sent is applicable          // check that the date sent is applicable
# Line 301  class ConsultationManager extends Metier Line 172  class ConsultationManager extends Metier
172          if ($res != $this->OK) {          if ($res != $this->OK) {
173              return $res;              return $res;
174          }          }
175            
176            // set the prefix for the filename to use in case file data
177            // was received
178            $this->filename_prefix = "consultation_".$id."_";
179          // check that data regarding fichier is complete          // check that data regarding fichier is complete
180          $res = $this->fichierDataValid($data, $id);          $res = $this->fichierDataValid($data, $id);
181          if ($res != $this->OK) {          if ($res != $this->OK) {
182              return $res;              return $res;
183          }          }
184                    
           
185          // check that the decision sent is one of the decisions found in DB          // check that the decision sent is one of the decisions found in DB
186          // and store the possible decisions in $this->decisions          // and store the possible decisions in $this->decisions
187          $res = $this->avisValid($data['avis'], $id);          $res = $this->avisValid($data['avis'], $id);
188          if ($res != $this->OK) {          if ($res != $this->OK) {
189              return $res;              return $res;
         }          
           
         // first store the file if needed  
         $res = $this->storeDecisionFile($data, $id);  
         if ($res != $this->OK) {  
             return $res;  
190          }          }
191                    if(isset($data['fichier_base64'])) {
192          // update the DB              if($file_content = base64_decode ($data['fichier_base64'] , TRUE )) {
193          $date = explode("/", $data['date_retour']);                  // first store the file if needed
194          $sql = "UPDATE consultation SET ".                  $res = $this->f->storeDecisionFile($file_content,
195              "date_retour = DATE '".                                             $data['nom_fichier'],
196                  $date[2]."-".$date[1]."-".$date[0]."', ";                                             $this->metier_instance->valF['dossier'],
197          if (isset($data['motivation'])) {                                             $this->filename_prefix);
198              $sql .= "motivation = " . $data['motivation'] . ", ";                  if ($res !== true) {
199                        return $res;
200                    }
201                } else {
202                    $this->setMessage(_("Le contenu du fichier n'est pas valide."));
203                    return $this->BAD_DATA;
204                }
205          }          }
206    
207            $this->metier_instance->valF['date_retour'] = $data['date_retour'];
208            $this->metier_instance->valF['avis_consultation'] = $this->decisions[$data['avis']];
209            $this->metier_instance->valF['lu'] = FALSE;
210          if (isset($data['nom_fichier'])) {          if (isset($data['nom_fichier'])) {
211              $sql .= "fichier = '".$data['nom_fichier'] . "', ";              $this->metier_instance->valF['fichier'] = $this->filename_prefix . $data['nom_fichier'];
212          }          }
213          $sql .= "avis_consultation = ".$this->decisions[$data['avis']].          if (isset($data['motivation'])) {
214              ", lu = false WHERE consultation = ".$id;              $this->metier_instance->valF['motivation'] = $data['motivation'];
   
         $res = $this->db->query($sql);  
         if ($this->checkDBError($res, 'Erreur lors de mis à jour '.  
                 'de la consultation '.$id.' dans le DB')) {  
             return $this->KO;  
215          }          }
216                    
217          $this->setMessage("L'avis de la consultation ".$id.          $ret = parent::modifier($this->metier_instance->valF,
218                            " a été pris en compte");              "L'avis de la consultation $id a été pris en compte",
219          return $this->OK;              "Erreur pendant le traitemande de la demande pour la consultation $id");
220            if ($ret != $this->OK) {
221                // delete the file on disk
222                if (isset($data['nom_fichier'])) {
223                    shell_exec("rm -f $this->filename");
224                }
225            }
226            return $ret;
227      }      }
228        
       
229  }  }
230    
231  ?>  ?>

Legend:
Removed from v.564  
changed lines
  Added in v.744

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26