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

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

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

revision 577 by mlimic, Fri Nov 2 10:10:56 2012 UTC revision 780 by fmichon, Tue Nov 20 16:37:20 2012 UTC
# Line 1  Line 1 
1  <?php  <?php
2    /**
3  /*   * Ce fichier permet de déclarer la classe de base MetierManager qui permet
4   * The base class for all of the xxxManagers used for processing the   * de fournir des méthodes communes aux classes métiers effectuant les
5   * received requests.   * traitements métiers nécessaires aux différentes ressources exposées.
  *  
  * @author: Mirna Limic <[email protected]>  
  *  
  * Date: 15/10/2012  
  * Follow-up:  
  * Bugs: Unknown  
6   *   *
7     * @package openfoncier
8     * @version SVN : $Id$
9   */   */
10    
11    //
12    require_once("../obj/utils.class.php");
13    
14    /**
15  require_once ("../obj/utils.class.php");   *
16  //require_once ("../obj/om_utilisateur.class.php");   */
   
17  class MetierManager {  class MetierManager {
18    
19        /**
     /**#@+  
20       * @access protected       * @access protected
21       * @var string       * @var string
22       */       */
# Line 29  class MetierManager { Line 25  class MetierManager {
25      var $NA = 'NA'; // not apllicable      var $NA = 'NA'; // not apllicable
26      var $BAD_DATA = 'BAD_DATA';      var $BAD_DATA = 'BAD_DATA';
27      var $DEBUG = 0;      var $DEBUG = 0;
28      var $GENERIC_ERROR = "Error during request processing";      /**#@-*/
29    
30      /*      /**
31       * Constructeur.       * Constructeur
32       *       *
33       * Sets 'collectivite', and 'login' in the $_SESSION.       * Attribue les valeurs au $_SESSION['collectivite'] et $_SESSION['login']
34       * @todo The value stored in the $_SESSION['collectivite'] needs to       * @todo La valeur stockee dans $_SESSION['collectivite'] doit etre
35       * be obtained rather than hardcoded.       * obtenue plutot que code en dur.
36       * @todo The value stored in the $_SESSION['login'] could be obtained       * @todo La valeur stockee dans $_SESSION['login'] doit etre
37       * rather than being hardcoded to "somelogin".       * obtenue plutot que code en dur.
38       * @uses utils Uses the obj/utils.class.php to establish a DB connection.       * @uses utils Utilise obj/utils.class.php pour etablir une connexion BD
39       * @uses application::connectDatabase() In this function the execution       * @uses application::connectDatabase() Dans cette fonction l'execution
40       * could terminate if the connection to DB cannot be established. The       * pourrait s'terminer si la connexion avec BD echuait. Pour empecher
41       * important thing to prevent this is to set the $_SESSION['login'] to       * que cela se produise, on mit $_SESSION['login'] a une valeur qui est
42       * value that is not empty and that is bogus.       * pas vide est qui donne l'utilisateur tout le droit necessaire.
43       */       */
44      protected function __construct() {      public function __construct() {
45    
46            // Logger
47            $this->addToLog("__construct(): start", EXTRA_VERBOSE_MODE);
48    
49            //
50          session_start();          session_start();
51          // Setter les variables de $_SESSION pour la connexion avec BD          // Setter les variables de $_SESSION pour la connexion avec BD
52          $_SESSION['collectivite'] = 1; // Arles          $_SESSION['collectivite'] = 1;
53          // login has to be set to some value, i.e. it must not be empty,          // login doit etre mis a une valeur qui n'est pas une chaine vide, et
54          // and $_SESSION['justlogin'] MUST NOT be set, otherwise          // le $_SESSION['justlogin'] NE DOIT PAS ETRE set pour que l'execution
55          // isAuthenticated() inside of om_application will fail, and the          // ne s'arrete pas dans la fonction isAuthenticated() de l'om_application
         // the script will stop executing  
56          $_SESSION['login'] = "admin";          $_SESSION['login'] = "admin";
57    
58          // Genere une connexion a la base de donnees          // Genere une connexion a la base de donnees
59          $this->f = new utils("nohtml");          $this->f = new utils("nohtml");
60          // set the type of the DB to use  
61          $this->f->db->phptype = 'pgsql';          // sauvegarde la reference au BD
         // save the reference to DB  
62          $this->db = $this->f->db;          $this->db = $this->f->db;
63    
64            // initialise le msg attribute qui est utilise pour stocker les
65            // messages de retour (reussite ou erreur)
66          $this->msg = '';          $this->msg = '';
     }// fin constructeur  
67    
68                // Logger
69            $this->addToLog("__construct(): end", EXTRA_VERBOSE_MODE);
70    
71        }
72    
73      /*      /*
74       * Destructor       * Destructeur
75       *       *
76       * Unsets the instance of the utils class.       * Unsets the instance of the utils class.
77       * Unsets in the $_SESSION the key=>value pairs that were set in       * Unsets in the $_SESSION the key=>value pairs that were set in
78       * the constructor.       * the constructor.
79       */       */
80      protected function __destruct() {      public function __destruct() {
81    
82            // Logger
83            $this->addToLog("__destruct(): start", EXTRA_VERBOSE_MODE);
84    
85            //
86          unset($this->f);          unset($this->f);
87    
88            //
89          unset($_SESSION['login']);          unset($_SESSION['login']);
90          unset($_SESSION['collectivite']);          unset($_SESSION['collectivite']);
91      }  
92                // Logger
93                $this->addToLog("__destruct(): end", EXTRA_VERBOSE_MODE);
94      /*  
95       * Checks that the data received in the request is valid.          // Mode DEBUG
96       *          // logger::instance()->writeLogToFile();
97       * To be overridden in the derived classes.  
      * @return bool Always return true.  
      */  
     protected function requestValid() {  
         // A etre implemente dans les classes derivees  
         return true;  
     }  
       
       
     /*  
      * Filters out the HTML tags from a string.  
      *  
      * @param string $var The string from which to filter out the HTML tags.  
      * @return string Returns $var without the HTML tags.  
      */  
     private function filterOutHtmlTags($var) {  
         $pattern = '/<[\/]*[\sa-zA-Z0-9="]*[\/]*>/';  
         $replacement = '';  
         return preg_replace($pattern, $replacement, $var);  
98      }      }
99    
       
100      /*      /*
101       * Executes the insertion of a record into DB by calling the       * Fait l'insertion d'un redord dans la BD par l'appel de la methode
102       * dbform::ajouter() method.       * dbform::ajouter().
103       *       *
104       * Precondition: $this->metier_instance is not null.       * Precondition: $this->metier_instance n'est pas NULL.
105       *       *
106       * @uses dbform::ajouter() The method that does insertion of data       * @uses dbform::ajouter() La methode qui fait l'insertion dans la BD.
107       * into a DB       * @param mixed $data Tableau qui contient les donnees a ajouter dans la BD
108       * @return string Returns 'OK' on success, error message set by the       * @param string $msg_OK Le message a retourner en cas de success
109       * application (if it was set), a generic error message otherwise.       * @param string $msg_KO Le message a retourner en cas de echec
110         * @return string En cas de success on retourne 'OK'. En cas d'erreur
111         * on retourne le message d'erreur stocke dans l'atribut $msg, si l'atribut
112         * $msg n'est pas vide, ou un message d'erreur generique si $msg est vide.
113       */       */
114      protected function ajouter(&$data) {      protected function ajouter(&$data, $msg_OK = null, $msg_KO = null) {
115          // essai d'ajout des donnees dans la base de donnees          // essai d'ajout des donnees dans la base de donnees
116          $this->metier_instance->ajouter($data, $this->db, $this->DEBUG);          $this->metier_instance->ajouter($data, $this->db, $this->DEBUG);
117          if ($this->metier_instance->correct == false) {          if ($this->metier_instance->correct == false) {
118              if (isset($this->metier_instance->msg)              if (isset($this->metier_instance->msg)
119                  && !empty($this->metier_instance->msg)) {                  && !empty($this->metier_instance->msg)) {
120                  return $this->filterOutHtmlTags($this->metier_instance->msg);                  $this->setMessage($this->filtreBalisesHtml(
121                                        $this->metier_instance->msg));
122                    return $this->KO;
123              }              }
124              return $this->GENERIC_ERROR;              $this->setMessage($msg_KO);
125                return $this->KO;
126            }
127            // now check for any DB errors
128            if (isset($this->metier_instance->errors['db_debuginfo'])) {
129                $this->setMessage($msg_KO);
130                return $this->KO;            
131          }          }
132            // everything went fine, so OK
133            $this->setMessage($msg_OK);
134          return $this->OK;          return $this->OK;
135      }      }
136    
137    
138      /*      /*
139       * Executes the update of a record in DB by calling the       * Fait l'insertion d'un redord dans la BD par l'appel de la methode
140       * dbform::modifier() method.       * dbform::modifier() method.
141       *       *
142       * Precondition: $this->metier_instance is not null.       * Precondition: $this->metier_instance n'est pas NULL.
143       *       *
144       * @uses dbform::modifier() The method that does insertion of data       * @uses dbform::modifier() La methode qui fait la modification des
145       * into a DB       * donnees dans la BD.
146       * @return string Returns 'OK' on success, error message set by the       * @param mixed $data Tableau qui contient les donnees a modifier dans la BD
147       * application (if it was set), a generic error message otherwise.       * @param string $msg_OK Le message a retourner en cas de success
148         * @param string $msg_KO Le message a retourner en cas de echec
149         * @return string Retourne 'OK' en reussite, une message d'erreur en
150         * cas d'echec si le message d'erreur etait stocke dans $this->msg, ou
151         * un message d'erreur generique autrement.
152       */           */    
153      protected function modifier($data, $msg_OK = null, $msg_KO = null) {      protected function modifier($data, $msg_OK = null, $msg_KO = null) {
154          // essai de la modification des donnees dans la base de donnees          // essai de la modification des donnees dans la base de donnees
155          $ret = $this->metier_instance->modifier($data, $this->db, $this->DEBUG);          $this->metier_instance->modifier($data, $this->db, $this->DEBUG);
156          if ($this->metier_instance->correct == false) {          if ($this->metier_instance->correct == false) {
157              if (isset($this->metier_instance->msg)              if (isset($this->metier_instance->msg)
158                  && !empty($this->metier_instance->msg)) {                  && !empty($this->metier_instance->msg)) {
159                  $this->setMessage($this->metier_instance->msg);                  $this->setMessage($this->filtreBalisesHtml(
160                                        $this->metier_instance->msg));
161                  return $this->KO;                  return $this->KO;
162              }              }
163              $this->setMessage($msg_KO);              $this->setMessage($msg_KO);
164              return $this->KO;              return $this->KO;
165          }          }
166            // now check for any DB errors
167            if (isset($this->metier_instance->errors['db_debuginfo'])) {
168                $this->setMessage($msg_KO);
169                return $this->KO;            
170            }
171          $this->setMessage($msg_OK);          $this->setMessage($msg_OK);
172          return $this->OK;          return $this->OK;
173      }      }
174    
175    
176      /*      /*
177       * Executes the insertion of a record into DB by calling the       * Fait la suppression d'un redord dans la BD par l'appel de la methode
178       * dbform::supprimer() method.       * dbform::supprimer() method.
179       *       *
180       * Precondition: $this->metier_instance is not null.       * Precondition: $this->metier_instance n'est pas NULL.
181       *       *
182       * @uses dbform::supprimer() The method that does insertion of data       * @uses dbform::supprimer() La methode qui fait la suppression des
183       * into a DB       * donnees dans la BD.
184       * @return string Returns 'OK' on success, error message set by the       * @param mixed $data Tableau qui contient les donnees a modifier dans la BD
185       * application (if it was set), a generic error message otherwise.       * @param string $msg_OK Le message a retourner en cas de success
186         * @param string $msg_KO Le message a retourner en cas de echec     *
187         * @return string Retourne 'OK' en reussite, une message d'erreur en
188         * cas d'echec si le message d'erreur etait stocke dans $this->msg, ou
189         * un message d'erreur generique autrement.
190       */       */
191      protected function supprimer(&$data) {      protected function supprimer(&$data, $msg_OK, $msg_KO) {
192          // essai de la suppression des donnes dans la base de donnees          // essai de la suppression des donnes dans la base de donnees
193          $ret = $this->metier_instance->supprimer($data, $this->db, $this->DEBUG);          $this->metier_instance->supprimer($data, $this->db, $this->DEBUG);
194          if ($this->metier_instance->correct == false) {          if ($this->metier_instance->correct == false) {
195              if (isset($this->metier_instance->msg)              if (isset($this->metier_instance->msg)
196                  && !empty($this->metier_instance->msg)) {                  && !empty($this->metier_instance->msg)) {
197                  return $this->filterOutHtmlTags($this->metier_instance->msg);                  $this->setMessage($this->filtreBalisesHtml(
198                                        $this->metier_instance->msg));
199                    return $this->KO;
200              }              }
201              return $this->GENERIC_ERROR;              $this->setMessage($msg_KO);
202                return $this->KO;
203            }
204            // verifie que il n'y a pas eu des erreurs de la BD
205            if (isset($this->metier_instance->errors['db_debuginfo'])) {
206                $this->setMessage($msg_KO);
207                return $this->KO;            
208          }          }
209            $this->setMessage($msg_OK);
210          return $this->OK;          return $this->OK;
211      }      }
212    
213      /*      /*
214       * This function is to be overwritten by the derived classes when a GET       * Attribue une valeur au attribute $msg de la classe. Utilise dans le
215       * request is received.       * retour d'une demande arrive par l'inteface REST
216       *       * @param string $msg The chaine des caracteres a stocker dans
217       * @return bool Always returns 'KO' to indicate that by default,       * l'attribute msg.
      * extraction of data from the DB is not supported.  
      */  
     protected function extraire(&$data) {  
         //  
         return $this->KO;  
     }  
   
   
     /*  
      * Formats error and debug info messages created on DB failure.  
      * @param string $debuginfo The debug info returned from DB connection.  
      * @param string $message The message returned from the failed DB attempt.  
      * @return string Formatted error message.  
      */  
     protected function formatDBerror($debuginfo, $message) {  
         return "DEBUG INFO: ".$debuginfo."              DEBUG MESSAGE: ".$message;  
     }  
       
       
     /*  
      * Sets the $msg attribute. Usefult for returning a message supplementary  
      * to the one associated with the return code.  
      * @param string $msg The message.  
218       */       */
219      protected function setMessage($msg) {      protected function setMessage($msg) {
220          if ($msg) {          if ($msg) {
# Line 217  class MetierManager { Line 224  class MetierManager {
224    
225            
226      /*      /*
227       * Returns the string stored in $msg attribute       * Retourne le chaine des caracteres stocke dans l'attribut $msg
228       * @return string The value of $this->msg.       * @return string La valeur de $this->msg.
229       */       */
230      public function getMessage() {      public function getMessage() {
231          return $this->msg;          return $this->msg;
232      }      }
233    
       
     /*  
      * Verifies the result object returned from a DB query for any  
      * errors. If there was a DB error, the error message is stored  
      * in the $msg attribute.  
      * @param object $result DB result object.  
      * @param string $msg The prefix to the constructed DB error message.  
      * @return bool True on DB error, false otherwise.  
      */  
     protected function checkDBError($result, $msg = '') {  
         if (database::isError($result, true)) {  
             $this->addToLog("Error: $msg ".  
                     $this->formatDBerror($result->getDebugInfo(),  
                     $result->getMessage()));  
             $this->setMessage('ERREUR DE LA BD : '. $msg);  
             return true;  
         }  
         return false;  
     }  
       
       
234      /*      /*
235       * Adds errors to log       * Ajoute une chaine des caracteres dans le log.
236       * @param string $message The message to add to log       * @param string $message Le message qui doit etre ajoute dans le log.
237       * @param string $type The logging mode       * @param string $type Le mode de log.
238       * @todo what do we do with DB error messages if a REST call is made       * @todo Qu'est ce que on va faire avec des messages d'erreur de la BD si
239         * le traitement etait initie par une demande arrivee par REST ?
240       */       */
241      function addToLog($message, $type = DEBUG_MODE) {      function addToLog($message, $type = DEBUG_MODE) {
242          //          //
243          if (!defined('REST_REQUEST')) {          logger::instance()->log("class ".get_class($this)." - ".$message, $type);
244              logger::instance()->log("class ".get_class($this)." - ".$message, $type);      }
245    
246        // {{{
247    
248        /**
249         * Le principe de cette méthode est de récupérer la valeur de la clé
250         * primaire de l'instance de l'objet métier.
251         */
252        protected function getMetierInstanceValForPrimaryKey() {
253    
254            //
255            return $this->getMetierInstanceValForField($this->metier_instance->clePrimaire);
256    
257        }
258    
259        /**
260         * Le principe de cette méthode est de récupérer la valeur du field passé
261         * en paramètre dans l'attribut 'val' de l'instance de l'objet métier.
262         *
263         * @param string $field Nom du champ  à récupérer
264         */
265        protected function getMetierInstanceValForField($field) {
266    
267            // Si l'objet métier n'a pas été instancié alors on retourne NULL
268            if ($this->metier_instance == NULL) {
269                return NULL;
270          }          }
271            // On récupère la clé de la valeur '$field' dans l'attribut 'champs' de
272            // l'objet
273            $key = array_search($field,
274                                $this->metier_instance->champs);
275            // Si la clé n'est pas présente dans le tableau alors on retourne NULL
276            if (is_null($key) || $key === false) {
277                return NULL;
278            }
279            // Si on ne retrouve pas la clé dans l'attribut 'val' de l'objet alors
280            // on retour NULL
281            if (!isset($this->metier_instance->val[$key])) {
282                return NULL;
283            }
284            // Logger
285            $this->addToLog("getMetierInstanceValForField(): \$field = \"".$field."\" ; return ".$this->metier_instance->val[$key].";", EXTRA_VERBOSE_MODE);
286            // On retourne la valeur du champ représentant la clé primaire
287            return $this->metier_instance->val[$key];
288    
289      }      }
   
290    
291        // }}}
292      /*  
293        // {{{ METHODES UTILITAIRES
294    
295        /**
296         * Cette méthode permet de supprimer les balises HTML d'une chaîne de
297         * caractères
298         *
299         * Filters out the HTML tags from a string.
300         *
301         * @param string $var The string from which to filter out the HTML tags.
302         * @return string Returns $var without the HTML tags.
303         */
304        private function filtreBalisesHtml($var) {
305            $pattern = '/<[\/]*[\sa-zA-Z0-9="]*[\/]*>/';
306            $replacement = '';
307            return preg_replace($pattern, $replacement, $var);
308        }
309    
310        /**
311         * Cette méthode vérifier qu'une date se trouve dans un intervalle
312         *
313       * Verifies that a date falls inside of a date interval       * Verifies that a date falls inside of a date interval
314       * @param string $date_str The string that should fall       * @param string $date_str The string that should fall
315       * within the interval       * within the interval
# Line 290  class MetierManager { Line 339  class MetierManager {
339              $prev_date = $date;              $prev_date = $date;
340          }          }
341          return true;          return true;
342      }          }
343    
344        /**
345         * Cette méthode vérife la validité d'un timestamp
346         * @param string $date_str Chaine des chracteres contenant le datestamp
347         * dans la forme JJ/MM/YYYY H:MI"
348         * @param string $date_db Parametre de sortie. Il contient la date dans le
349         * format de BD timestamp: 'YYYY-MM-JJ hh:mm'
350         * @param bool $time_search Indicated wheather hours and minutes should be
351         * searched for in the $date_str or not
352         * @return True if the timestamp is valid, false otherwise.
353         */
354        protected function timestampValide($date_str, &$date_db, $time_search = false) {
355            $date_db = null;
356            // check that the date is valid
357            $date_time = explode(" ", $date_str);
358            if (count($date_time) != 2 && $time_search) {
359                return false; // bad date
360            }
361            // first verify that the date is correct
362            $date = explode("/", $date_time[0]);
363            if (count($date) != 3) {
364                return false; // bad date
365            }
366            if (!checkdate($date[1], $date[0], $date[2])) {
367                return false; // bad date
368            }
369            
370            if ($time_search && count($date_time) != 2) {
371                return false; // time not present even though searched for
372            }
373            // verify that the time is good
374            if ($time_search) {
375                $time_str = explode(':', $date_time[1]);
376                if (count($time_str) <= 1) {
377                    return false; // time in bad format
378                }
379                // only interested in hours and minutes
380                $hours = intval($time_str[0]);
381                $minutes = intval($time_str[1]);
382                if ($hours < 0 || $hours > 23) {
383                    return false; // bad hour
384                }
385                if ($minutes < 0 || $minutes > 59) {
386                    return false;
387                }
388            }
389            $date_db = $date[2].'-'.$date[1].'-'.$date[0];
390            if ($time_search) {
391                $date_db .= ' '.$hours.':'.$minutes;
392            }
393            return true;
394        }
395    
396        // }}}
397            
398  }// fin classe  }
399    
400  ?>  ?>

Legend:
Removed from v.577  
changed lines
  Added in v.780

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26