/[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 559 by mlimic, Tue Oct 30 17:05:34 2012 UTC revision 573 by mlimic, Wed Oct 31 16:23:31 2012 UTC
# Line 13  Line 13 
13    
14    
15  require_once ("./metier/metiermanager.php");  require_once ("./metier/metiermanager.php");
16    require_once("../obj/consultation.class.php");
17    
18  class ConsultationManager extends MetierManager {  class ConsultationManager extends MetierManager {
19            
# Line 20  class ConsultationManager extends Metier Line 21  class ConsultationManager extends Metier
21      /*      /*
22       * Constructor.       * Constructor.
23       *       *
24       * Calls it's parent constructor to establish a DB connection.       * Calls it's parent constructor to establish a DB connection
25         * and initializes the instance variables
26       */           */    
27      public function __construct() {      public function __construct() {
28          parent::__construct();          parent::__construct();
29          $this->date_limite = null;          /*$this->date_limite = null;
30          $this->date_retour = null;          $this->date_retour = null;
31          $this->date_envoi = null;          $this->date_envoi = null;
32          $this->dossier_id = null;          $this->dossier_id = null;*/
33          $this->decisions = null;          $this->decisions = null;
34            $this->metier_instance = null;
35            $this->filename_prefix = null;
36            $this->filename = null;
37      }      }
38            
39            
# Line 42  class ConsultationManager extends Metier Line 47  class ConsultationManager extends Metier
47      }      }
48    
49            
50      private function dateValid($date_str, $date_start_str = null,      /*
51         * Verifies that a date falls inside of a date interval
52         * @param string $date_str The string that should fall
53         * within the interval
54         * @param string $date_start_str The begining of the interval
55         * @param string $date_end_str The end of the interval
56         * @return book true if $date_str is found inside of the
57         * interval, false otherwise
58         */
59        private function dateInsideInterval($date_str, $date_start_str = null,
60                                 $date_end_str = null) {                                 $date_end_str = null) {
61          $dates_str = array($date_start_str, $date_end_str);          $dates_str = array($date_start_str, $date_str, $date_end_str);
62            if (count($dates_str) == 1) {
63                return true;
64            }
65          $dates = array();          $dates = array();
66          for ($i = 0; $i < 2; $i++) {          $prev_date = -1;
67            for ($i = 0; $i < 3; $i++) {
68              if ($dates_str[$i] == null) {              if ($dates_str[$i] == null) {
69                  $dates[] = null;                  $dates[] = null;
70                  continue;                  continue;
71              }              }
72              $d = explode('-', $dates_str[$i]);              $d = explode('/', $dates_str[$i]);
73              $dates[] = strtotime($d[2].'-'.$d[1].'-'.$d[0]);              $date = strtotime($d[2].'-'.$d[1].'-'.$d[0]);
74          }              if ($i > 0 && $date < $prev_date) {
75          $d = explode('/', $date_str);                  return false;
76          $date = strtotime(implode('-', $d));              }
77                        $prev_date = $date;
         print '  start:'.strval($dates[0]);  
         print '  end:'.strval($dates[1]);  
         print '  sent:'.strval($date);  
         if ($dates[0] && $date < $dates[0]) {  
             return false;  
         }  
         if ($dates[1] && $date > $dates[1]) {  
             return false;  
78          }          }
79          return true;          return true;
80      }      }    
81            
82        
83      private function getDataFromDB($id) {      /*
84          $sql = 'SELECT date_envoi, date_retour, date_limite, dossier FROM '.       * Verifies that the date_retour received in the incomming data
85              'consultation WHERE consultation = '.$id;       * is in the (date_envoi, date_limite) interval. Also, check that
86          $res = $this->db->query($sql);       * there is no date_retour set for the consultation, as well as the
87          if ($this->checkDBError($res, 'Erreur lors de recuperation des dates '.       * validity of the date itself
88                  'de la consultation :'.$id)) {       * @param string $date_str The date_retour recived in the request
89              return $this->KO;       * @param string $id The discussion id
90          }       * @return string OK on success, BAD_DATA if the data sent is invalid,
91          while ($row =& $res->fetchRow(DB_FETCHMODE_ORDERED)) {       * KO otherwise
92              $this->date_envoi = $row[0];;       */    
93              $this->date_retour = $row[1];      private function checkDates($date_str, $id) {
             $this->date_limite = $row[2];  
             $this->dossier_id = $row[3];  
         }  
           
         print ' date_envoi:'.$this->date_envoi;  
         print ' date_limite:'.$this->date_limite;  
         $res->free();  
         return $this->OK;  
     }  
       
     private function checkDates($date_str) {  
94          // check that the consultation exists in DB          // check that the consultation exists in DB
95          if (!$this->date_limite) {          if (empty($this->metier_instance->valF['date_limite'])) {
96              $this->setMessage("La consultation n'était pas trouvé");              $this->setMessage("La consultation ".$id." n'était pas trouvé");
97              return $this->BAD_DATA;              return $this->BAD_DATA;
98          }          }
99    
100          // check that the date_retour does not already exist          // check that the date_retour does not already exist
101          if (!empty($this->date_retour)) {          if (!empty($this->metier_instance->valF['date_retour'])) {
102              $this->setMessage('Le date de retour déjà existe pour la '.              $this->setMessage("Le date de retour de la consultation ".$id.
103                  'consultation');                  " existe déjà");
104              return $this->BAD_DATA;              return $this->BAD_DATA;
105          }          }
106                    
107          // check that the date is valid          // check that the date is valid
108          $date = explode("/", $date_str);          $date = explode("/", $date_str);
         print '  date:';  
         print_r($date);  
109          if (!checkdate($date[1], $date[0], $date[2])) {          if (!checkdate($date[1], $date[0], $date[2])) {
110              $this->setMessage("Le date fourni n'est pas bon (en bon format)");              $this->setMessage("Le date de retour fourni pour la consultation ".
111                                  $id." n'est pas bon (en bon format)");
112              return $this->BAD_DATA;              return $this->BAD_DATA;
113          }          }
114                    
115          if (!$this->dateValid($date_str, $this->date_envoi, $this->date_limite)) {          if (!$this->dateInsideInterval($date_str,
116              $this->setMessage("Le date fourni n'est pas entre le date d'envoi ".                      $this->metier_instance->valF['date_envoi'],
117                        $this->metier_instance->valF['date_limite'])) {
118                $this->setMessage("Le date de retour fourni pour la consultation ".
119                                  $id." n'est pas entre le date d'envoi ".
120                                "et le date limite de la demande de consultation");                                "et le date limite de la demande de consultation");
121              return $this->BAD_DATA;              return $this->BAD_DATA;
122          }          }
# Line 123  class ConsultationManager extends Metier Line 124  class ConsultationManager extends Metier
124      }      }
125    
126    
127      private function avisValid($avis) {      /*
128         * Verifies that the avis received in the incomming data corresponds
129         * to one of the avis found in DB.
130         * @param string $avis The avis recived in the request
131         * @param string $id The discussion id
132         * @return string OK on success, KO otherwise
133         */
134        private function avisValid($avis, $id) {
135          // get all of the decisions possible from table avis_decision          // get all of the decisions possible from table avis_decision
136          $sql = "SELECT libelle, avis_consultation FROM avis_consultation";          $sql = "SELECT libelle, avis_consultation FROM avis_consultation";
137          $res = $this->db->query($sql);          $res = $this->db->query($sql);
138          if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.          if ($this->checkDBError($res, 'Erreur lors de recuperation des avis '.
139                  'possibles pendant traitement de la consultation :'.$id)) {                  'possibles pendant traitement de la consultation '.$id)) {
140              return $this->KO;              return $this->KO;
141          }          }
142    
# Line 140  class ConsultationManager extends Metier Line 148  class ConsultationManager extends Metier
148                    
149          // check that the decision received corresponds to a decision in DB          // check that the decision received corresponds to a decision in DB
150          if (!in_array($avis, array_keys($this->decisions))) {          if (!in_array($avis, array_keys($this->decisions))) {
151              $this->setMessage(__FILE__."::".__FUNCTION__.              $this->setMessage(
152                          ": L'avis reçu n'est pas trouvé dans la BD.");                  "L'avis de consultation reçu n'est pas feasible");
153              $this->KO;              return $this->KO;
154          }          }
         print '   decisions:';  
         print_r($this->decisions);  
155          return $this->OK;          return $this->OK;
156      }      }
157    
158            
159      private function fichierDataValid(&$data) {      /*
160         * Verifies that all the data concerning file to be stored (if any)
161         * are present in full or not present at all
162         * @param mixed $data The data recived in the request
163         * @param string $id The discussion id
164         * @return string OK on success, KO otherwise
165         */
166        private function fichierDataValid(&$data, $id) {
167          // do the check          // do the check
168          if (!isset($data['nom_fichier']) && isset($data['fichier_base64'])          if (!isset($data['nom_fichier']) && isset($data['fichier_base64'])
169              || isset($data['nom_fichier']) && !isset($data['fichier_base64'])) {              || isset($data['nom_fichier']) && !isset($data['fichier_base64'])) {
             print '  problem_fichier_data  ';  
170              $this->setMessage(              $this->setMessage(
171                      "Les données concernant le fichier ne sont pas complètes");                      "Les données de fichier d'avis de la consultation ".$id.
172              return $this->KO;                                  " ne sont pas complètes ");
173                return $this->KO;
174          }          }
         print '  ok_fichier_data  ';  
175          return $this->OK;          return $this->OK;
176      }      }
177    
178    
179        /*
180      private function storeDecisionFile(&$data) {       * Store the data recived in the request into a file on the
181         * local filesystem.
182         * @todo This function will need to be changed for the save to
183         * be on GED
184         * @param mixed $data The data received with the request
185         * @param string $id The consultation ID
186         * @return string OK on success, KO otherwise
187         */
188        private function storeDecisionFile(&$data, $id) {
189          if (isset($data['fichier_base64'])) {          if (isset($data['fichier_base64'])) {
190              $dir = dirname(__FILE__).'/../trs/'.$dossier_id;              $dir = dirname(__FILE__).'/../../trs/'.$this->dossier_id;
191              if (!file_exists($dir) && !is_dir($dir)) {              
192                  mkdir($dir, 755);              // if a file already exists by that name and it
193                // is not a directory, back out
194                if (file_exists($dir) && !is_dir($dir)) {
195                    $this->setMessage("Fichier d'avis ne peut pas être ".
196                    "enregistré pour la consultation ".$id);
197                    return $this->KO;      
198                }
199                // if a dirextory by that name exists, make sure it does
200                // not already contain an avis de consultation
201                if (file_exists($dir) && is_dir($dir)) {
202                    $dir_contents = trim(shell_exec('ls '.$dir));
203                    if (strpos($dir_contents, ' ') != false) {
204                        $dir_contents = explode(' ', $dir_contents);
205                    } else {
206                        $dir_contents = array($dir_contents);
207                    }
208                    foreach ($dir_contents as $filename) {
209                        if (strspn($filename, $this->filename_prefix, 0) > 0) {
210                            $this->setMessage("Un fichier d'avis existe déjà ".
211                            "pour la consultation ".$id);
212                            return $this->KO;
213                        }
214                    }
215              }              }
216                // if no file by that name exists, create the directory
217                if (!file_exists($dir)) {
218                    if (!mkdir($dir, 0775)) {
219                        $this->setMessage("Erreur dans la création de répertoire ".
220                        "pour la sauvegarde de l'avis de la consultation ".$id);
221                        return $this->KO;
222                    }
223                }
224    
225                
226                // store the file contents into the file named:
227                //      consultation_<ID>_<file_name_received>
228              $file_len = strlen($data['fichier_base64']);              $file_len = strlen($data['fichier_base64']);
229              $filename = $dir.'/consultation_'.$id.'_'.$data['nom_fichier'];              $filename = $dir.$this->metier_instance->valF['dossier'].'/'.
230                        $this->filename_prefix.$data['nom_fichier'];
231                $this->filename = $filename;
232              $file = fopen($filename, 'w');              $file = fopen($filename, 'w');
233              if (!$file) {              if (!$file) {
234                  $this->setMessage(__FILE__."::".__FUNCTION__.                  $this->setMessage("Echec en création de pointeur de fichier ".
235                          ": Echec en création de pointeur de fichier");                      "pour la sauvegarde de l'avis de la consultation ".$id);
236                  $this->KO;                              return $this->KO;
237              }              }
238              $num_written = fwrite($file, $data[''], $file_len);              // check that the number of bytes written is equal to the length
239              if (!$num_writeen || $num_written != $file_len) {              // of the data received
240                  $this->setMessage(__FILE__."::".__FUNCTION__.              $num_written = fwrite($file, $data['fichier_base64'], $file_len);
241                          ": Sauvegarde de fichier échouée");              if (!$num_written || $num_written != $file_len) {
242                  $this->KO;                                          $this->setMessage("Sauvegarde de fichier d'avis pour la ".
243                    "consultation ".$id." a échouée");
244                    // remove the file
245                    // the return value from shell can't be used for checking since
246                    // one can not know if the NULL returned is because there was no
247                    // output or because there was an error
248                    $ret = shell_exec("rm -f $filename 2>&1");
249                    //if ($ret == NULL) { // an error occured while deleting the file
250                    //    $msg = $this->getMessage();
251                    //    $this->setMessage($msg . ' Problème pendent la suppression '.
252                    //            'des données corrompues');
253                    //}
254                    return $this->KO;
255              }              }
256              fclose($file);              fclose($file);
257          }          }
# Line 198  class ConsultationManager extends Metier Line 266  class ConsultationManager extends Metier
266       * @return bool 'OK'       * @return bool 'OK'
267       */       */
268      public function consultationDecision($data, $id) {      public function consultationDecision($data, $id) {
269                  
270          // get all of the dates for the consultation from DB          // get all of the dates for the consultation from DB
271          // and check the date received is ok with respect to the          // and check the date received is ok with respect to the
272          // time interval set by (date_envoi, date_limite)          // time interval set by (date_envoi, date_limite)
273          // equally extract the dossier ID while at it          // equally extract the dossier ID while at it
274          $res = $this->getDataFromDB($id);          $this->metier_instance = new consultation($id, $this->db, 0);
275          if ($res != $this->OK) {          
276              return $res;          // check that the consultation was found
277            if (isset($this->metier_instance->errors['db_debuginfo'])
278                && !empty($consultation->errors['db_debuginfo'])) {
279                $this->setMessage("Erreur lors de recuperation de la ".
280                            "consultation $id");
281                return $this->KO;
282          }          }
283                    
284          $res = $this->checkDates($data['date_retour']);          // check that the date sent is applicable
285            $res = $this->checkDates($data['date_retour'], $id);
286          if ($res != $this->OK) {          if ($res != $this->OK) {
287              return $res;              return $res;
288          }          }
289            
290            // set the prefix for the filename to use in case file data
291            // was received
292            $this->filename_prefix = "consultation_".$id."_";
293          // check that data regarding fichier is complete          // check that data regarding fichier is complete
294          $res = $this->fichierDataValid($data);          $res = $this->fichierDataValid($data, $id);
295          if ($res != $this->OK) {          if ($res != $this->OK) {
296              return $res;              return $res;
297          }          }
298                    
           
299          // 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
300          // and store the possible decisions in $this->decisions          // and store the possible decisions in $this->decisions
301          $res = $this->avisValid($data['avis']);          $res = $this->avisValid($data['avis'], $id);
302          if ($res != $this->OK) {          if ($res != $this->OK) {
303              return $res;              return $res;
304          }                  }        
           
305          // first store the file if needed          // first store the file if needed
306          $res = $this->storeDecisionFile($data);          $res = $this->storeDecisionFile($data, $id);
307          if ($res != $this->OK) {          if ($res != $this->OK) {
308              return $res;              return $res;
309          }          }
310                    $this->metier_instance->valF['date_retour'] = $data['date_retour'];
311          // update the DB          $this->metier_instance->valF['avis_consultation'] = $this->decisions[$data['avis']];
312          $date = explode("/", $data['date_retour']);          $this->metier_instance->valF['lu'] = FALSE;
         $sql = "UPDATE consultation SET ".  
             "date_retour = DATE '".  
                 $date[2]."-".$date[1]."-".$date[0]."', ";  
         if (isset($data['motivation'])) {  
             $sql .= "motivation = " . $data['motivation'] . ', ';  
         }  
313          if (isset($data['nom_fichier'])) {          if (isset($data['nom_fichier'])) {
314              $sql .= "fichier = ".$data['nom_fichier'] . ', ';              $this->metier_instance->valF['fichier'] = $this->filename_prefix . $data['nom_fichier'];
315          }          }
316          $sql .= "avis_consultation = ".$this->decisions[$data['avis']].          if (isset($data['motivation'])) {
317              ", lu = false WHERE consultation = ".$id;              $this->metier_instance->valF['motivation'] = $data['motivation'];
           
           
         print '   $sql:'.$sql.'   ';  
   
         $res = $this->db->query($sql);  
         if ($this->checkDBError($res, 'Erreur lors de mis à jour '.  
                 'de la consultation '.$id.' dans le DB')) {  
             return $this->KO;  
318          }          }
319                    
320          $this->setMessage("L'avis été pris en compte");          $ret = parent::modifier($this->metier_instance->valF,
321          return $this->OK;              "L'avis de la consultation $id a été pris en compte",
322                "Erreur pendant le traitemande de la demande pour la consultation $id");
323            if ($ret != $this->OK) {
324                // delete the file on disk
325                if (isset($data['nom_fichier'])) {
326                    shell_exec("rm -f $this->filename");
327                }
328            }
329            return $ret;
330      }      }
331            
332            

Legend:
Removed from v.559  
changed lines
  Added in v.573

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26