/[openfoncier]/trunk/obj/instruction.class.php
ViewVC logotype

Diff of /trunk/obj/instruction.class.php

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

revision 6272 by softime, Fri Mar 3 15:27:53 2017 UTC revision 11418 by softime, Mon Feb 7 14:59:54 2022 UTC
# Line 1  Line 1 
1  <?php  <?php
2  /**  /**
3     * DBFORM - 'instruction' - Surcharge gen.
4     *
5   * specific :   * specific :
6   * - cle secondaire   * - cle secondaire
7   *   destruction autorisée que pour le dernier evenement   *   destruction autorisée que pour le dernier evenement
# Line 12  Line 14 
14   * - function mois_date : pour ajouter des mois a une date   * - function mois_date : pour ajouter des mois a une date
15   *   [add months (delay) and calculation final date]   *   [add months (delay) and calculation final date]
16   * - voir script_lang.js : bible ...   * - voir script_lang.js : bible ...
17   *   *
18   * @package openfoncier   * @package openfoncier
19   * @version SVN : $Id$   * @version SVN : $Id$
20   */   */
# Line 27  class instruction extends instruction_ge Line 29  class instruction extends instruction_ge
29      var $abstract_type = array(      var $abstract_type = array(
30          "om_fichier_instruction" => "file",          "om_fichier_instruction" => "file",
31      );      );
32        
     var $retourformulaire;   // specific  
     var $idxformulaire;      // specific  
33      var $valEvenement;      var $valEvenement;
34      var $restriction_valid = null;      var $restriction_valid = null;
35      // Tableau contenant une partie des métadonnées arrêtés      // Tableau contenant une partie des métadonnées arrêtés
# Line 69  class instruction extends instruction_ge Line 69  class instruction extends instruction_ge
69              "groupeInstruction" => 'getGroupeInstruction',              "groupeInstruction" => 'getGroupeInstruction',
70              "title" => 'getTitle',              "title" => 'getTitle',
71              'concerneERP' => 'get_concerne_erp',              'concerneERP' => 'get_concerne_erp',
72    
73                'date_cloture_metier' => 'getDossierDateDecision',
74                'type' => 'getDocumentType',
75                'dossier_autorisation_type_detaille' => 'getDossierAutorisationTypeDetaille',
76                'dossier_instruction_type' => 'getDossierInstructionTypeLibelle',
77                'region' => 'getDossierRegion',
78                'departement' => 'getDossierDepartement',
79                'commune' => 'getDossierCommune',
80                'annee' => 'getDossierAnnee',
81                'division' => 'getDossierDivision',
82                'collectivite' => 'getDossierServiceOrCollectivite',
83          ),          ),
84          "arrete" => array(          "arrete" => array(
85              "numArrete" => "getNumArrete",              "numArrete" => "getNumArrete",
# Line 85  class instruction extends instruction_ge Line 96  class instruction extends instruction_ge
96              "ap_ville" => "getAp_ville",              "ap_ville" => "getAp_ville",
97              "activite" => "getActivite",              "activite" => "getActivite",
98              "dateControleLegalite" => "getDateControleLegalite",              "dateControleLegalite" => "getDateControleLegalite",
99          ),          )
100      );      );
     /** @var boolean Les nouvelles actions sont activées sur cet objet */  
     var $activate_class_action;  
101    
102      function __construct($id, &$db, $debug) {      /**
103          //On active les nouvelles actions       * Flag pour identifier la reprise de l'instruction d'un dossier.
104          $this->activate_class_action = true;       * Le statut de l'état passe de "cloture" à "encours".
105          $this->constructeur($id, $db, $debug);       *
106      }       * @var boolean
107         */
108        var $di_reopened = null;
109    
110      // {{{ Gestion de la confidentialité des données spécifiques      // {{{ Gestion de la confidentialité des données spécifiques
111            
# Line 109  class instruction extends instruction_ge Line 120  class instruction extends instruction_ge
120    
121          // ACTION - 000 - ajouter          // ACTION - 000 - ajouter
122          // Modifie la condition d'affichage du bouton ajouter          // Modifie la condition d'affichage du bouton ajouter
123          $this->class_actions[0]["condition"] = array("is_addable");          $this->class_actions[0]["condition"] = array("is_addable", "can_user_access_dossier_contexte_ajout");
124    
125          // ACTION - 001 - modifier          // ACTION - 001 - modifier
126          // Modifie la condition et le libellé du bouton modifier          // Modifie la condition et le libellé du bouton modifier
127          $this->class_actions[1]["condition"] = array("is_editable", "is_finalizable_without_bypass");          $this->class_actions[1]["condition"] = array(
128                "is_editable",
129                "is_finalizable_without_bypass",
130                "can_user_access_dossier_contexte_modification",
131                "is_evenement_modifiable",
132            );
133          $this->class_actions[1]["portlet"]["libelle"] = _("Modifier");          $this->class_actions[1]["portlet"]["libelle"] = _("Modifier");
134                    
135          // ACTION - 002 - supprimer          // ACTION - 002 - supprimer
136          // Modifie la condition et le libellé du bouton supprimer          // Modifie la condition et le libellé du bouton supprimer
137          $this->class_actions[2]["condition"] = array("is_deletable", "is_finalizable_without_bypass");          $this->class_actions[2]["condition"] = array(
138                "is_deletable",
139                "is_finalizable_without_bypass",
140                "can_user_access_dossier_contexte_modification",
141                "is_evenement_supprimable",
142            );
143          $this->class_actions[2]["portlet"]["libelle"] = _("Supprimer");          $this->class_actions[2]["portlet"]["libelle"] = _("Supprimer");
144    
145            // ACTION - 003 - consulter
146            //
147            $this->class_actions[3]["condition"] = "can_user_access_dossier_contexte_modification";
148    
149          // ACTION - 100 - finaliser          // ACTION - 100 - finaliser
150          // Finalise l'enregistrement          // Finalise l'enregistrement
151          $this->class_actions[100] = array(          $this->class_actions[100] = array(
# Line 135  class instruction extends instruction_ge Line 160  class instruction extends instruction_ge
160              "method" => "finalize",              "method" => "finalize",
161              "button" => "finaliser",              "button" => "finaliser",
162              "permission_suffix" => "finaliser",              "permission_suffix" => "finaliser",
163              "condition" => array("is_finalizable", "is_finalizable_without_bypass", "has_an_edition"),              "condition" => array(
164                    "is_finalizable",
165                    "is_finalizable_without_bypass",
166                    "has_an_edition",
167                    "can_user_access_dossier_contexte_modification",
168                ),
169          );          );
170    
171          // ACTION - 110 - definaliser          // ACTION - 110 - definaliser
# Line 152  class instruction extends instruction_ge Line 182  class instruction extends instruction_ge
182              "method" => "unfinalize",              "method" => "unfinalize",
183              "button" => "definaliser",              "button" => "definaliser",
184              "permission_suffix" => "definaliser",              "permission_suffix" => "definaliser",
185              "condition" => array("is_unfinalizable", "is_unfinalizable_without_bypass"),              "condition" => array(
186                    "is_unfinalizable",
187                    "is_unfinalizable_without_bypass",
188                    "can_user_access_dossier_contexte_modification",
189                    "is_not_sent_for_signature",
190                ),
191          );          );
192    
193          // ACTION - 120 - edition          // ACTION - 120 - edition
# Line 166  class instruction extends instruction_ge Line 201  class instruction extends instruction_ge
201                  "class" => "pdf-16",                  "class" => "pdf-16",
202              ),              ),
203              "view" => "view_edition",              "view" => "view_edition",
204              "condition" => "has_an_edition",              "condition" => array("has_an_edition", "can_user_access_dossier_contexte_modification"),
205              "permission_suffix" => "om_fichier_instruction_telecharger",              "permission_suffix" => "om_fichier_instruction_telecharger",
206          );          );
207    
# Line 181  class instruction extends instruction_ge Line 216  class instruction extends instruction_ge
216                  "class" => "suivi-dates-16",                  "class" => "suivi-dates-16",
217              ),              ),
218              "crud" => "update",              "crud" => "update",
219              "condition" => "can_monitoring_dates",              "condition" => array("can_monitoring_dates", "can_user_access_dossier_contexte_modification"),
220              "permission_suffix" => "modification_dates",              "permission_suffix" => "modification_dates",
221          );          );
222    
# Line 226  class instruction extends instruction_ge Line 261  class instruction extends instruction_ge
261          );          );
262    
263          // ACTION - 180 - pdf_lettre_rar          // ACTION - 180 - pdf_lettre_rar
264          // Génère PDF sur bordereaux de lettres RAR          // Génère PDF sur bordereaux de lettres AR
265          $this->class_actions[180] = array(          $this->class_actions[180] = array(
266              "identifier" => "pdf_lettre_rar",              "identifier" => "pdf_lettre_rar",
267              "view" => "view_pdf_lettre_rar",              "view" => "view_pdf_lettre_rar",
# Line 263  class instruction extends instruction_ge Line 298  class instruction extends instruction_ge
298              "view" => "formulaire",              "view" => "formulaire",
299              "method" => "notifier_commune",              "method" => "notifier_commune",
300              "permission_suffix" => "notifier_commune",              "permission_suffix" => "notifier_commune",
301              "condition" => "is_notifiable",              "condition" => array("is_notifiable", "can_user_access_dossier_contexte_modification"),
302          );          );
303    
304          // ACTION - 220 - generate_suivi_bordereaux          // ACTION - 220 - generate_suivi_bordereaux
# Line 271  class instruction extends instruction_ge Line 306  class instruction extends instruction_ge
306          $this->class_actions[220] = array(          $this->class_actions[220] = array(
307              "identifier" => "generate_suivi_bordereaux",              "identifier" => "generate_suivi_bordereaux",
308              "view" => "view_generate_suivi_bordereaux",              "view" => "view_generate_suivi_bordereaux",
309              "permission_suffix" => "consulter",              "permission_suffix" => "consulter",
310          );          );
311    
312            // ACTION - 777 - pdf_temp
313            // Crée un PDF temporaire et affiche son contenu en base64
314            $this->class_actions[777] = array(
315                "identifier" => "pdf_temp",
316                "view" => "view_pdf_temp",
317                "permission_suffix" => "modifier",
318                "condition" => array("can_user_access_dossier_contexte_modification"),
319            );
320    
321            // ACTION - 701
322            $this->class_actions[701] = array(
323                "identifier" => "enable-edition-integrale",
324                "portlet" => array(
325                    "type" => "action-direct-with-confirmation",
326                    "libelle" => _("Rédaction libre"),
327                    "order" => 50,
328                    "class" => "redac-libre-16",
329                ),
330                "view" => "formulaire",
331                "method" => "enable_edition_integrale",
332                "permission_suffix" => "modifier",
333                "condition" => array(
334                    "is_editable",
335                    "is_finalizable_without_bypass",
336                    "can_user_access_dossier_contexte_modification",
337                    "is_edition_integrale_not_enabled",
338                    "is_option_redaction_libre_enabled",
339                    "has_an_edition",
340                ),
341            );
342            // ACTION - 702
343            $this->class_actions[702] = array(
344                "identifier" => "disable-edition-integrale",
345                "portlet" => array(
346                    "type" => "action-direct-with-confirmation",
347                    "libelle" => _("Rédaction par compléments"),
348                    "order" => 50,
349                    "class" => "redac-complement-16",
350                ),
351                "view" => "formulaire",
352                "method" => "disable_edition_integrale",
353                "permission_suffix" => "modifier",
354                "condition" => array(
355                    "is_editable",
356                    "is_finalizable_without_bypass",
357                    "can_user_access_dossier_contexte_modification",
358                    "is_edition_integrale_enabled",
359                    "is_option_redaction_libre_enabled",
360                    "has_an_edition",
361                ),
362            );
363            // ACTION - 300 - evenement_has_an_edition_json
364            //
365            $this->class_actions[300] = array(
366                "identifier" => "evenement_has_an_edition_json",
367                "view" => "view_evenement_has_an_edition_json",
368                "permission_suffix" => "consulter",
369            );
370    
371            // ACTION - 301 - evenement_has_a_commentaire
372            //
373            $this->class_actions[301] = array(
374                "identifier" => "evenement_has_a_commentaire_json",
375                "view" => "view_evenement_has_a_commentaire_json",
376                "permission_suffix" => "consulter",
377            );
378    
379            // ACTION - 400 - Envoyer en signature
380            // Cet évenement permet d'envoyer le document au parapheur pour signature
381            $this->class_actions[400] = array(
382                "identifier" => "envoyer_a_signature",
383                "portlet" => array(
384                    "libelle" => _("Envoyer à signature"),
385                    "type" => "action-direct-with-confirmation",
386                    "class" => "envoyer_a_signature-16",
387                ),
388                "view" => "formulaire",
389                "method" => "envoyer_a_signature_sans_relecture",
390                "condition" => array(
391                    "can_be_signed",
392                ),
393                "permission_suffix" => "envoyer_a_signature",
394            );
395    
396            // ACTION - 402 - Envoyer en signature avec relecture
397            // Cet évenement permet d'envoyer le document au parapheur pour signature
398            $this->class_actions[402] = array(
399                "identifier" => "envoyer_a_signature_relecture",
400                "portlet" => array(
401                    "libelle" => __("Envoyer à signature avec relecture"),
402                    "type" => "action-direct-with-confirmation",
403                    "class" => "envoyer_a_signature-16",
404                ),
405                "view" => "formulaire",
406                "method" => "envoyer_a_signature_avec_relecture",
407                "condition" => array(
408                    "can_be_signed",
409                    "is_parapheur_relecture_parameter_enabled"
410                ),
411                "permission_suffix" => "envoyer_a_signature",
412            );
413    
414            //
415            $this->class_actions[401] = array(
416                "identifier" => "preview_edition",
417                "view" => "formulaire",
418                "permission_suffix" => "tab",
419            );
420    
421            // ACTION - 410 - Notifier les pétitionnaires (mail ou autre)
422            $this->class_actions[410] = array(
423                "identifier" => "overlay_notification_manuelle",
424                "portlet" => array(
425                    "libelle" => __("Notifier les pétitionnaires"),
426                    "type" => "action-self",
427                    "class" => "notifier_commune-16",
428                ),
429                "condition" => array(
430                    "is_notifiable_by_task_manual",
431                    "is_not_portail_notification_sans_annexe"
432                ),
433                "view" => "view_overlay_notification_manuelle",
434                "permission_suffix" => "modifier",
435            );
436    
437            // ACTION - 410 - Notifier les pétitionnaires (portail citoyen)
438            $this->class_actions[411] = array(
439                "identifier" => "notification_manuelle_portal",
440                "portlet" => array(
441                    "libelle" => __("Notifier les pétitionnaires"),
442                    "type" => "action-direct-with-confirmation",
443                    "class" => "notifier_commune-16",
444                ),
445                "condition" => array(
446                    "is_notifiable_by_task_manual",
447                    "is_portail_notification_sans_annexe"
448                ),
449                "method" => "notifier_demandeur_principal",
450                "permission_suffix" => "modifier",
451            );
452    
453            //
454            $this->class_actions[403] = array(
455                "identifier" => "envoyer_au_controle_de_legalite",
456                "portlet" => array(
457                    "libelle" => __("Envoyer au contrôle de légalité"),
458                    "type" => "action-direct-with-confirmation",
459                    "class" => "envoyer_au_controle_de_legalite-16",
460                ),
461                "view" => "formulaire",
462                "method" => "envoyer_au_controle_de_legalite",
463                "condition" => array(
464                    "can_be_sended_to_cl"
465                ),
466                "permission_suffix" => "envoyer_au_controle_de_legalite",
467            );
468    
469            //
470            $this->class_actions[998] = array(
471                "identifier" => "json_data",
472                "view" => "view_json_data",
473                "permission_suffix" => "consulter",
474            );
475      }      }
476    
477      /**      /**
478       * Cette variable permet de stocker le résultat de la méthode       * Clause select pour la requête de sélection des données de l'enregistrement.
479       * getDivisionFromDossier() afin de ne pas effectuer le recalcul à chacun de       *
480       * ces appels.       * @return array
      * @var string Code de la division du dossier en cours  
481       */       */
482      var $_division_from_dossier = NULL;      function get_var_sql_forminc__champs() {
483            return array(
484                "instruction",
485                "destinataire",
486                "instruction.evenement",
487                "instruction.commentaire",
488                "date_evenement",
489                "instruction.lettretype",
490                "signataire_arrete",
491                "flag_edition_integrale",
492                "om_final_instruction_utilisateur",
493                "date_finalisation_courrier",
494                "date_envoi_signature",
495                "date_envoi_rar",
496                "date_envoi_controle_legalite",
497    
498                "date_retour_signature",
499                "date_retour_rar",
500                "date_retour_controle_legalite",
501    
502                "numero_arrete",
503    
504                "complement_om_html",
505                "'' as bible_auto",
506                "'' as bible",
507                "complement2_om_html",
508                "'' as bible2",
509                "complement3_om_html",
510                "'' as bible3",
511                "complement4_om_html",
512                "'' as bible4",
513    
514                "titre_om_htmletat",
515                "corps_om_htmletatex",
516    
517                "'' as btn_preview",
518                "'' as btn_redaction",
519    
520                "'' as btn_refresh",
521                "'' as live_preview",
522    
523                "dossier",
524                "instruction.action",
525                "instruction.delai",
526                "instruction.etat",
527                "instruction.autorite_competente",
528                "instruction.accord_tacite",
529                "instruction.delai_notification",
530                "instruction.avis_decision",
531                "archive_delai",
532                "archive_accord_tacite",
533                "archive_etat",
534                "archive_avis",
535                "archive_date_complet",
536                "archive_date_rejet",
537                "archive_date_limite",
538                "archive_date_notification_delai",
539                "archive_date_decision",
540                "archive_date_validite",
541                "archive_date_achevement",
542                "archive_date_conformite",
543                "archive_date_chantier",
544                "archive_date_dernier_depot",
545                "date_depot",
546                "date_depot_mairie",
547                "complement5_om_html",
548                "'' as bible5",
549                "complement6_om_html",
550                "'' as bible6",
551                "complement7_om_html",
552                "'' as bible7",
553                "complement8_om_html",
554                "'' as bible8",
555                "complement9_om_html",
556                "'' as bible9",
557                "complement10_om_html",
558                "'' as bible10",
559                "complement11_om_html",
560                "'' as bible11",
561                "complement12_om_html",
562                "complement13_om_html",
563                "complement14_om_html",
564                "complement15_om_html",
565                "archive_incompletude",
566                "archive_incomplet_notifie",
567                "archive_evenement_suivant_tacite",
568                "archive_evenement_suivant_tacite_incompletude",
569                "archive_etat_pendant_incompletude",
570                "archive_date_limite_incompletude",
571                "archive_delai_incompletude",
572                "archive_autorite_competente",
573                "code_barres",
574                "om_fichier_instruction",
575                "om_final_instruction",
576                "om_fichier_instruction_dossier_final",
577                "document_numerise",
578                "duree_validite_parametrage",
579                "duree_validite",
580                "created_by_commune",
581                "archive_date_cloture_instruction",
582                "archive_date_premiere_visite",
583                "archive_date_derniere_visite",
584                "archive_date_contradictoire",
585                "archive_date_retour_contradictoire",
586                "archive_date_ait",
587                "archive_date_transmission_parquet",
588                "archive_dossier_instruction_type",
589                "archive_date_affichage",
590                "pec_metier",
591                "archive_pec_metier",
592                "archive_a_qualifier",
593                "id_parapheur_signature",
594                "statut_signature",
595                "commentaire_signature",
596                "historique_signature",
597                "'' as suivi_notification",
598    
599    
600                "'' as preview_edition",
601                "envoye_cl_platau",
602            );
603        }
604    
605      /**      /**
606       * Cette méthode permet de récupérer le code de division correspondant       * CONDITION - is_edition_integrale_enabled
607       * au dossier sur lequel on se trouve.       *
608         * Vérifie que la rédaction libre est activée sur l'instruction en cours.
609       *       *
610       * @return string Code de la division du dossier en cours       * @return boolean
611       */       */
612      function getDivisionFromDossier() {      function is_edition_integrale_enabled() {
613            if ($this->getVal("flag_edition_integrale") == 't') {
614                return true;
615            }
616            return false;
617        }
618    
619        /**
620         * CONDITION - is_edition_integrale_not_enabled
621         *
622         * Vérifie que la rédaction libre est désactivée sur l'instruction en cours.
623         *
624         * @return boolean
625         */
626        function is_edition_integrale_not_enabled() {
627            return !$this->is_edition_integrale_enabled();
628        }
629    
630        /**
631         * CONDITION - is_option_redaction_libre_enabled
632         *
633         * Vérifie que l'option de rédaction libre est activée.
634         *
635         * @return boolean
636         */
637        function is_option_redaction_libre_enabled() {
638            $collectivite_di = $this->get_dossier_instruction_om_collectivite();
639            return $this->f->is_option_redaction_libre_enabled($collectivite_di);
640        }
641    
642          // Cette méthode peut être appelée plusieurs fois lors d'une requête.      /**
643          // Pour éviter de refaire le traitement de recherche de la division       * CONDITION - is_option_parapheur_relecture_enabled
644          // alors on vérifie si nous ne l'avons pas déjà calculé.       *
645          if ($this->_division_from_dossier != NULL) {       * Vérifie que l'option de relecture lors de l'envoi en signature est activée.
646              // Logger       *
647              $this->addToLog("getDivisionFromDossier(): retour de la valeur déjà calculée - '".$this->_division_from_dossier."'", EXTRA_VERBOSE_MODE);       * @return boolean
648              // On retourne la valeur déjà calculée       */
649              return $this->_division_from_dossier;      function is_parapheur_relecture_parameter_enabled() {
650            //Instanciation de la classe electronicsignature
651            $inst_es = $this->get_electronicsignature_instance();
652            if ($inst_es === false) {
653                return false;
654          }          }
655    
656          // Par défaut, on définit la valeur du dossier à NULL          if ($inst_es->get_conf('is_forced_view_files') !== 'true' && $inst_es->get_conf('is_forced_view_files') !== true) {
657          $dossier = NULL;              return false;
658          // Test sur le mode et le contexte du formulaire          }
659          if ($this->getParameter("maj") == 0  
660              && ($this->getParameter("retourformulaire") == "dossier"          return true;
661                  || $this->getParameter("retourformulaire") == "dossier_instruction"      }
662                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"  
663                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"  
664                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"      /**
665                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures")) {       * CONDITION - is_sent_for_signature
666              // Si on se trouve en mode AJOUT (seul mode où l'enregistrement       *
667              // n'existe pas en base de données) ET que nous nous trouvons       * Vérifie que l'instruction a été envoyé à signature
668              // dans le contexte d'un dossier d'instruction alors on récupère       *
669              // le numéro de dossier depuis le paramètre 'idxformulaire'       * @return boolean
670              $dossier = $this->getParameter("idxformulaire");       */
671        function is_sent_for_signature() {
672            // Si un parapheur a été configuré
673            // et que le champ id_parapheur_signature n'est pas vide
674            // que le status est différent de "canceled" ou "expired"
675            // alors l'évènement a été envoyé en signature
676            if ($this->has_connector_electronicsignature() === true
677                && empty($this->getVal("id_parapheur_signature")) === false
678                && ($this->getVal("statut_signature") != "canceled"
679                || $this->getVal("statut_signature") != "expired"
680                || $this->getVal("statut_signature") != "finished")) {
681                //
682                return true;
683            }
684    
685            return false;
686        }
687    
688        /**
689         * CONDITION - is_not_sent_for_signature
690         *
691         * Vérifie que l'instruction n'a pas été envoyé à signature
692         *
693         * @return boolean
694         */
695        function is_not_sent_for_signature() {
696            // Contrôle si l'utilisateur possède un bypass
697            $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_definaliser_bypass");
698            if ($bypass == true) {
699                return true;
700            }
701    
702            return !$this->is_sent_for_signature();
703        }
704    
705    
706        /**
707         * CONDITION - is_signed
708         *
709         * Vérifie que l'instruction a été signé
710         *
711         * @return boolean
712         */
713        function is_signed() {
714            // Si un parapheur a été configuré
715            // et que le champ id_parapheur_signature n'est pas vide
716            //  et que le statut est égal à "finished"
717            // alors le document de l'instruciton à été signé
718            if ($this->has_connector_electronicsignature() === true
719                && empty($this->getVal("id_parapheur_signature")) === false
720                && $this->getVal("statut_signature") == "finished") {
721                //
722                return true;
723            }
724    
725            return false;
726        }
727    
728        function is_sent_to_cl() {
729            // Si l'instruction a une édition
730            // et que l'événement est paramétré pour envoyer le contrôle de légalité
731            // par Plat'AU
732            // et que la date de retour signature est renseignée
733            // et que la date d'envoi au contrôle légalité n'est pas renseignée
734            // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)
735            if ($this->has_an_edition() === true) {
736                $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));
737                if ($inst_evenement->getVal('envoi_cl_platau') === 't'
738                    || $this->getVal('envoye_cl_platau') === 't') {
739                    //
740                    return true;
741                }
742            }
743            //
744            return false;
745        }
746    
747        /**
748         * CONDITION - is_portail_notification
749         *
750         * Vérifie si la notification est une notification de catégorie portail
751         *
752         * @return boolean
753         */
754        function is_portail_notification_sans_annexe() {
755            $collectiviteDi = $this->get_dossier_instruction_om_collectivite();
756            $ev = $this->get_inst_evenement($this->getVal('evenement'));
757            if (($this->f->get_param_option_notification($collectiviteDi) === null ||
758                $this->f->get_param_option_notification($collectiviteDi) === 'portal')
759                && $ev->getVal('notification') != 'notification_manuelle_annexe'
760                && $ev->getVal('notification') != 'notification_manuelle_annexe_signature_requise'
761            ) {
762                return true;
763            }
764            return false;
765        }
766    
767        /**
768         * CONDITION - is_not_portail_notification
769         *
770         * Vérifie si la notification n'est pas une notification de catégorie portail
771         *
772         * @return boolean
773         */
774        function is_not_portail_notification_sans_annexe() {
775            return (! $this->is_portail_notification_sans_annexe());
776        }
777    
778        /**
779         * CONDITION - can_be_signed
780         *
781         * Vérifie que le document de l'instruction peut être envoyé au parapheur pour signature
782         *
783         * @return boolean
784         */
785        function can_be_signed() {
786            // Instanciation de l'objet signataire_arrete
787            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
788                "obj" => "signataire_arrete",
789                "idx" => $this->getVal("signataire_arrete"),
790            ));
791            // Si un parapheur a été configuré, que le document est finalisé, que le signataire
792            // possède une adresse email, on vérifie le champ id_parapheur_signature
793            // S'il est vide l'évènement peut être envoyé en signature
794            // S'il ne l'est pas, alors on vérifie le champ statut_signature
795            // Si la valeur de ce champ est égal à "canceled" ou "expired"
796            // alors l'évènement peut être envoyé en signature
797            if ($this->has_connector_electronicsignature() === true
798                && $this->getVal("om_final_instruction") == 't'
799                && empty($inst_signataire_arrete->getVal('email')) === false) {
800                //
801                if (empty($this->getVal("id_parapheur_signature")) === true
802                    || $this->getVal("statut_signature") == "canceled"
803                    || $this->getVal("statut_signature") == "expired") {
804                    //
805                    return true;
806                }
807            }
808    
809            $this->addToLog(__METHOD__."() has_connector_electronicsignature: ".var_export($this->has_connector_electronicsignature(), true), EXTRA_VERBOSE_MODE);
810            $this->addToLog(__METHOD__."() om_final_instruction: ".var_export($this->getVal("om_final_instruction"), true), EXTRA_VERBOSE_MODE);
811            $this->addToLog(__METHOD__."() email: ".var_export($inst_signataire_arrete->getVal('email'), true), EXTRA_VERBOSE_MODE);
812            $this->addToLog(__METHOD__."() id_parapheur_signature: ".var_export($this->getVal("id_parapheur_signature"), true), EXTRA_VERBOSE_MODE);
813            $this->addToLog(__METHOD__."() statut_signature: ".var_export($this->getVal("statut_signature"), true), EXTRA_VERBOSE_MODE);
814    
815            return false;
816        }
817    
818        /**
819         * CONDITION - has_connector_electronicsignature
820         *
821         * Vérifie qu'un parapheur est paramétré
822         *
823         * @return boolean
824         */
825        function has_connector_electronicsignature() {
826            $inst_es = $this->get_electronicsignature_instance(false);
827            if ($inst_es === false) {
828                return false;
829            }
830            return true;
831        }
832    
833        /**
834         * CONDITION - can_display_parapheur
835         *
836         * Vérifie que le fieldset "Suivi Parapheur" soit affichable
837         *
838         * @return boolean
839         */
840        function can_display_parapheur() {
841            $evenement_id = $this->getVal("evenement");
842            $inst_evenement = $this->get_inst_evenement($evenement_id);
843            if ($this->has_connector_electronicsignature() === true
844                && $inst_evenement->getVal('lettretype') !== ''
845                && $inst_evenement->getVal('lettretype') !== null
846                && (empty($this->getVal("id_parapheur_signature")) === false
847                    || empty($this->getVal("historique_signature")) === false)) {
848                //
849                return true;
850            }
851    
852            return false;
853        }
854    
855        /**
856         * CONDITION - can_display_notification
857         *
858         * Vérifie que le fieldset "Suivi notification" soit affichable
859         *
860         * @return boolean
861         */
862        function can_display_notification() {
863            // Le suivi des notification est affiché si l'événement est notifiable
864            // et si des notifications ont été envoyées
865            $evenement_id = $this->getVal("evenement");
866            $inst_evenement = $this->get_inst_evenement($evenement_id);
867            if ($inst_evenement->getVal('notification') != null &&
868                $inst_evenement->getVal('notification') != '') {
869                // Des notifications ont été envoyé si il existe au moins une notification
870                // liées à l'instruction
871                $idsNotifs = $this->get_instruction_notification($this->getVal($this->clePrimaire));
872                if (isset($idsNotifs) && $idsNotifs !== array()) {
873                    return true;
874                }
875            }
876            return false;
877        }
878    
879        /**
880         * TREATMENT - disable_edition_integrale.
881         *
882         * Cette methode permet de passer la consultation en "lu"
883         *
884         * @return boolean true si maj effectué false sinon
885         */
886        function disable_edition_integrale() {
887            // Cette méthode permet d'exécuter une routine en début des méthodes
888            // dites de TREATMENT.
889            $this->begin_treatment(__METHOD__);
890            $this->correct = true;
891            $valF = array(
892                "flag_edition_integrale" => false,
893                "titre_om_htmletat" => null,
894                "corps_om_htmletatex" => null,
895            );
896            $res = $this->f->db->autoExecute(
897                DB_PREFIXE.$this->table,
898                $valF,
899                DB_AUTOQUERY_UPDATE,
900                $this->clePrimaire."=".$this->getVal($this->clePrimaire)
901            );
902            if ($this->f->isDatabaseError($res, true)) {
903                // Appel de la methode de recuperation des erreurs
904                $this->erreur_db($res->getDebugInfo(), $res->getMessage(), '');
905                $this->correct = false;
906                // Termine le traitement
907                return $this->end_treatment(__METHOD__, false);
908          } else {          } else {
909              // Sinon on récupère le numéro de dossier dans le champs dossier de              $this->addToMessage(_("Rédaction par compléments activé."));
910              // l'enregistrement (en base de données)              return $this->end_treatment(__METHOD__, true);
             $dossier = $this->getVal("dossier");  
911          }          }
912    
913          // On appelle la méthode de la classe utils qui renvoi le code de la          // Termine le traitement
914          // division d'un dossier, on la stocke pour ne pas refaire le calcul au          return $this->end_treatment(__METHOD__, false);
915          // prochain appel de cette méthode      }
916          $this->_division_from_dossier = $this->f->getDivisionFromDossier($dossier);  
917          // Logger      /**
918          $this->addToLog("getDivisionFromDossier(): retour de la valeur nouvellement calculée - '".$this->_division_from_dossier."'", EXTRA_VERBOSE_MODE);       * TREATMENT - enable_edition_integrale.
919          // On retourne la valeur retournée       *
920          return $this->_division_from_dossier;       * Cette methode permet de passer la consultation en "lu"
921         *
922         * @return boolean true si maj effectué false sinon
923         */
924        function enable_edition_integrale() {
925            // Cette méthode permet d'exécuter une routine en début des méthodes
926            // dites de TREATMENT.
927            $this->begin_treatment(__METHOD__);
928            $this->correct = true;
929    
930            // Récupère la collectivite du dossier d'instruction
931            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
932            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
933            //
934            $params = array(
935                "specific" => array(
936                    "corps" => array(
937                        "mode" => "get",
938                    )
939                ),
940            );
941            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
942            $corps = $result['pdf_output'];
943            //
944            $params = array(
945                "specific" => array(
946                    "titre" => array(
947                        "mode" => "get",
948                    )
949                ),
950            );
951            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
952            $titre = $result['pdf_output'];
953            //
954            $valF = array(
955                "flag_edition_integrale" => true,
956                "titre_om_htmletat" => $titre,
957                "corps_om_htmletatex" => $corps,
958            );
959            $res = $this->f->db->autoExecute(
960                DB_PREFIXE.$this->table,
961                $valF,
962                DB_AUTOQUERY_UPDATE,
963                $this->clePrimaire."=".$this->getVal($this->clePrimaire)
964            );
965            if ($this->f->isDatabaseError($res, true)) {
966                // Appel de la methode de recuperation des erreurs
967                $this->erreur_db($res->getDebugInfo(), $res->getMessage(), '');
968                $this->correct = false;
969                // Termine le traitement
970                return $this->end_treatment(__METHOD__, false);
971            } else {
972                $this->addToMessage(_("Rédaction libre activé."));
973                return $this->end_treatment(__METHOD__, true);
974            }
975    
976            // Termine le traitement
977            return $this->end_treatment(__METHOD__, false);
978      }      }
979    
980      /**      /**
# Line 345  class instruction extends instruction_ge Line 989  class instruction extends instruction_ge
989          $sql = "select dossier_autorisation from ".DB_PREFIXE."dossier ";          $sql = "select dossier_autorisation from ".DB_PREFIXE."dossier ";
990          $sql .= " where dossier='".$id."'";          $sql .= " where dossier='".$id."'";
991          //          //
992          $dossier_autorisation = $this->db->getOne($sql);          $dossier_autorisation = $this->f->db->getOne($sql);
993          $this->addToLog("getNumDemandeAutorFromDossier(): db->getone(\"".$sql."\")", VERBOSE_MODE);          $this->addToLog("getNumDemandeAutorFromDossier(): db->getone(\"".$sql."\")", VERBOSE_MODE);
994          database::isError($dossier_autorisation);          database::isError($dossier_autorisation);
995          //          //
# Line 355  class instruction extends instruction_ge Line 999  class instruction extends instruction_ge
999      // }}}      // }}}
1000    
1001      function setType(&$form, $maj) {      function setType(&$form, $maj) {
1002          //          // Récupération du mode de l'action
1003          parent::setType($form, $maj);          $crud = $this->get_action_crud($maj);
1004          // On cache tous les champs          // Récupère la collectivité du dossier d'instruction
1005          // XXX          $collectivite_di = $this->get_dossier_instruction_om_collectivite();
         $form->setType('complement5_om_html', 'hidden');  
         $form->setType('bible5', 'hidden');  
         $form->setType('complement6_om_html', 'hidden');  
         $form->setType('bible6', 'hidden');  
         $form->setType('complement7_om_html', 'hidden');  
         $form->setType('bible7', 'hidden');  
         $form->setType('complement8_om_html', 'hidden');  
         $form->setType('bible8', 'hidden');  
         $form->setType('complement9_om_html', 'hidden');  
         $form->setType('bible9', 'hidden');  
         $form->setType('complement10_om_html', 'hidden');  
         $form->setType('bible10', 'hidden');  
         $form->setType('complement11_om_html', 'hidden');  
         $form->setType('bible11', 'hidden');  
         $form->setType('complement12_om_html', 'hidden');  
         $form->setType('bible12', 'hidden');  
         $form->setType('complement13_om_html', 'hidden');  
         $form->setType('bible13', 'hidden');  
         $form->setType('complement14_om_html', 'hidden');  
         $form->setType('bible14', 'hidden');  
         $form->setType('complement15_om_html', 'hidden');  
         $form->setType('bible15', 'hidden');  
         //  
         $form->setType('delai', 'hidden');  
         $form->setType('etat', 'hidden');  
         $form->setType('accord_tacite', 'hidden');  
         $form->setType('action', 'hidden');  
         $form->setType('delai_notification', 'hidden');  
         $form->setType('avis_decision', 'hidden');  
         $form->setType('autorite_competente', 'hidden');  
         //  
         $form->setType('archive_delai', 'hidden');  
         $form->setType('archive_etat', 'hidden');  
         $form->setType('archive_accord_tacite', 'hidden');  
         $form->setType('archive_avis', 'hidden');  
         $form->setType('archive_date_complet', 'hiddendate');  
         $form->setType('archive_date_dernier_depot', 'hiddendate');  
         $form->setType('archive_date_rejet', 'hiddendate');  
         $form->setType('archive_date_limite', 'hiddendate');  
         $form->setType('archive_date_notification_delai', 'hiddendate');  
         $form->setType('archive_date_decision', 'hiddendate');  
         $form->setType('archive_date_validite', 'hiddendate');  
         $form->setType('archive_date_achevement', 'hiddendate');  
         $form->setType('archive_date_conformite', 'hiddendate');  
         $form->setType('archive_date_chantier', 'hiddendate');  
         $form->setType('archive_autorite_competente','hidden');  
         $form->setType('date_depot','hidden');  
         //  
         $form->setType('numero_arrete', 'hidden');  
         //  
         $form->setType('code_barres', 'hidden');  
           
         //  
         $form->setType('archive_incompletude','hidden');  
         $form->setType('archive_incomplet_notifie','hidden');  
         $form->setType('archive_evenement_suivant_tacite','hidden');  
         $form->setType('archive_evenement_suivant_tacite_incompletude','hidden');  
         $form->setType('archive_etat_pendant_incompletude','hidden');  
         $form->setType('archive_date_limite_incompletude','hiddendate');  
         $form->setType('archive_delai_incompletude','hidden');  
1006    
1007          //          // Cache tous les champs
1008          $form->setType('duree_validite','hidden');          foreach ($this->champs as $value) {
1009          $form->setType('duree_validite_parametrage','hidden');              $form->setType($value, 'hidden');
1010            }
1011    
1012          //          // Les champs historique_signature et statut_signature ne sont pas saisissable dans tous les cas
1013          $form->setType('created_by_commune','hidden');          if ($this->can_display_parapheur() === true && $maj == 3) {
1014          //              $form->setType('statut_signature', 'selectstatic');
1015          // gestion du champ "finalisé par"              $form->setType('historique_signature', 'jsontotab');
1016          if ($this->getVal("om_final_instruction") == 't') {              if ($this->getVal('commentaire_signature') == null) {
1017              $form->setType('om_final_instruction_utilisateur', 'static');                  $form->setType('commentaire_signature', 'hidden');
1018          } else {              } else {
1019              $form->setType('om_final_instruction_utilisateur', 'hidden');                  $form->setType('commentaire_signature', 'hiddenstatic');
1020                }
1021          }          }
1022          //  
1023          if ($maj < 2 || $maj == 125) { //ajouter, modifier et suivi des dates          // Le champ de suivi des notifications n'est pas affichable dans tous les cas
1024              $form->setType('destinataire', 'hidden');          if ($this->can_display_notification() === true && $maj == 3) {
1025              $form->setType('lettretype', 'hiddenstatic');              $form->setType('suivi_notification', 'jsontotab');
1026              $form->setType('complement_om_html', 'html');          }
1027              $form->setType('complement2_om_html', 'html');  
1028              $form->setType('complement3_om_html', 'html');          // MODE AJOUTER
1029              $form->setType('complement4_om_html', 'html');          if ($this->getParameter('maj') == 0) {
1030              $form->setType('bible_auto', 'httpclick');              $form->setType('commentaire', 'textareahidden');
1031              $form->setType('bible', 'httpclick');              // Si l'option est active passage du champ date en lecture seule
1032              $form->setType('bible2', 'httpclick');              if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1033              $form->setType('bible3', 'httpclick');                  $form->setType("date_evenement", "hiddenstaticdate");
1034              $form->setType('bible4', 'httpclick');              } else {
1035              $form->setType('dossier', 'hidden');                    $form->setType("date_evenement", "date");
1036              $form->setType('libelle', 'hiddenstatic');              }
1037              $form->setType('signataire_arrete','select');              if ($this->is_in_context_of_foreign_key("evenement", $this->getParameter("retourformulaire"))) {
1038              $form->setType('date_envoi_signature','datedisabled');                  $form->setType("evenement", "selecthiddenstatic");
1039              $form->setType('date_retour_signature','datedisabled');              } else {
1040              $form->setType('date_envoi_rar','datedisabled');                  $form->setType("evenement", "select");
1041              $form->setType('date_retour_rar','datedisabled');              }
1042              $form->setType('date_envoi_controle_legalite','datedisabled');              if ($this->is_in_context_of_foreign_key("signataire_arrete", $this->getParameter("retourformulaire"))) {
1043              $form->setType('date_retour_controle_legalite','datedisabled');                  $form->setType("signataire_arrete", "selecthiddenstatic");
1044              $form->setType('date_finalisation_courrier','datedisabled');              } else {
1045                    $form->setType("signataire_arrete", "select");
1046              if($maj==0){ // ajouter              }
1047                  $form->setType('instruction', 'hidden');              if ($this->is_option_redaction_libre_enabled() === true) {
1048                  $form->setType('lettretype', 'hidden');                  $form->setType("flag_edition_integrale", "select");
1049                  $form->setType('evenement', 'select');              }
1050                  $form->setType('date_evenement', 'date2');          }
1051              }else{ // modifier et suivi des dates  
1052                  $form->setType('instruction', 'hiddenstatic');          // MODE MODIFIER
1053                  $form->setType('evenement', 'selecthiddenstatic');          if ($this->getParameter('maj') == 1) {
1054                  //$form->setType('date_evenement', 'hiddenstaticdate');              // Si l'option est active passage du champ date en lecture seule
1055                  $form->setType('date_evenement', 'date2');              if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1056                    $form->setType("date_evenement", "hiddenstaticdate");
1057                } else {
1058                    $form->setType("date_evenement", "date");
1059                }
1060                $form->setType("evenement", "selecthiddenstatic");
1061                if ($this->has_an_edition() === true) {
1062                    $form->setType('lettretype', 'hiddenstatic');
1063                    if ($this->is_in_context_of_foreign_key("signataire_arrete", $this->getParameter("retourformulaire"))) {
1064                        $form->setType("signataire_arrete", "selecthiddenstatic");
1065                    } else {
1066                        $form->setType("signataire_arrete", "select");
1067                    }
1068                    if ($this->getVal("flag_edition_integrale") == "t") {
1069                        $form->setType("titre_om_htmletat", "htmlEtat");
1070                        $form->setType("corps_om_htmletatex", "htmlEtatEx");
1071                    } else {
1072                        $form->setType("complement_om_html", "html");
1073                        $form->setType("complement2_om_html", "html");
1074                        $form->setType("complement3_om_html", "html");
1075                        $form->setType("complement4_om_html", "html");
1076                        $form->setType('bible_auto', 'httpclick');
1077                        $form->setType('bible', 'httpclick');
1078                        $form->setType('bible2', 'httpclick');
1079                        $form->setType('bible3', 'httpclick');
1080                        $form->setType('bible4', 'httpclick');
1081                    }
1082                    if ($this->f->is_option_preview_pdf_enabled($collectivite_di) === true) {
1083                        //
1084                        $form->setType('btn_refresh', 'httpclickbutton');
1085                        $form->setType('btn_preview', 'httpclickbutton');
1086                        $form->setType('btn_redaction', 'httpclickbutton');
1087                        $form->setType('live_preview', 'previsualiser_pdf');
1088                    }
1089    
1090                  // necessaire pour calcul de date en modification                  // necessaire pour calcul de date en modification
1091                  //$form->setType('delai', 'hiddenstatic');                  //$form->setType('delai', 'hiddenstatic');
1092                  // les administrateurs technique et fonctionnel peuvent                  // les administrateurs technique et fonctionnel peuvent
1093                  // modifier tous les champs de date                  // modifier tous les champs de date
1094                  // si l'instruction a déjà été finalisée au moins une fois                  // si l'instruction a déjà été finalisée au moins une fois
1095                  if ($this->f->isAccredited(array("instruction", "instruction_modification_dates"), "OR")                  if (($this->f->isAccredited(array($this->get_absolute_class_name(), $this->get_absolute_class_name()."modification_dates"), "OR")
1096                            || $this->f->isAccredited(array('instruction', 'instruction_modification_dates'), "OR"))
1097                      && $this->getVal("date_finalisation_courrier") != '') {                      && $this->getVal("date_finalisation_courrier") != '') {
1098                        //
1099                      $form->setType('date_envoi_signature', 'date');                      $form->setType('date_envoi_signature', 'date');
1100                      $form->setType('date_retour_signature', 'date');                      $form->setType('date_retour_signature', 'date');
1101                        if ($this->is_sent_for_signature() === true
1102                            && $this->is_signed() === true) {
1103                            //
1104                            $form->setType("date_envoi_signature", "datereadonly");
1105                            $form->setType("date_retour_signature", "datereadonly");
1106                        }
1107                      $form->setType('date_envoi_rar', 'date');                      $form->setType('date_envoi_rar', 'date');
1108                      $form->setType('date_retour_rar', 'date');                      $form->setType('date_retour_rar', 'date');
1109                      $form->setType('date_envoi_controle_legalite', 'date');                      $form->setType('date_envoi_controle_legalite', 'date');
1110                        if ($this->is_sent_to_cl() === true) {
1111                            $form->setType("date_envoi_controle_legalite", "datereadonly");
1112                        }
1113                      $form->setType('date_retour_controle_legalite', 'date');                      $form->setType('date_retour_controle_legalite', 'date');
1114                      $form->setType('date_finalisation_courrier', 'date');                      $form->setType('date_finalisation_courrier', 'date');
                     // suivi des dates  
                     if ($maj == 125) {  
                         $form->setType('date_evenement', 'hiddenstaticdate');  
                         $form->setType('complement_om_html', 'hiddenstatic');  
                         $form->setType('complement2_om_html', 'hiddenstatic');  
                         $form->setType('complement3_om_html', 'hiddenstatic');  
                         $form->setType('complement4_om_html', 'hiddenstatic');  
                         $form->setType('bible_auto', 'hidden');  
                         $form->setType('bible', 'hidden');  
                         $form->setType('bible2', 'hidden');  
                         $form->setType('bible3', 'hidden');  
                         $form->setType('bible4', 'hidden');  
                         $form->setType('signataire_arrete','selecthiddenstatic');  
                         $form->setType('om_final_instruction_utilisateur', 'hiddenstatic');  
                     }  
1115                  }                  }
1116              }              }
         } elseif($maj==2){  
             $form->setType('dossier', 'hidden');  
             $form->setType('bible_auto', 'hidden');  
             $form->setType('bible', 'hidden');  
             $form->setType('bible2', 'hidden');  
             $form->setType('bible3', 'hidden');  
             $form->setType('bible4', 'hidden');  
         }else {  
             $form->setType('destinataire', 'hidden');  
             $form->setType('dossier', 'hidden');  
             $form->setType('bible_auto', 'hidden');  
             $form->setType('bible', 'hidden');  
             $form->setType('bible2', 'hidden');  
             $form->setType('bible3', 'hidden');  
             $form->setType('bible4', 'hidden');  
         }  
   
         //Cache les champs pour la finalisation  
         $form->setType('om_fichier_instruction', 'hidden');  
         $form->setType('om_final_instruction', 'hidden');  
         // Cache le document arrêté  
         $form->setType('document_numerise', 'hidden');  
           
         //Masquer les champs date_envoi_controle_legalite et  
         //date_retour_controle_legalite si ce n'est pas un arrêté et si ce n'est  
         //pas un utilisateur ayant le droit spécifique  
         if ( !is_numeric($this->getVal("avis_decision"))&&  
             !$this->f->isAccredited(array("instruction", "instruction_modification_dates"), "OR")){  
               
             $form->setType("date_envoi_controle_legalite", "hiddendate");  
             $form->setType("date_retour_controle_legalite", "hiddendate");  
1117          }          }
1118    
1119          // Pour les actions finalize, unfinalize et notifier_commune          // MODE CONSULTER + SUPPRIMER + SUIVI DES DATES 125 + NOTIFICATION MANUELLE
1120          if($maj == 100 || $maj == 110 || $maj == 210) {          if ($this->getParameter('maj') == 3
1121              //              || $this->getParameter('maj') == 2
1122              foreach ($this->champs as $value) {              || $this->getParameter('maj') == 125
1123                  // Cache tous les champs              || $this->getParameter('maj') == 410) {
1124                  $form->setType($value, 'hidden');              //
1125                $form->setType("date_evenement", "datestatic");
1126                $form->setType("evenement", "selecthiddenstatic");
1127                if ($this->has_an_edition() === true) {
1128                    $form->setType('lettretype', 'hiddenstatic');
1129                    $form->setType("signataire_arrete", "selecthiddenstatic");
1130                    if ($this->getVal("om_final_instruction") == 't') {
1131                        $form->setType('om_final_instruction_utilisateur', 'textareastatic');
1132                    } else {
1133                        $form->setType('om_final_instruction_utilisateur', 'hidden');
1134                    }
1135                }
1136                if ($this->evenement_has_a_commentaire($this->getVal('evenement')) === true ) {
1137                    $form->setType('commentaire', 'textareastatic');
1138                }
1139            }
1140    
1141            // MODE CONSULTER + SUPPRIMER + NOTIFICATION MANUELLE
1142            if ($this->getParameter('maj') == 3
1143                || $this->getParameter('maj') == 2
1144                || $this->getParameter('maj') == 410) {
1145                // Si il n'y a pas de lettre type (edition) associé à l'événement
1146                // les dates de suivi ne sont pas affichée
1147                if ($this->has_an_edition() === true) {
1148                    $form->setType('date_envoi_signature', 'datestatic');
1149                    $form->setType('date_retour_signature', 'datestatic');
1150                    $form->setType('date_envoi_rar', 'datestatic');
1151                    $form->setType('date_retour_rar', 'datestatic');
1152                    $form->setType('date_envoi_controle_legalite', 'datestatic');
1153                    $form->setType('date_retour_controle_legalite', 'datestatic');
1154                    $form->setType('date_finalisation_courrier', 'datestatic');
1155                    if ($this->getVal("flag_edition_integrale") == "t") {
1156                        $form->setType("titre_om_htmletat", "htmlstatic");
1157                        $form->setType("corps_om_htmletatex", "htmlstatic");
1158                    } else {
1159                        $form->setType("complement_om_html", "htmlstatic");
1160                        $form->setType("complement2_om_html", "htmlstatic");
1161                        $form->setType("complement3_om_html", "htmlstatic");
1162                        $form->setType("complement4_om_html", "htmlstatic");
1163                    }
1164                }
1165            }
1166    
1167            // MODE SUIVI DES DATES 125
1168            if ($this->getParameter('maj') == 125) {
1169                $form->setType("date_evenement", "hiddenstaticdate");
1170                $form->setType('om_final_instruction_utilisateur', 'hiddenstatic');
1171                $form->setType('date_envoi_signature', 'date');
1172                $form->setType('date_retour_signature', 'date');
1173                if ($this->is_sent_for_signature() === true
1174                    || $this->is_signed() === true) {
1175                    //
1176                    $form->setType("date_envoi_signature", "datereadonly");
1177                    $form->setType("date_retour_signature", "datereadonly");
1178                }
1179                $form->setType('date_envoi_rar', 'date');
1180                $form->setType('date_retour_rar', 'date');
1181                $form->setType('date_envoi_controle_legalite', 'date');
1182                if ($this->is_sent_to_cl() === true) {
1183                    $form->setType("date_envoi_controle_legalite", "datereadonly");
1184                }
1185                $form->setType('date_retour_controle_legalite', 'date');
1186                $form->setType('date_finalisation_courrier', 'date');
1187            }
1188    
1189            if ($maj == 401) {
1190                foreach ($this->champs as $champ) {
1191                    $form->setType($champ, 'hidden');
1192                }
1193                $form->setType('preview_edition', 'previsualiser');
1194            }
1195        }
1196    
1197        function setOnchange(&$form,$maj){
1198            parent::setOnchange($form,$maj);
1199    
1200            // MODE AJOUTER
1201            if ($this->getParameter('maj') == 0) {
1202                $form->setOnchange(
1203                    "evenement",
1204                    "manage_instruction_evenement_lettretype(this.value, '".addslashes($this->getParameter('idxformulaire'))."');
1205                    manage_instruction_evenement_commentaire(this.value, '".addslashes($this->getParameter('idxformulaire'))."');"
1206                );
1207            }
1208        }
1209    
1210        function evenement_has_an_edition($evenement_id) {
1211            $evenement = $this->get_inst_evenement($evenement_id);
1212            $lettretype = $evenement->getVal('lettretype');
1213            if ($lettretype !== '' && $lettretype !== null) {
1214                return true;
1215            }
1216            return false;
1217        }
1218    
1219        function view_evenement_has_an_edition_json() {
1220            $json_return = array(
1221                "lettretype" => $this->evenement_has_an_edition($this->f->get_submitted_get_value('evenement_id')),
1222                "option_redaction_libre_enabled" => $this->is_option_redaction_libre_enabled(),
1223            );
1224            echo json_encode($json_return);
1225        }
1226    
1227        function evenement_has_a_commentaire($evenement_id) {
1228            $evenement = $this->get_inst_evenement($evenement_id);
1229            return $this->get_boolean_from_pgsql_value($evenement->getVal('commentaire'));
1230        }
1231    
1232        function view_evenement_has_a_commentaire_json() {
1233            $json_return = array(
1234                "commentaire" => $this->evenement_has_a_commentaire($this->f->get_submitted_get_value('evenement_id'))
1235            );
1236            echo json_encode($json_return);
1237        }
1238    
1239    
1240        /**
1241         * CONDITION - can_be_sended_to_cl
1242         *
1243         * Vérifie que le contrôle de légalité est disponible
1244         *
1245         * @return boolean
1246         */
1247        function can_be_sended_to_cl() {
1248            // Si l'instruction a une édition
1249            // et que l'événement est paramétré pour envoyer le contrôle de légalité
1250            // par Plat'AU
1251            // et que la date de retour signature est renseignée
1252            // et que la date d'envoi au contrôle légalité n'est pas renseignée
1253            // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)
1254            if ($this->has_an_edition() === true) {
1255                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
1256                $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));
1257                if ($inst_evenement->getVal('envoi_cl_platau') === 't'
1258                    && empty($this->getVal('date_retour_signature')) === false
1259                    && empty($this->getVal('date_envoi_controle_legalite')) === true
1260                    && $this->getVal('envoye_cl_platau') === 'f'
1261                    && $this->f->is_type_dossier_platau($inst_di->getVal('dossier_autorisation')) === true
1262                    && $inst_di->getVal('etat_transmission_platau') !== 'jamais_transmissible') {
1263                    //
1264                    return true;
1265              }              }
1266          }          }
1267            //
1268            return false;
1269        }
1270    
1271        /**
1272         *
1273         * @return string
1274         */
1275        function get_var_sql_forminc__sql_signataire_arrete() {
1276            return "SELECT
1277                signataire_arrete.signataire_arrete,
1278                CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1279                FROM ".DB_PREFIXE."signataire_arrete
1280                WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1281                ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
1282        }
1283    
1284        /**
1285         *
1286         * @return string
1287         */
1288        function get_var_sql_forminc__sql_signataire_arrete_by_id() {
1289            return "SELECT
1290                signataire_arrete.signataire_arrete,
1291                CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1292                FROM ".DB_PREFIXE."signataire_arrete
1293                WHERE signataire_arrete.signataire_arrete = <idx>";
1294        }
1295    
1296        /**
1297         *
1298         * @return string
1299         */
1300        function get_var_sql_forminc__sql_signataire_arrete_by_di() {
1301            return "SELECT
1302                signataire_arrete.signataire_arrete,
1303                CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1304                FROM ".DB_PREFIXE."signataire_arrete
1305                LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1306                WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1307                AND (om_collectivite.niveau = '2' OR signataire_arrete.om_collectivite = <collectivite_di>)
1308                ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
1309        }
1310    
1311        /**
1312         *
1313         * @return string
1314         */
1315        function get_var_sql_forminc__sql_signataire_arrete_defaut() {
1316            return "SELECT
1317                signataire_arrete.signataire_arrete,
1318                CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1319                FROM ".DB_PREFIXE."signataire_arrete
1320                WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE
1321                ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
1322      }      }
1323    
1324      function setSelect(&$form, $maj,&$db,$debug) {      /**
1325         *
1326         * @return string
1327         */
1328        function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {
1329            return "SELECT
1330                signataire_arrete.signataire_arrete,
1331                CONCAT_WS(' - ', CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom), signataire_arrete.description)
1332                FROM ".DB_PREFIXE."signataire_arrete
1333                LEFT JOIN ".DB_PREFIXE."om_collectivite ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1334                WHERE ((signataire_arrete.om_validite_debut IS NULL AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE)) OR (signataire_arrete.om_validite_debut <= CURRENT_DATE AND (signataire_arrete.om_validite_fin IS NULL OR signataire_arrete.om_validite_fin > CURRENT_DATE))) AND signataire_arrete.defaut IS TRUE
1335                AND (om_collectivite.niveau = '2' OR signataire_arrete.om_collectivite = <collectivite_di>)
1336                ORDER BY signataire_arrete.prenom, signataire_arrete.nom";
1337        }
1338    
1339        /**
1340         * SETTER_FORM - setSelect.
1341         *
1342         * @return void
1343         */
1344        function setSelect(&$form, $maj, &$dnu1 = null, $dnu2 = null) {
1345            //parent::setSelect($form, $maj);
1346          /**          /**
1347           * On ne surcharge pas la méthode parent car une requête sur la table           * On ne surcharge pas la méthode parent car une requête sur la table
1348           * dossier est mauvaise pour les performances, car la requête qui           * dossier est mauvaise pour les performances, car la requête qui
# Line 549  class instruction extends instruction_ge Line 1350  class instruction extends instruction_ge
1350           * champs action, avis_decision et etat ne sont pas utilisés comme des           * champs action, avis_decision et etat ne sont pas utilisés comme des
1351           * select           * select
1352           */           */
         if(file_exists ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc.php"))  
             include ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc.php");  
         elseif(file_exists ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc"))  
             include ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc");  
   
1353          //// action          //// action
1354          //$this->init_select($form, $db, $maj, $debug, "action",          //$this->init_select($form, $this->f->db, $maj, null, "action",
1355          //                   $sql_action, $sql_action_by_id, false);          //                   $sql_action, $sql_action_by_id, false);
1356    
1357          //// avis_decision          //// avis_decision
1358          //$this->init_select($form, $db, $maj, $debug, "avis_decision",          //$this->init_select($form, $this->f->db, $maj, null, "avis_decision",
1359          //                   $sql_avis_decision, $sql_avis_decision_by_id, false);          //                   $sql_avis_decision, $sql_avis_decision_by_id, false);
1360    
1361          //// dossier          //// dossier
1362          //$this->init_select($form, $db, $maj, $debug, "dossier",          //$this->init_select($form, $this->f->db, $maj, null, "dossier",
1363          //                   $sql_dossier, $sql_dossier_by_id, false);          //                   $sql_dossier, $sql_dossier_by_id, false);
1364    
1365          //// etat          //// etat
1366          //$this->init_select($form, $db, $maj, $debug, "etat",          //$this->init_select($form, $this->f->db, $maj, null, "etat",
1367          //                   $sql_etat, $sql_etat_by_id, false);          //                   $sql_etat, $sql_etat_by_id, false);
1368    
1369          //// evenement          //// evenement
1370          //$this->init_select($form, $db, $maj, $debug, "evenement",          //$this->init_select($form, $this->f->db, $maj, null, "evenement",
1371          //                   $sql_evenement, $sql_evenement_by_id, false);          //                   $sql_evenement, $sql_evenement_by_id, false);
1372    
1373          // signataire_arrete          // signataire_arrete
# Line 581  class instruction extends instruction_ge Line 1377  class instruction extends instruction_ge
1377                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1378                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1379                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1380                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1381                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1382                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1383                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1384                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1385              // on recupère les signataires de la multicollectivité et de celle du DI              // on recupère les signataires de la multicollectivité et de celle du DI
1386              require_once "../obj/dossier_instruction.class.php";              $di = $this->f->get_inst__om_dbform(array(
1387              $di = new dossier_instruction($this->getParameter('idxformulaire'), $db, $debug);                  "obj" => "dossier_instruction",
1388              $sql_signataire_arrete_by_di = str_replace('<collectivite_di>', $di->getVal("om_collectivite"), $sql_signataire_arrete_by_di);                  "idx" => $this->getParameter('idxformulaire'),
1389              $this->init_select($form, $db, $maj, $debug, "signataire_arrete",              ));
1390                  $sql_signataire_arrete_by_di, $sql_signataire_arrete_by_id, true);              $sql_signataire_arrete_by_di = str_replace(
1391                    '<collectivite_di>',
1392                    $di->getVal("om_collectivite"),
1393                    $this->get_var_sql_forminc__sql("signataire_arrete_by_di")
1394                );
1395                $this->init_select(
1396                    $form,
1397                    $this->f->db,
1398                    $maj,
1399                    null,
1400                    "signataire_arrete",
1401                    $sql_signataire_arrete_by_di,
1402                    $this->get_var_sql_forminc__sql("signataire_arrete_by_id"),
1403                    true
1404                );
1405          } else {          } else {
1406              $this->init_select($form, $db, $maj, $debug, "signataire_arrete",              $this->init_select(
1407                  $sql_signataire_arrete, $sql_signataire_arrete_by_id, true);                  $form,
1408                    $this->f->db,
1409                    $maj,
1410                    null,
1411                    "signataire_arrete",
1412                    $this->get_var_sql_forminc__sql("signataire_arrete"),
1413                    $this->get_var_sql_forminc__sql("signataire_arrete_by_id"),
1414                    true
1415                );
1416          }          }
1417    
1418          /**          /**
# Line 615  class instruction extends instruction_ge Line 1437  class instruction extends instruction_ge
1437              INNER JOIN ".DB_PREFIXE."transition              INNER JOIN ".DB_PREFIXE."transition
1438                  ON evenement.evenement = transition.evenement                  ON evenement.evenement = transition.evenement
1439                  AND dossier.etat=transition.etat                  AND dossier.etat=transition.etat
1440              WHERE dossier.dossier='".$this->idxformulaire."' ";              WHERE dossier.dossier='".$this->getParameter("idxformulaire")."' ";
1441    
1442              // Si changement de décision par instructeur commune              // Si changement de décision par instructeur commune
1443              if($this->f->isUserInstructeur() === true              if($this->f->isUserInstructeur() === true
1444                  && $this->f->getDivisionFromDossier($this->idxformulaire) != $_SESSION["division"]                  && $this->getDivisionFromDossier($this->getParameter("idxformulaire")) != $_SESSION["division"]
1445                  && $this->f->isInstrCanChangeDecision($this->idxformulaire) === true) {                  && $this->isInstrCanChangeDecision($this->getParameter("idxformulaire")) === true) {
1446                  $sql .= "AND evenement.type IN ('arrete', 'changement_decision') ";                  $sql .= "AND evenement.type IN ('arrete', 'changement_decision') ";
1447              }              }
1448              $sql .= "ORDER BY evenement.libelle, evenement.action";              $sql .= "ORDER BY evenement.libelle, evenement.action";
1449              $res = $db->query($sql);              $res = $this->f->db->query($sql);
1450              $this->addToLog("setSelect(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->query(\"".$sql."\");", VERBOSE_MODE);
1451              if (database::isError($res)) {              if (database::isError($res)) {
1452                  die($res->getMessage());                  die($res->getMessage());
# Line 639  class instruction extends instruction_ge Line 1461  class instruction extends instruction_ge
1461                  $contenu[1][] = $row[1];                  $contenu[1][] = $row[1];
1462              }              }
1463              $form->setSelect("evenement", $contenu);              $form->setSelect("evenement", $contenu);
1464    
1465          } else {          } else {
1466              $sql = "SELECT              $sql = "SELECT
1467              evenement.libelle as lib              evenement.libelle as lib
1468              FROM ".DB_PREFIXE."evenement              FROM ".DB_PREFIXE."evenement
1469              WHERE evenement.evenement=".$this->getVal("evenement")."";              WHERE evenement.evenement=".$this->getVal("evenement")."";
1470              $res = $db->getone($sql);              $res = $this->f->db->getone($sql);
1471              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1472              if (database::isError($res)) {              if (database::isError($res)) {
1473                  die($res->getMessage());                  die($res->getMessage());
# Line 675  class instruction extends instruction_ge Line 1498  class instruction extends instruction_ge
1498          // lien bible4          // lien bible4
1499          $contenu = array(_("bible"));          $contenu = array(_("bible"));
1500          $form->setSelect("bible4",$contenu);          $form->setSelect("bible4",$contenu);
1501    
1502            if ($maj == 1) {
1503                $base64 = $this->init_pdf_temp();
1504                $form->setSelect('live_preview', array('base64'=>$base64));
1505                $form->setSelect("btn_refresh", array(_('Prévisualiser')));
1506                $form->setSelect("btn_preview", array(_('Prévisualiser >>')));
1507                $form->setSelect("btn_redaction", array(_('<< Rédiger')));
1508            }
1509    
1510            // Selection du type de rédaction à l'ajout
1511            $content = array(
1512                0 => array('f', 't', ),
1513                1 => array(_('Rédaction par compléments'), _('Rédaction libre'), ),
1514            );
1515            $form->setSelect('flag_edition_integrale', $content);
1516    
1517            $contenu = array();
1518            foreach(array('waiting', 'in_progress', 'canceled', 'expired', 'finished') as $value) {
1519                $contenu[0][] = $value;
1520                $contenu[1][] = $this->get_trad_for_statut($value);
1521            }
1522            $form->setSelect('statut_signature', $contenu);
1523    
1524    
1525            if ($maj == 401) {
1526                $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
1527                $form->setSelect('preview_edition', array(
1528                    'base64' => base64_encode($file['file_content']),
1529                    'mimetype' => $file['metadata']['mimetype'],
1530                    'label' => 'instruction_'.$this->getVal($this->clePrimaire),
1531                    'href' => sprintf(
1532                        '../app/index.php?module=form&snippet=file&obj=instruction&champ=om_fichier_instruction&id=%1$s',
1533                        $this->getVal($this->clePrimaire)
1534                    )
1535                ));
1536            }
1537      }      }
1538    
1539      function cleSecondaire($id, &$db, $val, $DEBUG) {      function cleSecondaire($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
1540          //          //
1541          parent::cleSecondaire($id, $db, $val, $DEBUG);          // Vérifie uniquementla cle secondaire : demande
1542            $this->rechercheTable($this->f->db, "demande", "instruction_recepisse", $id);
1543                    
1544          $id = $this->getVal($this->clePrimaire);          $id = $this->getVal($this->clePrimaire);
1545    
# Line 691  class instruction extends instruction_ge Line 1551  class instruction extends instruction_ge
1551              LEFT JOIN ".DB_PREFIXE."demande              LEFT JOIN ".DB_PREFIXE."demande
1552              ON demande.demande_type = demande_type.demande_type              ON demande.demande_type = demande_type.demande_type
1553              WHERE demande.instruction_recepisse = ".$id;              WHERE demande.instruction_recepisse = ".$id;
1554          $res = $this->db->getOne($sql);          $res = $this->f->db->getOne($sql);
1555          $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1556          if (database::isError($res)) {          if (database::isError($res)) {
1557              die($res->getMessage());              die($res->getMessage());
# Line 707  class instruction extends instruction_ge Line 1567  class instruction extends instruction_ge
1567              $sql = "SELECT demande              $sql = "SELECT demande
1568                  FROM ".DB_PREFIXE."demande                  FROM ".DB_PREFIXE."demande
1569                  WHERE instruction_recepisse = ".$id;                  WHERE instruction_recepisse = ".$id;
1570              $res = $this->db->getOne($sql);              $res = $this->f->db->getOne($sql);
1571              $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1572              if (database::isError($res)) {              if (database::isError($res)) {
1573                  die($res->getMessage());                  die($res->getMessage());
# Line 715  class instruction extends instruction_ge Line 1575  class instruction extends instruction_ge
1575    
1576              //Si c'est un événement d'instruction lié à une demande              //Si c'est un événement d'instruction lié à une demande
1577              if ($res != null || $res != ""){              if ($res != null || $res != ""){
1578                                    $demande = $this->f->get_inst__om_dbform(array(
1579                  require_once "../obj/demande.class.php";                      "obj" => "demande",
1580                  $demande = new demande($res, $this->db, DEBUG);                      "idx" => $res,
1581                    ));
1582    
1583                  //On met à jour la demande en supprimant la liaison vers                  //On met à jour la demande en supprimant la liaison vers
1584                  //l'événement d'instruction                  //l'événement d'instruction
# Line 728  class instruction extends instruction_ge Line 1589  class instruction extends instruction_ge
1589                  }                  }
1590                  $valF['date_demande']=$demande->dateDBToForm($valF['date_demande']);                  $valF['date_demande']=$demande->dateDBToForm($valF['date_demande']);
1591                  $valF['instruction_recepisse']=NULL;                  $valF['instruction_recepisse']=NULL;
1592                  $ret = $demande->modifier($valF, $this->db, DEBUG);                  $ret = $demande->modifier($valF);
1593              }              }
1594                                    
1595              /**              /**
# Line 741  class instruction extends instruction_ge Line 1602  class instruction extends instruction_ge
1602              // concerne le dossier en cours              // concerne le dossier en cours
1603              $sql = "SELECT max(instruction)              $sql = "SELECT max(instruction)
1604              FROM ".DB_PREFIXE."instruction              FROM ".DB_PREFIXE."instruction
1605              WHERE dossier ='".$this->idxformulaire."'";              WHERE dossier ='".$this->getParameter("idxformulaire")."'";
1606              $dernierevenement = $db->getOne($sql);              $dernierevenement = $this->f->db->getOne($sql);
1607              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1608              if (database::isError($dernierevenement)) {              if (database::isError($dernierevenement)) {
1609                  die($dernierevenement->getMessage());                  die($dernierevenement->getMessage());
# Line 772  class instruction extends instruction_ge Line 1633  class instruction extends instruction_ge
1633                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1634                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1635                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1636                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1637                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1638                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1639                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1640                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1641    
1642              // Vérification de la possibilité de modifier les dates si déjà éditées              // Vérification de la possibilité de modifier les dates si déjà éditées
1643              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {
# Line 788  class instruction extends instruction_ge Line 1653  class instruction extends instruction_ge
1653          return true;          return true;
1654      }      }
1655    
1656      /*Met des valeurs par défaut dans certains des sous-formulaire*/      /**
1657      function setValsousformulaire(&$form,$maj,$validation,$idxformulaire,$retourformulaire,$typeformulaire){       * SETTER_FORM - setValsousformulaire (setVal).
1658         *
1659         * @return void
1660         */
1661        function setValsousformulaire(&$form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire, &$dnu1 = null, $dnu2 = null) {
1662            // parent::setValsousformulaire($form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire);
1663            //
1664            $this->retourformulaire = $retourformulaire;
1665          //          //
         $this->retourformulaire=$retourformulaire;  
         $this->idxformulaire=$idxformulaire;  
         // Ajout  
1666          if ($maj == 0) {          if ($maj == 0) {
1667              $form->setVal("destinataire", $idxformulaire);              $form->setVal("destinataire", $this->getParameter("idxformulaire"));
1668              $form->setVal("dossier", $idxformulaire);              $form->setVal("dossier", $this->getParameter("idxformulaire"));
1669          }          }
1670          //          //
1671          $this->set_form_default_values($form, $maj, $validation);          $this->set_form_default_values($form, $maj, $validation);
1672      }      }
1673    
1674      /**      /**
1675       *  Permet de pré-remplir les valeurs des formulaires.       * SETTER_FORM - set_form_default_values (setVal).
1676       *         *
1677       * @param [object]   $form        formulaire       * @return void
      * @param [integer]  $maj         mode  
      * @param [integer]  $validation  validation  
1678       */       */
1679      function set_form_default_values(&$form, $maj, $validation) {      function set_form_default_values(&$form, $maj, $validation) {
1680            //
         // Ajout  
1681          if ($maj == 0) {          if ($maj == 0) {
             if(file_exists ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc.php"))  
                 include ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc.php");  
             elseif(file_exists ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc"))  
                 include ("../sql/".OM_DB_PHPTYPE."/".$this->table.".form.inc");  
1682              // si contexte DI              // si contexte DI
1683              if ($this->getParameter("retourformulaire") == "dossier"              if ($this->getParameter("retourformulaire") == "dossier"
1684                  || $this->getParameter("retourformulaire") == "dossier_instruction"                  || $this->getParameter("retourformulaire") == "dossier_instruction"
1685                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1686                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1687                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1688                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1689                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1690                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1691                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1692                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1693                  // on recupère les signataires de la multicollectivité et de celle du DI                  // on recupère les signataires de la multicollectivité et de celle du DI
1694                  require_once "../obj/dossier_instruction.class.php";                  $di = $this->f->get_inst__om_dbform(array(
1695                  $di = new dossier_instruction($this->getParameter('idxformulaire'), $db, DEBUG);                      "obj" => "dossier_instruction",
1696                  $sql = str_replace('<collectivite_di>', $di->getVal("om_collectivite"), $sql_signataire_arrete_defaut_by_di);                      "idx" => $this->getParameter("idxformulaire"),
1697                    ));
1698                    $sql = str_replace(
1699                        "<collectivite_di>",
1700                        $di->getVal("om_collectivite"),
1701                        $this->get_var_sql_forminc__sql("signataire_arrete_defaut_by_di")
1702                    );
1703              } else {              } else {
1704                  $sql = $sql_signataire_arrete_defaut;                  $sql = $this->get_var_sql_forminc__sql("signataire_arrete_defaut");
1705              }              }
             // Date du jour  
             $form->setVal("date_evenement", date('Y-m-d'));  
   
             // Exécution de la requête  
1706              $res = $this->f->db->query($sql);              $res = $this->f->db->query($sql);
1707              $this->f->addToLog("setVal(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
1708              if ( database::isError($res)){              $this->f->isDatabaseError($res);
                 die();  
             }  
           
1709              $row = $res->fetchrow(DB_FETCHMODE_ASSOC);              $row = $res->fetchrow(DB_FETCHMODE_ASSOC);
1710                            if (isset($row["signataire_arrete"])
1711              if (isset($row['signataire_arrete']) && is_numeric($row['signataire_arrete'])){                  && is_numeric($row["signataire_arrete"])) {
1712                  $form->setVal("signataire_arrete",$row['signataire_arrete']);                  //
1713                    $form->setVal("signataire_arrete", $row["signataire_arrete"]);
1714              }              }
1715                // Date du jour
1716                $form->setVal("date_evenement", date("Y-m-d"));
1717          }          }
1718            //
         // Ajout et modification  
1719          if ($maj == 0 || $maj == 1 || $maj == 125) {          if ($maj == 0 || $maj == 1 || $maj == 125) {
1720              $form->setVal("bible_auto","bible_auto()");              $form->setVal("bible_auto", "bible_auto()");
1721              $form->setVal("bible","bible(1)");              $form->setVal("bible", "bible(1)");
1722              $form->setVal("bible2","bible(2)");              $form->setVal("bible2", "bible(2)");
1723              $form->setVal("bible3","bible(3)");              $form->setVal("bible3", "bible(3)");
1724              $form->setVal("bible4","bible(4)");              $form->setVal("bible4", "bible(4)");
1725            }
1726            //
1727            $collectivite_di = $this->get_dossier_instruction_om_collectivite();
1728            if ($maj == 1
1729                && $this->f->is_option_preview_pdf_enabled($collectivite_di) === true
1730                && $this->has_an_edition() === true) {
1731                //
1732                $form->setVal("live_preview", $this->getVal($this->clePrimaire));
1733                $form->setVal("btn_refresh", "reload_pdf_viewer()");
1734                $form->setVal("btn_preview", "show_instr_preview()");
1735                $form->setVal("btn_redaction", "show_instr_redaction()");
1736          }          }
     }  
1737    
1738            if ($maj == 3
1739                && $this->can_display_notification()
1740            ) {
1741                $form->setVal("suivi_notification", $this->get_json_suivi_notification());
1742            }
1743        }
1744    
1745      function setLayout(&$form, $maj){      function setLayout(&$form, $maj){
1746          if ( $maj < 2 OR $maj == 3 OR $maj == 125 ) {          $form->setBloc('evenement','D',"","sousform-instruction-action-".$maj);
                         /*Champ sur lequel s'ouvre le bloc 1 */  
             $form->setBloc('evenement','D',"","col_12");  
1747    
1748              $form->setFieldset('evenement','D',_('Evenement'));          $form->setFieldset('evenement','D',_('Evenement'));
1749              $form->setFieldset('om_final_instruction_utilisateur','F','');          $form->setFieldset('om_final_instruction_utilisateur','F','');
1750                        
1751              $form->setBloc('om_final_instruction_utilisateur','F');          $form->setBloc('om_final_instruction_utilisateur','F');
1752    
1753              $form->setBloc('date_finalisation_courrier','D',"","col_12");          $form->setBloc('date_finalisation_courrier','D',"","");
1754    
1755              $form->setFieldset('date_finalisation_courrier','D',_('Dates'));          $form->setFieldset('date_finalisation_courrier','D',_('Dates'));
1756              $form->setBloc('date_finalisation_courrier','D',"","col_6");          $form->setBloc('date_finalisation_courrier','D',"","col_6");
1757              $form->setBloc('date_envoi_controle_legalite','F');          $form->setBloc('date_envoi_controle_legalite','F');
1758    
1759              $form->setBloc('signataire_arrete','D',"","col_6");          $form->setBloc('date_retour_signature','D',"","col_6");
1760              $form->setBloc('date_retour_controle_legalite','F');          $form->setBloc('date_retour_controle_legalite','F');
1761              $form->setFieldset('date_retour_controle_legalite','F','');          $form->setFieldset('date_retour_controle_legalite','F','');
1762                        
1763              $form->setBloc('date_retour_controle_legalite','F');          $form->setBloc('date_retour_controle_legalite','F');
1764    
1765            $form->setBloc('statut_signature','D');
1766            $form->setFieldset('statut_signature','D','Suivi Parapheur');
1767            $form->setBloc('commentaire_signature','F');
1768            $form->setBloc('historique_signature','D');
1769            $form->setFieldset('historique_signature', 'DF', __("Historique"), "collapsible, startClosed");
1770            $form->setBloc('historique_signature','F');
1771            $form->setFieldset('historique_signature','F');
1772    
1773            $form->setFieldset('suivi_notification', 'D', __("Suivi notification"), "collapsible");
1774            $form->setFieldset('suivi_notification','F');
1775    
1776            if ($maj == 1) {
1777                // Récupère la collectivité du dossier d'instruction
1778                $collectivite_di = $this->get_dossier_instruction_om_collectivite();
1779    
1780              $form->setBloc('complement_om_html','D',"","col_12");              //
1781                if ($this->f->is_option_preview_pdf_enabled($collectivite_di) === true
1782                    && $this->has_an_edition() === true) {
1783                    //
1784                    $form->setBloc('complement_om_html','D',"","container_instr_edition");
1785                    $form->setBloc('complement_om_html','D',"","hidelabel box_instr_edition redaction_instr_edition");
1786                    $form->setBloc('complement_om_html','D',"","box_instr_edition_main");
1787                    $form->setFieldset('complement_om_html','D',_('Complement'));
1788                    $form->setFieldset('bible','F','');
1789                    $form->setFieldset('complement2_om_html','D',_('Complement 2'));
1790                    $form->setFieldset('bible2','F','');
1791                    $form->setFieldset('complement3_om_html','D',_('Complement 3'));
1792                    $form->setFieldset('bible3','F','');
1793                    $form->setFieldset('complement4_om_html','D',_('Complement 4'));
1794                    $form->setFieldset('bible4','F','');
1795                    $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
1796                    $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
1797                    $form->setBloc('corps_om_htmletatex','F');
1798                    $form->setBloc('btn_preview','DF',"","box_instr_edition_btn");
1799                    $form->setBloc('btn_preview','F');
1800                    $form->setBloc('btn_redaction','D', '',"hidelabel box_instr_edition preview_instr_edition");
1801                    $form->setBloc('btn_redaction','DF',"","box_instr_edition_btn");
1802                    $form->setFieldset('btn_refresh','D',_('Prévisualisation'), "box_instr_edition_main");
1803                    $form->setFieldset('live_preview','F');
1804                    $form->setBloc('live_preview','F');
1805                    $form->setBloc('live_preview','F');
1806                } else {
1807                    $form->setBloc('complement_om_html','D',"","hidelabel");
1808                    $form->setFieldset('complement_om_html','D',_('Complement'));
1809                    $form->setFieldset('bible','F','');
1810                    $form->setFieldset('complement2_om_html','D',_('Complement 2'));
1811                    $form->setFieldset('bible2','F','');
1812                    $form->setFieldset('complement3_om_html','D',_('Complement 3'));
1813                    $form->setFieldset('bible3','F','');
1814                    $form->setFieldset('complement4_om_html','D',_('Complement 4'));
1815                    $form->setFieldset('bible4','F','');
1816                    $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
1817                    $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
1818                    $form->setBloc('corps_om_htmletatex','F');
1819                }
1820            } else {
1821                $form->setBloc('complement_om_html','D',"","hidelabel");
1822              $form->setFieldset('complement_om_html','D',_('Complement'));              $form->setFieldset('complement_om_html','D',_('Complement'));
1823              $form->setFieldset('bible','F','');              $form->setFieldset('bible','F','');
             $form->setBloc('bible','F');  
   
             $form->setBloc('complement2_om_html','D',"","col_12");  
1824              $form->setFieldset('complement2_om_html','D',_('Complement 2'));              $form->setFieldset('complement2_om_html','D',_('Complement 2'));
1825              $form->setFieldset('bible2','F','');              $form->setFieldset('bible2','F','');
             $form->setBloc('bible2','F');  
               
             $form->setBloc('complement3_om_html','D',"","col_12");  
1826              $form->setFieldset('complement3_om_html','D',_('Complement 3'));              $form->setFieldset('complement3_om_html','D',_('Complement 3'));
1827              $form->setFieldset('bible3','F','');              $form->setFieldset('bible3','F','');
             $form->setBloc('bible3','F');  
               
             $form->setBloc('complement4_om_html','D',"","col_12");  
1828              $form->setFieldset('complement4_om_html','D',_('Complement 4'));              $form->setFieldset('complement4_om_html','D',_('Complement 4'));
1829              $form->setFieldset('bible4','F','');              $form->setFieldset('bible4','F','');
1830              $form->setBloc('bible4','F');              $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
1831                $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
1832                $form->setBloc('corps_om_htmletatex','F');
1833          }          }
1834      }      }
1835            
# Line 913  class instruction extends instruction_ge Line 1842  class instruction extends instruction_ge
1842          $form->setLib('bible2', "");          $form->setLib('bible2', "");
1843          $form->setLib('bible3', "");          $form->setLib('bible3', "");
1844          $form->setLib('bible4', "");          $form->setLib('bible4', "");
1845            $form->setLib('btn_refresh', "");
1846            $form->setLib('btn_preview', "");
1847            $form->setLib('btn_redaction', "");
1848            $form->setLib('live_preview', "");
1849          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));
1850            $form->setLib('date_envoi_rar', __("date_envoi_ar"));
1851            $form->setLib('date_retour_rar', __("date_notification"));
1852            $form->setLib('statut_signature', __("statut"));
1853            $form->setLib('commentaire_signature', __("commentaire"));
1854            $form->setLib('historique_signature', '');
1855            $form->setLib('suivi_notification', '');
1856            $form->setLib('preview_edition', "");
1857    
1858            // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
1859            // ajout et que l'option de rédaction libre est activée sur la
1860            // collectivité du dossier
1861            if ($maj === '0' && $this->is_option_redaction_libre_enabled() === true) {
1862                //
1863                $help_text_template = '%s <span class="info-16" title="%s"></span>';
1864                $help_text = _("Attention: le passage du mode 'Rédaction libre' à celui de 'Rédaction par compléments' fait perdre toute la rédaction manuelle effectuée.");
1865                $form->setLib('flag_edition_integrale', sprintf($help_text_template, _("Type de rédaction"), $help_text));
1866            }
1867            else {
1868                $form->setLib('flag_edition_integrale', _("Type de rédaction"));
1869            }
1870    
1871            // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
1872            // modification et que l'option de prévisualisation de l'édition est
1873            // activée sur la collectivité du dossier
1874            if ($maj === '1'
1875                && $this->f->is_option_preview_pdf_enabled($this->get_dossier_instruction_om_collectivite()) === true) {
1876                //
1877                $help_text_template = '%s <span class="info-16" title="%s"></span>';
1878                $help_text = _("Attention la modification de la valeur de ce champ n'est pas prise en compte dans la prévisualisation. Pour que cette valeur soit mise à jour, il suffit de valider le formulaire.");
1879                $form->setLib('date_evenement', sprintf($help_text_template, _('date_evenement'), $help_text));
1880                $form->setLib('signataire_arrete', sprintf($help_text_template, _('signataire_arrete'), $help_text));
1881            }
1882      }      }
1883    
1884      function triggerajouter($id, &$db, $val, $DEBUG) {      /**
1885         * TRIGGER - triggerajouter.
1886         *
1887         * @return boolean
1888         */
1889        function triggerajouter($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
1890            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
1891          /**          /**
1892           * Le code suivant permet de récupérer des valeurs des tables evenement           * Le code suivant permet de récupérer des valeurs des tables evenement
1893           * et dossier pour les stocker dans l'instruction :           * et dossier pour les stocker dans l'instruction :
# Line 929  class instruction extends instruction_ge Line 1900  class instruction extends instruction_ge
1900           * - delai_notification           * - delai_notification
1901           * - lettretype           * - lettretype
1902           * - autorite_competente           * - autorite_competente
1903             * - pec_metier
1904             * - complement_om_html
1905             * - complement2_om_html
1906             * - complement3_om_html
1907             * - complement4_om_html
1908             * - complement5_om_html
1909           * DEPUIS LE DOSSIER D'INSTRUCTION           * DEPUIS LE DOSSIER D'INSTRUCTION
1910           * - archive_delai           * - archive_delai
1911           * - archive_accord_tacite           * - archive_accord_tacite
# Line 948  class instruction extends instruction_ge Line 1925  class instruction extends instruction_ge
1925          // Récupération de tous les paramètres de l'événement sélectionné          // Récupération de tous les paramètres de l'événement sélectionné
1926          $sql = "SELECT * FROM ".DB_PREFIXE."evenement          $sql = "SELECT * FROM ".DB_PREFIXE."evenement
1927          WHERE evenement=".$this->valF['evenement'];          WHERE evenement=".$this->valF['evenement'];
1928          $res = $db->query($sql);          $res = $this->f->db->query($sql);
1929          $this->addToLog("triggerajouter(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
1930          if (database::isError($res)) {          if (database::isError($res)) {
1931              die($res->getMessage());              die($res->getMessage());
1932          }          }
# Line 986  class instruction extends instruction_ge Line 1963  class instruction extends instruction_ge
1963              }              }
1964              // Récupération de la valeur de la lettre type              // Récupération de la valeur de la lettre type
1965              $this->valF['lettretype']=$row['lettretype'];              $this->valF['lettretype']=$row['lettretype'];
1966                // Récupération de la valeur de la prise en compte métier
1967                // si la prise en compte métier est paramétrée dans l'événement
1968                $this->valF['pec_metier'] = NULL;
1969                if(isset($row['pec_metier']) === true and empty($row['pec_metier']) === false) {
1970                    $this->valF['pec_metier'] = $row['pec_metier'];
1971                }
1972          }          }
1973          // Récupération de toutes les valeurs du dossier d'instruction en cours          // Récupération de toutes les valeurs du dossier d'instruction en cours
1974          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          $sql = "SELECT * FROM ".DB_PREFIXE."dossier
1975          WHERE dossier='".$this->valF['dossier']."'";          WHERE dossier='".$this->valF['dossier']."'";
1976          $res = $db->query($sql);          $res = $this->f->db->query($sql);
1977          $this->addToLog("triggerajouter(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
1978          if (database::isError($res)) {          if (database::isError($res)) {
1979              die($res->getMessage());              die($res->getMessage());
1980          }          }
# Line 1006  class instruction extends instruction_ge Line 1989  class instruction extends instruction_ge
1989                  LEFT JOIN ".DB_PREFIXE."dossier                  LEFT JOIN ".DB_PREFIXE."dossier
1990                      ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation                      ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation
1991          WHERE dossier.dossier='".$this->valF['dossier']."'";          WHERE dossier.dossier='".$this->valF['dossier']."'";
1992          $duree_validite_parametrage = $db->getOne($sql);          $duree_validite_parametrage = $this->f->db->getOne($sql);
1993          $this->addToLog("triggerajouter(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
1994          database::isError($duree_validite_parametrage);          database::isError($duree_validite_parametrage);
1995          if ($duree_validite_parametrage != '') {          if ($duree_validite_parametrage != '') {
1996              $this->valF['duree_validite_parametrage']= $duree_validite_parametrage;              $this->valF['duree_validite_parametrage']= $duree_validite_parametrage;
# Line 1206  class instruction extends instruction_ge Line 2189  class instruction extends instruction_ge
2189          $sql = "SELECT retour          $sql = "SELECT retour
2190              FROM ".DB_PREFIXE."evenement              FROM ".DB_PREFIXE."evenement
2191              WHERE evenement = ".$evenement;              WHERE evenement = ".$evenement;
2192          $retour = $this->db->getOne($sql);          $retour = $this->f->db->getOne($sql);
2193          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);
2194          if (database::isError($retour)) {          if (database::isError($retour)) {
2195              die($retour->getMessage());              die($retour->getMessage());
# Line 1237  class instruction extends instruction_ge Line 2220  class instruction extends instruction_ge
2220                WHERE                WHERE
2221                    evenement =".$evenement;                    evenement =".$evenement;
2222    
2223          $restriction = $this->db->getOne($sql);          $restriction = $this->f->db->getOne($sql);
2224          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);
2225          if (database::isError($restriction)) {          if (database::isError($restriction)) {
2226              die($restriction->getMessage());              die($restriction->getMessage());
# Line 1271  class instruction extends instruction_ge Line 2254  class instruction extends instruction_ge
2254          return $return;          return $return;
2255      }      }
2256    
2257    
2258      /**      /**
2259       * Calcul des règle d'action.       * Calcul des règle d'action selon leur type.
2260       * @param string $rule      Règle d'action       *
2261       * @param string $rule_name Nom de la règle       * Types de règle :
2262       * @param string $type      Type de la règle       * - date
2263         * - numeric
2264         * - text
2265         * - bool
2266         * - specific
2267         * - technical_data
2268         *
2269         * @param string $rule      Règle d'action.
2270         * @param string $rule_name Nom de la règle.
2271         * @param string $type      Type de la règle.
2272       *       *
2273       * @return mixed            Résultat de la règle       * @return mixed            Résultat de la règle
2274       */       */
2275      function regle($rule, $rule_name, $type = null) {      public function regle($rule, $rule_name, $type = null) {
2276    
2277          // Supprime tous les espaces de la chaîne de caractère          // Supprime tous les espaces de la chaîne de caractère
2278          $rule = str_replace(' ', '', $rule);          $rule = str_replace(' ', '', $rule);
# Line 1293  class instruction extends instruction_ge Line 2286  class instruction extends instruction_ge
2286              return null;              return null;
2287          }          }
2288    
         // Si c'est une règle spécifique  
         if ($rule_name == "regle_autorite_competente"  
             || $rule_name == "regle_etat"  
             || $rule_name == "regle_accord_tacite"  
             || $rule_name == "regle_avis") {  
             //  
             return $this->valF[$rule];  
         }  
   
2289          // Tableau des champs de type date          // Tableau des champs de type date
2290          $rule_type_date = array(          $rule_type_date = array(
2291              "regle_date_limite",              "regle_date_limite",
# Line 1315  class instruction extends instruction_ge Line 2299  class instruction extends instruction_ge
2299              "regle_date_rejet",              "regle_date_rejet",
2300              "regle_date_dernier_depot",              "regle_date_dernier_depot",
2301              "regle_date_limite_incompletude",              "regle_date_limite_incompletude",
2302                "regle_date_cloture_instruction",
2303                "regle_date_premiere_visite",
2304                "regle_date_derniere_visite",
2305                "regle_date_contradictoire",
2306                "regle_date_retour_contradictoire",
2307                "regle_date_ait",
2308                "regle_date_transmission_parquet",
2309                "regle_date_affichage",
2310          );          );
2311          // Tableau des champs de type numérique          // Tableau des champs de type numérique
2312          $rule_type_numeric = array(          $rule_type_numeric = array(
2313              "regle_delai",              "regle_delai",
2314              "regle_delai_incompletude",              "regle_delai_incompletude",
2315          );          );
2316            // Tableau des champs de type text
2317            $rule_type_text = array(
2318            );
2319            // Tableau des champs de type booléen
2320            $rule_type_bool = array(
2321                "regle_a_qualifier",
2322                "regle_incompletude",
2323                "regle_incomplet_notifie",
2324                "regle_evenement_suivant_tacite_incompletude",
2325            );
2326            // Tableau des champs spécifiques
2327            $rule_type_specific = array(
2328                "regle_autorite_competente",
2329                "regle_etat",
2330                "regle_accord_tacite",
2331                "regle_avis",
2332                "regle_pec_metier",
2333                "regle_etat_pendant_incompletude",
2334            );
2335            // Tableau des champs de données techniques
2336            $rule_type_technical_data = array(
2337                'regle_donnees_techniques1',
2338                'regle_donnees_techniques2',
2339                'regle_donnees_techniques3',
2340                'regle_donnees_techniques4',
2341                'regle_donnees_techniques5',
2342            );
2343            // Tableau des champs simple
2344            $rule_type_simple = array(
2345                "regle_dossier_instruction_type",
2346            );
2347    
2348          // Définit le type du champ          // Définit le type du champ
2349          if (in_array($rule_name, $rule_type_date) == true) {          if (in_array($rule_name, $rule_type_date) == true) {
# Line 1329  class instruction extends instruction_ge Line 2352  class instruction extends instruction_ge
2352          if (in_array($rule_name, $rule_type_numeric) == true) {          if (in_array($rule_name, $rule_type_numeric) == true) {
2353              $type = "numeric";              $type = "numeric";
2354          }          }
2355            if (in_array($rule_name, $rule_type_text) === true) {
2356                $type = "text";
2357            }
2358            if (in_array($rule_name, $rule_type_bool) === true) {
2359                $type = "bool";
2360            }
2361            if (in_array($rule_name, $rule_type_specific) === true) {
2362                $type = "specific";
2363            }
2364            if (in_array($rule_name, $rule_type_technical_data) === true) {
2365                $type = 'text';
2366            }
2367            if (in_array($rule_name, $rule_type_simple) === true) {
2368                $type = 'simple';
2369            }
2370    
2371            // Si c'est un type spécifique ou booléen alors il n'a qu'un opérande
2372            // Récupère directement la valeur de l'opérande
2373            if ($type === 'specific') {
2374                //
2375                return $this->get_value_for_rule($rule);
2376            }
2377    
2378          // Initialisation des variables          // Initialisation des variables
2379          $key_date = 0;          $key_date = 0;
2380          $total_numeric = 0;          $total_numeric = 0;
2381            $res_text = '';
2382    
2383          // Pour chaque opérande          // Pour chaque opérande
2384          foreach ($operands as $key => $operand) {          foreach ($operands as $key => $operand) {
# Line 1340  class instruction extends instruction_ge Line 2386  class instruction extends instruction_ge
2386              // Si c'est une règle de type date              // Si c'est une règle de type date
2387              if ($type == 'date') {              if ($type == 'date') {
2388                  // Vérifie si au moins une des opérandes est une date                  // Vérifie si au moins une des opérandes est une date
2389                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2390                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2391                      && $this->f->check_date($this->valF[$operand]) == true) {                      && $this->f->check_date($this->get_value_for_rule($operand)) == true) {
2392                      // Récupère la position de la date                      // Récupère la position de la date
2393                      $key_date = $key;                      $key_date = $key;
2394                  }                  }
# Line 1351  class instruction extends instruction_ge Line 2397  class instruction extends instruction_ge
2397                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2398                      $total_numeric += $operand;                      $total_numeric += $operand;
2399                  }                  }
2400                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2401                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2402                      && is_numeric($this->valF[$operand]) == true) {                      && is_numeric($this->get_value_for_rule($operand)) == true) {
2403                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2404                      $total_numeric += $this->valF[$operand];                      $total_numeric += $this->get_value_for_rule($operand);
2405                  }                  }
2406              }              }
2407    
# Line 1366  class instruction extends instruction_ge Line 2412  class instruction extends instruction_ge
2412                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2413                      $total_numeric += $operand;                      $total_numeric += $operand;
2414                  }                  }
2415                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2416                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2417                      && is_numeric($this->valF[$operand]) == true) {                      && is_numeric($this->get_value_for_rule($operand)) == true) {
2418                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2419                      $total_numeric += $this->valF[$operand];                      $total_numeric += $this->get_value_for_rule($operand);
2420                  }                  }
2421              }              }
2422    
2423                // Si c'est une règle de type text
2424                if ($type === 'text') {
2425                    // Concatène toutes les chaînes de caractère
2426                    $res_text .= $this->get_value_for_rule($operand);
2427                }
2428          }          }
2429    
2430          // Résultat pour une règle de type date          // Résultat pour une règle de type date
# Line 1387  class instruction extends instruction_ge Line 2439  class instruction extends instruction_ge
2439              // Retourne le calcul              // Retourne le calcul
2440              return $total_numeric;              return $total_numeric;
2441          }          }
2442    
2443            // Résultat pour une règle de type text
2444            if ($type === 'text') {
2445                // Retourne la chaîne de caractère
2446                return $res_text;
2447            }
2448            if ($type === 'simple' || $type === 'bool') {
2449                // Retourne la valeur du champs rule
2450                return $rule;
2451            }
2452        }
2453    
2454    
2455        /**
2456         * Récupère la valeur du champs dans l'instruction ou dans les données
2457         * techniques.
2458         * Spécifique au calcul des règles.
2459         *
2460         * @param string $field Champ
2461         *
2462         * @return mixed Valeur du champ
2463         */
2464        private function get_value_for_rule($field) {
2465            // Si le champ n'existe pas dans la table instruction
2466            if (array_key_exists($field, $this->valF) === false) {
2467                // Récupère l'instance de la classe donnees_techniques
2468                $inst_donnees_techniques = $this->get_inst_donnees_techniques();
2469                // Retourne la valeur de la donnée technique
2470                return $inst_donnees_techniques->getVal($field);
2471            }
2472    
2473            //
2474            return $this->valF[$field];
2475        }
2476    
2477    
2478        /**
2479         * [get_inst_donnees_techniques description]
2480         *
2481         * @param [type] $donnees_techniques [description]
2482         *
2483         * @return [type] [description]
2484         */
2485        function get_inst_donnees_techniques($donnees_techniques = null) {
2486            //
2487            if (isset($this->inst_donnees_techniques) === false or
2488                $this->inst_donnees_techniques === null) {
2489                //
2490                if (is_null($donnees_techniques)) {
2491                    $donnees_techniques = $this->getDonneesTechniques();
2492                }
2493                //
2494                $this->inst_donnees_techniques = $this->f->get_inst__om_dbform(array(
2495                    "obj" => "donnees_techniques",
2496                    "idx" => $donnees_techniques,
2497                ));
2498            }
2499            //
2500            return $this->inst_donnees_techniques;
2501        }
2502    
2503    
2504        /**
2505         * Retourne l'identifiant des données techniques liées du dossier
2506         * @return string L'identifiant des données techniques liées du dossier
2507         */
2508        function getDonneesTechniques() {
2509                    
2510            $donnees_techniques = '';
2511    
2512            $sql = "SELECT donnees_techniques
2513                FROM ".DB_PREFIXE."donnees_techniques
2514                WHERE dossier_instruction ='".$this->valF["dossier"]."'";
2515            $donnees_techniques = $this->f->db->getOne($sql);
2516            $this->f->addToLog("getStatut() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
2517            if ( database::isError($donnees_techniques)){
2518                die();
2519            }
2520    
2521            return $donnees_techniques;
2522      }      }
2523    
2524      /**      /**
# Line 1400  class instruction extends instruction_ge Line 2531  class instruction extends instruction_ge
2531       *       *
2532       * @return boolean       * @return boolean
2533       */       */
2534      function triggerajouterapres($id, &$db, $val, $DEBUG) {      function triggerajouterapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
2535            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
2536    
2537          // On a besoin de l'instance du dossier lié à l'événement d'instruction          // On a besoin de l'instance du dossier lié à l'événement d'instruction
2538          $inst_di = $this->get_inst_dossier($this->valF['dossier']);          $inst_di = $this->get_inst_dossier($this->valF['dossier']);
   
2539          // Instance de la classe evenement          // Instance de la classe evenement
2540          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);
2541            // Instance de l'état courant du dossier d'instruction
2542            $inst_current_etat = $this->f->get_inst__om_dbform(array(
2543                "obj" => "etat",
2544                "idx" => $inst_di->get_id_etat(),
2545            ));
2546    
2547          /**          /**
2548           * Mise à jour des valeurs du dossier en fonction des valeurs calculées           * Mise à jour des valeurs du dossier en fonction des valeurs calculées
# Line 1414  class instruction extends instruction_ge Line 2550  class instruction extends instruction_ge
2550           */           */
2551          // état de complétude actuel du dossier          // état de complétude actuel du dossier
2552          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);
2553            // L'événement suivant tacite paramétré est destiné à la gestion de l'incomplétude
2554            $ev_suiv_tacite_incompletude = false;
2555          // Initialisation          // Initialisation
2556          $valF = "";          $valF = array();
2557            $valF_dt = array();
2558          //          //
         if($incompletude === FALSE) {  
             // Si l'événement d'instruction est de type incompletude  
             if($inst_evenement->getVal('type') == "incompletude") {  
                 // On marque le dossier en incomplétude pour application des actions  
                 $incompletude = TRUE;  
                 // Set du flag incomplétude de la table dossier  
                 $valF['incompletude'] = TRUE;  
                 // Enregistrement de l'état dans la variable provisoire  
                 $valF['etat_pendant_incompletude'] = $this->valF['archive_etat'];  
             }  
         } else {  
             // Si l'evenement d'instruction est de type retour ou contient une  
             // decision, on sort d'incomplétude  
             if($inst_evenement->getVal('type') == "retour" OR  
                $inst_evenement->getVal('avis_decision') != NULL) {  
                 // On enlève la marque d'incomplétude pour application des actions  
                 $incompletude = FALSE;  
                 // On enlève le flag d'incomplétude sur l'enregistrement de la table dossier  
                 $valF['incompletude'] = FALSE;  
                 $valF['incomplet_notifie'] = FALSE;  
                  // Restauration de l'état depuis l'état provisoire  
                 $valF['etat'] = $this->valF['archive_etat_pendant_incompletude'];  
                 // On vide la variable provisoire ainsi que le délai de complétude  
                 // et la date limite de complétude  
                 $valF['etat_pendant_incompletude'] = NULL;  
                 $valF['delai_incompletude'] = NULL;  
                 $valF['date_limite_incompletude'] = NULL;  
                 $valF['evenement_suivant_tacite_incompletude'] = NULL;  
             }  
         }  
2559          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
2560          $sql = "SELECT * FROM ".DB_PREFIXE."action          $sql = "SELECT * FROM ".DB_PREFIXE."action
2561          WHERE action='".$this->valF['action']."'";          WHERE action='".$this->valF['action']."'";
2562          $res = $db->query($sql);          $res = $this->f->db->query($sql);
2563          $this->addToLog("triggerajouterapres(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
2564          if (database::isError($res)) {          if (database::isError($res)) {
2565              die($res->getMessage());              die($res->getMessage());
2566          }          }
2567          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
2568    
2569              // pour chacune des regles, on applique la regle              // pour chacune des regles, on applique la regle
2570              if($row['regle_delai']!=''){              if ($row['regle_delai'] != '') {
2571                  $valF['delai'] = $this->regle($row['regle_delai'], 'regle_delai');                  $valF['delai'] = $this->regle($row['regle_delai'], 'regle_delai');
2572              }              }
2573              if($row['regle_accord_tacite']!=''){              if ($row['regle_accord_tacite'] != '') {
2574                  $valF['accord_tacite'] = $this->regle($row['regle_accord_tacite'], 'regle_accord_tacite');                  $valF['accord_tacite'] = $this->regle($row['regle_accord_tacite'], 'regle_accord_tacite');
2575              }              }
2576              if($row['regle_avis']!=''){              if ($row['regle_avis'] != '') {
2577                  $valF['avis_decision'] = $this->regle($row['regle_avis'], 'regle_avis');                  $valF['avis_decision'] = $this->regle($row['regle_avis'], 'regle_avis');
2578              }              }
2579              if($row['regle_date_limite']!=''){              if ($row['regle_date_limite'] != '') {
2580                  $valF['date_limite']= $this->regle($row['regle_date_limite'], 'regle_date_limite');                  $valF['date_limite'] = $this->regle($row['regle_date_limite'], 'regle_date_limite');
2581              }              }
2582              if($row['regle_date_complet']!=''){              if ($row['regle_date_complet'] != '') {
2583                  $valF['date_complet']= $this->regle($row['regle_date_complet'], 'regle_date_complet');                  $valF['date_complet'] = $this->regle($row['regle_date_complet'], 'regle_date_complet');
2584              }              }
2585              if($row['regle_date_dernier_depot']!=''){              if ($row['regle_date_dernier_depot'] != '') {
2586                  $valF['date_dernier_depot']= $this->regle($row['regle_date_dernier_depot'], 'regle_date_dernier_depot');                  $valF['date_dernier_depot'] = $this->regle($row['regle_date_dernier_depot'], 'regle_date_dernier_depot');
2587              }              }
2588              if($row['regle_date_notification_delai']!=''){              if ($row['regle_date_notification_delai'] != '') {
2589                  $valF['date_notification_delai']= $this->regle($row['regle_date_notification_delai'], 'regle_date_notification_delai');                  $valF['date_notification_delai'] = $this->regle($row['regle_date_notification_delai'], 'regle_date_notification_delai');
2590              }              }
2591              if($row['regle_date_decision']!=''){              if ($row['regle_date_decision'] != '') {
2592                  $valF['date_decision']= $this->regle($row['regle_date_decision'], 'regle_date_decision');                  $valF['date_decision'] = $this->regle($row['regle_date_decision'], 'regle_date_decision');
2593              }              }
2594              if($row['regle_date_rejet']!=''){              if ($row['regle_date_rejet'] != '') {
2595                  $valF['date_rejet']= $this->regle($row['regle_date_rejet'], 'regle_date_rejet');                  $valF['date_rejet'] = $this->regle($row['regle_date_rejet'], 'regle_date_rejet');
2596              }              }
2597              if($row['regle_date_validite']!=''){              if ($row['regle_date_validite'] != '') {
2598                  $valF['date_validite']= $this->regle($row['regle_date_validite'], 'regle_date_validite');                  $valF['date_validite'] = $this->regle($row['regle_date_validite'], 'regle_date_validite');
2599              }              }
2600              if($row['regle_date_chantier']!=''){              if ($row['regle_date_chantier'] != '') {
2601                  $valF['date_chantier']= $this->regle($row['regle_date_chantier'], 'regle_date_chantier');                  $valF['date_chantier'] = $this->regle($row['regle_date_chantier'], 'regle_date_chantier');
2602              }              }
2603              if($row['regle_date_achevement']!=''){              if ($row['regle_date_achevement'] != '') {
2604                  $valF['date_achevement']= $this->regle($row['regle_date_achevement'], 'regle_date_achevement');                  $valF['date_achevement'] = $this->regle($row['regle_date_achevement'], 'regle_date_achevement');
2605              }              }
2606              if($row['regle_date_conformite']!=''){              if ($row['regle_date_conformite'] != '') {
2607                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');                  $valF['date_conformite'] = $this->regle($row['regle_date_conformite'], 'regle_date_conformite');
2608              }              }
2609              if($row['regle_date_limite_incompletude']!=''){              if ($row['regle_date_limite_incompletude'] != '') {
2610                  $valF['date_limite_incompletude']= $this->regle($row['regle_date_limite_incompletude'], 'regle_date_limite_incompletude');                  $valF['date_limite_incompletude'] = $this->regle($row['regle_date_limite_incompletude'], 'regle_date_limite_incompletude');
2611              }              }
2612              if($row['regle_delai_incompletude']!=''){              if ($row['regle_delai_incompletude'] != '') {
2613                  $valF['delai_incompletude']= $this->regle($row['regle_delai_incompletude'], 'regle_delai_incompletude');                  $valF['delai_incompletude'] = $this->regle($row['regle_delai_incompletude'], 'regle_delai_incompletude');
2614              }              }
2615              if($row['regle_autorite_competente']!=''){              if ($row['regle_autorite_competente'] != '') {
2616                  $valF['autorite_competente']= $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');                  $valF['autorite_competente'] = $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');
2617              }              }
2618              if($row['regle_etat']!=''){              if ($row['regle_etat'] != '') {
2619                  // Si on est dans le cas général ou qu'on est en incomplétude et                  $valF['etat'] = $this->regle($row['regle_etat'], 'regle_etat');
2620                  // qu'on a un événement de type incomplétude alors : on stocke              }
2621                  // l'état dans la variable courante              if ($row['regle_date_cloture_instruction'] !== '') {
2622                  if ($incompletude == FALSE OR $inst_evenement->getVal('type') == "incompletude") {                  $valF['date_cloture_instruction'] = $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
2623                      $valF['etat'] = $this->regle($row['regle_etat'], 'regle_etat');              }
2624                  } else {              if ($row['regle_date_premiere_visite'] !== '') {
2625                      $valF['etat_pendant_incompletude'] = $this->regle($row['regle_etat'], 'regle_etat');                  $valF['date_premiere_visite'] = $this->regle($row['regle_date_premiere_visite'], 'regle_date_premiere_visite');
2626                }
2627                if ($row['regle_date_derniere_visite'] !== '') {
2628                    $valF['date_derniere_visite'] = $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');
2629                }
2630                if ($row['regle_date_contradictoire'] !== '') {
2631                    $valF['date_contradictoire'] = $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');
2632                }
2633                if ($row['regle_date_retour_contradictoire'] !== '') {
2634                    $valF['date_retour_contradictoire'] = $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');
2635                }
2636                if ($row['regle_date_ait'] !== '') {
2637                    $valF['date_ait'] = $this->regle($row['regle_date_ait'], 'regle_date_ait');
2638                }
2639                if ($row['regle_donnees_techniques1'] !== '') {
2640                    $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');
2641                }
2642                if ($row['regle_donnees_techniques2'] !== '') {
2643                    $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');
2644                }
2645                if ($row['regle_donnees_techniques3'] !== '') {
2646                    $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');
2647                }
2648                if ($row['regle_donnees_techniques4'] !== '') {
2649                    $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');
2650                }
2651                if ($row['regle_donnees_techniques5'] !== '') {
2652                    $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');
2653                }
2654                if ($row['regle_date_transmission_parquet'] !== '') {
2655                    $valF['date_transmission_parquet'] = $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');
2656                }
2657                if ($row['regle_dossier_instruction_type'] !== '') {
2658                    $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');
2659                }
2660                // La date d'affichage est modifiée seulement si le champ n'est pas
2661                // renseigné
2662                if ($row['regle_date_affichage'] !== ''
2663                    && ($inst_di->getVal('date_affichage') === ''
2664                        || $inst_di->getVal('date_affichage') === null)) {
2665                    //
2666                    $valF['date_affichage'] = $this->regle($row['regle_date_affichage'], 'regle_date_affichage');
2667                }
2668                //
2669                if ($row['regle_pec_metier'] != '') {
2670                    $valF['pec_metier'] = $this->regle($row['regle_pec_metier'], 'regle_pec_metier');
2671                }
2672                if ($row['regle_a_qualifier'] != '') {
2673                    $valF['a_qualifier'] = $this->regle($row['regle_a_qualifier'], 'regle_a_qualifier');
2674                }
2675                //
2676                if ($row['regle_incompletude'] != '') {
2677                    $valF['incompletude'] = $this->regle($row['regle_incompletude'], 'regle_incompletude');
2678                }
2679                if ($row['regle_incomplet_notifie'] != '') {
2680                    $valF['incomplet_notifie'] = $this->regle($row['regle_incomplet_notifie'], 'regle_incomplet_notifie');
2681                }
2682                if ($row['regle_etat_pendant_incompletude'] != '') {
2683                    $valF['etat_pendant_incompletude'] = $this->regle($row['regle_etat_pendant_incompletude'], 'regle_etat_pendant_incompletude');
2684                }
2685                if ($row['regle_evenement_suivant_tacite_incompletude'] != '') {
2686                    $resti = $this->regle($row['regle_evenement_suivant_tacite_incompletude'], 'regle_evenement_suivant_tacite_incompletude');
2687                    if (strtolower($resti) === 't' || strtolower($resti) === 'true') {
2688                        $ev_suiv_tacite_incompletude = true;
2689                  }                  }
2690              }              }
2691          }          }
2692    
2693          // Si l'événement a un événement suivant tacite          // Si l'événement a un événement suivant tacite
2694          if($inst_evenement->getVal('evenement_suivant_tacite') != '') {          if($inst_evenement->getVal('evenement_suivant_tacite') != '') {
2695              // Si le DI n'est pas en incomplétude, l'événement tacite est stocké              // En fonction de l'action de l'événement, l'événement suivant tacite ne sera
2696              // dans le champ evenement_suivant_tacite du dossier              // pas associé de le même façon au dossier d'instruction
2697              if ($incompletude == false OR $inst_evenement->getVal('type') != "incompletude") {              if ($ev_suiv_tacite_incompletude === false) {
                 //  
2698                  $valF['evenement_suivant_tacite'] = $inst_evenement->getVal('evenement_suivant_tacite');                  $valF['evenement_suivant_tacite'] = $inst_evenement->getVal('evenement_suivant_tacite');
2699              } else {              }
2700                  // Sinon l'événement tacite est stocké dans le champ              if ($ev_suiv_tacite_incompletude === true) {
                 // evenement_suivant_tacite_incompletude du dossier  
2701                  $valF['evenement_suivant_tacite_incompletude'] = $inst_evenement->getVal('evenement_suivant_tacite');                  $valF['evenement_suivant_tacite_incompletude'] = $inst_evenement->getVal('evenement_suivant_tacite');
2702              }              }
2703          }          }
2704            // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement
2705          // Si des valeurs ont été calculées alors on met à jour l'enregistrement          if (count($valF_dt) > 0) {
2706          if ($valF != "") {              $dt_id = $this->getDonneesTechniques();
2707              // On met à jour le dossier              // On met à jour le dossier
2708              $cle = " dossier='".$this->valF['dossier']."'";              $cle = " donnees_techniques='".$dt_id."'";
2709              $res1 = $db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);
2710              $this->addToLog("triggerajouterapres(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);
2711              if (database::isError($res1)) {              if (database::isError($res1)) {
2712                  die($res->getMessage());                  die($res->getMessage());
2713              }              }
2714              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
2715              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
2716            }
2717            // Si des valeurs ont été calculées alors on met à jour l'enregistrement
2718            if (count($valF) > 0) {
2719                //
2720                $inst_dossier = $this->f->get_inst__om_dbform(array(
2721                    "obj" => "dossier",
2722                    "idx" => $this->valF['dossier'],
2723                ));
2724                $valF['instruction'] = $id;
2725                $valF['crud'] = 'create';
2726                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
2727                if ($update_by_instruction === false) {
2728                    $this->cleanMessage();
2729                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
2730                    return false;
2731                }
2732                // Affichage d'informations à l'utilisateur
2733                $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
2734          }          }
2735    
2736          /**          /**
# Line 1578  class instruction extends instruction_ge Line 2766  class instruction extends instruction_ge
2766              $this->addToMessage(_("Notification (105) du référentiel ERP OK."));              $this->addToMessage(_("Notification (105) du référentiel ERP OK."));
2767          }          }
2768    
2769            // Si le mode en rédaction intégrale est activé
2770            if (isset($this->valF['flag_edition_integrale']) === true
2771                && $this->valF['flag_edition_integrale'] === true) {
2772                $redactionIntegraleValF = array();
2773    
2774                // Récupère la collectivite du dossier d'instruction
2775                $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
2776                $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
2777                // Récupère le corps de la lettre type
2778                $params = array(
2779                    "specific" => array(
2780                        "corps" => array(
2781                            "mode" => "get",
2782                        )
2783                    ),
2784                );
2785                $result = $this->compute_pdf_output('lettretype', $this->valF['lettretype'], $collectivite, $id, $params);
2786                $redactionIntegraleValF['corps_om_htmletatex'] = $result['pdf_output'];
2787                // Récupère le titre de la lettre type
2788                $params = array(
2789                    "specific" => array(
2790                        "titre" => array(
2791                            "mode" => "get",
2792                        )
2793                    ),
2794                );
2795                $result = $this->compute_pdf_output('lettretype', $this->valF['lettretype'], $collectivite, $id, $params);
2796                $redactionIntegraleValF['titre_om_htmletat'] = $result['pdf_output'];
2797    
2798                // mise à jour en base de données
2799                $res = $this->f->db->autoExecute(
2800                    DB_PREFIXE.$this->table,
2801                    $redactionIntegraleValF,
2802                    DB_AUTOQUERY_UPDATE,
2803                    $this->clePrimaire."=".$id
2804                );
2805                $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($redactionIntegraleValF, true).", DB_AUTOQUERY_UPDATE, \"".$this->clePrimaire."=".$id."\");", VERBOSE_MODE);
2806                if ($this->f->isDatabaseError($res, true) === true) {
2807                    return false;
2808                }
2809            }
2810    
2811            /**
2812             * Finalisation automatique de l'instruction si le paramétrage de l'événement l'autorise
2813             */
2814            // Si la finalisation automatique de l'événement est activée
2815            // ET si l'instruction n'a pas déjà été finalisée
2816            // ET s'il existe une lettre type associée
2817            if ($inst_evenement->getVal('finaliser_automatiquement') === 't'
2818                && $inst_evenement->getVal('om_final_instruction') !== 't'
2819                && $inst_evenement->getVal('lettretype') !== ''
2820                && $inst_evenement->getVal('lettretype') !== null) {
2821    
2822                 // On instancie l'instruction
2823                $inst_instruction = $this->f->get_inst__om_dbform(array(
2824                    "obj" => "instruction",
2825                    "idx" => $this->valF[$this->clePrimaire],
2826                ));
2827    
2828                // On finalise l'instruction dans le contexte de finalisation : action 100
2829                $inst_instruction->setParameter('maj', 100);
2830                $finalize = $inst_instruction->finalize($inst_instruction->valF);
2831    
2832                // Une erreur de finalisation renvoie 'false' : ajout dans les logs
2833                // et dans le message d'erreur
2834                if ($finalize === false) {
2835                    $this->f->addToLog(__METHOD__."() : ERROR - Impossible de finaliser l'instruction.", DEBUG_MODE);
2836                    $this->addToMessage(_("Erreur lors de la finalisation de l'instruction. Contactez votre administrateur."));
2837                    return false;
2838                }
2839            }
2840    
2841            /**
2842             * Finalisation automatique des instructions tacites ou retours.
2843             */
2844            // Si l'option de finalisation automatique des instructions tacites ou
2845            // retours est activée et l'événement d'instruction a une lettre type
2846            // associée
2847            $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
2848            if ($this->f->is_option_finalisation_auto_enabled($collectivite_di) === true
2849                && $inst_evenement->getVal('lettretype') !== ''
2850                && $inst_evenement->getVal('lettretype') !== null) {
2851    
2852                // Rècupère l'identifiant de l'événement
2853                $evenement_id = $inst_evenement->getVal($inst_evenement->clePrimaire);
2854    
2855                // Si l'événement d'instruction est identifié comme un événement
2856                // retour
2857                // OU l'événement d'instruction est l'événement suivant tacite du
2858                // dossier d'instruction (incomplétude prise en compte)
2859                // ET l'événement d'instruction n'a pas déjà été finalisé
2860                if (($inst_evenement->getVal("retour") === 't'
2861                    || ($inst_di->getVal('evenement_suivant_tacite_incompletude') === $evenement_id
2862                        || $inst_di->getVal('evenement_suivant_tacite') === $evenement_id))
2863                        && ($inst_evenement->getVal('om_final_instruction') !== 't')) {
2864    
2865                    // Finalise l'instruction
2866                    $inst_instruction = $this->f->get_inst__om_dbform(array(
2867                        "obj" => "instruction",
2868                        "idx" => $this->valF[$this->clePrimaire],
2869                    ));
2870                    $inst_instruction->setParameter('maj', 100);
2871                    $finalize = $inst_instruction->finalize($inst_instruction->valF);
2872                    if ($finalize === false) {
2873                        //
2874                        return false;
2875                    }
2876                }
2877            }
2878    
2879            /**
2880             * Mise à jour de la version de clôture *version_clos* du dossier si et
2881             * seulement si l'instruction met à jour l'état du dossier.
2882             */
2883            if (isset($valF['etat']) === true
2884                && $valF['etat'] !== null
2885                && $valF['etat'] !== '') {
2886                // Instanciation de l'état appliqué sur le dossier par l'instruction
2887                $inst_etat = $this->f->get_inst__om_dbform(array(
2888                    "obj" => "etat",
2889                    "idx" => $valF['etat'],
2890                ));
2891                //
2892                $update_version_clos = null;
2893                // En cas d'instruction qui clôture le dossier
2894                if ($inst_etat->getVal('statut') === 'cloture') {
2895                    $update_version_clos = $inst_di->update_version_clos('up');
2896                }
2897                // En cas d'instruction qui rouvre le dossier
2898                if ($inst_current_etat->getVal('statut') === 'cloture'
2899                    && $inst_etat->getVal('statut') !== 'cloture') {
2900                    //
2901                    $update_version_clos = $inst_di->update_version_clos('down');
2902                    //
2903                    $params = array(
2904                        'di_reopened' => true,
2905                    );
2906                }
2907                //
2908                if ($update_version_clos === false) {
2909                    $this->f->addToLog(sprintf(
2910                        "%s() : ERREUR - %s %s",
2911                        __METHOD__,
2912                        sprintf(
2913                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
2914                            $inst_di->getVal($inst_di->clePrimaire)
2915                        ),
2916                        sprintf(
2917                            __("L'instruction tente d'appliquer l'état %s."),
2918                            $inst_etat->getVal($inst_etat->clePrimaire)
2919                        )
2920                    ));
2921                    $this->addToMessage(sprintf(
2922                        "%s %s",
2923                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
2924                        __("Veuillez contacter votre administrateur.")
2925                    ));
2926                    return false;
2927                }
2928            }
2929    
2930            /**
2931             * Notification automatique
2932             */
2933            // Notification automatique à l'ajout de l'instruction si la notification
2934            // automatique est choisie et qu'il n'y a pas de lettretype associée à l'événement
2935            if ($inst_evenement->getVal('notification') === 'notification_automatique' &&
2936                ($inst_evenement->getVal('lettretype') === null ||
2937                $inst_evenement->getVal('lettretype') === '')) {
2938                // Récupération de la liste des demandeurs à notifier et de la catégorie
2939                $categorie = $this->f->get_param_option_notification($collectivite_di);
2940                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
2941                $demandeursANotifie = $this->get_demandeurs_notifiable(
2942                    $this->valF['dossier'],
2943                    $isPortal
2944                );
2945    
2946                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
2947                foreach ($demandeursANotifie as $demandeur) {
2948                    // Ajout de la notif et récupération de son id
2949                    $idNotif = $this->ajouter_notification(
2950                        $this->valF[$this->clePrimaire],
2951                        $this->f->get_connected_user_login_name(),
2952                        $demandeur,
2953                        $collectivite_di,
2954                        true
2955                    );
2956                    if ($idNotif === false) {
2957                        return false;
2958                    }
2959                    // Création de la tache en lui donnant l'id de la notification
2960                    $notification_by_task = $this->notification_by_task(
2961                        $idNotif,
2962                        $this->valF['dossier'],
2963                        $categorie
2964                    );
2965                    if ($notification_by_task === false) {
2966                        $this->addToMessage(
2967                            __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
2968                        );
2969                        return false;
2970                    }
2971                }
2972                $this->addToMessage($message = sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
2973            }
2974    
2975            /**
2976             * Mise à jour de la date de dernière modification du dossier
2977             */
2978            $inst_di->update_last_modification_date();
2979    
2980          /**          /**
2981           * Mise à jour des données du DA.           * Mise à jour des données du DA.
2982           */           */
         //  
2983          $inst_da = $inst_di->get_inst_dossier_autorisation();          $inst_da = $inst_di->get_inst_dossier_autorisation();
2984          //          $params['di_id'] = $this->valF['dossier'];
2985          if ($inst_da->majDossierAutorisation() === false) {          if ($inst_da->majDossierAutorisation($params) === false) {
2986              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));
2987              $this->correct = false;              $this->correct = false;
2988              return false;              return false;
# Line 1597  class instruction extends instruction_ge Line 2995  class instruction extends instruction_ge
2995          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));
2996      }      }
2997    
2998      function triggermodifierapres($id,&$db,$val,$DEBUG) {      public function is_notifiable_by_task_manual() {
2999            $ev = $this->get_inst_evenement($this->getVal('evenement'));
3000    
3001            // Si l'instruction a une édition non finalisé quel que soit
3002            // le type de notification, il n'est pas notifiable
3003            if ($this->has_an_edition() === true) {
3004                if ($this->is_unfinalizable_without_bypass() === false) {
3005                    return false;
3006                }
3007            }
3008    
3009            // Gestion des différents cas selon la valeur du champs notification
3010            switch ($ev->getVal('notification')) {
3011                case 'notification_manuelle':
3012                    return true;
3013                case 'notification_manuelle_annexe':
3014                    return true;
3015                case 'notification_automatique':
3016                    return false;
3017                case 'notification_auto_signature_requise':
3018                    return false;
3019                case 'notification_manuelle_signature_requise':
3020                    // Si il y a une date de retour de signature la notification est possible
3021                    if ($this->getVal('date_retour_signature') === null
3022                        || $this->getVal('date_retour_signature') === '') {
3023                        return false;
3024                    }
3025                    return true;
3026                case 'notification_manuelle_annexe_signature_requise':
3027                    // Si il y a une date de retour de signature la notification est possible
3028                    if ($this->getVal('date_retour_signature') === null
3029                        || $this->getVal('date_retour_signature') === '') {
3030                        return false;
3031                    }
3032                    return true;
3033                default:
3034                    return false;
3035            }
3036        }
3037    
3038        /**
3039         * Crée une instance et une tache de notification pour le demandeur
3040         * principal.
3041         *
3042         * @return boolean true si le traitement à réussi
3043         */
3044        protected function notifier_demandeur_principal() {
3045            $this->begin_treatment(__METHOD__);
3046            $message = '';
3047            // Récupération des informations concernant le demandeur
3048            $dossier = $this->getVal('dossier');
3049            $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
3050            $demandeur = $this->get_demandeurs_notifiable(
3051                $dossier,
3052                true
3053            );
3054            if ($demandeur !== array()) {
3055                $destinataire = array_values($demandeur);
3056                // Ajout de la notif et récupération de son id
3057                $idNotification = $this->ajouter_notification(
3058                    $this->getVal($this->clePrimaire),
3059                    $this->f->get_connected_user_login_name(),
3060                    $destinataire[0],
3061                    $collectivite_di,
3062                    true
3063                );
3064                if ($idNotification === false) {
3065                    return $this->end_treatment(__METHOD__, false);
3066                }
3067                // Création de la tâche en lui donnant l'id de la notification
3068                $notification_by_task = $this->notification_by_task($idNotification, $dossier);
3069                if ($notification_by_task === false) {
3070                    $this->addToMessage(
3071                        __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3072                    );
3073                    return $this->end_treatment(__METHOD__, false);
3074                }
3075                $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
3076                return $this->end_treatment(__METHOD__, true);
3077            }
3078            $this->addToMessage( __("Le demandeur principal n'est pas notifiable."));
3079            return $this->end_treatment(__METHOD__, true);
3080        }
3081    
3082        public function notification_by_task($object_id, $dossier, $category = null, $type = null) {
3083            // Par défaut le type est portal
3084            if ($category === null) {
3085                $category = 'portal';
3086            }
3087            // Si le type n'est pas correctement spécifié, alors il est calculé
3088            if ($type === null
3089                || $type !== 'notification_recepisse'
3090                || $type !== 'notification_instruction'
3091                || $type !== 'notification_decision') {
3092                //
3093                $type = 'notification_instruction';
3094                // Vérifie si l'instruction est un récépissé
3095                $trace = debug_backtrace();
3096                foreach ($trace as $key => $value) {
3097                    if (isset($trace[$key]['class']) === true
3098                        && empty($trace[$key]['class']) === false) {
3099                        //
3100                        if (strtolower($trace[$key]['class']) === 'demande') {
3101                            $type = 'notification_recepisse';
3102                        }
3103                    }
3104                }
3105                // Vérifie si l'instruction est une décision
3106                if ($type !== 'notification_recepisse') {
3107                    $avis_decision = $this->getVal('avis_decision') !== null ? $this->getVal('avis_decision') : $this->valF['avis_decision'];
3108                    if ($avis_decision !== null && $avis_decision !== '') {
3109                        $type = 'notification_decision';
3110                    }
3111                }
3112            }
3113            // Préparation de la tache de notification
3114            $inst_task = $this->f->get_inst__om_dbform(array(
3115                "obj" => "task",
3116                "idx" => 0,
3117            ));
3118            $task_val = array(
3119                'type' => $type,
3120                'object_id' => $object_id,
3121                'dossier' => $dossier,
3122                'category' => $category,
3123            );
3124    
3125            $add_task = $inst_task->add_task(array('val' => $task_val));
3126            if ($add_task === false) {
3127                return false;
3128            }
3129    
3130            return true;
3131        }
3132    
3133        /**
3134         * A partir des informations passée en argument ajoute un nouvel élément
3135         * dans la table instruction_notification.
3136         * Avant l'ajout vérifie en utilisant l'id de la collectivité passée en
3137         * paramètre si le paramétrage attendus est ok.
3138         * Ajoute également un nouvel élement dans instruction_notification_document
3139         * si l'instruction possède une lettretype.
3140         * Si un identifiant d'une instruction annexe est donnée ajoute un deuxième
3141         * élement dans la table instruction_notification_document qui correspondra
3142         * à l'annexe de la notification.
3143         *
3144         * @param integer identifiant de l'instruction notifiée
3145         * @param string information concernant l'emetteur
3146         * @param array tableau contenant 2 entrées
3147         *  - destinatire : nom, prenom ou raison sociale, dénomination et courriel
3148         *  - courriel : adresse mail de la personne à notifier
3149         * @param integer identifiant de la collectivité permettant de récupèrer les
3150         * paramètres à valider
3151         * @param boolean indique si la notification est automatique ou manuelle
3152         * @param integer identifiant d'une instruction dont l'édition sera annexé
3153         * à la notification
3154         *
3155         * @return integer|boolean identifiant de la notification créée si le traitement
3156         * a réussie, false sinon.
3157         */
3158        protected function ajouter_notification(
3159            $idInstruction,
3160            $emetteur,
3161            $destinataire,
3162            $collectiviteId,
3163            $demandeAuto = false,
3164            $idInstrDocAnnexe = null
3165        ) {
3166            // Vérification que les paramètres nécessaires à l'envoi de la notification existe avant
3167            // de créer la notification
3168            if (! $this->is_parametrage_notification_correct($collectiviteId)) {
3169                $this->addToMessage(__("Erreur de paramétrage. L'url d'accès au(x) document(s) notifié(s) n'est pas paramétrée."));
3170                return false;
3171            }
3172            // Préparation de la notification
3173            $inst_notif = $this->f->get_inst__om_dbform(array(
3174                "obj" => "instruction_notification",
3175                "idx" => "]",
3176            ));
3177            $notif_val = array(
3178                'instruction_notification' => null,
3179                'instruction' => $idInstruction,
3180                'automatique' => $demandeAuto,
3181                'emetteur' => $emetteur,
3182                'date_envoi' => null,
3183                'destinataire' => $destinataire['destinataire'],
3184                'courriel' => $destinataire['courriel'],
3185                'date_premier_acces' => null,
3186                'statut' => 'en cours d\'envoi',
3187                'commentaire' => 'Notification en cours de traitement'
3188            );
3189    
3190            // Création de la notification
3191            $add_notif = $inst_notif->ajouter($notif_val);
3192            if ($add_notif === false) {
3193                $this->addToMessage(__("Erreur lors de la génération de la notification au(x) pétitionnaire(s)."));
3194                return false;
3195            }
3196    
3197            // Si il y a une lettretype finalisé stockage de la clé d'accès au documents
3198            if ($this->evenement_has_an_edition($this->getVal('evenement')) === true) {
3199                $add_notif_doc = $this->ajouter_notification_document(
3200                    $this->getVal($this->clePrimaire),
3201                    $inst_notif->getVal($inst_notif->clePrimaire)
3202                );
3203                if ($add_notif_doc === false) {
3204                    $this->addToMessage(__("Erreur lors de la génération de la notification du document."));
3205                    return false;
3206                }
3207            }
3208            // Si une annexe a été choisie stockage de la clé d'accès à l'annexe
3209            if ($idInstrDocAnnexe != null || $idInstrDocAnnexe != '') {
3210                $add_notif_annexe = $this->ajouter_notification_document(
3211                    $idInstrDocAnnexe,
3212                    $inst_notif->getVal($inst_notif->clePrimaire),
3213                    true
3214                );
3215                if ($add_notif_annexe === false) {
3216                    $this->addToMessage(__("Erreur lors de la génération de la notification de l'annexe."));
3217                    return false;
3218                }
3219            }
3220    
3221            // Renvoie l'id de la nouvelle instance de instruction_notification
3222            return $inst_notif->getVal($inst_notif->clePrimaire);
3223        }
3224    
3225        /**
3226         * Vérifie si le paramétrage de la notification des demandeurs est correct.
3227         *
3228         * @param integer identifiant de la collectivité
3229         * @return boolean
3230         */
3231        protected function is_parametrage_notification_correct($collectiviteId) {
3232            $categorie = $this->f->get_param_option_notification($collectiviteId);
3233            $urlAccesNotif = $this->f->get_parametre_notification_url_acces($collectiviteId);
3234            if ($categorie == 'mail' && $urlAccesNotif == null) {
3235                return false;
3236            }
3237            return true;
3238        }
3239    
3240        /**
3241         * Ajoute un élément dans la table instruction_notification_document.
3242         *
3243         * @param integer $idInstruction : id de l'instruction à laquelle est rattaché le document
3244         * @param integer $idNotification : id de la notification à laquelle on associe le document
3245         * @param boolean $isAnnexe : indique si le document est une annexe ou pas
3246         *
3247         * @return boolean indique si le traitement a réussi
3248         */
3249        protected function ajouter_notification_document($idInstruction, $idNotification, $isAnnexe = false) {
3250            $inst_notif_doc = $this->f->get_inst__om_dbform(array(
3251                "obj" => "instruction_notification_document",
3252                "idx" => "]",
3253            ));
3254            $notif_doc_val = array(
3255                'instruction_notification_document' => null,
3256                'instruction_notification' => $idNotification,
3257                'instruction' => $idInstruction,
3258                'cle' => $this->getCleAccesDocument(),
3259                'annexe' => $isAnnexe
3260            );
3261    
3262            $add_notif_doc = $inst_notif_doc->ajouter($notif_doc_val);
3263            if ($add_notif_doc === false) {
3264                return false;
3265            }
3266            return true;
3267        }
3268        
3269        /**
3270         * TRIGGER - triggermodifierapres.
3271         *
3272         * @return boolean
3273         */
3274        function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
3275            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
3276            $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
3277            $message = '';
3278          /**          /**
3279           * L'objectif ici est d'effectuer les recalculs de date dans le dossier           * L'objectif ici est d'effectuer les recalculs de date dans le dossier
3280           * si la date de l'evenement est modifiee           * si la date de l'evenement est modifiee
3281           */           */
3282          // Initialisation          // Initialisation
3283          $valF = "";          $valF = array();
3284            $valF_dt = array();
3285          // Initialisation du type d'événement          // Initialisation du type d'événement
3286          $type_evmt = "";          $type_evmt = "";
3287          // Récupération de l'action correspondante à l'événement          // Récupération de l'action correspondante à l'événement
3288          $sql = "SELECT action          $sql = "SELECT action
3289          FROM ".DB_PREFIXE."evenement          FROM ".DB_PREFIXE."evenement
3290          WHERE evenement=".$this->valF['evenement'];          WHERE evenement=".$this->valF['evenement'];
3291          $action = $db->getOne($sql);          $action = $this->f->db->getOne($sql);
3292          $this->addToLog("triggermodifierapres(): db->getone(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->getone(\"".$sql."\");", VERBOSE_MODE);
3293          if (database::isError($action)) {          if (database::isError($action)) {
3294              die($action->getMessage());              die($action->getMessage());
3295          }          }
# Line 1619  class instruction extends instruction_ge Line 3297  class instruction extends instruction_ge
3297          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
3298          $sql = "SELECT * FROM ".DB_PREFIXE."action          $sql = "SELECT * FROM ".DB_PREFIXE."action
3299          WHERE action='".$action."'";          WHERE action='".$action."'";
3300          $res = $db->query($sql);          $res = $this->f->db->query($sql);
3301          $this->addToLog("triggermodifierapres(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
3302          if (database::isError($res)) {          if (database::isError($res)) {
3303              die($res->getMessage());              die($res->getMessage());
3304          }          }
# Line 1656  class instruction extends instruction_ge Line 3334  class instruction extends instruction_ge
3334              if(preg_match("/date_evenement/",$row['regle_date_conformite'])){              if(preg_match("/date_evenement/",$row['regle_date_conformite'])){
3335                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');
3336              }              }
3337                if(preg_match("/date_evenement/",$row['regle_date_cloture_instruction'])){
3338                    $valF['date_cloture_instruction']= $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
3339                }
3340                if(preg_match("/date_evenement/",$row['regle_date_premiere_visite'])){
3341                    $valF['date_premiere_visite']= $this->regle($row['regle_date_premiere_visite'], 'regle_date_premiere_visite');
3342                }
3343                if(preg_match("/date_evenement/",$row['regle_date_derniere_visite'])){
3344                    $valF['date_derniere_visite']= $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');
3345                }
3346                if(preg_match("/date_evenement/",$row['regle_date_contradictoire'])){
3347                    $valF['date_contradictoire']= $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');
3348                }
3349                if(preg_match("/date_evenement/",$row['regle_date_retour_contradictoire'])){
3350                    $valF['date_retour_contradictoire']= $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');
3351                }
3352                if(preg_match("/date_evenement/",$row['regle_date_ait'])){
3353                    $valF['date_ait']= $this->regle($row['regle_date_ait'], 'regle_date_ait');
3354                }
3355                if(preg_match("/date_evenement/",$row['regle_date_transmission_parquet'])){
3356                    $valF['date_transmission_parquet']= $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');
3357                }
3358                if ($row['regle_donnees_techniques1'] !== '') {
3359                    $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');
3360                }
3361                if ($row['regle_donnees_techniques2'] !== '') {
3362                    $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');
3363                }
3364                if ($row['regle_donnees_techniques3'] !== '') {
3365                    $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');
3366                }
3367                if ($row['regle_donnees_techniques4'] !== '') {
3368                    $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');
3369                }
3370                if ($row['regle_donnees_techniques5'] !== '') {
3371                    $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');
3372                }
3373                if ($row['regle_dossier_instruction_type'] !== '') {
3374                    $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');
3375                }
3376          }          }
3377          // Si des valeurs ont été calculées alors on met à jour l'enregistrement          // Si des valeurs de données techniques ont été calculées alors on met à jour l'enregistrement
3378          if ($valF != "") {          if (count($valF_dt) > 0) {
3379                $dt_id = $this->getDonneesTechniques();
3380              // On met à jour le dossier              // On met à jour le dossier
3381              $cle = " dossier='".$this->valF['dossier']."'";              $cle = " donnees_techniques='".$dt_id."'";
3382              $res1 = $db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);              $res1 = $this->f->db->autoExecute(DB_PREFIXE.'donnees_techniques', $valF_dt, DB_AUTOQUERY_UPDATE, $cle);
3383              $this->addToLog("triggermodifierapres(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE."donnees_techniques\", ".print_r($valF_dt, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);
3384              if (database::isError($res1)) {              if (database::isError($res1)) {
3385                  die($res->getMessage());                  die($res->getMessage());
3386              }              }
3387              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
3388              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");              $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3389            }
3390            // Si des valeurs ont été calculées alors on met à jour l'enregistrement
3391            if (count($valF) > 0) {
3392                //
3393                $inst_dossier = $this->f->get_inst__om_dbform(array(
3394                    "obj" => "dossier",
3395                    "idx" => $this->valF['dossier'],
3396                ));
3397                $valF['instruction'] = $id;
3398                $valF['crud'] = 'update';
3399                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
3400                if ($update_by_instruction === false) {
3401                    $this->cleanMessage();
3402                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
3403                    return false;
3404                }
3405                // Affichage d'informations à l'utilisateur
3406                $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3407          }          }
3408    
3409          $restriction = $this->get_restriction($val['evenement']);          $restriction = $this->get_restriction($val['evenement']);
# Line 1677  class instruction extends instruction_ge Line 3413  class instruction extends instruction_ge
3413              // Récupération de tous les paramètres de l'événement sélectionné              // Récupération de tous les paramètres de l'événement sélectionné
3414              $sql = "SELECT * FROM ".DB_PREFIXE."evenement              $sql = "SELECT * FROM ".DB_PREFIXE."evenement
3415              WHERE evenement=".$this->valF['evenement'];              WHERE evenement=".$this->valF['evenement'];
3416              $res = $db->query($sql);              $res = $this->f->db->query($sql);
3417              $this->addToLog("triggermodifierapres(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
3418              if (database::isError($res)) {              if (database::isError($res)) {
3419                  die($res->getMessage());                  die($res->getMessage());
3420              }              }
# Line 1688  class instruction extends instruction_ge Line 3424  class instruction extends instruction_ge
3424                  if ($this->getVal('date_retour_signature') == "" AND                  if ($this->getVal('date_retour_signature') == "" AND
3425                      $this->valF['date_retour_signature'] != "" AND                      $this->valF['date_retour_signature'] != "" AND
3426                      $row['evenement_retour_signature'] != "") {                      $row['evenement_retour_signature'] != "") {
3427                      $new_instruction = new instruction("]", $db, $DEBUG);                      $new_instruction = $this->f->get_inst__om_dbform(array(
3428                            "obj" => "instruction",
3429                            "idx" => "]",
3430                        ));
3431                      // Création d'un tableau avec la liste des champs de l'instruction                      // Création d'un tableau avec la liste des champs de l'instruction
3432                      foreach($new_instruction->champs as $champ) {                      foreach($new_instruction->champs as $champ) {
3433                          $valNewInstr[$champ] = "";                          $valNewInstr[$champ] = "";
# Line 1707  class instruction extends instruction_ge Line 3446  class instruction extends instruction_ge
3446                      $new_instruction->setParameter("maj", 0);                      $new_instruction->setParameter("maj", 0);
3447                      $new_instruction->class_actions[0]["identifier"] =                      $new_instruction->class_actions[0]["identifier"] =
3448                          "retour signature de l'instruction $current_id";                          "retour signature de l'instruction $current_id";
3449                      $retour = $new_instruction->ajouter($valNewInstr,$db, $DEBUG);                      $retour = $new_instruction->ajouter($valNewInstr);
3450                                            
3451                      //Si une erreur s'est produite et qu'il s'agit d'un problème                      //Si une erreur s'est produite et qu'il s'agit d'un problème
3452                      //de restriction                      //de restriction
3453                      if ($retour == false && !$new_instruction->restriction_valid){                      if ($retour == false && !$new_instruction->restriction_valid){
3454                          $error_message = $this->get_restriction_error_message($restriction);                          $error_message = $this->get_restriction_error_message($restriction);
3455                          $this->f->displayMessage("error", $error_message);                          $this->f->displayMessage("error", $error_message);
3456                          $this->addToLog("triggermodifierapres() : evenement retour ".                          $this->addToLog(__METHOD__."(): evenement retour ".
3457                              "instruction ".$this->valF[$this->clePrimaire]." : ".                              "instruction ".$this->valF[$this->clePrimaire]." : ".
3458                              $new_instruction->msg);                              $new_instruction->msg);
3459                      }                      }
# Line 1730  class instruction extends instruction_ge Line 3469  class instruction extends instruction_ge
3469                      $this->valF['date_retour_rar'] != "") {                      $this->valF['date_retour_rar'] != "") {
3470                                            
3471                      if($row['evenement_retour_ar'] != "") {                      if($row['evenement_retour_ar'] != "") {
3472                          $new_instruction = new instruction("]", $db, $DEBUG);                          $new_instruction = $this->f->get_inst__om_dbform(array(
3473                                "obj" => "instruction",
3474                                "idx" => "]",
3475                            ));
3476                          // Création d'un tableau avec la liste des champs de l'instruction                          // Création d'un tableau avec la liste des champs de l'instruction
3477                          foreach($new_instruction->champs as $champ) {                          foreach($new_instruction->champs as $champ) {
3478                              $valNewInstr[$champ] = "";                              $valNewInstr[$champ] = "";
# Line 1748  class instruction extends instruction_ge Line 3490  class instruction extends instruction_ge
3490                          $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);                          $valNewInstr["date_retour_controle_legalite"] = $this->f->formatDate($this->valF['date_retour_controle_legalite']);
3491                          $new_instruction->setParameter("maj", 0);                          $new_instruction->setParameter("maj", 0);
3492                          $new_instruction->class_actions[0]["identifier"] =                          $new_instruction->class_actions[0]["identifier"] =
3493                              "retour RAR de l'instruction $current_id";                              "notification de l'instruction $current_id";
3494                          $retour = $new_instruction->ajouter($valNewInstr,$db, $DEBUG);                          $retour = $new_instruction->ajouter($valNewInstr);
3495    
3496                          //Si une erreur s'est produite et qu'il s'agit d'un problème                          //Si une erreur s'est produite et qu'il s'agit d'un problème
3497                          //de restriction                          //de restriction
# Line 1757  class instruction extends instruction_ge Line 3499  class instruction extends instruction_ge
3499                              $error_message = $this->get_restriction_error_message($restriction);                              $error_message = $this->get_restriction_error_message($restriction);
3500                              $this->f->displayMessage("error", $error_message);                              $this->f->displayMessage("error", $error_message);
3501                              $this->addToLog(                              $this->addToLog(
3502                                  "triggermodifierapres() : evenement retour instruction ".                                  __METHOD__."(): evenement retour instruction ".
3503                                  $this->valF[$this->clePrimaire]." : ".                                  $this->valF[$this->clePrimaire]." : ".
3504                                  $new_instruction->msg                                  $new_instruction->msg
3505                              );                              );
# Line 1769  class instruction extends instruction_ge Line 3511  class instruction extends instruction_ge
3511                              return false;                              return false;
3512                          }                          }
3513                      }                      }
                     // Mise à jour du flag incomplet_notifie dans dossier si la  
                     // date limite d'instruction n'est pas dépassée  
                     if($row['type']=='incompletude' &&  
                         ($this->valF['archive_date_notification_delai'] >= $this->valF['date_retour_rar'] ||  
                         $this->valF['archive_date_notification_delai'] == "")) {  
                         $valFIncomp['incomplet_notifie'] = true;  
                         $cle = " dossier='".$val['dossier']."'";  
                         $resIncomp = $db->autoExecute(  
                             DB_PREFIXE.'dossier',  
                             $valFIncomp,  
                             DB_AUTOQUERY_UPDATE,  
                             $cle  
                         );  
                         $this->addToLog(  
                             "triggersupprimer(): db->autoexecute(\"".  
                                 DB_PREFIXE."dossier\", ".print_r($valFIncomp, true).  
                                 ", DB_AUTOQUERY_UPDATE, \"".$cle."\");",  
                             VERBOSE_MODE  
                         );  
                         if (database::isError($resIncomp)) {  
                             die($resIncomp->getMessage());  
                         }  
                     }  
3514                  }                  }
3515              }              }
3516          }          }
3517    
3518            /**
3519             * Mise à jour de la date de dernière modification du dossier
3520             * d'instruction
3521             */
3522            $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
3523            $inst_di->update_last_modification_date();
3524    
3525          // Mise à jour des données du dossier d'autorisation          // Mise à jour des données du dossier d'autorisation
3526          require_once "../obj/dossier_autorisation.class.php";          $da = $this->f->get_inst__om_dbform(array(
3527          $da = new dossier_autorisation($this->getNumDemandeAutorFromDossier($this->valF['dossier']), $this->db, DEBUG);              "obj" => "dossier_autorisation",
3528          if($da->majDossierAutorisation() === false) {              "idx" => $this->getNumDemandeAutorFromDossier($this->valF['dossier']),
3529            ));
3530            $params = array(
3531                'di_id' => $this->getVal('dossier'),
3532            );
3533            if($da->majDossierAutorisation($params) === false) {
3534              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));
3535              $this->correct = false;              $this->correct = false;
3536              return false;              return false;
3537          }          }
3538    
3539            // mise à jour des métadonnées issues des dates de suivi
3540            $dateRetourSignatureModified = ($this->valF['date_retour_signature'] != $this->getVal('date_retour_signature'));
3541            $dateRetourRARModified = ($this->valF['date_retour_rar'] != $this->getVal('date_retour_rar'));
3542            if ($dateRetourSignatureModified || $dateRetourRARModified) {
3543    
3544                // Calculs des nouvelles métadonnées
3545                $metadata = $this->getMetadata("om_fichier_instruction");
3546    
3547                // On vérifie si l'instruction à finaliser a un événement de type arrete
3548                $sql = "SELECT type FROM ".DB_PREFIXE."evenement WHERE evenement = ".$this->getVal("evenement");
3549                $typeEvenement = $this->f->db->getOne($sql);
3550                $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
3551                if ($this->f->isDatabaseError($typeEvenement, true) === true) {
3552                    $this->correct = false;
3553                    $this->addToMessage(__("Erreur de traitement de fichier."));
3554                    $this->addToLog(__METHOD__."() erreur BDD: ".var_export($typeEvenement->getMessage(), true), DEBUG_MODE);
3555                    return false;
3556                }
3557    
3558                // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques
3559                if ($typeEvenement == 'arrete'){
3560                    $metadata = array_merge($metadata, $this->getMetadata("arrete"));
3561                }
3562    
3563                // Filtre pour conserver uniquement les métadonnées liées aux dates
3564                $metadataToKeep = array(
3565                    "statutAutorisation",
3566                    "dateEvenementDocument",
3567                    'date_cloture_metier',
3568                    "NotificationArrete",
3569                    "dateNotificationArrete",
3570                    "controleLegalite",
3571                    "dateSignature",
3572                    "nomSignataire",
3573                    "qualiteSignataire",
3574                    "dateControleLegalite",
3575                );
3576                $metadata = array_filter(
3577                    $metadata,
3578                    function($key) use ($metadataToKeep) { return in_array($key, $metadataToKeep); },
3579                    ARRAY_FILTER_USE_KEY
3580                );
3581    
3582                // Mise à jour des métadonnées du document en GED
3583                $docUid = $this->getVal("om_fichier_instruction");
3584                $operationOrUID = $this->f->storage->update_metadata($docUid, $metadata);
3585                if ($operationOrUID == 'OP_FAILURE') {
3586                    $this->correct = false;
3587                    $this->addToMessage(__("Erreur de traitement de fichier."));
3588                    $this->addToLog(__METHOD__."() failed to update metadata: ".var_export($operationOrUID, true), DEBUG_MODE);
3589                    return false;
3590                }
3591    
3592                // mise à jour de l'UID du document en BDD
3593                else {
3594                    $valF = array('om_fichier_instruction' => $operationOrUID);
3595                    $res = $this->f->db->autoExecute(DB_PREFIXE.$this->table, $valF, DB_AUTOQUERY_UPDATE, $this->getCle($id));
3596                    $this->addToLog(__METHOD__.'() : db->autoExecute("'.DB_PREFIXE.$this->table.'", '.print_r($valF, true).', DB_AUTOQUERY_UPDATE, "'.$this->getCle($id).'")', VERBOSE_MODE);
3597                    if ($this->f->isDatabaseError($res, true) === true) {
3598                        $this->correct = false;
3599                        $this->addToMessage(__("Erreur de traitement de fichier."));
3600                        $this->addToLog(__METHOD__."() erreur BDD: ".var_export($res->getMessage(), true), DEBUG_MODE);
3601                        return false;
3602                    }
3603                    $this->addToMessage(__("La mise a jour du document s'est effectuee avec succes."));
3604                }
3605            }
3606    
3607            // Notification auto des demandeurs
3608            if ($dateRetourSignatureModified === true
3609                && $this->valF['date_retour_signature'] !== ''
3610                && $this->valF['date_retour_signature'] !== null) {
3611                //
3612                $ev = $this->get_inst_evenement($this->valF['evenement']);
3613                if ($ev->getVal('notification') === 'notification_auto_signature_requise') {
3614                    // Récupération de la liste des demandeurs à notifier et de la catégorie
3615                    $categorie = $this->f->get_param_option_notification($collectivite_di);
3616                    $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
3617                    $demandeursANotifie = $this->get_demandeurs_notifiable(
3618                        $this->valF['dossier'],
3619                        $isPortal
3620                    );
3621    
3622                    // Création d'une notification et d'une tâche pour chaque demandeur à notifier
3623                    foreach ($demandeursANotifie as $demandeur) {
3624                        // Ajout de la notif et récupération de son id
3625                        $idNotif = $this->ajouter_notification(
3626                            $this->valF[$this->clePrimaire],
3627                            $this->f->get_connected_user_login_name(),
3628                            $demandeur,
3629                            $collectivite_di,
3630                            true
3631                        );
3632                        if ($idNotif === false) {
3633                            return false;
3634                        }
3635                        // Création de la tache en lui donnant l'id de la notification
3636                        $notification_by_task = $this->notification_by_task(
3637                            $idNotif,
3638                            $this->valF['dossier'],
3639                            $categorie
3640                        );
3641                        if ($notification_by_task === false) {
3642                            $this->addToMessage(
3643                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3644                            );
3645                            return false;
3646                        }
3647                    }
3648                    $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
3649                }
3650            }
3651    
3652          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
3653      }      }
3654    
3655      function triggersupprimer($id,&$db,$val,$DEBUG) {      /**
3656         * TRIGGER - triggersupprimer.
3657         *
3658         * @return boolean
3659         */
3660        function triggersupprimer($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
3661            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
3662          /**          /**
3663           * L'objectif ici est de repositionner les valeurs récupérées en           * L'objectif ici est de repositionner les valeurs récupérées en
3664           * archive dans le dossier d'instruction avant de supprimer l'événement           * archive dans le dossier d'instruction avant de supprimer l'événement
3665           * d'instruction           * d'instruction si les valeurs du dossier sont différentes
3666           */           */
3667                    $valF = array();
3668          // Mise à jour des 4 valeurs modifiées par l'action          $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
3669          $valF['delai'] = $val['archive_delai'];          foreach ($inst_di->champs as $key => $champ) {
3670          $valF['accord_tacite'] = $val['archive_accord_tacite'];              // Si le champ du DI à une archive dans l'instruction
3671          $valF['etat'] = $val['archive_etat'];              if (isset($val[sprintf('archive_%s', $champ)]) === true) {
3672          if ($val['archive_avis'] != '') {                  // Si la valeur entre le champ du DI et son archive dans instruction
3673              $valF['avis_decision'] = $val['archive_avis'];                  // est différente
3674          } else {                  if ($inst_di->getVal($champ) !== $val[sprintf('archive_%s', $champ)]) {
3675              $valF['avis_decision'] = NULL;                      $val[sprintf('archive_%s', $champ)] === '' ? $valF[$champ] = null : $valF[$champ] = $val[sprintf('archive_%s', $champ)];
3676          }                  }
3677          // Mise à jour des 10 dates avec la valeur présente dans le formulaire              }
         // de suppression. Si la valeur de la date est vide alors on fixe  
         // à la valeur NULL  
         //  
         if ($val['archive_date_complet'] != '') {  
             $valF['date_complet'] = $val['archive_date_complet'];  
         } else {  
             $valF['date_complet'] = NULL;  
         }  
         if ($val['archive_date_dernier_depot'] != '') {  
             $valF['date_dernier_depot'] = $val['archive_date_dernier_depot'];  
         } else {  
             $valF['date_dernier_depot'] = NULL;  
         }  
         if ($val['archive_date_rejet'] != '') {  
             $valF['date_rejet'] = $val['archive_date_rejet'];  
         } else {  
             $valF['date_rejet'] = NULL;  
         }  
         if ($val['archive_date_limite'] != '') {  
             $valF['date_limite'] = $val['archive_date_limite'];  
         } else {  
             $valF['date_limite'] = NULL;  
         }  
         if ($val['archive_date_notification_delai'] != '') {  
             $valF['date_notification_delai'] = $val['archive_date_notification_delai'];  
         } else {  
             $valF['date_notification_delai'] = NULL;  
         }  
         if ($val['archive_date_decision'] != '') {  
             $valF['date_decision'] = $val['archive_date_decision'];  
         } else {  
             $valF['date_decision'] = NULL;  
         }  
         if ($val['archive_date_validite'] != '') {  
             $valF['date_validite'] = $val['archive_date_validite'];  
         } else {  
             $valF['date_validite'] = NULL;  
         }  
         if ($val['archive_date_achevement'] != '') {  
             $valF['date_achevement'] = $val['archive_date_achevement'];  
         } else {  
             $valF['date_achevement'] = NULL;  
         }  
         if ($val['archive_date_chantier'] != '') {  
             $valF['date_chantier'] = $val['archive_date_chantier'];  
         } else {  
             $valF['date_chantier'] = NULL;  
         }  
         if ($val['archive_date_conformite'] != '') {  
             $valF['date_conformite'] = $val['archive_date_conformite'];  
         } else {  
             $valF['date_conformite'] = NULL;  
         }  
         if ($val['archive_incompletude'] != '') {  
             $valF['incompletude'] = $val['archive_incompletude'];  
         } else {  
             $valF['incompletude'] = NULL;  
         }  
         if ($val['archive_incomplet_notifie'] != '') {  
             $valF['incomplet_notifie'] = $val['archive_incomplet_notifie'];  
         } else {  
             $valF['incomplet_notifie'] = NULL;  
         }  
         if ($val['archive_evenement_suivant_tacite'] != '') {  
             $valF['evenement_suivant_tacite'] = $val['archive_evenement_suivant_tacite'];  
         } else {  
             $valF['evenement_suivant_tacite'] = NULL;  
         }  
         if ($val['archive_evenement_suivant_tacite_incompletude'] != '') {  
             $valF['evenement_suivant_tacite_incompletude'] = $val['archive_evenement_suivant_tacite_incompletude'];  
         } else {  
             $valF['evenement_suivant_tacite_incompletude'] = NULL;  
         }  
         if ($val['archive_etat_pendant_incompletude'] != '') {  
             $valF['etat_pendant_incompletude'] = $val['archive_etat_pendant_incompletude'];  
         } else {  
             $valF['etat_pendant_incompletude'] = NULL;  
         }  
         if ($val['archive_date_limite_incompletude'] != '') {  
             $valF['date_limite_incompletude'] = $val['archive_date_limite_incompletude'];  
         } else {  
             $valF['date_limite_incompletude'] = NULL;  
3678          }          }
3679          if ($val['archive_delai_incompletude'] != '') {          // Spécificité du champ avis_decision dont le champ archive est nommé
3680              $valF['delai_incompletude'] = $val['archive_delai_incompletude'];          // différemment
3681          } else {          if ($inst_di->getVal('avis_decision') !== $val['archive_avis']) {
3682              $valF['delai_incompletude'] = NULL;              $val['archive_avis'] === '' ? $valF['avis_decision'] = null : $valF['avis_decision'] = $val['archive_avis'];
3683            }
3684            // Spécificité de la date d'affichage dont la valeur n'ai jamais modifiée
3685            // par l'archive
3686            unset($valF['date_affichage']);
3687    
3688            /**
3689             * Mise à jour de la version de clôture *version_clos* du dossier si et
3690             * seulement si l'instruction met à jour l'état du dossier.
3691             */
3692            if (isset($valF['etat']) === true
3693                && $valF['etat'] !== null
3694                && $valF['etat'] !== '') {
3695                // Récupère l'état actuel du dossier d'instruction
3696                $inst_current_etat = $this->f->get_inst__om_dbform(array(
3697                    "obj" => "etat",
3698                    "idx" => $inst_di->get_id_etat(),
3699                ));
3700                // Instanciation de l'état archivé appliqué sur le dossier
3701                $inst_etat = $this->f->get_inst__om_dbform(array(
3702                    "obj" => "etat",
3703                    "idx" => $valF['etat'],
3704                ));
3705                //
3706                $update_version_clos = null;
3707                // En cas de clôture du dossier par l'état archivé
3708                if ($inst_etat->getVal('statut') === 'cloture') {
3709                    $update_version_clos = $inst_di->update_version_clos('up');
3710                }
3711                // En cas de réouverture du dossier par l'état archivé
3712                if ($inst_current_etat->getVal('statut') === 'cloture'
3713                    && $inst_etat->getVal('statut') !== 'cloture') {
3714                    //
3715                    $update_version_clos = $inst_di->update_version_clos('down');
3716                    //
3717                    $this->set_att_di_reopened(true);
3718                }
3719                //
3720                if ($update_version_clos === false) {
3721                    $this->f->addToLog(sprintf(
3722                        "%s() : ERREUR - %s %s",
3723                        __METHOD__,
3724                        sprintf(
3725                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
3726                            $inst_di->getVal($inst_di->clePrimaire)
3727                        ),
3728                        sprintf(
3729                            __("L'instruction tente d'appliquer l'état %s."),
3730                            $inst_etat->getVal($inst_etat->clePrimaire)
3731                        )
3732                    ));
3733                    $this->addToMessage(sprintf(
3734                        "%s %s",
3735                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
3736                        __("Veuillez contacter votre administrateur.")
3737                    ));
3738                    return false;
3739                }
3740          }          }
3741          if ($val['archive_autorite_competente'] != '') {          // On supprime toutes les notications liées à l'instruction
3742              $valF['autorite_competente'] = $val['archive_autorite_competente'];          $notifASupprimer = $this->get_instruction_notification($this->getVal($this->clePrimaire));
3743          } else {          foreach ($notifASupprimer as $idNotif) {
3744              $valF['autorite_competente'] = NULL;              $inst_notif = $this->f->get_inst__om_dbform(array(
3745                    "obj" => "instruction_notification",
3746                    "idx" => $idNotif,
3747                ));
3748                $val_notif = array();
3749                foreach ($inst_notif->champs as $champ) {
3750                    $val_notif[$champ] = $inst_notif->getVal($champ);
3751                }
3752                // La suppression des notifications entrainera la suppression des tâches qui y sont
3753                // liées
3754                $supprNotif = $inst_notif->supprimer($val_notif);
3755                if ($supprNotif == false) {
3756                    $this->addToMessage(sprintf(
3757                        "%s %s",
3758                        __("Erreur lors de la suppression des notifications de l'instruction."),
3759                        __("Veuillez contacter votre administrateur.")
3760                    ));
3761                    return false;
3762                }
3763          }          }
3764    
3765          // On met à jour le dossier          // On met à jour le dossier
3766          $cle = " dossier='".$val['dossier']."'";          $valF['instruction'] = $id;
3767          $res = $db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);          $valF['crud'] = 'delete';
3768          $this->addToLog("triggersupprimer(): db->autoexecute(\"".DB_PREFIXE."dossier\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$cle."\");", VERBOSE_MODE);          $update_by_instruction = $inst_di->update_by_instruction($valF);
3769          if (database::isError($res)) {          if ($update_by_instruction === false) {
3770              die($res->getMessage());              $this->cleanMessage();
3771                $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
3772                return false;
3773          }          }
3774    
3775          // Affichage d'informations à l'utilisateur          // Affichage d'informations à l'utilisateur
3776          $this->addToMessage(_("Suppression de l'instruction")." [".$db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");          $this->addToMessage(_("Suppression de l'instruction")." [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3777    
3778          // Mise à jour de la demande si un récépissé d'instruction correspond à l'instruction à supprimer          // Mise à jour de la demande si un récépissé d'instruction correspond à l'instruction à supprimer
3779      }      }
3780    
3781      function triggersupprimerapres($id,&$db,$val,$DEBUG) {      /**
3782         * TRIGGER - triggersupprimerapres.
3783         *
3784         * @return boolean
3785         */
3786        function triggersupprimerapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
3787            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
3788            /**
3789             * Mise à jour de la date de dernière modification du dossier
3790             * d'instruction
3791             */
3792            $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
3793            $inst_di->update_last_modification_date();
3794    
3795          // Mise à jour des données du dossier d'autorisation          /**
3796          require_once "../obj/dossier_autorisation.class.php";           * Mise à jour des données du dossier d'autorisation
3797          $da = new dossier_autorisation($this->getNumDemandeAutorFromDossier($val["dossier"]), $this->db, DEBUG);           */
3798          if($da->majDossierAutorisation() === false) {          $da = $this->f->get_inst__om_dbform(array(
3799                "obj" => "dossier_autorisation",
3800                "idx" => $this->getNumDemandeAutorFromDossier($val["dossier"]),
3801            ));
3802            $params = array(
3803                'di_id' => $this->getVal('dossier'),
3804                'di_reopened' => $this->get_att_di_reopened(),
3805            );
3806            if($da->majDossierAutorisation($params) === false) {
3807              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));              $this->addToMessage(_("Erreur lors de la mise a jour des donnees du dossier d'autorisation. Contactez votre administrateur."));
3808              $this->correct = false;              $this->correct = false;
3809              return false;              return false;
3810          }          }
3811    
3812            /**
3813             * Gestion des tâches pour la dématérialisation
3814             */
3815            $inst_task_empty = $this->f->get_inst__om_dbform(array(
3816                "obj" => "task",
3817                "idx" => 0,
3818            ));
3819            foreach ($inst_di->task_types as $task_type) {
3820                $task_exists = $inst_task_empty->task_exists($task_type, $id);
3821                if ($task_exists !== false) {
3822                    $inst_task = $this->f->get_inst__om_dbform(array(
3823                        "obj" => "task",
3824                        "idx" => $task_exists,
3825                    ));
3826                    if ($inst_task->getVal('state') === $inst_task::STATUS_NEW || $inst_task->getVal('state') === $inst_task::STATUS_DRAFT) {
3827                        $task_val = array(
3828                            'state' => $inst_task::STATUS_CANCELED,
3829                        );
3830                        $update_task = $inst_task->update_task(array('val' => $task_val));
3831                        if ($update_task === false) {
3832                            $this->addToMessage(sprintf('%s %s',
3833                                sprintf(__("Une erreur s'est produite lors de la modification de la tâche %."), $inst_task->getVal($inst_task->clePrimaire)),
3834                                __("Veuillez contacter votre administrateur.")
3835                            ));
3836                            $this->correct = false;
3837                            return false;
3838                        }
3839                    }
3840                }
3841            }
3842    
3843            //
3844          $val['evenement'] = $this->getVal('evenement');          $val['evenement'] = $this->getVal('evenement');
3845          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
3846      }      }
3847    
3848      /**      /**
3849         * Permet de mettre la valeur passée en paramètre dans l'attribut de classe
3850         * "di_reopened".
3851         *
3852         * @param boolean $val
3853         */
3854        function set_att_di_reopened($val) {
3855            $this->di_reopened = $val;
3856        }
3857    
3858        /**
3859         * Permet de récupérer la valeur de l'attribut de classe "di_reopened".
3860         *
3861         * @return boolean
3862         */
3863        function get_att_di_reopened() {
3864            return $this->di_reopened;
3865        }
3866    
3867        /**
3868       * Permet de composer un message d'erreur sur restriction non valide en       * Permet de composer un message d'erreur sur restriction non valide en
3869       * fonction du contexte.       * fonction du contexte.
3870       *       *
# Line 1983  class instruction extends instruction_ge Line 3903  class instruction extends instruction_ge
3903      }      }
3904    
3905      /**      /**
3906       * Vérifie la restriction sur l'événement.       * @return void
      *  
      * @param array    $val   valeurs du formulaire  
      * @param database $db    handler database  
      * @param boolean  $DEBUG NA  
      *  
      * @return [type] [description]  
3907       */       */
3908      function verifier($val = array(), &$db, $DEBUG) {      function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {
3909          parent::verifier($val, $db, $DEBUG);          parent::verifier($val);
3910            //
3911          if ( isset($val['evenement']) && is_numeric($val['evenement'])){          if ( isset($val['evenement']) && is_numeric($val['evenement'])){
3912              $restriction = $this->get_restriction($val['evenement']);              $restriction = $this->get_restriction($val['evenement']);
3913            
# Line 2102  class instruction extends instruction_ge Line 4016  class instruction extends instruction_ge
4016    
4017              //              //
4018              $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);              $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
4019                
4020                //
4021                $params = array(
4022                    "specific" => array(),
4023                );
4024                // Si la rédaction libre est activée sur l'instruction
4025                if ($this->getVal("flag_edition_integrale") == 't') {
4026                    $params["specific"]["corps"] = array(
4027                        "mode" => "set",
4028                        "value" => $this->getVal("corps_om_htmletatex"),
4029                    );
4030                    $params["specific"]["titre"] = array(
4031                        "mode" => "set",
4032                        "value" => $this->getVal("titre_om_htmletat"),
4033                    );
4034                }
4035              // Génération du PDF              // Génération du PDF
4036              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite);              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
4037              $pdf_output = $result['pdf_output'];              $pdf_output = $result['pdf_output'];
4038                
4039              //Métadonnées du document              //Métadonnées du document
4040              $metadata = array(              $metadata = array(
4041                  'filename' => 'instruction_'.$id_inst.'.pdf',                  'filename' => 'instruction_'.$id_inst.'.pdf',
# Line 2121  class instruction extends instruction_ge Line 4050  class instruction extends instruction_ge
4050              $sql = "SELECT type              $sql = "SELECT type
4051                  FROM ".DB_PREFIXE."evenement                  FROM ".DB_PREFIXE."evenement
4052                  WHERE evenement = ".$this->getVal("evenement");                  WHERE evenement = ".$this->getVal("evenement");
4053              $typeEvenement = $this->db->getOne($sql);              $typeEvenement = $this->f->db->getOne($sql);
4054              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
4055              if ($this->f->isDatabaseError($typeEvenement, true) === true) {              if ($this->f->isDatabaseError($typeEvenement, true) === true) {
4056                  $this->correct = false;                  $this->correct = false;
# Line 2138  class instruction extends instruction_ge Line 4067  class instruction extends instruction_ge
4067    
4068              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);
4069    
4070                /*
4071                // transforme le tableau de métadonnées en objet
4072                $mdf = new MetadataFactory();
4073                $md = $mdf->build('Instruction', $metadata);
4074                */
4075    
4076              // Si le document a déjà été finalisé on le met à jour              // Si le document a déjà été finalisé on le met à jour
4077              // en conservant son UID              // en conservant son UID
4078              if ($this->getVal("om_fichier_instruction") != ''){              if ($this->getVal("om_fichier_instruction") != ''){
# Line 2146  class instruction extends instruction_ge Line 4081  class instruction extends instruction_ge
4081              }              }
4082              // Sinon on crée un nouveau document et dont on récupère l'UID              // Sinon on crée un nouveau document et dont on récupère l'UID
4083              else {              else {
4084                  $uid = $this->f->storage->create($pdf_output, $metadata);                  $uid = $this->f->storage->create($pdf_output, $metadata, "from_content", $this->table.".om_fichier_instruction");
4085              }              }
4086          }          }
4087    
# Line 2163  class instruction extends instruction_ge Line 4098  class instruction extends instruction_ge
4098          if ($uid == '' || $uid == 'OP_FAILURE' ) {          if ($uid == '' || $uid == 'OP_FAILURE' ) {
4099              $this->correct = false;              $this->correct = false;
4100              $this->addToMessage($file_msg_error);              $this->addToMessage($file_msg_error);
4101              $this->addToLog(sprintf($log_msg_error, $id_inst, $uid));              $this->addToLog(sprintf($log_msg_error, $id_inst, $uid), DEBUG_MODE);
4102              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
4103          }          }
4104    
# Line 2174  class instruction extends instruction_ge Line 4109  class instruction extends instruction_ge
4109          }          }
4110    
4111          //          //
4112          $val['date_evenement']=$this->dateDBToForm($val['date_evenement']);          $val['date_evenement'] = $this->dateDBToForm($val['date_evenement']);
4113          $val['archive_date_complet']=$this->dateDBToForm($val['archive_date_complet']);          $val['archive_date_complet'] = $this->dateDBToForm($val['archive_date_complet']);
4114          $val['archive_date_rejet']=$this->dateDBToForm($val['archive_date_rejet']);          $val['archive_date_rejet'] = $this->dateDBToForm($val['archive_date_rejet']);
4115          $val['archive_date_limite']=$this->dateDBToForm($val['archive_date_limite']);          $val['archive_date_limite'] = $this->dateDBToForm($val['archive_date_limite']);
4116          $val['archive_date_notification_delai']=$this->dateDBToForm($val['archive_date_notification_delai']);          $val['archive_date_notification_delai'] = $this->dateDBToForm($val['archive_date_notification_delai']);
4117          $val['archive_date_decision']=$this->dateDBToForm($val['archive_date_decision']);          $val['archive_date_decision'] = $this->dateDBToForm($val['archive_date_decision']);
4118          $val['archive_date_validite']=$this->dateDBToForm($val['archive_date_validite']);          $val['archive_date_validite'] = $this->dateDBToForm($val['archive_date_validite']);
4119          $val['archive_date_achevement']=$this->dateDBToForm($val['archive_date_achevement']);          $val['archive_date_achevement'] = $this->dateDBToForm($val['archive_date_achevement']);
4120          $val['archive_date_chantier']=$this->dateDBToForm($val['archive_date_chantier']);          $val['archive_date_chantier'] = $this->dateDBToForm($val['archive_date_chantier']);
4121          $val['archive_date_conformite']=$this->dateDBToForm($val['archive_date_conformite']);          $val['archive_date_conformite'] = $this->dateDBToForm($val['archive_date_conformite']);
4122          $val['archive_date_dernier_depot']=$this->dateDBToForm($val['archive_date_dernier_depot']);          $val['archive_date_dernier_depot'] = $this->dateDBToForm($val['archive_date_dernier_depot']);
4123          $val['archive_date_limite_incompletude']=$this->dateDBToForm($val['archive_date_limite_incompletude']);          $val['archive_date_limite_incompletude'] = $this->dateDBToForm($val['archive_date_limite_incompletude']);
4124          $val['date_finalisation_courrier']=$this->dateDBToForm($val['date_finalisation_courrier']);          $val['date_finalisation_courrier'] = $this->dateDBToForm($val['date_finalisation_courrier']);
4125          $val['date_envoi_signature']=$this->dateDBToForm($val['date_envoi_signature']);          $val['date_envoi_signature'] = $this->dateDBToForm($val['date_envoi_signature']);
4126          $val['date_retour_signature']=$this->dateDBToForm($val['date_retour_signature']);          $val['date_retour_signature'] = $this->dateDBToForm($val['date_retour_signature']);
4127          $val['date_envoi_rar']=$this->dateDBToForm($val['date_envoi_rar']);          $val['date_envoi_rar'] = $this->dateDBToForm($val['date_envoi_rar']);
4128          $val['date_retour_rar']=$this->dateDBToForm($val['date_retour_rar']);          $val['date_retour_rar'] = $this->dateDBToForm($val['date_retour_rar']);
4129          $val['date_envoi_controle_legalite']=$this->dateDBToForm($val['date_envoi_controle_legalite']);          $val['date_envoi_controle_legalite'] = $this->dateDBToForm($val['date_envoi_controle_legalite']);
4130          $val['date_retour_controle_legalite']=$this->dateDBToForm($val['date_retour_controle_legalite']);          $val['date_retour_controle_legalite'] = $this->dateDBToForm($val['date_retour_controle_legalite']);
4131            $val['archive_date_cloture_instruction'] = $this->dateDBToForm($val['archive_date_cloture_instruction']);
4132            $val['archive_date_premiere_visite'] = $this->dateDBToForm($val['archive_date_premiere_visite']);
4133            $val['archive_date_derniere_visite'] = $this->dateDBToForm($val['archive_date_derniere_visite']);
4134            $val['archive_date_contradictoire'] = $this->dateDBToForm($val['archive_date_contradictoire']);
4135            $val['archive_date_retour_contradictoire'] = $this->dateDBToForm($val['archive_date_retour_contradictoire']);
4136            $val['archive_date_ait'] = $this->dateDBToForm($val['archive_date_ait']);
4137            $val['archive_date_transmission_parquet'] = $this->dateDBToForm($val['archive_date_transmission_parquet']);
4138            $val['archive_date_affichage'] = $this->dateDBToForm($val['archive_date_affichage']);
4139          $this->setvalF($val);          $this->setvalF($val);
4140    
4141          // Verification de la validite des donnees          // Verification de la validite des donnees
4142          $this->verifier($this->val, $this->db, DEBUG);          $this->verifier($this->val);
4143          // Si les verifications precedentes sont correctes, on procede a          // Si les verifications precedentes sont correctes, on procede a
4144          // la modification, sinon on ne fait rien et on retourne une erreur          // la modification, sinon on ne fait rien et on retourne une erreur
4145          if ($this->correct === true) {          if ($this->correct === true) {
# Line 2230  class instruction extends instruction_ge Line 4173  class instruction extends instruction_ge
4173    
4174              // Execution de la requête de modification des donnees de l'attribut              // Execution de la requête de modification des donnees de l'attribut
4175              // valF de l'objet dans l'attribut table de l'objet              // valF de l'objet dans l'attribut table de l'objet
4176              $res = $this->db->autoExecute(DB_PREFIXE.$this->table, $valF,              $res = $this->f->db->autoExecute(DB_PREFIXE.$this->table, $valF,
4177                  DB_AUTOQUERY_UPDATE, $this->getCle($id_inst));                  DB_AUTOQUERY_UPDATE, $this->getCle($id_inst));
4178               $this->addToLog(__METHOD__."() : db->autoExecute(\"".DB_PREFIXE.$this->table."\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($id_inst)."\")", VERBOSE_MODE);               $this->addToLog(__METHOD__."() : db->autoExecute(\"".DB_PREFIXE.$this->table."\", ".print_r($valF, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($id_inst)."\")", VERBOSE_MODE);
4179              //              //
# Line 2251  class instruction extends instruction_ge Line 4194  class instruction extends instruction_ge
4194          }          }
4195          // L'appel de verifier() a déjà positionné correct à false          // L'appel de verifier() a déjà positionné correct à false
4196          // et défini un message d'erreur.          // et défini un message d'erreur.
4197          $this->addToLog(sprintf($log_msg_error, $id_inst, $uid));          $this->addToLog(sprintf($log_msg_error, $id_inst, $uid), DEBUG_MODE);
4198          return $this->end_treatment(__METHOD__, false);          return $this->end_treatment(__METHOD__, false);
4199      }      }
4200    
# Line 2259  class instruction extends instruction_ge Line 4202  class instruction extends instruction_ge
4202       * Récupération du numéro de dossier d'instruction à ajouter aux métadonnées       * Récupération du numéro de dossier d'instruction à ajouter aux métadonnées
4203       * @return string numéro de dossier d'instruction       * @return string numéro de dossier d'instruction
4204       */       */
4205      protected function getDossier() {      protected function getDossier($champ = null) {
4206          if(empty($this->specificMetadata)) {          if(empty($this->specificMetadata)) {
4207              $this->getSpecificMetadata();              $this->getSpecificMetadata();
4208          }          }
# Line 2358  class instruction extends instruction_ge Line 4301  class instruction extends instruction_ge
4301          // Requête sql          // Requête sql
4302          $sql = "SELECT libelle FROM ".DB_PREFIXE."evenement          $sql = "SELECT libelle FROM ".DB_PREFIXE."evenement
4303                  WHERE evenement=".$evenement;                  WHERE evenement=".$evenement;
4304          $evenement_libelle = $this->db->getOne($sql);          $evenement_libelle = $this->f->db->getOne($sql);
4305          $this->addToLog("getTitle(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("getTitle(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
4306          if (database::isError($evenement_libelle)) {          if (database::isError($evenement_libelle)) {
4307              die();              die();
# Line 2420  class instruction extends instruction_ge Line 4363  class instruction extends instruction_ge
4363                      LEFT JOIN ".DB_PREFIXE."groupe                      LEFT JOIN ".DB_PREFIXE."groupe
4364                          ON dossier_autorisation_type.groupe = groupe.groupe                          ON dossier_autorisation_type.groupe = groupe.groupe
4365                  WHERE dossier.dossier = '".$dossier."'";                  WHERE dossier.dossier = '".$dossier."'";
4366          $res = $this->db->query($sql);          $res = $this->f->db->query($sql);
4367          $this->f->addToLog("getSpecificMetadata() : db->query(".$sql.")", VERBOSE_MODE);          $this->f->addToLog("getSpecificMetadata() : db->query(".$sql.")", VERBOSE_MODE);
4368          if ( database::isError($res)){          if ( database::isError($res)){
4369              die();              die();
# Line 2465  class instruction extends instruction_ge Line 4408  class instruction extends instruction_ge
4408                      ON                      ON
4409                          dossier.etat = etat.etat                          dossier.etat = etat.etat
4410                  WHERE dossier ='".$idx."'";                  WHERE dossier ='".$idx."'";
4411              $statut = $this->db->getOne($sql);              $statut = $this->f->db->getOne($sql);
4412              $this->f->addToLog("getStatutAutorisationDossier() : db->getOne(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog("getStatutAutorisationDossier() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
4413              if ( database::isError($statut)){              if ( database::isError($statut)){
4414                  die();                  die();
# Line 2486  class instruction extends instruction_ge Line 4429  class instruction extends instruction_ge
4429          // Récupération de toutes les valeurs du dossier d'instruction en cours          // Récupération de toutes les valeurs du dossier d'instruction en cours
4430          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          $sql = "SELECT * FROM ".DB_PREFIXE."dossier
4431          WHERE dossier='".$this->valF['dossier']."'";          WHERE dossier='".$this->valF['dossier']."'";
4432          $res = $this->db->query($sql);          $res = $this->f->db->query($sql);
4433          $this->addToLog("get_dossier_actual(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("get_dossier_actual(): db->query(\"".$sql."\");", VERBOSE_MODE);
4434          $this->f->isDatabaseError($res);          $this->f->isDatabaseError($res);
4435    
# Line 2495  class instruction extends instruction_ge Line 4438  class instruction extends instruction_ge
4438    
4439              // Récupération de la valeur actuelle du délai, de l'accord tacite,              // Récupération de la valeur actuelle du délai, de l'accord tacite,
4440              // de l'état et de l'avis du dossier d'instruction              // de l'état et de l'avis du dossier d'instruction
4441              $return['archive_delai']=$row['delai'];              $return['archive_delai'] = $row['delai'];
4442              $return['archive_accord_tacite']=$row['accord_tacite'];              $return['archive_accord_tacite'] = $row['accord_tacite'];
4443              $return['archive_etat']=$row['etat'];              $return['archive_etat'] = $row['etat'];
4444              $return['archive_avis']=$row['avis_decision'];              $return['archive_avis'] = $row['avis_decision'];
4445              // Récupération de la valeur actuelle des 9 dates du dossier              // Récupération de la valeur actuelle des dates du dossier
4446              // d'instruction              // d'instruction
4447              $return['archive_date_complet']=$row['date_complet'];              $return['archive_date_complet'] = $row['date_complet'];
4448              $return['archive_date_dernier_depot']=$row['date_dernier_depot'];              $return['archive_date_dernier_depot'] = $row['date_dernier_depot'];
4449              $return['archive_date_rejet']= $row['date_rejet'];              $return['archive_date_rejet'] = $row['date_rejet'];
4450              $return['archive_date_limite']= $row['date_limite'];              $return['archive_date_limite'] = $row['date_limite'];
4451              $return['archive_date_notification_delai']= $row['date_notification_delai'];              $return['archive_date_notification_delai'] = $row['date_notification_delai'];
4452              $return['archive_date_decision']= $row['date_decision'];              $return['archive_date_decision'] = $row['date_decision'];
4453              $return['archive_date_validite']= $row['date_validite'];              $return['archive_date_validite'] = $row['date_validite'];
4454              $return['archive_date_achevement']= $row['date_achevement'];              $return['archive_date_achevement'] = $row['date_achevement'];
4455              $return['archive_date_chantier']= $row['date_chantier'];              $return['archive_date_chantier'] = $row['date_chantier'];
4456              $return['archive_date_conformite']= $row['date_conformite'];              $return['archive_date_conformite'] = $row['date_conformite'];
4457              $return['archive_incompletude']= $row['incompletude'];              $return['archive_incompletude'] = $row['incompletude'];
4458              $return['archive_incomplet_notifie']= $row['incomplet_notifie'];              $return['archive_incomplet_notifie'] = $row['incomplet_notifie'];
4459              $return['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];              $return['archive_evenement_suivant_tacite'] = $row['evenement_suivant_tacite'];
4460              $return['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];              $return['archive_evenement_suivant_tacite_incompletude'] = $row['evenement_suivant_tacite_incompletude'];
4461              $return['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];              $return['archive_etat_pendant_incompletude'] = $row['etat_pendant_incompletude'];
4462              $return['archive_date_limite_incompletude']= $row['date_limite_incompletude'];              $return['archive_date_limite_incompletude'] = $row['date_limite_incompletude'];
4463              $return['archive_delai_incompletude']= $row['delai_incompletude'];              $return['archive_delai_incompletude'] = $row['delai_incompletude'];
4464              $return['archive_autorite_competente']= $row['autorite_competente'];              $return['archive_autorite_competente'] = $row['autorite_competente'];
4465              $return['duree_validite']= $row['duree_validite'];              $return['archive_dossier_instruction_type'] = $row['dossier_instruction_type'];
4466              $return['date_depot']= $row['date_depot'];              $return['duree_validite'] = $row['duree_validite'];
4467                $return['date_depot'] = $row['date_depot'];
4468                $return['date_depot_mairie'] = $row['date_depot_mairie'];
4469                $return['archive_date_cloture_instruction'] = $row['date_cloture_instruction'];
4470                $return['archive_date_premiere_visite'] = $row['date_premiere_visite'];
4471                $return['archive_date_derniere_visite'] = $row['date_derniere_visite'];
4472                $return['archive_date_contradictoire'] = $row['date_contradictoire'];
4473                $return['archive_date_retour_contradictoire'] = $row['date_retour_contradictoire'];
4474                $return['archive_date_ait'] = $row['date_ait'];
4475                $return['archive_date_transmission_parquet'] = $row['date_transmission_parquet'];
4476                $return['archive_date_affichage'] = $row['date_affichage'];
4477                $return['archive_pec_metier'] = $row['pec_metier'];
4478                $return['archive_a_qualifier'] = $row['a_qualifier'];
4479          }          }
4480    
4481          // Retour de la fonction          // Retour de la fonction
# Line 2548  class instruction extends instruction_ge Line 4503  class instruction extends instruction_ge
4503                          ON instruction.evenement = evenement.evenement                          ON instruction.evenement = evenement.evenement
4504                      WHERE instruction.instruction = $idx";                      WHERE instruction.instruction = $idx";
4505              $this->f->addToLog("checkEvenementNonVerrouillable() : db->getOne(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog("checkEvenementNonVerrouillable() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
4506              $res = $this->db->getOne($sql);              $res = $this->f->db->getOne($sql);
4507              $this->f->isDatabaseError($res);              $this->f->isDatabaseError($res);
4508    
4509              // Si le retour de la requête est true              // Si le retour de la requête est true
# Line 2582  class instruction extends instruction_ge Line 4537  class instruction extends instruction_ge
4537          if ($row['date_dernier_depot'] != '') {          if ($row['date_dernier_depot'] != '') {
4538              $this->valF['archive_date_dernier_depot']=$row['date_dernier_depot'];              $this->valF['archive_date_dernier_depot']=$row['date_dernier_depot'];
4539          }          }
4540          if ($row['date_rejet']!='') {          if ($row['date_rejet'] != '') {
4541              $this->valF['archive_date_rejet']= $row['date_rejet'];              $this->valF['archive_date_rejet']= $row['date_rejet'];
4542          }          }
4543          if ($row['date_limite']!='') {          if ($row['date_limite'] != '') {
4544              $this->valF['archive_date_limite']= $row['date_limite'];              $this->valF['archive_date_limite']= $row['date_limite'];
4545          }          }
4546          if ($row['date_notification_delai']!='') {          if ($row['date_notification_delai'] != '') {
4547              $this->valF['archive_date_notification_delai']= $row['date_notification_delai'];              $this->valF['archive_date_notification_delai']= $row['date_notification_delai'];
4548          }          }
4549          if ($row['date_decision']!='') {          if ($row['date_decision'] != '') {
4550              $this->valF['archive_date_decision']= $row['date_decision'];              $this->valF['archive_date_decision']= $row['date_decision'];
4551          }          }
4552          if ($row['date_validite']!='') {          if ($row['date_validite'] != '') {
4553              $this->valF['archive_date_validite']= $row['date_validite'];              $this->valF['archive_date_validite']= $row['date_validite'];
4554          }          }
4555          if ($row['date_achevement']!='') {          if ($row['date_achevement'] != '') {
4556              $this->valF['archive_date_achevement']= $row['date_achevement'];              $this->valF['archive_date_achevement']= $row['date_achevement'];
4557          }          }
4558          if ($row['date_chantier']!='') {          if ($row['date_chantier'] != '') {
4559              $this->valF['archive_date_chantier']= $row['date_chantier'];              $this->valF['archive_date_chantier']= $row['date_chantier'];
4560          }          }
4561          if ($row['date_conformite']!='') {          if ($row['date_conformite'] != '') {
4562              $this->valF['archive_date_conformite']= $row['date_conformite'];                $this->valF['archive_date_conformite']= $row['date_conformite'];  
4563          }          }
4564          if ($row['incompletude']!='') {          if ($row['incompletude'] != '') {
4565              $this->valF['archive_incompletude']= $row['incompletude'];                $this->valF['archive_incompletude']= $row['incompletude'];  
4566          }          }
4567          if ($row['incomplet_notifie']!='') {          if ($row['incomplet_notifie'] != '') {
4568              $this->valF['archive_incomplet_notifie']= $row['incomplet_notifie'];                $this->valF['archive_incomplet_notifie']= $row['incomplet_notifie'];  
4569          }          }
4570          if ($row['evenement_suivant_tacite']!='') {          if ($row['evenement_suivant_tacite'] != '') {
4571              $this->valF['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];                $this->valF['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];  
4572          }          }
4573          if ($row['evenement_suivant_tacite_incompletude']!='') {          if ($row['evenement_suivant_tacite_incompletude'] != '') {
4574              $this->valF['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];                $this->valF['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];  
4575          }          }
4576          if ($row['etat_pendant_incompletude']!='') {          if ($row['etat_pendant_incompletude'] != '') {
4577              $this->valF['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];                $this->valF['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];  
4578          }          }
4579          if ($row['date_limite_incompletude']!='') {          if ($row['date_limite_incompletude'] != '') {
4580              $this->valF['archive_date_limite_incompletude']= $row['date_limite_incompletude'];                $this->valF['archive_date_limite_incompletude']= $row['date_limite_incompletude'];  
4581          }          }
4582          if ($row['delai_incompletude']!='') {          if ($row['delai_incompletude'] != '') {
4583              $this->valF['archive_delai_incompletude']= $row['delai_incompletude'];                $this->valF['archive_delai_incompletude']= $row['delai_incompletude'];  
4584          }          }
4585          if ($row['autorite_competente']!='') {          if ($row['autorite_competente'] != '') {
4586              $this->valF['archive_autorite_competente']= $row['autorite_competente'];                $this->valF['archive_autorite_competente']= $row['autorite_competente'];  
4587          }          }
4588          if ($row['duree_validite']!='') {          if ($row['duree_validite'] != '') {
4589              $this->valF['duree_validite']= $row['duree_validite'];                $this->valF['duree_validite']= $row['duree_validite'];  
4590          }          }
4591          if ($row['date_depot']!='') {          if ($row['date_depot'] != '') {
4592              $this->valF['date_depot']= $row['date_depot'];                $this->valF['date_depot']= $row['date_depot'];  
4593          }          }
4594            if ($row['date_depot_mairie'] != '') {
4595                $this->valF['date_depot_mairie']= $row['date_depot_mairie'];  
4596            }
4597            // Dates concernant les dossiers contentieux
4598            if ($row['date_cloture_instruction'] != '') {
4599                $this->valF['archive_date_cloture_instruction']= $row['date_cloture_instruction'];  
4600            }
4601            if ($row['date_premiere_visite'] != '') {
4602                $this->valF['archive_date_premiere_visite']= $row['date_premiere_visite'];  
4603            }
4604            if ($row['date_derniere_visite'] != '') {
4605                $this->valF['archive_date_derniere_visite']= $row['date_derniere_visite'];  
4606            }
4607            if ($row['date_contradictoire'] != '') {
4608                $this->valF['archive_date_contradictoire']= $row['date_contradictoire'];  
4609            }
4610            if ($row['date_retour_contradictoire'] != '') {
4611                $this->valF['archive_date_retour_contradictoire']= $row['date_retour_contradictoire'];  
4612            }
4613            if ($row['date_ait'] != '') {
4614                $this->valF['archive_date_ait']= $row['date_ait'];  
4615            }
4616            if ($row['date_transmission_parquet'] != '') {
4617                $this->valF['archive_date_transmission_parquet']= $row['date_transmission_parquet'];  
4618            }
4619            //
4620            if ($row['dossier_instruction_type'] != '') {
4621                $this->valF['archive_dossier_instruction_type']= $row['dossier_instruction_type'];  
4622            }
4623            if ($row['date_affichage'] != '') {
4624                $this->valF['archive_date_affichage']= $row['date_affichage'];  
4625            }
4626            if (isset($row['pec_metier']) === true && $row['pec_metier'] != '') {
4627                $this->valF['archive_pec_metier']= $row['pec_metier'];  
4628            }
4629            if (isset($row['a_qualifier']) === true && $row['a_qualifier'] != '') {
4630                $this->valF['archive_a_qualifier']= $row['a_qualifier'];  
4631            }
4632      }      }
4633    
4634      // {{{      // {{{
# Line 2767  class instruction extends instruction_ge Line 4760  class instruction extends instruction_ge
4760          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",
4761          "ap_codepostal"=>"", "ap_ville"=>"");          "ap_codepostal"=>"", "ap_ville"=>"");
4762    
4763          $sqlArrete = "SELECT    signataire_arrete.nom as \"nomsignataire\",          $sqlArrete = "SELECT
4764                    signataire_arrete.prenom || ' ' ||signataire_arrete.nom as \"nomsignataire\",
4765                  signataire_arrete.qualite as \"qualitesignataire\",                  signataire_arrete.qualite as \"qualitesignataire\",
4766                  instruction.etat as \"decisionarrete\",                  instruction.etat as \"decisionarrete\",
4767                  instruction.date_retour_rar as \"datenotification\",                  instruction.date_retour_rar as \"datenotification\",
# Line 2785  class instruction extends instruction_ge Line 4779  class instruction extends instruction_ge
4779              LEFT JOIN ".DB_PREFIXE."donnees_techniques ON              LEFT JOIN ".DB_PREFIXE."donnees_techniques ON
4780                      donnees_techniques.dossier_instruction = dossier.dossier                      donnees_techniques.dossier_instruction = dossier.dossier
4781              WHERE instruction.instruction = ".$this->getVal("instruction");              WHERE instruction.instruction = ".$this->getVal("instruction");
4782          $resArrete = $this->db->query($sqlArrete);          $resArrete = $this->f->db->query($sqlArrete);
4783          $this->f->addToLog("getArreteMetadata(): db->query(\"".$sqlArrete."\");", VERBOSE_MODE);          $this->f->addToLog("getArreteMetadata(): db->query(\"".$sqlArrete."\");", VERBOSE_MODE);
4784          if ( database::isError($resArrete)){          if ( database::isError($resArrete)){
4785              die();              die();
# Line 2805  class instruction extends instruction_ge Line 4799  class instruction extends instruction_ge
4799          // Récupère la valeur du champ lettretype          // Récupère la valeur du champ lettretype
4800          $lettretype = $this->getVal("lettretype");          $lettretype = $this->getVal("lettretype");
4801          // Si le champ est vide          // Si le champ est vide
4802          if (empty($lettretype)) {          if ($lettretype !== '' && $lettretype !== null) {
4803              //              //
4804              return false;              return true;
4805          }          }
4806    
4807          //          //
4808          return true;          return false;
4809        }
4810    
4811        /**
4812         * CONDITION - is_modifiable.
4813         *
4814         * Controle si l'évenement est modifiable.
4815         *
4816         * @return boolean
4817         */
4818        function is_evenement_modifiable() {
4819            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
4820            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_modifiable'));
4821      }      }
4822    
4823      /**      /**
# Line 2822  class instruction extends instruction_ge Line 4828  class instruction extends instruction_ge
4828       * @return boolean       * @return boolean
4829       */       */
4830      function is_editable() {      function is_editable() {
4831    
4832            // XXX
4833            // Identifier si l'instruction est lié à une tâche depuis le champ object_id (mais aussi voir le log car object_id peut être modifié)
4834            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
4835    
4836          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
4837          $bypass = $this->f->isAccredited(get_class()."_modifier_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modifier_bypass");
4838          //          //
4839          if ($bypass == true) {          if ($bypass == true) {
   
4840              //              //
4841              return true;              return true;
4842          }          }
4843            
         // Si l'utilisateur est un intructeur qui ne correspond pas à la  
         // division du dossier  
         if ($this->f->isUserInstructeur()  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && $this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === false) {  
   
             //  
             return false;  
         }  
   
         // si instructeur commune  
         if($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === true  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && ($this->f->isInstrCanChangeDecision($this->getVal('dossier')) !== true  
             || $this->getVal('created_by_commune') !== 't')) {  
             return false;  
         }  
4844          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
4845          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
4846          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
4847              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
4848              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
4849              //              //
4850              return false;              return false;
4851          }          }
4852    
4853            // Si l'utilisateur est un intructeur qui correspond à la division du
4854            // dossier
4855            if ($this->is_instructeur_from_division_dossier() === true) {
4856                //
4857                return true;
4858            }
4859    
4860            // Si l'utilisateur est instructeur de la commune du dossier et que
4861            // l'instruction est créée par un instructeur de la commune
4862            if ($this->is_instructeur_from_collectivite_dossier() === true and
4863                $this->getVal('created_by_commune') === 't') {
4864                return true;
4865            }
4866    
4867          //          //
4868          return true;          return false;
4869        }
4870    
4871        /**
4872         * Vérifie si l'événement est supprimable ou pas.
4873         *
4874         * @return boolean
4875         */
4876        function is_evenement_supprimable() {
4877            // Controle si l'évenement est supprimable
4878            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
4879            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_supprimable'));
4880      }      }
4881    
4882      /**      /**
4883       * CONDITION - is_deletable.       * CONDITION - is_deletable.
4884       *       *
4885       * Condition pour lma modification.       * Condition pour la suppression.
4886       *       *
4887       * @return boolean       * @return boolean
4888       */       */
4889      function is_deletable() {      function is_deletable() {
4890          // Contrôle si l'utilisateur possède un bypass  
4891          $bypass = $this->f->isAccredited(get_class()."_supprimer_bypass");          // XXX
4892            // Identifier si l'instruction est lié à une tâche depuis le champ object_id (mais aussi voir le log car object_id peut être modifié)
4893            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
4894    
4895            // Contrôle si l'utilisateur possède un bypass intégral
4896            $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass");
4897          //          //
4898          if ($bypass == true) {          if ($bypass == true) {
4899    
# Line 2880  class instruction extends instruction_ge Line 4902  class instruction extends instruction_ge
4902          }          }
4903    
4904          // Si l'utilisateur est un intructeur qui ne correspond pas à la          // Si l'utilisateur est un intructeur qui ne correspond pas à la
4905          // division du dossier          // division du dossier et si l'utilisateur n'a pas la permission bypass
4906          if ($this->f->isUserInstructeur()          // de la division
4907              && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()) {          if ($this->is_instructeur_from_division_dossier() === false
4908                && $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass_division") === false) {
4909    
4910              //              //
4911              return false;              return false;
# Line 2891  class instruction extends instruction_ge Line 4914  class instruction extends instruction_ge
4914          // l'événement est-il le dernier ?          // l'événement est-il le dernier ?
4915          $dernier_evenement = false;          $dernier_evenement = false;
4916          // instanciation dossier          // instanciation dossier
4917          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
4918          $dossier = new dossier($this->getVal('dossier'), $this->db, DEBUG);              "obj" => "dossier",
4919                "idx" => $this->getVal('dossier'),
4920            ));
4921          // récupération dernier événement          // récupération dernier événement
4922          $id_dernier_evenement = $dossier->get_dernier_evenement();          $id_dernier_evenement = $dossier->get_dernier_evenement();
4923          if ($id_dernier_evenement == $this->getVal($this->clePrimaire)) {          if ($id_dernier_evenement == $this->getVal($this->clePrimaire)) {
# Line 2918  class instruction extends instruction_ge Line 4943  class instruction extends instruction_ge
4943          //          //
4944          return true;          return true;
4945      }      }
4946        
4947        
4948        /**
4949         * Vérifie que l'utilisateur est instructeur et qu'il est de la division du
4950         * dossier.
4951         *
4952         * @return,  boolean true/false
4953         */
4954        function is_instructeur_from_collectivite_dossier() {
4955            if ($this->f->isUserInstructeur() === true and
4956                $this->f->om_utilisateur["om_collectivite"] == $this->get_dossier_instruction_om_collectivite()) {
4957                return true;
4958            }
4959            return false;
4960        }
4961        
4962      /**      /**
4963       * CONDITION - is_addable.       * CONDITION - is_addable.
4964       *       *
# Line 2928  class instruction extends instruction_ge Line 4968  class instruction extends instruction_ge
4968       */       */
4969      function is_addable() {      function is_addable() {
4970          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
4971          $bypass = $this->f->isAccredited(get_class()."_ajouter_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_ajouter_bypass");
4972          //          //
4973          if ($bypass == true) {          if ($bypass == true) {
4974    
4975              //              //
4976              return true;              return true;
4977          }          }
4978            // Si l'utilisateur est un intructeur qui correspond à la
4979          // Si l'utilisateur est un intructeur qui ne correspond pas à la          // division du dossier ou qu'il peut changer la décision
4980          // division du dossier          if ($this->is_instructeur_from_division_dossier() === true or
4981          if ($this->f->isUserInstructeur()              $this->isInstrCanChangeDecision($this->getParameter('idxformulaire')) === true) {
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && $this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === false) {  
   
4982              //              //
4983              return false;              return true;
         }  
   
         // si instructeur commune  
         if($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === false  
             && $this->f->isInstrCanChangeDecision($this->getVal('dossier')) === true) {  
             return false;  
4984          }          }
4985    
   
4986          //          //
4987          return true;          return false;
4988      }      }
4989    
4990      /**      /**
# Line 2966  class instruction extends instruction_ge Line 4996  class instruction extends instruction_ge
4996       */       */
4997      function is_finalizable() {      function is_finalizable() {
4998          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
4999          $bypass = $this->f->isAccredited(get_class()."_finaliser_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_finaliser_bypass");
5000          //          //
5001          if ($bypass == true) {          if ($bypass == true) {
   
5002              //              //
5003              return true;              return true;
5004          }          }
5005            
         // Si l'utilisateur est un intructeur qui ne correspond pas à la  
         // division du dossier  
         if ($this->f->isUserInstructeur()  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && $this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === false) {  
   
             //  
             return false;  
         }  
   
         // si instructeur commune  
         if($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === true  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && ($this->f->isInstrCanChangeDecision($this->getVal('dossier')) !== true  
             || $this->getVal('created_by_commune') !== 't')) {  
             return false;  
         }  
   
5006          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
5007          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
5008          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
5009              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
5010              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
5011              //              //
5012              return false;              return false;
5013          }          }
5014            
5015            // Si l'utilisateur est un intructeur qui correspond à la division du
5016            // dossier
5017            if ($this->is_instructeur_from_division_dossier() === true) {
5018                //
5019                return true;
5020            }
5021    
5022            // Si l'utilisateur est instructeur de la commune du dossier et que
5023            // l'instruction est créée par un instructeur de la commune
5024            if ($this->is_instructeur_from_collectivite_dossier() === true and
5025                $this->getVal('created_by_commune') === 't') {
5026                return true;
5027            }
5028    
5029          //          //
5030          return true;          return false;
5031      }      }
5032    
5033      /**      /**
# Line 3037  class instruction extends instruction_ge Line 5061  class instruction extends instruction_ge
5061       */       */
5062      function is_unfinalizable(){      function is_unfinalizable(){
5063          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5064          $bypass = $this->f->isAccredited(get_class()."_definaliser_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_definaliser_bypass");
5065          //          //
5066          if ($bypass == true) {          if ($bypass == true) {
   
5067              //              //
5068              return true;              return true;
5069          }          }
5070            
         // Si l'utilisateur est un intructeur qui ne correspond pas à la  
         // division du dossier  
         if ($this->f->isUserInstructeur()  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && $this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === false) {  
   
             //  
             return false;  
         }  
   
         // si instructeur commune  
         if($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") === true  
             && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()  
             && ($this->f->isInstrCanChangeDecision($this->getVal('dossier')) !== true  
             || $this->getVal('created_by_commune') !== 't')) {  
             return false;  
         }  
   
5071          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
5072          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
5073          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
5074              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
5075              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
5076              //              //
5077              return false;              return false;
5078          }          }
5079    
5080            // Si l'utilisateur est un intructeur qui correspond à la division du
5081            // dossier
5082            if ($this->is_instructeur_from_division_dossier() === true) {
5083                //
5084                return true;
5085            }
5086    
5087            // Si l'utilisateur est instructeur de la commune du dossier et que
5088            // l'instruction est créée par un instructeur de la commune
5089            if ($this->is_instructeur_from_collectivite_dossier() === true and
5090                $this->getVal('created_by_commune') === 't') {
5091                return true;
5092            }
5093    
5094          //          //
5095          return true;          return false;
5096      }      }
5097    
5098      /**      /**
# Line 3100  class instruction extends instruction_ge Line 5118  class instruction extends instruction_ge
5118    
5119    
5120      /**      /**
5121         * Permet de définir si un instructeur commune peut editer une instruction
5122         *
5123         * @return boolean true si il peut
5124         */
5125        function isInstrCanChangeDecision($idx) {
5126            
5127            if ($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") !== true or
5128                $this->f->isUserInstructeur() !== true) {
5129                return false;
5130            }
5131            
5132            
5133    
5134            // Sinon on vérifie l'éligibilité du dossier au changement de décision
5135            $sql =
5136                "SELECT
5137                    dossier.dossier
5138                FROM
5139                    ".DB_PREFIXE."dossier
5140                JOIN ".DB_PREFIXE."instruction ON instruction.instruction = (
5141                    SELECT instruction
5142                    FROM ".DB_PREFIXE."instruction
5143                    JOIN ".DB_PREFIXE."evenement on instruction.evenement=evenement.evenement
5144                    WHERE instruction.dossier = dossier.dossier
5145                    AND evenement.retour IS FALSE
5146                    ORDER BY date_evenement DESC, instruction DESC
5147                    LIMIT 1
5148                )
5149                JOIN ".DB_PREFIXE."evenement ON instruction.evenement=evenement.evenement
5150                JOIN ".DB_PREFIXE."instructeur ON dossier.instructeur=instructeur.instructeur
5151                JOIN ".DB_PREFIXE."om_utilisateur ON instructeur.om_utilisateur=om_utilisateur.om_utilisateur
5152                JOIN ".DB_PREFIXE."om_collectivite ON om_collectivite.om_collectivite=om_utilisateur.om_collectivite
5153                JOIN ".DB_PREFIXE."etat ON dossier.etat = etat.etat
5154                WHERE
5155                    
5156                        (
5157                            evenement.type = 'arrete' AND
5158                            (
5159                                instruction.om_final_instruction IS TRUE
5160                                OR instruction.created_by_commune IS TRUE
5161                            ) OR
5162                            evenement.type = 'changement_decision'
5163                        )
5164                    AND evenement.retour IS FALSE
5165                    AND instruction.date_retour_signature IS NULL
5166                    AND instruction.date_envoi_rar IS NULL
5167                    AND instruction.date_retour_rar IS NULL
5168                    AND instruction.date_envoi_controle_legalite IS NULL
5169                    AND instruction.date_retour_controle_legalite IS NULL
5170                    AND etat.statut = 'encours'
5171                    AND dossier.dossier = '".$idx."'
5172                    AND om_collectivite.niveau = '2'
5173                ";
5174    
5175    
5176            // Si collectivité de l'utilisateur niveau mono alors filtre sur celle-ci
5177            if ($this->f->isCollectiviteMono($_SESSION['collectivite']) === true) {
5178                $sql .= " AND dossier.om_collectivite=".$_SESSION['collectivite'];
5179            }
5180            $res = $this->f->db->getone($sql);
5181            if (database::isError($res)) {
5182                die();
5183            }
5184            // Si le dossier n'est pas sujet au changement de decision
5185            if($res == null) {
5186                return false;
5187            }
5188            return true;
5189        }
5190    
5191    
5192        /**
5193       * CONDITION - can_monitoring_dates.       * CONDITION - can_monitoring_dates.
5194       *       *
5195       * Condition pour afficher le bouton de suivi des dates.       * Condition pour afficher le bouton de suivi des dates.
# Line 3117  class instruction extends instruction_ge Line 5207  class instruction extends instruction_ge
5207          }          }
5208    
5209          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5210          $bypass = $this->f->isAccredited(get_class()."_modification_dates_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modification_dates_bypass");
5211          if ($bypass === true) {          if ($bypass === true) {
5212              return true;              return true;
5213          }          }
5214    
5215          // On vérifie en premier lieu que le DI n'est pas clôturé          // Permission de modifier le suivi des dates sur un dossier cloturé pour
5216            // un utilisateur lié à un instructeur
5217            $perm_moni_dates_d_closed = $this->f->isAccredited($this->get_absolute_class_name()."_modification_dates_cloture");
5218    
5219            // On vérifie en premier lieu que le DI n'est pas clôturé et que
5220            // l'utilisateur ne possède pas la permission de modifier le suivi des
5221            // dates sur un dossier clôturé
5222          $inst_dossier = $this->get_inst_dossier();          $inst_dossier = $this->get_inst_dossier();
5223          if ($inst_dossier->getStatut() === 'cloture') {          if ($inst_dossier->getStatut() === 'cloture'
5224                && $perm_moni_dates_d_closed === false) {
5225              //              //
5226              return false;              return false;
5227          }          }
# Line 3134  class instruction extends instruction_ge Line 5231  class instruction extends instruction_ge
5231          // et celles de son éventuel instructeur          // et celles de son éventuel instructeur
5232          $instr_di = $inst_dossier->getVal('instructeur');          $instr_di = $inst_dossier->getVal('instructeur');
5233    
5234            // Il faut disposer d'une entrée instructeur
5235            if ($this->f->isUserInstructeur() === false) {
5236                return false;
5237            }
5238    
5239          // Par défaut on prétend que l'instructeur n'est pas multi          // Par défaut on prétend que l'instructeur n'est pas multi
5240          $instr_di_coll_multi = false;          $instr_di_coll_multi = false;
5241          // Si un instructeur est affecté au dossier          // Si un instructeur est affecté au dossier
# Line 3146  class instruction extends instruction_ge Line 5248  class instruction extends instruction_ge
5248              }              }
5249          }          }
5250    
5251          // S'il s'agit d'un instructeur          // Il faut qu'il instruise le dossier ou soit de la même division
5252          if ($this->f->isUserInstructeur() === true) {          if ($this->f->om_utilisateur['instructeur'] === $instr_di
5253              // Il faut qu'il instruise le dossier ou soit de la même division                  || $this->f->om_utilisateur['division'] === $div_di) {
             if ($this->f->om_utilisateur['instructeur'] === $instr_di  
                     || $this->f->om_utilisateur['division'] === $div_di) {  
                 //  
                 return true;  
             }  
   
             // On donne également le droit s'il est de la même collectivité que  
             // le dossier et si l'instruction est déléguée à la communauté  
             if ($this->f->isCollectiviteMono($this->f->om_utilisateur['om_collectivite']) === true  
                 && $this->f->om_utilisateur['om_collectivite'] === $coll_di  
                 && $instr_di_coll_multi === true) {  
                 //  
                 return true;  
             }  
   
             // Si l'instructeur ne rentre pas dans les deux cas précédents  
             return false;  
         }  
   
         //  
         // A ce stade l'utilisateur connecté n'est pas instructeur  
         //  
   
         // Il a le droit s'il est de la communauté  
         if ($this->f->isCollectiviteMono($this->f->om_utilisateur['om_collectivite']) === false) {  
5254              //              //
5255              return true;              return true;
5256          }          }
5257    
5258          // Sinon il faut qu'il soit de la même commune que celle du dossier          // On donne également le droit s'il est de la même collectivité que
5259          if ($this->f->om_utilisateur['om_collectivite'] === $coll_di) {          // le dossier ET si l'instruction est déléguée à la communauté
5260            if ($this->f->isCollectiviteMono($this->f->om_utilisateur['om_collectivite']) === true
5261                && $this->f->om_utilisateur['om_collectivite'] === $coll_di
5262                && $instr_di_coll_multi === true) {
5263              //              //
5264              return true;              return true;
5265          }          }
5266    
5267          //          // Si l'instructeur ne rentre pas dans les deux cas précédents
5268          return false;          return false;
5269      }      }
5270    
# Line 3203  class instruction extends instruction_ge Line 5283  class instruction extends instruction_ge
5283          // Cette méthode permet d'exécuter une routine en début des méthodes          // Cette méthode permet d'exécuter une routine en début des méthodes
5284          // dites de TREATMENT.          // dites de TREATMENT.
5285          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
5286            $message = '';
5287    
5288          // Traitement de la finalisation          // Traitement de la finalisation
5289          $ret = $this->manage_finalizing("finalize", $val);          $ret = $this->manage_finalizing("finalize", $val);
# Line 3214  class instruction extends instruction_ge Line 5295  class instruction extends instruction_ge
5295              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
5296          }          }
5297    
5298            // Envoi des notifications aux demandeurs si la notification est automatique
5299            // et que la signature n'est pas requise
5300            $ev = $this->get_inst_evenement($this->getVal('evenement'));
5301            if ($ev->getVal('notification') === 'notification_automatique') {
5302                // Récupération de la catégorie et envoie des notifications au(x) demandeur(s)
5303                $collectivite_di = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));
5304                // Récupération de la liste des demandeurs à notifier et de la catégorie
5305                $categorie = $this->f->get_param_option_notification($collectivite_di);
5306                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
5307                $demandeursANotifie = $this->get_demandeurs_notifiable(
5308                    $this->getVal('dossier'),
5309                    $isPortal
5310                );
5311    
5312                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
5313                if (count($demandeursANotifie) > 0) {
5314                    foreach ($demandeursANotifie as $demandeur) {
5315                        // Ajout de la notif et récupération de son id
5316                        $idNotif = $this->ajouter_notification(
5317                            $this->getVal($this->clePrimaire),
5318                            $this->f->get_connected_user_login_name(),
5319                            $demandeur,
5320                            $collectivite_di,
5321                            true
5322                        );
5323                        if ($idNotif === false) {
5324                            // Termine le traitement
5325                            return $this->end_treatment(__METHOD__, false);
5326                        }
5327                        $notification_by_task = $this->notification_by_task(
5328                            $idNotif,
5329                            $this->getVal('dossier'),
5330                            $categorie
5331                        );
5332                        if ($notification_by_task === false) {
5333                            $this->addToMessage(
5334                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
5335                            );
5336                            // Termine le traitement
5337                            return $this->end_treatment(__METHOD__, false);
5338                        }
5339                    }
5340                    $this->addToMessage($message .= sprintf('%s<br/>%s', __("La notification a été générée."), __("Le suivi de la notification est disponible depuis l'instruction.")));
5341                }
5342            }
5343    
5344          // Termine le traitement          // Termine le traitement
5345          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
5346      }      }
# Line 3261  class instruction extends instruction_ge Line 5388  class instruction extends instruction_ge
5388              && $this->getVal("om_final_instruction") != null) {              && $this->getVal("om_final_instruction") != null) {
5389    
5390              // Ouvre le document              // Ouvre le document
5391              $lien = '../spg/file.php?obj='.$this->table.'&'.              $lien = '../app/index.php?module=form&snippet=file&obj='.$this->table.'&'.
5392                      'champ=om_fichier_instruction&id='.$this->getVal($this->clePrimaire);                      'champ=om_fichier_instruction&id='.$this->getVal($this->clePrimaire);
5393              //              //
5394              header("Location: ".$lien);              header("Location: ".$lien);
# Line 3280  class instruction extends instruction_ge Line 5407  class instruction extends instruction_ge
5407                      "mode" => "previsualisation",                      "mode" => "previsualisation",
5408                  ),                  ),
5409              );              );
5410                // Si la rédaction libre est activée sur l'instruction
5411                if ($this->getVal("flag_edition_integrale") == 't') {
5412                    $params["specific"]["corps"] = array(
5413                        "mode" => "set",
5414                        "value" => $this->getVal("corps_om_htmletatex"),
5415                    );
5416                    $params["specific"]["titre"] = array(
5417                        "mode" => "set",
5418                        "value" => $this->getVal("titre_om_htmletat"),
5419                    );
5420                }
5421    
5422              // Génération du PDF              // Génération du PDF
5423              $result = $this->compute_pdf_output('lettretype', $this->getVal("lettretype"), $collectivite, null, $params);              $result = $this->compute_pdf_output('lettretype', $this->getVal("lettretype"), $collectivite, null, $params);
# Line 3294  class instruction extends instruction_ge Line 5432  class instruction extends instruction_ge
5432      /**      /**
5433       * Récupère la collectivité du dossier d'instruction.       * Récupère la collectivité du dossier d'instruction.
5434       *       *
5435         * @param string $dossier_instruction_id Identifiant du DI.
5436         *
5437       * @return integer       * @return integer
5438       */       */
5439      function get_dossier_instruction_om_collectivite() {      function get_dossier_instruction_om_collectivite($dossier_instruction_id = null) {
5440    
5441            // Si l'identifiant n'est pas renseigné
5442            if ($dossier_instruction_id === null) {
5443                // Récupère la valeur
5444                if ($this->getVal('dossier') !== null && $this->getVal('dossier') !== '') {
5445                    $dossier_instruction_id = $this->getVal('dossier');
5446                } elseif ($this->getParameter('idxformulaire') !== null
5447                    && $this->getParameter('idxformulaire') !== '') {
5448                    //
5449                    $dossier_instruction_id = $this->getParameter('idxformulaire');
5450                } elseif ($this->f->get_submitted_get_value('idxformulaire') !== null
5451                    && $this->f->get_submitted_get_value('idxformulaire') !== '') {
5452                    //
5453                    $dossier_instruction_id = $this->f->get_submitted_get_value('idxformulaire');
5454                }
5455            }
5456    
5457          //          //
5458          require_once "../obj/dossier_instruction.class.php";          $dossier_instruction = $this->f->get_inst__om_dbform(array(
5459          $dossier_instruction = new dossier_instruction($this->getVal('dossier'), $this->f->db, false);              "obj" => "dossier_instruction",
5460                "idx" => $dossier_instruction_id,
5461            ));
5462    
5463          //          //
5464          return $dossier_instruction->getVal('om_collectivite');          return $dossier_instruction->getVal('om_collectivite');
# Line 3317  class instruction extends instruction_ge Line 5475  class instruction extends instruction_ge
5475          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
5476          $this->checkAccessibility();          $this->checkAccessibility();
5477    
         // XXX APP  
   
         $f = $this->f;  
   
5478          /**          /**
5479           * Affichage de la structure HTML           * Affichage de la structure HTML
5480           */           */
5481          //          //
5482          if ($f->isAjaxRequest()) {          if ($this->f->isAjaxRequest()) {
5483              //              //
5484              header("Content-type: text/html; charset=".HTTPCHARSET."");              header("Content-type: text/html; charset=".HTTPCHARSET."");
5485          } else {          } else {
5486              //              //
5487              $f->setFlag("htmlonly");              $this->f->setFlag("htmlonly");
5488              $f->display();              $this->f->display();
5489          }          }
5490          //          //
5491          $f->displayStartContent();          $this->f->displayStartContent();
5492          //          //
5493          $f->setTitle(_("Liste des éléments de la bible en lien avec un evenement"));          $this->f->setTitle(_("Liste des éléments de la bible en lien avec un evenement"));
5494          $f->displayTitle();          $this->f->displayTitle();
5495    
5496          /**          /**
5497           *           *
5498           */           */
5499          //          //
5500          ($f->get_submitted_get_value("ev") ? $evenement = $f->get_submitted_get_value("ev") : $evenement = "");          ($this->f->get_submitted_get_value("ev") ? $evenement = $this->f->get_submitted_get_value("ev") : $evenement = "");
5501          $evenement = intval($evenement);          $evenement = intval($evenement);
5502          //          //
5503          ($f->get_submitted_get_value("idx") ? $idx = $f->get_submitted_get_value("idx") : $idx = "");          ($this->f->get_submitted_get_value("idx") ? $idx = $this->f->get_submitted_get_value("idx") : $idx = "");
5504          // Récupération du code du type de DA          // Récupération du code du type de DA
5505          $code_da_type = '';          $code_da_type = '';
5506          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {
5507              $code_da_type = $matches[0];              $code_da_type = $matches[0];
5508          }          }
5509          //          //
5510          ($f->get_submitted_get_value("complement") ? $complement = $f->get_submitted_get_value("complement") : $complement = "1");          ($this->f->get_submitted_get_value("complement") ? $complement = $this->f->get_submitted_get_value("complement") : $complement = "1");
5511    
5512          // Récupération de la collectivité du dossier          // Récupération de la collectivité du dossier
5513          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
5514          $dossier = new dossier($idx, $f->db, DEBUG);              "obj" => "dossier",
5515                "idx" => $idx,
5516            ));
5517    
5518          /**          /**
5519           *           *
# Line 3369  class instruction extends instruction_ge Line 5525  class instruction extends instruction_ge
5525              ON bible.dossier_autorisation_type=dossier_autorisation_type.dossier_autorisation_type              ON bible.dossier_autorisation_type=dossier_autorisation_type.dossier_autorisation_type
5526          LEFT JOIN ".DB_PREFIXE."om_collectivite          LEFT JOIN ".DB_PREFIXE."om_collectivite
5527              ON bible.om_collectivite = om_collectivite.om_collectivite              ON bible.om_collectivite = om_collectivite.om_collectivite
5528          WHERE evenement=".$evenement."          WHERE (evenement=".$evenement." OR evenement IS NULL)
5529              AND complement=".$complement."              AND (complement=".$complement." OR complement IS NULL)
5530              AND (bible.dossier_autorisation_type IS NULL              AND (bible.dossier_autorisation_type IS NULL
5531                  OR dossier_autorisation_type.code ='".$code_da_type."')                  OR dossier_autorisation_type.code ='".$code_da_type."')
5532              AND (om_collectivite.niveau = '2'              AND (om_collectivite.niveau = '2'
5533                  OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")                  OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")
5534          ORDER BY bible_lib ASC";          ORDER BY bible_lib ASC";
5535          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
5536          $f->addToLog(__METHOD__.": db->query(\"".$sql."\");", VERBOSE_MODE);          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\");", VERBOSE_MODE);
5537          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
5538          //          //
5539          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";
5540          //          //
# Line 3410  class instruction extends instruction_ge Line 5566  class instruction extends instruction_ge
5566              echo "\t</table>\n";              echo "\t</table>\n";
5567              //              //
5568              echo "<div class=\"formControls\">\n";              echo "<div class=\"formControls\">\n";
5569              $f->layout->display_form_button(array(              $this->f->layout->display_form_button(array(
5570                  "value" => _("Valider"),                  "value" => _("Valider"),
5571                  "onclick" => "bible_return('f2', 'complement".($complement == "1" ? "" : $complement)."_om_html'); return false;",                  "onclick" => "bible_return('f2', 'complement".($complement == "1" ? "" : $complement)."_om_html'); return false;",
5572              ));              ));
5573              $f->displayLinkJsCloseWindow();              $this->f->displayLinkJsCloseWindow();
5574              echo "</div>\n";              echo "</div>\n";
5575    
5576          } else {          } else {
5577              //              //
5578              $message_class = "error";              $message_class = "error";
5579              $message = _("Aucun element dans la bible pour l'evenement")." : ".$evenement;              $message = _("Aucun element dans la bible pour l'evenement")." : ".$evenement;
5580              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
5581              //              //
5582              echo "<div class=\"formControls\">\n";              echo "<div class=\"formControls\">\n";
5583              $f->displayLinkJsCloseWindow();              $this->f->displayLinkJsCloseWindow();
5584              echo "</div>\n";              echo "</div>\n";
5585          }          }
5586          //          //
# Line 3434  class instruction extends instruction_ge Line 5590  class instruction extends instruction_ge
5590           * Affichage de la structure HTML           * Affichage de la structure HTML
5591           */           */
5592          //          //
5593          $f->displayEndContent();          $this->f->displayEndContent();
5594      }      }
5595    
5596      /**      /**
# Line 3447  class instruction extends instruction_ge Line 5603  class instruction extends instruction_ge
5603      function view_bible_auto() {      function view_bible_auto() {
5604          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
5605          $this->checkAccessibility();          $this->checkAccessibility();
   
         // XXX APP  
   
         $f = $this->f;  
   
5606          //          //
5607          $f->disableLog();          $this->f->disableLog();
5608    
5609          $formatDate="AAAA-MM-JJ";          $formatDate="AAAA-MM-JJ";
5610    
5611          // Récupération des paramètres          // Récupération des paramètres
5612          $idx = $f->get_submitted_get_value('idx');          $idx = $this->f->get_submitted_get_value('idx');
5613          $evenement = $f->get_submitted_get_value('ev');          $evenement = $this->f->get_submitted_get_value('ev');
5614    
5615          // Initialisation de la variable de retour          // Initialisation de la variable de retour
5616          $retour['complement_om_html'] = '';          $retour['complement_om_html'] = '';
# Line 3467  class instruction extends instruction_ge Line 5618  class instruction extends instruction_ge
5618          $retour['complement3_om_html'] = '';          $retour['complement3_om_html'] = '';
5619          $retour['complement4_om_html'] = '';          $retour['complement4_om_html'] = '';
5620          // Vérification d'une consultation liée à l'événement          // Vérification d'une consultation liée à l'événement
5621          $consultation = $f->db->getOne(          $consultation = $this->f->db->getOne(
5622              "select consultation from ".DB_PREFIXE."evenement where evenement=".$evenement              "select consultation from ".DB_PREFIXE."evenement where evenement=".$evenement
5623          );          );
5624          $f->isDatabaseError($consultation);          $this->f->isDatabaseError($consultation);
5625          // Si consultation liée, récupération du retour d'avis          // Si consultation liée, récupération du retour d'avis
5626          if($consultation=='Oui'){          if($consultation=='Oui'){
5627              $sql="select date_retour,avis_consultation.libelle as avis_consultation,              $sql="select date_retour,avis_consultation.libelle as avis_consultation,
# Line 3479  class instruction extends instruction_ge Line 5630  class instruction extends instruction_ge
5630                    on consultation.service =service.service                    on consultation.service =service.service
5631                    left join ".DB_PREFIXE."avis_consultation on                    left join ".DB_PREFIXE."avis_consultation on
5632                      consultation.avis_consultation = avis_consultation.avis_consultation                      consultation.avis_consultation = avis_consultation.avis_consultation
5633                    where dossier ='".$idx."'";                    where dossier ='".$idx."' and consultation.visible";
5634              $res = $f->db->query($sql);              $res = $this->f->db->query($sql);
5635              $f->isDatabaseError($res);              $this->f->isDatabaseError($res);
5636              // Récupération des consultations              // Récupération des consultations
5637              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){
5638                  $correct=false;                  $correct=false;
# Line 3506  class instruction extends instruction_ge Line 5657  class instruction extends instruction_ge
5657                      $temp=$temp." du ".$date_retour_f;                      $temp=$temp." du ".$date_retour_f;
5658                  }                  }
5659                  // Concaténation des retours d'avis de consultation                  // Concaténation des retours d'avis de consultation
5660                  $retour['complement_om_html'] .= $temp;                  $retour['complement_om_html'] .= $temp . "<br/><br/>";
5661              } // while              } // while
5662                            
5663          } // consultation          } // consultation
5664          // Récupération des bibles automatiques pour le champ complement_om_html          // Récupération des bibles automatiques pour le champ complement_om_html
5665          $retour['complement_om_html'] .= $this->getBible($f, $evenement, $idx, '1');          $retour['complement_om_html'] .= $this->getBible($evenement, $idx, '1');
5666          // Récupération des bibles automatiques pour le champ complement2_om_html          // Récupération des bibles automatiques pour le champ complement2_om_html
5667          $retour['complement2_om_html'] .= $this->getBible($f, $evenement, $idx, '2');          $retour['complement2_om_html'] .= $this->getBible($evenement, $idx, '2');
5668          // Récupération des bibles automatiques pour le champ complement3_om_html          // Récupération des bibles automatiques pour le champ complement3_om_html
5669          $retour['complement3_om_html'] .= $this->getBible($f, $evenement, $idx, '3');          $retour['complement3_om_html'] .= $this->getBible($evenement, $idx, '3');
5670          // Récupération des bibles automatiques pour le champ complement4_om_html          // Récupération des bibles automatiques pour le champ complement4_om_html
5671          $retour['complement4_om_html'] .= $this->getBible($f, $evenement, $idx, '4');          $retour['complement4_om_html'] .= $this->getBible($evenement, $idx, '4');
5672    
5673    
5674    
# Line 3525  class instruction extends instruction_ge Line 5676  class instruction extends instruction_ge
5676      }      }
5677    
5678      /**      /**
5679         * VIEW - view_pdf_temp
5680         *
5681         * @return void
5682         */
5683        function view_pdf_temp() {
5684            $this->checkAccessibility();
5685            // Utilisation de $_POST pour ne pas que les textes soient altérés.
5686            $this->f->set_submitted_value();
5687            $merge_fields = array();
5688            //
5689            if (array_key_exists('c1', $_POST) === true) {
5690                $merge_fields['[complement_instruction]'] = urldecode($_POST['c1']);
5691                $merge_fields['[complement1_instruction]'] = urldecode($_POST['c1']);
5692            }
5693            if (array_key_exists('c2', $_POST) === true) {
5694                $merge_fields['[complement2_instruction]'] = urldecode($_POST['c2']);
5695            }
5696            if (array_key_exists('c3', $_POST) === true) {
5697                $merge_fields['[complement3_instruction]'] = urldecode($_POST['c3']);
5698            }
5699            if (array_key_exists('c4', $_POST) === true) {
5700                $merge_fields['[complement4_instruction]'] = urldecode($_POST['c4']);
5701            }
5702            $params = array(
5703                "watermark" => true,
5704                "specific" => array(
5705                    "merge_fields" => $merge_fields,
5706                ),
5707            );
5708            //
5709            if (array_key_exists('corps', $_POST) === true) {
5710                $params["specific"]["corps"] = array(
5711                    "mode" => "set",
5712                    "value" => urldecode($_POST['corps']),
5713                );
5714            }
5715            if (array_key_exists('titre', $_POST) === true) {
5716                $params["specific"]["titre"] = array(
5717                    "mode" => "set",
5718                    "value" => urldecode($_POST['titre']),
5719                );
5720            }
5721            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
5722            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
5723            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
5724            $retour = array(
5725                'base' => base64_encode($result['pdf_output']),
5726            );
5727            echo json_encode($retour);
5728        }
5729    
5730        /**
5731         * Dans le contexte de prévisualisation des éditions, génère le rendu du
5732         * PDF sans prise en compte de la valeur des compléments et le retourne en
5733         * base 64.
5734         *
5735         * @return string Rendu PDF converti en base 64.
5736         */
5737        function init_pdf_temp() {
5738            $params = array(
5739                "watermark" => true,
5740            );
5741            // Si la rédaction libre est activée sur l'instruction
5742            if ($this->getVal("flag_edition_integrale") == 't') {
5743                $params["specific"]["corps"] = array(
5744                    "mode" => "set",
5745                    "value" => $this->getVal("corps_om_htmletatex"),
5746                );
5747                $params["specific"]["titre"] = array(
5748                    "mode" => "set",
5749                    "value" => $this->getVal("titre_om_htmletat"),
5750                );
5751            }
5752            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
5753            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
5754            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
5755    
5756            return base64_encode($result['pdf_output']);
5757        }
5758    
5759        /**
5760       * Récupération des éléments de bible.       * Récupération des éléments de bible.
5761       *       *
      * @param utils   $f      handler de om_application  
5762       * @param integer $event  id de l'événement       * @param integer $event  id de l'événement
5763       * @param string  $idx    id du dossier       * @param string  $idx    id du dossier
5764       * @param integer $compnb numéro du champ complement       * @param integer $compnb numéro du champ complement
5765       *       *
5766       * @return string   Chaîne de texte à insérer dans le champ complement       * @return string   Chaîne de texte à insérer dans le champ complement
5767       */       */
5768      function getBible($f, $event, $idx, $compnb) {      function getBible($event, $idx, $compnb) {
5769          // Récupération de la collectivité du dossier          // Récupération de la collectivité du dossier
5770          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
5771          $dossier = new dossier($idx, $f->db, DEBUG);              "obj" => "dossier",
5772                "idx" => $idx,
5773            ));
5774          // Récupération du code du type de DA          // Récupération du code du type de DA
5775          $code_da_type = '';          $code_da_type = '';
5776          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {
# Line 3551  class instruction extends instruction_ge Line 5784  class instruction extends instruction_ge
5784              LEFT JOIN              LEFT JOIN
5785                      ".DB_PREFIXE."om_collectivite                      ".DB_PREFIXE."om_collectivite
5786                      ON bible.om_collectivite = om_collectivite.om_collectivite                      ON bible.om_collectivite = om_collectivite.om_collectivite
5787              WHERE evenement =".$event." and              WHERE (evenement =".$event." or evenement IS NULL) and
5788                  complement=".$compnb." and                  (complement=".$compnb." OR complement IS NULL) and
5789                  automatique='Oui' and                  automatique='Oui' and
5790                  (dossier_autorisation_type.code ='".$code_da_type."' or                  (dossier_autorisation_type.code ='".$code_da_type."' or
5791                      bible.dossier_autorisation_type IS NULL) and                      bible.dossier_autorisation_type IS NULL) and
5792                  (om_collectivite.niveau = '2' OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")";                  (om_collectivite.niveau = '2' OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")";
5793    
5794          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
5795          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
5796          $temp = "";          $temp = "";
5797          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){
5798              // Remplacement des retours à la ligne par des br              // Remplacement des retours à la ligne par des br
5799              $temp .= preg_replace(              $temp .= preg_replace(
5800                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']
5801              );              );
5802                // Ajout d'un saut de ligne entre chaque bible.
5803                $temp .= '<br/>';
5804          } // fin while          } // fin while
5805          return $temp;          return $temp;
5806      }      }
# Line 3583  class instruction extends instruction_ge Line 5818  class instruction extends instruction_ge
5818          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
5819          $this->checkAccessibility();          $this->checkAccessibility();
5820    
         // XXX APP  
   
         $f = $this->f;  
   
5821          /**          /**
5822           * Validation du formulaire           * Validation du formulaire
5823           */           */
5824          // Si le formulaire a été validé          // Si le formulaire a été validé
5825          if ($f->get_submitted_post_value("validation") !== null) {          if ($this->f->get_submitted_post_value("validation") !== null) {
5826              // Si un bordereau à été sélectionné              // Si un bordereau à été sélectionné
5827              if ($f->get_submitted_post_value("bordereau") !== null && $f->get_submitted_post_value("bordereau") == "" ) {              if ($this->f->get_submitted_post_value("bordereau") !== null && $this->f->get_submitted_post_value("bordereau") == "" ) {
5828                  // Si aucun bordereau n'a été sélectionné                  // Si aucun bordereau n'a été sélectionné
5829                  $message_class = "error";                  $message_class = "error";
5830                  $message = _("Veuillez selectionner un bordereau.");                  $message = _("Veuillez selectionner un bordereau.");
5831              }              }
5832              // Sinon si les dates ne sont pas valide              // Sinon si les dates ne sont pas valide
5833              elseif (($f->get_submitted_post_value("date_bordereau_debut") !== null              elseif (($this->f->get_submitted_post_value("date_bordereau_debut") !== null
5834                  && $f->get_submitted_post_value("date_bordereau_debut") == "")                  && $this->f->get_submitted_post_value("date_bordereau_debut") == "")
5835                  || ($f->get_submitted_post_value("date_bordereau_fin") !== null                  || ($this->f->get_submitted_post_value("date_bordereau_fin") !== null
5836                  && $f->get_submitted_post_value("date_bordereau_fin") == "")) {                  && $this->f->get_submitted_post_value("date_bordereau_fin") == "")) {
5837                  // Si aucune date n'a été saisie                  // Si aucune date n'a été saisie
5838                  $message_class = "error";                  $message_class = "error";
5839                  $message = _("Veuillez saisir une date valide.");                  $message = _("Veuillez saisir une date valide.");
5840              }              }
5841                // Sinon si les dates ne sont pas valides
5842                elseif ($this->f->get_submitted_post_value("bordereau") === "bordereau_avis_maire_prefet"
5843                    && $this->f->getParameter("id_evenement_bordereau_avis_maire_prefet") == null) {
5844                    // Si aucune date n'a été saisie
5845                    $message_class = "error";
5846                    $message = _("Erreur de parametrage. Contactez votre administrateur.");
5847                }
5848              // Affiche le message de validation              // Affiche le message de validation
5849              else {              else {
5850                  // On récupère le libellé du bordereau pour l'afficher à l'utilisateur                  // On récupère le libellé du bordereau pour l'afficher à l'utilisateur
5851                  $sql = "SELECT om_etat.libelle                  $sql = "SELECT om_etat.libelle
5852                  FROM ".DB_PREFIXE."om_etat                  FROM ".DB_PREFIXE."om_etat
5853                  WHERE om_etat.id = '".$f->get_submitted_post_value("bordereau")."'";                  WHERE om_etat.id = '".$this->f->get_submitted_post_value("bordereau")."'";
5854                  $res = $f->db->getone($sql);                  $res = $this->f->db->getone($sql);
5855                  $f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);
5856                  $f->isDatabaseError($res);                  $this->f->isDatabaseError($res);
5857                  //                  //
5858                  $message_class = "valid";                  $message_class = "valid";
5859                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");
5860                  $message .= " : <br/><br/>";                  $message .= " : <br/><br/>";
5861                  $message .= "<a class='om-prev-icon pdf-16'";                  $message .= "<a class='om-prev-icon pdf-16'";
5862                  $message .= " title=\""._("Bordereau")."\"";                  $message .= " title=\""._("Bordereau")."\"";
5863                  $message .= "href='../scr/form.php?obj=instruction";                  $message .= "href='".OM_ROUTE_FORM."&obj=instruction";
5864                  $message .= "&action=220";                  $message .= "&action=220";
5865                  $message .= "&idx=0";                  $message .= "&idx=0";
5866                  $message .= "&type_bordereau=".$f->get_submitted_post_value("bordereau");                  $message .= "&type_bordereau=".$this->f->get_submitted_post_value("bordereau");
5867                  $message .= "&date_bordereau_debut=".$f->get_submitted_post_value("date_bordereau_debut");                  $message .= "&date_bordereau_debut=".$this->f->get_submitted_post_value("date_bordereau_debut");
5868                  $message .= "&date_bordereau_fin=".$f->get_submitted_post_value("date_bordereau_fin");                  $message .= "&date_bordereau_fin=".$this->f->get_submitted_post_value("date_bordereau_fin");
5869                  // Si l'utilisateur est MULTI alors on ajoute le paramètre collectivite                  // Si l'utilisateur est MULTI alors on ajoute le paramètre collectivite
5870                  if ($f->get_submitted_post_value("om_collectivite") !== null) {                  if ($this->f->get_submitted_post_value("om_collectivite") !== null) {
5871                      $message .= "&collectivite=".$f->get_submitted_post_value("om_collectivite");                      $message .= "&collectivite=".$this->f->get_submitted_post_value("om_collectivite");
5872                  }                  }
5873                  $message .= "'"." target='_blank'>";                  $message .= "'"." target='_blank'>";
5874                  $message .= $res." "._("du")." ".$f->get_submitted_post_value("date_bordereau_debut")                  $message .= $res." "._("du")." ".$this->f->get_submitted_post_value("date_bordereau_debut")
5875                      ." "._("au")." ".$f->get_submitted_post_value("date_bordereau_fin");                      ." "._("au")." ".$this->f->get_submitted_post_value("date_bordereau_fin");
5876                  $message .= "</a>";                  $message .= "</a>";
5877              }              }
5878          }          }
# Line 3644  class instruction extends instruction_ge Line 5882  class instruction extends instruction_ge
5882           */           */
5883          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
5884          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
5885              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
5886          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
5887          // Ouverture du formulaire          // Ouverture du formulaire
5888          printf("\t<form");          printf("\t<form");
5889          printf(" method=\"post\"");          printf(" method=\"post\"");
# Line 3656  class instruction extends instruction_ge Line 5892  class instruction extends instruction_ge
5892          printf(">\n");          printf(">\n");
5893          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
5894          $champs = array("date_bordereau_debut", "date_bordereau_fin", "bordereau");          $champs = array("date_bordereau_debut", "date_bordereau_fin", "bordereau");
5895          // Si l'utilisateur est d'une collectivité de niveau 2 on affiche un select          // Si l'utilisateur est d'une collectivité de niveau 2 on affiche un select
5896          // collectivité dans le formulaire          // collectivité dans le formulaire
5897          if($_SESSION["niveau"] == 2) {          if ($_SESSION["niveau"] == 2) {
5898              array_push($champs, "om_collectivite");              array_push($champs, "om_collectivite");
5899          }          }
5900          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
5901          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
5902                "validation" => 0,
5903                "maj" => 0,
5904                "champs" => $champs,
5905            ));
5906          // Paramétrage du champ date_bordereau_debut          // Paramétrage du champ date_bordereau_debut
5907          $form->setLib("date_bordereau_debut", _("date_bordereau_debut"));          $form->setLib("date_bordereau_debut", _("date_bordereau_debut"));
5908          $form->setType("date_bordereau_debut", "date");          $form->setType("date_bordereau_debut", "date");
# Line 3684  class instruction extends instruction_ge Line 5924  class instruction extends instruction_ge
5924          $form->setType("bordereau", "select");          $form->setType("bordereau", "select");
5925          $form->setRequired("bordereau");          $form->setRequired("bordereau");
5926          // Valeurs des champs          // Valeurs des champs
5927          if ($f->get_submitted_post_value("validation") !== null) {          if ($this->f->get_submitted_post_value("validation") !== null) {
5928              $form->setVal("date_bordereau_debut", $f->get_submitted_post_value("date_bordereau_debut"));              $form->setVal("date_bordereau_debut", $this->f->get_submitted_post_value("date_bordereau_debut"));
5929              $form->setVal("date_bordereau_fin", $f->get_submitted_post_value("date_bordereau_fin"));              $form->setVal("date_bordereau_fin", $this->f->get_submitted_post_value("date_bordereau_fin"));
5930              $form->setVal("bordereau", $f->get_submitted_post_value("bordereau"));              $form->setVal("bordereau", $this->f->get_submitted_post_value("bordereau"));
5931              $form->setVal("om_collectivite", $f->get_submitted_post_value("om_collectivite"));              $form->setVal("om_collectivite", $this->f->get_submitted_post_value("om_collectivite"));
5932          }          }
5933          // Données du select - On récupère ici la liste de tous les états disponibles          // Données du select - On récupère ici la liste de tous les états disponibles
5934          // dans la table om_etat qui ont un id qui commence par la cahine de caractères          // dans la table om_etat qui ont un id qui commence par la cahine de caractères
# Line 3697  class instruction extends instruction_ge Line 5937  class instruction extends instruction_ge
5937                  FROM ".DB_PREFIXE."om_etat                  FROM ".DB_PREFIXE."om_etat
5938                  WHERE om_etat.id LIKE 'bordereau_%'                  WHERE om_etat.id LIKE 'bordereau_%'
5939                  ORDER BY om_etat.id";                  ORDER BY om_etat.id";
5940          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
5941          $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
5942          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
5943          // Données du select          // Données du select
5944          $contenu = array(          $contenu = array(
5945              0 => array("", ),              0 => array("", ),
# Line 3710  class instruction extends instruction_ge Line 5950  class instruction extends instruction_ge
5950              $contenu[1][] = $row['libelle'];              $contenu[1][] = $row['libelle'];
5951          }          }
5952          $form->setSelect("bordereau", $contenu);          $form->setSelect("bordereau", $contenu);
5953      //          //
5954      if($_SESSION["niveau"] == 2) {          if ($_SESSION["niveau"] == 2) {
5955          $form->setLib("om_collectivite", _("collectivite"));              $form->setLib("om_collectivite", _("collectivite"));
5956          $form->setType("om_collectivite", "select");              $form->setType("om_collectivite", "select");
5957    
5958          // Données du select - On récupère ici la liste de tous toutes les collectivités              // Données du select - On récupère ici la liste de tous toutes les collectivités
5959          // de niveau 1              // de niveau 1
5960          $sql = "SELECT om_collectivite, libelle              $sql = "SELECT om_collectivite, libelle
5961                  FROM ".DB_PREFIXE."om_collectivite                      FROM ".DB_PREFIXE."om_collectivite
5962                  WHERE niveau = '1' ORDER BY libelle";                      WHERE niveau = '1' ORDER BY libelle";
5963          $res = $f->db->query($sql);              $res = $this->f->db->query($sql);
5964          $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
5965          $f->isDatabaseError($res);              $this->f->isDatabaseError($res);
5966          // La valeur par défaut du select est Toutes              // La valeur par défaut du select est Toutes
5967          $list_collectivites = array(              $list_collectivites = array(
5968              0 => array("", ),                  0 => array("", ),
5969              1 => array(_("toutes"))                  1 => array(_("toutes"))
5970          );              );
   
         $id_colls = "";  
         // On stocke dans $id_colls l'id de toutes les collectivités de niveau 1 séparées  
         // par des virgules, pour un traitement plus facile dans la requête de sous-état  
         while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {  
             if ($id_colls != "") {  
                 $id_colls .= ",";  
             }  
             $id_colls .= $row['om_collectivite'];  
             $list_collectivites[0][] = $row['om_collectivite'];  
             $list_collectivites[1][] = $row['libelle'];  
         }  
         // On affecte la liste d'identifiants à l'option Toutes  
         $list_collectivites[0][0] = $id_colls ;  
         $form->setSelect("om_collectivite", $list_collectivites);  
     }  
5971    
5972                $id_colls = "";
5973                // On stocke dans $id_colls l'id de toutes les collectivités de niveau 1 séparées
5974                // par des virgules, pour un traitement plus facile dans la requête de sous-état
5975                while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
5976                    if ($id_colls != "") {
5977                        $id_colls .= ",";
5978                    }
5979                    $id_colls .= $row['om_collectivite'];
5980                    $list_collectivites[0][] = $row['om_collectivite'];
5981                    $list_collectivites[1][] = $row['libelle'];
5982                }
5983                // On affecte la liste d'identifiants à l'option Toutes
5984                $list_collectivites[0][0] = $id_colls ;
5985                $form->setSelect("om_collectivite", $list_collectivites);
5986            }
5987          // Affichage du formulaire          // Affichage du formulaire
5988          $form->entete();          $form->entete();
5989          $form->afficher($champs, 0, false, false);          $form->afficher($champs, 0, false, false);
5990          $form->enpied();          $form->enpied();
5991          // Affichage du bouton          // Affichage du bouton
5992          printf("\t<div class=\"formControls\">\n");          printf("\t<div class=\"formControls\">\n");
5993          $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));          $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
5994          printf("\t</div>\n");          printf("\t</div>\n");
5995          // Fermeture du formulaire          // Fermeture du formulaire
5996          printf("\t</form>\n");          printf("\t</form>\n");
   
5997      }      }
5998    
5999    
# Line 3784  class instruction extends instruction_ge Line 6022  class instruction extends instruction_ge
6022      /**      /**
6023       * VIEW - view_suivi_envoi_lettre_rar.       * VIEW - view_suivi_envoi_lettre_rar.
6024       *       *
6025       * Vu pour imprimer les RAR.       * Vue pour imprimer les AR.
6026       *       *
6027       * @return void       * @return void
6028       */       */
# Line 3792  class instruction extends instruction_ge Line 6030  class instruction extends instruction_ge
6030          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6031          $this->checkAccessibility();          $this->checkAccessibility();
6032    
         // XXX APP  
   
         $f = $this->f;  
   
6033          //          //
6034          if ($f->get_submitted_post_value("date") !== null) {          if ($this->f->get_submitted_post_value("date") !== null) {
6035              $date = $f->get_submitted_post_value("date");              $date = $this->f->get_submitted_post_value("date");
6036          } else {          } else {
6037              $date = "";              $date = "";
6038          }          }
6039          //          //
6040          if ($f->get_submitted_post_value("liste_code_barres_instruction") !== null) {          if ($this->f->get_submitted_post_value("liste_code_barres_instruction") !== null) {
6041              $liste_code_barres_instruction = $f->get_submitted_post_value("liste_code_barres_instruction");              $liste_code_barres_instruction = $this->f->get_submitted_post_value("liste_code_barres_instruction");
6042          } else {          } else {
6043              $liste_code_barres_instruction = "";              $liste_code_barres_instruction = "";
6044          }          }
# Line 3830  class instruction extends instruction_ge Line 6064  class instruction extends instruction_ge
6064           * Validation du formulaire           * Validation du formulaire
6065           */           */
6066          // Si le formulaire a été validé          // Si le formulaire a été validé
6067          if ($f->get_submitted_post_value('validation') !== null) {          if ($this->f->get_submitted_post_value('validation') !== null) {
6068              //              //
6069              if (empty($date) || empty($liste_code_barres_instruction)) {              if (empty($date) || empty($liste_code_barres_instruction)) {
6070                  //                  //
# Line 3838  class instruction extends instruction_ge Line 6072  class instruction extends instruction_ge
6072                  $message = _("Tous les champs doivent etre remplis.");                  $message = _("Tous les champs doivent etre remplis.");
6073              } else {              } else {
6074                  // Création d'un tableau d'instruction                  // Création d'un tableau d'instruction
6075                  $liste = explode("\r\n", $f->get_submitted_post_value("liste_code_barres_instruction"));                  $liste = explode("\r\n", $this->f->get_submitted_post_value("liste_code_barres_instruction"));
6076                  //                  //
6077                  foreach ($liste as $code_barres) {                  foreach ($liste as $code_barres) {
6078                      // On enlève les éventuels espaces saisis                      // On enlève les éventuels espaces saisis
# Line 3848  class instruction extends instruction_ge Line 6082  class instruction extends instruction_ge
6082                          // Si la valeur transmise est numérique                          // Si la valeur transmise est numérique
6083                          if (is_numeric($code_barres)) {                          if (is_numeric($code_barres)) {
6084                              //                              //
6085                              $sql = "SELECT count(*) FROM ".DB_PREFIXE."instruction WHERE code_barres='".$code_barres."'";                              $sql = "SELECT count(*)
6086                              $nbInstr = $f->db->getone($sql);                                      FROM ".DB_PREFIXE."instruction
6087                              $f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                                          INNER JOIN ".DB_PREFIXE."dossier
6088                              $f->isDatabaseError($nbInstr);                                              ON dossier.dossier=instruction.dossier
6089                                            INNER JOIN ".DB_PREFIXE."dossier_instruction_type
6090                                                ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
6091                                            INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
6092                                                ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
6093                                            INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
6094                                                ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
6095                                            INNER JOIN ".DB_PREFIXE."groupe
6096                                                ON dossier_autorisation_type.groupe = groupe.groupe
6097                                            WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";
6098                                            
6099                                // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès
6100                                $group_clause = array();
6101                                foreach ($_SESSION["groupe"] as $key => $value) {
6102                                    $group_clause[$key] = "(groupe.code = '".$key."'";
6103                                    if($value["confidentiel"] !== true) {
6104                                        $group_clause[$key] .= " AND dossier_autorisation_type.confidentiel IS NOT TRUE";
6105                                    }
6106                                    $group_clause[$key] .= ")";
6107                                }
6108                                $conditions = implode(" OR ", $group_clause);
6109                                $sql .= " AND (" . $conditions . ")";
6110    
6111                                $nbInstr = $this->f->db->getone($sql);
6112                                $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);
6113                                $this->f->isDatabaseError($nbInstr);
6114                              //                              //
6115                              if ($nbInstr == "1") {                              if ($nbInstr == "1") {
6116                                  // Récupération de la date d'envoi de l'instruction bippé                                  // Récupération de la date d'envoi de l'instruction bippé
6117                                  $sql = "SELECT to_char(date_envoi_rar,'DD/MM/YYYY')  as date_envoi_rar, instruction FROM ".DB_PREFIXE."instruction WHERE code_barres='".$code_barres."'";                                  $sql = "SELECT to_char(date_envoi_rar,'DD/MM/YYYY')  as date_envoi_rar, instruction FROM ".DB_PREFIXE."instruction WHERE code_barres='".$code_barres."'";
6118                                  $res = $f->db->query($sql);                                  $res = $this->f->db->query($sql);
6119                                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
6120                                  $f->isDatabaseError($res);                                  $this->f->isDatabaseError($res);
6121                                  $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);                                  $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);
6122                                  // Si pas de date ou correspond à la date du formulaire on                                  // Si pas de date ou correspond à la date du formulaire on
6123                                  // effectue le traitement                                  // effectue le traitement
6124                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {
6125                                                                            $instr = $this->f->get_inst__om_dbform(array(
6126                                      require_once '../obj/instruction.class.php';                                          "obj" => "instruction",
6127                                      require_once '../obj/dossier.class.php';                                          "idx" => $row['instruction'],
6128                                                                ));
                                     $instr = new instruction($row['instruction'], $f->db, DEBUG);  
6129                                      $valF = array();                                      $valF = array();
6130                                      foreach($instr->champs as $id => $champ) {                                      foreach($instr->champs as $id => $champ) {
6131                                          $valF[$champ] = $instr->val[$id];                                          $valF[$champ] = $instr->val[$id];
# Line 3876  class instruction extends instruction_ge Line 6134  class instruction extends instruction_ge
6134                                      # Si on peut consulter les dossiers et que le dossier n'existe pas déjà dans la liste                                      # Si on peut consulter les dossiers et que le dossier n'existe pas déjà dans la liste
6135                                      if ($isAccredited === true                                      if ($isAccredited === true
6136                                          && array_key_exists($instr->getVal("dossier"), $dossierTab) === false) {                                          && array_key_exists($instr->getVal("dossier"), $dossierTab) === false) {
6137                                          $dossier = new dossier($instr->getVal("dossier"));                                          $dossier = $this->f->get_inst__om_dbform(array(
6138                                                "obj" => "dossier",
6139                                                "idx" => $instr->getVal("dossier"),
6140                                            ));
6141                                          if ($dossier->is_user_from_allowed_collectivite()){                                          if ($dossier->is_user_from_allowed_collectivite()){
6142                                              $dossierTab[$instr->getVal("dossier")] = $dossier;                                              $dossierTab[$instr->getVal("dossier")] = $dossier;
6143                                          } else {                                          } else {
# Line 3922  class instruction extends instruction_ge Line 6183  class instruction extends instruction_ge
6183                                          $instr->dateDBToForm($valF['date_envoi_controle_legalite']);                                          $instr->dateDBToForm($valF['date_envoi_controle_legalite']);
6184                                      $valF['date_retour_controle_legalite']=                                      $valF['date_retour_controle_legalite']=
6185                                          $instr->dateDBToForm($valF['date_retour_controle_legalite']);                                          $instr->dateDBToForm($valF['date_retour_controle_legalite']);
   
6186                                      $valF['date_envoi_rar'] = $date;                                      $valF['date_envoi_rar'] = $date;
6187    
6188                                      // Vérification de la finalisation du document                                      // Vérification de la finalisation du document
# Line 3931  class instruction extends instruction_ge Line 6191  class instruction extends instruction_ge
6191                                          $instr->setParameter('maj', 1);                                          $instr->setParameter('maj', 1);
6192                                          $instr->class_actions[1]["identifier"] =                                          $instr->class_actions[1]["identifier"] =
6193                                              "envoi lettre RAR (depuis le menu suivi des pièces)";                                              "envoi lettre RAR (depuis le menu suivi des pièces)";
6194                                          if ($instr->modifier($valF, $f->db, DEBUG) == true) {                                          if ($instr->modifier($valF) == true) {
6195                                              $id4Gen[] = $code_barres;                                              $id4Gen[] = $code_barres;
6196                                              $nbLettres ++;                                              $nbLettres ++;
6197                                          } else {                                          } else {
# Line 3986  class instruction extends instruction_ge Line 6246  class instruction extends instruction_ge
6246           */           */
6247          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
6248          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
6249              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
6250          }          }
6251          // Affichage du message d'erreur          // Affichage du message d'erreur
6252          if(!empty($error)) {          if(!empty($error)) {
6253              $f->displayMessage("error", $error);              $this->f->displayMessage("error", $error);
6254          }          }
6255          // Affichage du message de validation de la saisie          // Affichage du message de validation de la saisie
6256          if ($nbLettres > 0) {          if ($nbLettres > 0) {
# Line 4002  class instruction extends instruction_ge Line 6262  class instruction extends instruction_ge
6262              echo _("Cliquez sur le lien ci-dessous pour telecharger votre document");              echo _("Cliquez sur le lien ci-dessous pour telecharger votre document");
6263              echo " : \n<br/><br/>";              echo " : \n<br/><br/>";
6264              echo "\n<a class='om-prev-icon pdf-16'";              echo "\n<a class='om-prev-icon pdf-16'";
6265              echo "\n title=\""._("imprimer les RAR")."\"";              echo "\n title=\""._("imprimer les AR")."\"";
6266              echo "\n href=\"../scr/form.php?obj=instruction&action=180&idx=0&liste=".implode(",",$id4Gen)."\"";              echo "\n href=\"".OM_ROUTE_FORM."&obj=instruction&action=180&idx=0&liste=".implode(",",$id4Gen)."\"";
6267              echo "\n target='_blank'>";              echo "\n target='_blank'>";
6268              echo _("Telecharger le document pour")." ".$nbLettres." "._("RAR");              echo _("Telecharger le document pour")." ".$nbLettres." "._("AR");
6269              echo "\n</a>";              echo "\n</a>";
6270              echo "\n</span>";              echo "\n</span>";
6271              echo "\n</p>";              echo "\n</p>";
# Line 4027  class instruction extends instruction_ge Line 6287  class instruction extends instruction_ge
6287                      echo "\n<br/>";                      echo "\n<br/>";
6288                  }                  }
6289                  foreach ($dossierTab as $dossier) {                  foreach ($dossierTab as $dossier) {
6290                      
6291                        $inst_da = $this->get_inst_common("dossier_autorisation", $dossier->getVal('dossier_autorisation'));
6292                        $inst_datd = $this->get_inst_common("dossier_autorisation_type_detaille", $inst_da->getVal('dossier_autorisation_type_detaille'));
6293                        $code_datd = $inst_datd->getVal('code');
6294    
6295                        $obj = "dossier_instruction";
6296                        if ($code_datd === 'REC' OR $code_datd === 'REG') {
6297                            $obj = "dossier_contentieux_tous_recours";
6298                        }
6299                        if ($code_datd === 'IN') {
6300                            $obj = "dossier_contentieux_toutes_infractions";
6301                        }
6302    
6303                      echo "\n<div class=\"bloc group\">";                      echo "\n<div class=\"bloc group\">";
6304                      echo "\n<div class=\"field field-type-text\">";                      echo "\n<div class=\"field field-type-text\">";
6305    
6306                      echo "\n<p>";                      echo "\n<p>";
6307                      echo "\n<span class='text'>";                      echo "\n<span class='text'>";
6308                      echo "\n<a class=\"om-icon om-icon-16 consult-16\" title=\"" . _('Consulter') . "\"";                      echo "\n<a class=\"om-icon om-icon-16 consult-16\" title=\"" . _('Consulter') . "\"";
6309                      echo "\n href=\"../scr/form.php?obj=dossier_instruction&action=3&idx=";                      echo "\n href=\"".OM_ROUTE_FORM."&obj=dossier_instruction&action=3&idx=";
6310                      echo $dossier->getVal("dossier");                      echo $dossier->getVal("dossier");
6311                      echo "\">";                      echo "\">";
6312                      echo "\n</a>";                      echo "\n</a>";
6313    
6314                      echo "\n<a title=\""._("Consulter")."\" style=\"vertical-align:middle;\"";                      echo "\n<a title=\""._("Consulter")."\" style=\"vertical-align:middle;\"";
6315                      echo " href=\"../scr/form.php?obj=dossier_instruction&action=3&idx=";                      echo " href=\"".OM_ROUTE_FORM."&obj=";
6316                        echo $obj;
6317                        echo "&action=3&idx=";
6318                      echo $dossier->getVal("dossier");                      echo $dossier->getVal("dossier");
6319                      echo "\">";                      echo "\">";
6320                      echo $dossier->getVal("dossier_libelle");                      echo $dossier->getVal("dossier_libelle");
# Line 4056  class instruction extends instruction_ge Line 6331  class instruction extends instruction_ge
6331              echo "\n</div>";              echo "\n</div>";
6332              echo "\n</div>";              echo "\n</div>";
6333          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
6334          // Ouverture du formulaire          // Ouverture du formulaire
6335          echo "\t<form";          echo "\t<form";
6336          echo " method=\"post\"";          echo " method=\"post\"";
# Line 4067  class instruction extends instruction_ge Line 6340  class instruction extends instruction_ge
6340          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
6341          $champs = array("date", "liste_code_barres_instruction");          $champs = array("date", "liste_code_barres_instruction");
6342          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
6343          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
6344                "validation" => 0,
6345                "maj" => 0,
6346                "champs" => $champs,
6347            ));
6348          // Paramétrage du champ date du formulaire          // Paramétrage du champ date du formulaire
6349          $form->setLib("date", _("Date")."* :");          $form->setLib("date", _("Date")."* :");
6350          $form->setType("date", "date");          $form->setType("date", "date");
# Line 4087  class instruction extends instruction_ge Line 6364  class instruction extends instruction_ge
6364          $form->enpied();          $form->enpied();
6365          // Affichage du bouton          // Affichage du bouton
6366          echo "\t<div class=\"formControls\">\n";          echo "\t<div class=\"formControls\">\n";
6367          $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));          $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
6368          echo "\t</div>\n";          echo "\t</div>\n";
6369          // Fermeture du formulaire          // Fermeture du formulaire
6370          echo "\t</form>\n";          echo "\t</form>\n";
# Line 4104  class instruction extends instruction_ge Line 6381  class instruction extends instruction_ge
6381          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6382          $this->checkAccessibility();          $this->checkAccessibility();
6383    
         // XXX APP  
   
         $f = $this->f;  
   
6384          // Récupération des valeur passées en POST ou GET          // Récupération des valeur passées en POST ou GET
6385          if($f->get_submitted_post_value("type_mise_a_jour") !== null) {          if($this->f->get_submitted_post_value("type_mise_a_jour") !== null) {
6386              $type_mise_a_jour = $f->get_submitted_post_value("type_mise_a_jour");              $type_mise_a_jour = $this->f->get_submitted_post_value("type_mise_a_jour");
6387          } elseif($f->get_submitted_get_value('type_mise_a_jour') !== null) {          } elseif($this->f->get_submitted_get_value('type_mise_a_jour') !== null) {
6388              $type_mise_a_jour = $f->get_submitted_get_value('type_mise_a_jour');              $type_mise_a_jour = $this->f->get_submitted_get_value('type_mise_a_jour');
6389          } else {          } else {
6390              $type_mise_a_jour = "";              $type_mise_a_jour = "";
6391          }          }
6392          if($f->get_submitted_post_value('date') !== null) {          if($this->f->get_submitted_post_value('date') !== null) {
6393              $date = $f->get_submitted_post_value('date');              $date = $this->f->get_submitted_post_value('date');
6394          } elseif($f->get_submitted_get_value('date') !== null) {          } elseif($this->f->get_submitted_get_value('date') !== null) {
6395              $date = $f->get_submitted_get_value('date');              $date = $this->f->get_submitted_get_value('date');
6396          } else {          } else {
6397              $date = "";              $date = "";
6398          }          }
6399          if($f->get_submitted_post_value('code_barres') !== null) {          if($this->f->get_submitted_post_value('code_barres') !== null) {
6400              $code_barres = $f->get_submitted_post_value('code_barres');              $code_barres = $this->f->get_submitted_post_value('code_barres');
6401          } elseif($f->get_submitted_get_value('code_barres') !== null) {          } elseif($this->f->get_submitted_get_value('code_barres') !== null) {
6402              $code_barres = $f->get_submitted_get_value('code_barres');              $code_barres = $this->f->get_submitted_get_value('code_barres');
6403          } else {          } else {
6404              $code_barres = "";              $code_barres = "";
6405          }          }
# Line 4138  class instruction extends instruction_ge Line 6411  class instruction extends instruction_ge
6411          $liste_champs=array();          $liste_champs=array();
6412    
6413          // Si le formulaire a été validé          // Si le formulaire a été validé
6414          if ($f->get_submitted_post_value('validation') !== null) {          if ($this->f->get_submitted_post_value('validation') !== null) {
6415              if(!empty($type_mise_a_jour) and !empty($date) and !empty($code_barres)) {              if(!empty($type_mise_a_jour) and !empty($date) and !empty($code_barres)) {
6416    
6417                  //Vérification de l'existance de l'instruction                  // Vérification de l'existence de l'instruction
6418                  $sql = "SELECT instruction FROM ".DB_PREFIXE."instruction WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";                  $sql = "SELECT instruction
6419                  $res = $f->db->query($sql);                          FROM ".DB_PREFIXE."instruction
6420                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                              INNER JOIN ".DB_PREFIXE."dossier
6421                  $f->isDatabaseError($res);                                  ON dossier.dossier=instruction.dossier
6422                                INNER JOIN ".DB_PREFIXE."dossier_instruction_type
6423                                    ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
6424                                INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
6425                                    ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
6426                                INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
6427                                    ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
6428                                INNER JOIN ".DB_PREFIXE."groupe
6429                                    ON dossier_autorisation_type.groupe = groupe.groupe
6430                                WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";
6431    
6432                    // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès
6433                    $group_clause = array();
6434                    foreach ($_SESSION["groupe"] as $key => $value) {
6435                        $group_clause[$key] = "(groupe.code = '".$key."'";
6436                        if($value["confidentiel"] !== true) {
6437                            $group_clause[$key] .= " AND dossier_autorisation_type.confidentiel IS NOT TRUE";
6438                        }
6439                        $group_clause[$key] .= ")";
6440                    }
6441                    $conditions = implode(" OR ", $group_clause);
6442                    $sql .= " AND (" . $conditions . ")";
6443    
6444    
6445                    $res = $this->f->db->query($sql);
6446                    $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
6447                    $this->f->isDatabaseError($res);
6448    
6449                  if($res->numrows() == 1) {                  if($res->numrows() == 1) {
6450                      $liste_champs = explode(";", $type_mise_a_jour);                      $liste_champs = explode(";", $type_mise_a_jour);
6451                        $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);
6452                        $instr = $this->f->get_inst__om_dbform(array(
6453                            "obj" => "instruction",
6454                            "idx" => $row['instruction'],
6455                        ));
6456                      // Mise à jour des dates après l'écran de verification                      // Mise à jour des dates après l'écran de verification
6457                      if($f->get_submitted_post_value('is_valid') !== null and $f->get_submitted_post_value('is_valid') == "true") {                      if($this->f->get_submitted_post_value('is_valid') !== null and $this->f->get_submitted_post_value('is_valid') == "true") {
                         require_once '../obj/instruction.class.php';  
                         $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);  
                         $instr = new instruction($row['instruction'], $f->db, DEBUG);  
6458                          $valF = array();                          $valF = array();
6459                          foreach($instr->champs as $id => $champ) {                          foreach($instr->champs as $id => $champ) {
6460                              $valF[$champ] = $instr->val[$id];                              $valF[$champ] = $instr->val[$id];
6461                          }                          }
6462                          $valF['date_evenement']=$instr->dateDBToForm($valF['date_evenement']);                          $valF['date_evenement'] = $instr->dateDBToForm($valF['date_evenement']);
6463                          $valF['archive_date_complet']=$instr->dateDBToForm($valF['archive_date_complet']);                          $valF['archive_date_complet'] = $instr->dateDBToForm($valF['archive_date_complet']);
6464                          $valF['archive_date_rejet']=$instr->dateDBToForm($valF['archive_date_rejet']);                          $valF['archive_date_rejet'] = $instr->dateDBToForm($valF['archive_date_rejet']);
6465                          $valF['archive_date_limite']=$instr->dateDBToForm($valF['archive_date_limite']);                          $valF['archive_date_limite'] = $instr->dateDBToForm($valF['archive_date_limite']);
6466                          $valF['archive_date_notification_delai']=$instr->dateDBToForm($valF['archive_date_notification_delai']);                          $valF['archive_date_notification_delai'] = $instr->dateDBToForm($valF['archive_date_notification_delai']);
6467                          $valF['archive_date_decision']=$instr->dateDBToForm($valF['archive_date_decision']);                          $valF['archive_date_decision'] = $instr->dateDBToForm($valF['archive_date_decision']);
6468                          $valF['archive_date_validite']=$instr->dateDBToForm($valF['archive_date_validite']);                          $valF['archive_date_validite'] = $instr->dateDBToForm($valF['archive_date_validite']);
6469                          $valF['archive_date_achevement']=$instr->dateDBToForm($valF['archive_date_achevement']);                          $valF['archive_date_achevement'] = $instr->dateDBToForm($valF['archive_date_achevement']);
6470                          $valF['archive_date_chantier']=$instr->dateDBToForm($valF['archive_date_chantier']);                          $valF['archive_date_chantier'] = $instr->dateDBToForm($valF['archive_date_chantier']);
6471                          $valF['archive_date_conformite']=$instr->dateDBToForm($valF['archive_date_conformite']);                          $valF['archive_date_conformite'] = $instr->dateDBToForm($valF['archive_date_conformite']);
6472                          $valF['archive_date_dernier_depot']=$instr->dateDBToForm($valF['archive_date_dernier_depot']);                          $valF['archive_date_dernier_depot'] = $instr->dateDBToForm($valF['archive_date_dernier_depot']);
6473                          $valF['archive_date_limite_incompletude']=$instr->dateDBToForm($valF['archive_date_limite_incompletude']);                          $valF['archive_date_limite_incompletude'] = $instr->dateDBToForm($valF['archive_date_limite_incompletude']);
6474                          $valF['date_finalisation_courrier']=$instr->dateDBToForm($valF['date_finalisation_courrier']);                          $valF['date_finalisation_courrier'] = $instr->dateDBToForm($valF['date_finalisation_courrier']);
6475                          $valF['date_envoi_signature']=$instr->dateDBToForm($valF['date_envoi_signature']);                          $valF['date_envoi_signature'] = $instr->dateDBToForm($valF['date_envoi_signature']);
6476                          $valF['date_retour_signature']=$instr->dateDBToForm($valF['date_retour_signature']);                          $valF['date_retour_signature'] = $instr->dateDBToForm($valF['date_retour_signature']);
6477                          $valF['date_envoi_rar']=$instr->dateDBToForm($valF['date_envoi_rar']);                          $valF['date_envoi_rar'] = $instr->dateDBToForm($valF['date_envoi_rar']);
6478                          $valF['date_retour_rar']=$instr->dateDBToForm($valF['date_retour_rar']);                          $valF['date_retour_rar'] = $instr->dateDBToForm($valF['date_retour_rar']);
6479                          $valF['date_envoi_controle_legalite']=$instr->dateDBToForm($valF['date_envoi_controle_legalite']);                          $valF['date_envoi_controle_legalite'] = $instr->dateDBToForm($valF['date_envoi_controle_legalite']);
6480                          $valF['date_retour_controle_legalite']=$instr->dateDBToForm($valF['date_retour_controle_legalite']);                          $valF['date_retour_controle_legalite'] = $instr->dateDBToForm($valF['date_retour_controle_legalite']);
6481                            $valF['archive_date_cloture_instruction'] = $instr->dateDBToForm($valF['archive_date_cloture_instruction']);
6482                            $valF['archive_date_premiere_visite'] = $instr->dateDBToForm($valF['archive_date_premiere_visite']);
6483                            $valF['archive_date_derniere_visite'] = $instr->dateDBToForm($valF['archive_date_derniere_visite']);
6484                            $valF['archive_date_contradictoire'] = $instr->dateDBToForm($valF['archive_date_contradictoire']);
6485                            $valF['archive_date_retour_contradictoire'] = $instr->dateDBToForm($valF['archive_date_retour_contradictoire']);
6486                            $valF['archive_date_ait'] = $instr->dateDBToForm($valF['archive_date_ait']);
6487                            $valF['archive_date_transmission_parquet'] = $instr->dateDBToForm($valF['archive_date_transmission_parquet']);
6488    
6489                          foreach(explode(";", $type_mise_a_jour) as $maj_date) {                          foreach(explode(";", $type_mise_a_jour) as $maj_date) {
6490                              $valF[$maj_date]=$date;                              $valF[$maj_date]=$date;
# Line 4189  class instruction extends instruction_ge Line 6497  class instruction extends instruction_ge
6497                              $code_barres = "";                              $code_barres = "";
6498                                                            
6499                              //Désactivation de l'autocommit                              //Désactivation de l'autocommit
6500                              $f->db->autoCommit(false);                              $this->f->db->autoCommit(false);
6501                                                            
6502                              //On modifie les valeurs de l'instruction                              //On modifie les valeurs de l'instruction
6503                              $instr->setParameter('maj', 170);                              $instr->setParameter('maj', 170);
6504                              $instr->class_actions[170]["identifier"] =                              $instr->class_actions[170]["identifier"] =
6505                              "mise à jour des dates (depuis le menu suivi des pièces)";                              "mise à jour des dates (depuis le menu suivi des pièces)";
6506                              $retour = $instr->modifier($valF, $f->db, DEBUG);                              $retour = $instr->modifier($valF);
6507                                                            
6508                              //Si une erreur s'est produite, on défait les modifications                              //Si une erreur s'est produite, on défait les modifications
6509                              //qui ont été faites                              //qui ont été faites
# Line 4204  class instruction extends instruction_ge Line 6512  class instruction extends instruction_ge
6512                              }                              }
6513                              //Sinon, on valide en base de données les modifications                              //Sinon, on valide en base de données les modifications
6514                              else {                              else {
6515                                  $f->db->commit();                                  $this->f->db->commit();
6516                              }                              }
6517                                                            
6518                              // Variable correct retourné depuis la classe instruction                              // Variable correct retourné depuis la classe instruction
# Line 4245  class instruction extends instruction_ge Line 6553  class instruction extends instruction_ge
6553                                      INNER JOIN ".DB_PREFIXE."evenement ON                                      INNER JOIN ".DB_PREFIXE."evenement ON
6554                                          instruction.evenement=evenement.evenement                                          instruction.evenement=evenement.evenement
6555                                      WHERE code_barres='".$code_barres."'";                                      WHERE code_barres='".$code_barres."'";
6556                          $resInfo = $f->db->query($sqlInfo);                          $resInfo = $this->f->db->query($sqlInfo);
6557                          $f->isDatabaseError($resInfo);                          $this->f->isDatabaseError($resInfo);
6558                          $infos = $resInfo->fetchRow(DB_FETCHMODE_ASSOC);                          $infos = $resInfo->fetchRow(DB_FETCHMODE_ASSOC);
6559    
6560                          // Vérification de la non modification des dates de suivi                          // Vérification de la non modification des dates de suivi
6561                          foreach(explode(";", $type_mise_a_jour) as $champ) {                          foreach(explode(";", $type_mise_a_jour) as $champ) {
6562                                if ($champ === 'date_envoi_controle_legalite') {
6563                                    if ($instr->is_sent_to_cl() === true) {
6564                                        $error = __("Les dates de suivis ne peuvent etre modifiees");
6565                                        $date_error = true;
6566                                        break;
6567                                    }
6568                                }
6569                              if($infos[$champ] != "" AND $infos[$champ] != $date) {                              if($infos[$champ] != "" AND $infos[$champ] != $date) {
6570                                  $error = _("Les dates de suivis ne peuvent etre modifiees");                                  $error = _("Les dates de suivis ne peuvent etre modifiees");
6571                                  $date_error = true;                                  $date_error = true;
6572                                    break;
6573                              }                              }
6574                          }                          }
6575                      }                      }
# Line 4271  class instruction extends instruction_ge Line 6587  class instruction extends instruction_ge
6587           */           */
6588          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
6589          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
6590              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
6591          }          }
6592          // Affichage du message d'erreur          // Affichage du message d'erreur
6593          if(!empty($error)) {          if(!empty($error)) {
6594              $f->displayMessage("error", $error);              $this->f->displayMessage("error", $error);
6595          }          }
6596    
6597          // Affichage du message de validation de la saisie          // Affichage du message de validation de la saisie
6598          if($correct === true) {          if($correct === true) {
6599              $f->displayMessage("ok", _("Saisie enregistree"));              $this->f->displayMessage("ok", _("Saisie enregistree"));
6600          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
6601          // Ouverture du formulaire          // Ouverture du formulaire
6602          echo "\t<form";          echo "\t<form";
6603          echo " method=\"post\"";          echo " method=\"post\"";
# Line 4301  class instruction extends instruction_ge Line 6615  class instruction extends instruction_ge
6615              $champs = array("type_mise_a_jour", "date", "code_barres");              $champs = array("type_mise_a_jour", "date", "code_barres");
6616          }          }
6617          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
6618          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
6619                "validation" => 0,
6620                "maj" => 0,
6621                "champs" => $champs,
6622            ));
6623          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
6624          // Parametrage du champ type_mise_a_jour          // Parametrage du champ type_mise_a_jour
6625          $form->setLib("type_mise_a_jour", _("Date a mettre a jour")."* :");          $form->setLib("type_mise_a_jour", _("Date a mettre a jour")."* :");
# Line 4331  class instruction extends instruction_ge Line 6649  class instruction extends instruction_ge
6649          $contenu[1][4] = _("date de retour de controle de legalite");          $contenu[1][4] = _("date de retour de controle de legalite");
6650    
6651          $contenu[0][5] = "date_retour_rar";          $contenu[0][5] = "date_retour_rar";
6652          $contenu[1][5] = _("date de retour de l'AR");          $contenu[1][5] = __("date de notification du correspondant");
6653    
6654          $form->setSelect("type_mise_a_jour", $contenu);          $form->setSelect("type_mise_a_jour", $contenu);
6655    
# Line 4391  class instruction extends instruction_ge Line 6709  class instruction extends instruction_ge
6709              $form->setType("autorite_competente", "static");              $form->setType("autorite_competente", "static");
6710              $form->setVal("autorite_competente", $infos['autorite_competente']);              $form->setVal("autorite_competente", $infos['autorite_competente']);
6711    
6712              // Parametrage des libellés d'envoi avec RAR              // Parametrage des libellés d'envoi avec AR
6713              $form->setLib("date_envoi_rar", _("date_envoi_rar")." :");              $form->setLib("date_envoi_rar", __("date_envoi_ar")." :");
6714              $form->setLib("date_retour_rar", _("date_retour_rar")." :");              $form->setLib("date_retour_rar", __("date_notification")." :");
6715    
6716              $form->setLib("date_envoi_signature", _("date_envoi_signature")." :");              $form->setLib("date_envoi_signature", _("date_envoi_signature")." :");
6717              $form->setLib("date_retour_signature", _("date_retour_signature")." :");              $form->setLib("date_retour_signature", _("date_retour_signature")." :");
# Line 4427  class instruction extends instruction_ge Line 6745  class instruction extends instruction_ge
6745          echo "\t<div class=\"formControls\">\n";          echo "\t<div class=\"formControls\">\n";
6746          //          //
6747          if(!$date_error) {          if(!$date_error) {
6748              $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));              $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
6749          }          }
6750          // Si pas sur l'écran de validation          // Si pas sur l'écran de validation
6751          if(isset($infos)) {          if(isset($infos)) {
6752              echo "<a class=\"retour\" href=\"../scr/form.php?obj=instruction_suivi_mise_a_jour_des_dates&action=170&idx=0";              echo "<a class=\"retour\" href=\"".OM_ROUTE_FORM."&obj=instruction_suivi_mise_a_jour_des_dates&action=170&idx=0";
6753                  echo "&amp;type_mise_a_jour=".$type_mise_a_jour."&amp;date=".$date."&amp;code_barres=".$code_barres;                  echo "&amp;type_mise_a_jour=".$type_mise_a_jour."&amp;date=".$date."&amp;code_barres=".$code_barres;
6754              echo "\">Retour</a>";              echo "\">Retour</a>";
6755          }          }
# Line 4448  class instruction extends instruction_ge Line 6766  class instruction extends instruction_ge
6766      function view_pdf_lettre_rar() {      function view_pdf_lettre_rar() {
6767          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6768          $this->checkAccessibility();          $this->checkAccessibility();
6769            //
6770            $this->f->disableLog();
6771    
6772          // XXX APP          if($this->f->get_submitted_get_value('liste') != null) {
6773                $listeCodeBarres = explode(',',$this->f->get_submitted_get_value('liste'));
         $f = $this->f;  
   
         $f->disableLog();  
   
         if($f->get_submitted_get_value('liste') != null) {  
             $listeCodeBarres = explode(',',$f->get_submitted_get_value('liste'));  
6774    
6775              // Classe permettant la mise en page de l'édition pdf              // Classe permettant la mise en page de l'édition pdf
6776              require_once "../obj/pdf_lettre_rar.class.php";              require_once "../obj/pdf_lettre_rar.class.php";
6777              $pdf_lettre_rar = new pdf_lettre_rar('P', 'mm', 'A4');              $pdf_lettre_rar = new pdf_lettre_rar('P', 'mm', 'A4');
6778              // Initialisation de la mise en page              // Initialisation de la mise en page
6779              $pdf_lettre_rar->init($f);              $pdf_lettre_rar->init($this->f);
6780    
6781              foreach ($listeCodeBarres as $code_barres) {              foreach ($listeCodeBarres as $code_barres) {
6782    
6783                    // On récupère le dossier
6784                    $sql = "SELECT dossier
6785                            FROM " . DB_PREFIXE . "instruction
6786                            WHERE code_barres = '" . $code_barres . "'";
6787                    $dossier = $this->f->db->getOne($sql);
6788                    $this->f->addToLog(__METHOD__."(): db->getOne(\"".$sql."\")", VERBOSE_MODE);
6789                    $this->f->isDatabaseError($dossier);
6790                    $inst_dossier = $this->f->get_inst__om_dbform(array(
6791                        "obj" => "dossier",
6792                        "idx" => $dossier,
6793                    ));
6794    
6795                    // En fonction du type de dossier, on récupère un demandeur différent dans les requêtes
6796                    $groupe = $inst_dossier->get_type_affichage_formulaire();
6797                    switch ($groupe) {
6798                        case 'CTX IN':
6799                            $sql_demandeur = "(lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='plaignant')";
6800                            break;
6801                        case 'CTX RE':
6802                            $sql_demandeur = "(lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='requerant')";
6803                            break;
6804                        case 'ADS':
6805                        case 'DPC':
6806                        case 'CONSULTATION ENTRANTE':
6807                        default:
6808                            $sql_demandeur = "((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire') OR demandeur.type_demandeur='delegataire')";
6809                            break;
6810                    }
6811    
6812                  // Test si l'evenement est de type arrete et si un délégataire a été nommé                  // Test si l'evenement est de type arrete et si un délégataire a été nommé
6813                  $sql = "SELECT                  $sql = "SELECT
6814                              dossier.dossier_libelle,                              dossier.dossier_libelle,
# Line 4491  class instruction extends instruction_ge Line 6834  class instruction extends instruction_ge
6834                          inner join ".DB_PREFIXE."demandeur on                          inner join ".DB_PREFIXE."demandeur on
6835                              demandeur.demandeur=lien_dossier_demandeur.demandeur                              demandeur.demandeur=lien_dossier_demandeur.demandeur
6836                          WHERE code_barres='".$code_barres."'                          WHERE code_barres='".$code_barres."'
6837                              AND ((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire')                              AND " . $sql_demandeur . "
                             OR demandeur.type_demandeur='delegataire')  
6838                          GROUP BY dossier.dossier_libelle, evenement.type, phase.code, division.libelle";                          GROUP BY dossier.dossier_libelle, evenement.type, phase.code, division.libelle";
6839    
6840                  $res = $f->db->query($sql);                  $res = $this->f->db->query($sql);
6841                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
6842                  $f->isDatabaseError($res);                  $this->f->isDatabaseError($res);
6843                  $testDemandeur = $res->fetchrow(DB_FETCHMODE_ASSOC);                  $testDemandeur = $res->fetchrow(DB_FETCHMODE_ASSOC);
6844                                    
6845    
# Line 4546  class instruction extends instruction_ge Line 6888  class instruction extends instruction_ge
6888                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {
6889                      $sqlAdresse .= " AND demandeur.type_demandeur='delegataire'";                      $sqlAdresse .= " AND demandeur.type_demandeur='delegataire'";
6890                  } else {                  } else {
6891                      $sqlAdresse .= " AND lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire'";                      $sqlAdresse .= " AND demandeur.type_demandeur='petitionnaire' AND lien_dossier_demandeur.petitionnaire_principal IS TRUE";
6892                  }                  }
6893    
6894                  $resAdresse = $f->db->query($sqlAdresse);                  $resAdresse = $this->f->db->query($sqlAdresse);
6895                  $adresse_dest = $resAdresse->fetchrow(DB_FETCHMODE_ASSOC);                  $adresse_dest = $resAdresse->fetchrow(DB_FETCHMODE_ASSOC);
6896                  $f->addToLog(__METHOD__.": db->query(\"".$sqlAdresse."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->query(\"".$sqlAdresse."\")", VERBOSE_MODE);
6897                  $f->isDatabaseError($resAdresse);                  $this->f->isDatabaseError($resAdresse);
6898    
6899                  // Création adresse destinataire sans ligne vide                  // Création adresse destinataire sans ligne vide
6900                  $adresse_destinataire = array();                  $adresse_destinataire = array();
# Line 4582  class instruction extends instruction_ge Line 6924  class instruction extends instruction_ge
6924                  $specifique_content[] = $testDemandeur['dossier_libelle'];                  $specifique_content[] = $testDemandeur['dossier_libelle'];
6925                  $specifique_content[] = "|||||".$adresse_dest['code_barres']."|||||";                  $specifique_content[] = "|||||".$adresse_dest['code_barres']."|||||";
6926                  unset($adresse_dest['code_barres']);                  unset($adresse_dest['code_barres']);
   
6927                  // Ajout d'une page aux pdf                  // Ajout d'une page aux pdf
6928                  $pdf_lettre_rar->addLetter($adresse_destinataire, $specifique_content, $testDemandeur['code_phase']);                  $pdf_lettre_rar->addLetter($adresse_destinataire, $specifique_content, $testDemandeur['code_phase']);
6929    
6930              }              }
6931              $pdf_output = $pdf_lettre_rar->output("lettre_rar".date("dmYHis").".pdf","S");              $pdf_output = $pdf_lettre_rar->output("lettre_rar".date("dmYHis").".pdf","S");
6932              require_once PATH_OPENMAIRIE."om_edition.class.php";              $om_edition = $this->f->get_inst__om_edition();
             $om_edition = new edition();  
6933              $om_edition->expose_pdf_output($pdf_output, "lettre_rar".date("dmYHis").".pdf");              $om_edition->expose_pdf_output($pdf_output, "lettre_rar".date("dmYHis").".pdf");
6934          }          }
6935      }      }
# Line 4652  class instruction extends instruction_ge Line 6992  class instruction extends instruction_ge
6992                              $message .= "<a class='om-prev-icon pdf-16'";                              $message .= "<a class='om-prev-icon pdf-16'";
6993                              $message .= " id=\"generer_bordereau_envoi_maire\"";                              $message .= " id=\"generer_bordereau_envoi_maire\"";
6994                              $message .= " title=\""._("Bordereau")."\"";                              $message .= " title=\""._("Bordereau")."\"";
6995                              $message .= " href='../scr/form.php?obj=instruction";                              $message .= " href='".OM_ROUTE_FORM."&obj=instruction";
6996                              $message .= "&action=200";                              $message .= "&action=200";
6997                              $message .= "&idx=".$id_instruction."'";                              $message .= "&idx=".$id_instruction."'";
6998                              $message .= " target='_blank'>";                              $message .= " target='_blank'>";
# Line 4693  class instruction extends instruction_ge Line 7033  class instruction extends instruction_ge
7033              $this->f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
7034          }          }
7035    
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
7036          // Ouverture du formulaire          // Ouverture du formulaire
7037          $datasubmit = $this->getDataSubmit();          $datasubmit = $this->getDataSubmit();
7038          echo "\n<!-- ########## START DBFORM ########## -->\n";          echo "\n<!-- ########## START DBFORM ########## -->\n";
# Line 4711  class instruction extends instruction_ge Line 7049  class instruction extends instruction_ge
7049          $champs = array("code_barres","date");          $champs = array("code_barres","date");
7050    
7051          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
7052          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
7053                "validation" => 0,
7054                "maj" => 0,
7055                "champs" => $champs,
7056            ));
7057    
7058          $template_required_label = '%s *';          $template_required_label = '%s *';
7059          // Parametrage du champ code_barres          // Parametrage du champ code_barres
# Line 4770  class instruction extends instruction_ge Line 7112  class instruction extends instruction_ge
7112      }      }
7113    
7114      /**      /**
7115       * Retourne l'événement d'instruction dont on donne le code-barres       * VIEW - view_rapport_instruction.
7116         *
7117         * Ouvre le sous-formulaire en ajaxIt dans un overlay.
7118         * Cette action est bindée pour utiliser la fonction popUpIt.
7119         *
7120         * @return void
7121         */
7122        function view_overlay_notification_manuelle() {
7123    
7124            // Vérification de l'accessibilité sur l'élément
7125            $this->checkAccessibility();
7126    
7127            printf(
7128                '<script type="text/javascript" >
7129                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=411&idx=%3$s\', 1);
7130                </script>',
7131                'instruction_notification_manuelle',
7132                OM_ROUTE_SOUSFORM,
7133                $this->getVal($this->clePrimaire),
7134                $this->getVal('dossier')
7135            );
7136        }
7137    
7138        /**
7139         * Retourne l'événement d'instruction dont on donne le code-barres, avec un filtre
7140         * pour exclure les dossiers du groupe contentieux.
7141       *       *
7142       * @param   [string]  $barcode  numéro du code-barres       * @param   [string]  $barcode  numéro du code-barres
7143       * @return  [mixed]             ID de son instruction ou null si aucun code       * @return  [mixed]             ID de son instruction ou null si aucun code
# Line 4779  class instruction extends instruction_ge Line 7146  class instruction extends instruction_ge
7146          // Begin          // Begin
7147          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
7148          // Vérification de l'existence de l'événement d'instruction          // Vérification de l'existence de l'événement d'instruction
7149          // pour le code-barres donné          // pour le code-barres donné, en excluant les dossiers liés au groupe CTX
7150          $sql = "SELECT instruction          $sql = "SELECT instruction
7151              FROM ".DB_PREFIXE."instruction                  FROM ".DB_PREFIXE."instruction
7152              WHERE code_barres = '".$this->f->db->escapesimple($barcode)."'";                      INNER JOIN ".DB_PREFIXE."dossier
7153                            ON dossier.dossier=instruction.dossier
7154                        INNER JOIN ".DB_PREFIXE."dossier_instruction_type
7155                            ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
7156                        INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
7157                            ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
7158                        INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
7159                            ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
7160                        INNER JOIN ".DB_PREFIXE."groupe
7161                            ON dossier_autorisation_type.groupe = groupe.groupe
7162                                AND groupe.code != 'CTX'
7163                    WHERE code_barres = '".$this->f->db->escapesimple($barcode)."'";
7164          $res = $this->f->db->getOne($sql);          $res = $this->f->db->getOne($sql);
7165          $this->f->addToLog(__METHOD__." : db->getOne(\"".$sql."\")", VERBOSE_MODE);          $this->f->addToLog(__METHOD__." : db->getOne(\"".$sql."\")", VERBOSE_MODE);
7166          $this->f->isDatabaseError($res);          $this->f->isDatabaseError($res);
# Line 4805  class instruction extends instruction_ge Line 7183  class instruction extends instruction_ge
7183          // Begin          // Begin
7184          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
7185          // Requête          // Requête
7186          $res = $this->db->autoExecute(          $res = $this->f->db->autoExecute(
7187              DB_PREFIXE.$this->table,              DB_PREFIXE.$this->table,
7188              $valF,              $valF,
7189              DB_AUTOQUERY_UPDATE,              DB_AUTOQUERY_UPDATE,
# Line 4824  class instruction extends instruction_ge Line 7202  class instruction extends instruction_ge
7202       * validation du formulaire d'ajout.       * validation du formulaire d'ajout.
7203       * @param array $val tableau des valeurs retournées par le formulaire       * @param array $val tableau des valeurs retournées par le formulaire
7204       */       */
7205      function setValFAjout($val) {      function setValFAjout($val = array()) {
7206          // Mise à jour du flag created_by_commune lors d'un changement de décision          // Mise à jour du flag created_by_commune lors d'un changement de décision
7207          // par un utilisateur de commune sur un dossier instruit par la comcom          // par un utilisateur de commune sur un dossier instruit par la comcom
7208          if($this->f->isInstrCanChangeDecision($this->valF["dossier"])) {          if ($this->isInstrCanChangeDecision($this->valF["dossier"])) {
7209              $this->valF['created_by_commune'] = true;              $this->valF['created_by_commune'] = true;
7210          }          }
     }  
7211    
     /**  
      * Récupère l'instance du dossier d'instruction  
      *  
      * @param mixed Identifiant du dossier d'instruction  
      *  
      * @return object  
      */  
     function get_inst_dossier($dossier = null) {  
7212          //          //
7213          return $this->get_inst_common("dossier", $dossier);          if ($this->evenement_has_an_edition($this->valF['evenement']) === false) {
7214                if (isset($this->valF['flag_edition_integrale']) === true) {
7215                    unset($this->valF['flag_edition_integrale']);
7216                }
7217                if (isset($this->valF['signataire_arrete']) === true) {
7218                    unset($this->valF['signataire_arrete']);
7219                }
7220            }
7221      }      }
7222    
7223    
7224      /**      /**
7225       * Récupère l'instance d'un événement de workflow.       * Récupère l'instance d'un événement de workflow.
7226       *       *
# Line 5105  class instruction extends instruction_ge Line 7482  class instruction extends instruction_ge
7482       */       */
7483      public function formater_modele($modele, $id_di, $id_inst) {      public function formater_modele($modele, $id_di, $id_inst) {
7484          // Création du lien d'accès direct à l'instruction          // Création du lien d'accès direct à l'instruction
7485          $url_inst = PATH_BASE_URL.'spg/direct_link.php?obj=dossier_instruction&action=3'.          $url_inst = PATH_BASE_URL.'app/index.php?module=form&direct_link=true&obj=dossier_instruction&action=3'.
7486              '&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx='.$id_inst;              '&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx='.$id_inst;
7487          $url_inst = '<a href="'.$url_inst.'">'.$url_inst.'</a>';          $url_inst = '<a href="'.$url_inst.'">'.$url_inst.'</a>';
7488          // Remplacement des champs de fusion          // Remplacement des champs de fusion
# Line 5145  class instruction extends instruction_ge Line 7522  class instruction extends instruction_ge
7522      }      }
7523    
7524    
7525       /**      /**
7526       * Récupère l'instance de la division.       * Récupère l'instance de la division.
7527       *       *
7528       * @param integer $division Identifiant de la division.       * @param integer $division Identifiant de la division.
# Line 5192  class instruction extends instruction_ge Line 7569  class instruction extends instruction_ge
7569          return $om_collectivite;          return $om_collectivite;
7570      }      }
7571    
7572        /*
7573         * CONDITION - can_user_access_dossier_contexte_ajout
7574         *
7575         * Vérifie que l'utilisateur a bien accès au dossier d'instruction passé dans le
7576         * formulaire d'ajout.
7577         * Cette méthode vérifie que l'utilisateur est lié au groupe du dossier, et si le
7578         * dossier est confidentiel qu'il a accès aux confidentiels de ce groupe.
7579         *
7580         */
7581        function can_user_access_dossier_contexte_ajout() {
7582    
7583  }// fin classe          ($this->f->get_submitted_get_value('idxformulaire') !== null ? $id_dossier =
7584                $this->f->get_submitted_get_value('idxformulaire') : $id_dossier = "");
7585            //
7586            if ($id_dossier !== "") {
7587                $dossier = $this->f->get_inst__om_dbform(array(
7588                    "obj" => "dossier_instruction",
7589                    "idx" => $id_dossier,
7590                ));
7591                //
7592                return $dossier->can_user_access_dossier();
7593            }
7594            return false;
7595        }
7596    
7597       /*
7598         * CONDITION - can_user_access_dossier
7599         *
7600         * Vérifie que l'utilisateur a bien accès au dossier lié à l'instruction instanciée.
7601         * Cette méthode vérifie que l'utilisateur est lié au groupe du dossier, et si le
7602         * dossier est confidentiel qu'il a accès aux confidentiels de ce groupe.
7603         *
7604         */
7605        function can_user_access_dossier_contexte_modification() {
7606    
7607            $id_dossier = $this->getVal('dossier');
7608            //
7609            if ($id_dossier !== "" && $id_dossier !== null) {
7610                $dossier = $this->f->get_inst__om_dbform(array(
7611                    "obj" => "dossier_instruction",
7612                    "idx" => $id_dossier,
7613                ));
7614                //
7615                return $dossier->can_user_access_dossier();
7616            }
7617            return false;
7618        }
7619    
7620        /**
7621         * TREATMENT - envoyer_a_signature_sans_relecture
7622         *
7623         * Permet d'envoyer le document de l'instruction au parapheur pour signature sans relecture
7624         *
7625         * @return boolean true si l'envoi a été effectué avec succès false sinon
7626         */
7627        function envoyer_a_signature_sans_relecture() {
7628            return $this->envoyer_a_signature();
7629        }
7630    
7631        /**
7632         * TREATMENT - envoyer_a_signature_avec_relecture
7633         *
7634         * Permet d'envoyer le document de l'instruction au parapheur pour signature avec relecture
7635         *
7636         * @return boolean true si l'envoi a été effectué avec succès false sinon
7637         */
7638        function envoyer_a_signature_avec_relecture() {
7639            $is_forced_view_files = true;
7640            return $this->envoyer_a_signature($is_forced_view_files);
7641        }
7642    
7643        /**
7644         * TREATMENT - envoyer_a_signature
7645         *
7646         * Permet d'envoyer le document de l'instruction au parapheur pour signature
7647         *
7648         * @param  boolean  $is_forced_view_files  Indique si il y a une relecture (true) ou non (false)
7649         *
7650         * @return boolean true si l'envoi a été effectué avec succès false sinon
7651         */
7652        function envoyer_a_signature($is_forced_view_files = false) {
7653            $this->begin_treatment(__METHOD__);
7654            $this->correct = true;
7655    
7656            // Instanciation de l'objet signataire_arrete
7657            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
7658                'obj' => 'signataire_arrete',
7659                'idx' => $this->getVal('signataire_arrete'),
7660            ));
7661    
7662            // Instanciation de l'objet dossier
7663            $inst_dossier = $this->f->get_inst__om_dbform(array(
7664                'obj' => 'dossier',
7665                'idx' => $this->getVal('dossier'),
7666            ));
7667    
7668            // Récupération du document à signer
7669            $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
7670            if ($file === OP_FAILURE) {
7671                $this->correct = false;
7672                $this->addToMessage(__("Une erreur est survenue lors de la récupération du contenu du document de l'instruction."));
7673                // Termine le traitement
7674                return $this->end_treatment(__METHOD__, false);
7675            }
7676    
7677            // Initialisation des paramètre à passer pour l'envoi en signature
7678            $data = array(
7679                "om_utilisateur_email" => $this->f->om_utilisateur['email'],
7680                "om_utilisateur_nom" => $this->f->om_utilisateur['nom'],
7681                "signataire_arrete_email" => $inst_signataire_arrete->getVal('email'),
7682                "signataire_arrete_nom" => $inst_signataire_arrete->getVal('nom'),
7683                "signataire_arrete_prenom" => $inst_signataire_arrete->getVal('prenom'),
7684                "date_limite_instruction" => $inst_dossier->getVal('incomplet_notifie') === 't' ? $inst_dossier->getVal('date_limite_incompletude') : $inst_dossier->getVal('date_limite'),
7685                "dossier" => $this->getVal('dossier'),
7686                "is_forced_view_files" => $is_forced_view_files,
7687                'commentaire_signature' => $is_forced_view_files === true ? __('relecture demandee.') : null
7688            );
7689    
7690            // Initialisation des métadonnées
7691            $metadonnee_dossier = $file['metadata'];
7692            // récupération de l'extension du fichier
7693            $extension = substr($metadonnee_dossier['filename'], strrpos($metadonnee_dossier['filename'], '.'));
7694            // Modification du libellé du document transmis au parapheur
7695            // pour le mettre sous la forme : instruction_xxx_libelle_lettretype.extension
7696            $metadonnee_dossier['filename'] = $this->getDocumentLibelle().$extension;
7697            $metadonnee_dossier['titre_document'] = $this->getDocumentTitre();
7698    
7699            $metadonnee_dossier['url_di'] = sprintf(
7700                '%sapp/index.php?module=form&direct_link=true&obj=dossier_instruction&action=3&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx=%s',
7701                $this->f->get_param_base_path_metadata_url_di() !== null ? $this->f->get_param_base_path_metadata_url_di() : PATH_BASE_URL,
7702                $this->getVal($this->clePrimaire)
7703            );
7704    
7705            $optional_data = null;
7706            // Si il y a des paramètres supplémentaire spécifié dans le signataire alors on les récupère
7707            if ($inst_signataire_arrete->getVal('parametre_parapheur') !== null && $inst_signataire_arrete->getVal('parametre_parapheur') !== '') {
7708                $optional_data = json_decode($inst_signataire_arrete->getVal('parametre_parapheur'), true);
7709                if (json_last_error() !== JSON_ERROR_NONE) {
7710                    $this->correct = false;
7711                    $this->addToMessage(__("Les paramètres supplémentaires envoyés au parapheur ne sont pas au bon format."));
7712                    $this->addToLog(__METHOD__."(): ".
7713                        __("Erreur lors du décodage du format json des paramètres supplémentaires envoyé au parapheur.
7714                            Tableau : ").var_export($inst_signataire_arrete->getVal('parametre_parapheur'), true)
7715                    );
7716                    // Termine le traitement
7717                    return $this->end_treatment(__METHOD__, false);
7718                }
7719            }
7720    
7721            //Instanciation de la classe electronicsignature
7722            $inst_es = $this->get_electronicsignature_instance();
7723            if ($inst_es === false) {
7724                $this->correct = false;
7725                return $this->end_treatment(__METHOD__, false);
7726            }
7727    
7728            // Appel de la méthode de l'abstracteur send_for_signature()
7729            // Cette méthode doit retourner un tableau de valeur
7730            try {
7731                $result = $inst_es->send_for_signature($data, $file['file_content'], $metadonnee_dossier, $optional_data);
7732            }  catch (electronicsignature_exception $e) {
7733                $this->handle_electronicsignature_exception($e);
7734                return $this->end_treatment(__METHOD__, false);
7735            }
7736    
7737            // Après avoir reçu le résultat du parapheur, il faut mettre à jour les champs
7738            $valF = array();
7739    
7740            // Pour appeler la fonction modifier il faut traiter tous les champs de l'objet
7741            foreach($this->champs as $identifiant => $champ) {
7742                $valF[$champ] = $this->val[$identifiant];
7743            }
7744            // On fait ensuite nos modifications spécifiques
7745            $valF['id_parapheur_signature'] = $result['id_parapheur_signature'];
7746            $valF['statut_signature'] = $result['statut'];
7747            $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
7748            $valF['date_envoi_signature'] = date("Y-m-d", strtotime($result['date_envoi_signature']));
7749            $valF['historique_signature'] = $this->get_updated_historique_signature($result);
7750    
7751            $ret = $this->modifier($valF);
7752    
7753            if ($ret === false) {
7754                $this->correct = false;
7755                $this->addToMessage(__("Une erreur est survenue lors de la mise à jour des champs."));
7756                // Termine le traitement
7757                return $this->end_treatment(__METHOD__, false);
7758            }
7759    
7760            // Message
7761            $this->addToMessage(__("Le document a été envoyé pour signature dans le parapheur."));
7762            if (array_key_exists('signature_page_url', $result) === true) {
7763                $this->addToMessage(sprintf(
7764                    '<br> > <a href="%1$s" title="%2$s" target="_blank">%2$s</a>',
7765                    $result['signature_page_url'],
7766                    __("Signez directement le document")
7767                ));
7768            }
7769    
7770            // Tout s'est bien passé, on termine le traitement
7771            return $this->end_treatment(__METHOD__, true);
7772        }
7773    
7774        /**
7775         * Permet de récupérer la traduction de la valeur de statut_signature
7776         *
7777         * @return string la valeur de statut_signature traduite | false
7778         */
7779        function get_trad_for_statut($value_to_trad){
7780            $statut_signature_tab = array(
7781                'waiting' => __('en préparation'),
7782                'in_progress' => __('en cours de signature'),
7783                'canceled' => __('signature annulée'),
7784                'expired' => __('délai de signature expiré'),
7785                'finished' => __('signé')
7786            );
7787            if (array_key_exists($value_to_trad, $statut_signature_tab) === true) {
7788                return $statut_signature_tab[$value_to_trad];
7789            }
7790    
7791            return false;
7792        }
7793    
7794        /**
7795         * Permet de mettre à jour le tableau json sotcké dans le champ historique_signature
7796         *
7797         * @return string (json) la valeur de historique_signature mis à jour | false
7798         */
7799        function get_updated_historique_signature($historique_signature_values) {
7800            
7801            $historique_signature_value_tab = $this->get_historique_signature_decoded();
7802    
7803            if ($historique_signature_value_tab === false) {
7804                $this->addToLog(__METHOD__."(): erreur historique signature", DEBUG_MODE);
7805                return false;
7806            }
7807    
7808            $last_val_historique_signature = array();
7809    
7810            // Si la tableau récupéré n'est pas vide alors
7811            // on récupère la dernière ligne du tableau
7812            if (empty($historique_signature_value_tab) === false) {
7813                $last_val_historique_signature = end($historique_signature_value_tab);
7814            }
7815    
7816            $format_date = '';
7817            $format_date_hour = '';
7818            $date_converted=array();
7819    
7820            $date_to_convert = array(
7821                'date_envoi_signature' => $historique_signature_values['date_envoi_signature'],
7822                'date_limite_instruction' => $historique_signature_values['date_limite_instruction'],
7823                'date_retour_signature' => $historique_signature_values['date_retour_signature']
7824            );
7825    
7826            // Conversion des dates en fonction de leur format
7827            foreach ($date_to_convert as $key => $value) {
7828                $date_converted[$key] = null;
7829                if ($value != null) {
7830                    $format_date = 'd/m/Y';
7831                    $format_date_hour = 'd/m/Y H:i:s';
7832                    $date_converted[$key] = empty(date_parse($value)['hour']) === false ? date($format_date_hour, strtotime($value)) : date($format_date, strtotime($value));
7833                }
7834            }
7835    
7836            // Ce tableau permet de lister les colonnes de historique_signature et de les rendre traduisibles.
7837            // Il faut en effet mettre les gettext avec l'intitulé explicite au moins
7838            // une fois afin qu'il puisse être reconnu par le logiciel de traduction.
7839            $tab_for_columns_trad = array(
7840                __('entry_date'),
7841                __('id_parapheur_signature'),
7842                __('emetteur'),
7843                __('signataire'),
7844                __('date_envoi'),
7845                __('date_limite'),
7846                __('date_retour'),
7847                __('statut_signature'),
7848                __('commentaire_signature')
7849            );
7850    
7851            array_push($historique_signature_value_tab, array(
7852                'entry_date' => date('d/m/Y H:i:s'),
7853                'id_parapheur_signature' => $historique_signature_values['id_parapheur_signature'] == null ? (isset($last_val_historique_signature['id_parapheur_signature']) === true ? $last_val_historique_signature['id_parapheur_signature'] : null) : $historique_signature_values['id_parapheur_signature'],
7854                'emetteur' => $historique_signature_values['om_utilisateur_email'] == null ? (isset($last_val_historique_signature['emetteur']) === true ? $last_val_historique_signature['emetteur'] : null) : $historique_signature_values['om_utilisateur_email'],
7855                'signataire' => $historique_signature_values['signataire_arrete_email'] == null ? (isset($last_val_historique_signature['signataire']) === true ? $last_val_historique_signature['signataire'] : null) : $historique_signature_values['signataire_arrete_email'],
7856                'date_envoi' => $historique_signature_values['date_envoi_signature'] == null ? (isset($last_val_historique_signature['date_envoi']) === true ? $last_val_historique_signature['date_envoi'] : null) : $date_converted['date_envoi_signature'],
7857                'date_limite' => $historique_signature_values['date_limite_instruction'] == null ? (isset($last_val_historique_signature['date_limite']) === true ? $last_val_historique_signature['date_limite'] : null) : $date_converted['date_limite_instruction'],
7858                'date_retour' => $historique_signature_values['date_retour_signature'] == null ? (isset($last_val_historique_signature['date_retour']) === true ? $last_val_historique_signature['date_retour'] : null) : $date_converted['date_retour_signature'],
7859                'statut_signature' => $historique_signature_values['statut'] == null ? (isset($last_val_historique_signature['statut_signature']) === true ? $last_val_historique_signature['statut_signature'] : null) : $this->get_trad_for_statut($historique_signature_values['statut']),
7860                'commentaire_signature' => isset($historique_signature_values['commentaire_signature']) === false || $historique_signature_values['commentaire_signature'] == null ? null : $historique_signature_values['commentaire_signature'],
7861            ));
7862            
7863            return json_encode($historique_signature_value_tab, JSON_HEX_APOS);
7864        }
7865    
7866    
7867        /**
7868         * Récupère le contenu du champ historique_signature et le converti en tableau
7869         *
7870         * @return array sinon false en cas d'erreur
7871         */
7872        protected function get_historique_signature_decoded() {
7873            $val = $this->getVal('historique_signature');
7874            if ($val === '') {
7875                $val = json_encode(array());
7876            }
7877            if($this->isJson($val) === false) {
7878                return false;
7879            }
7880            return json_decode($val, true);
7881        }
7882    
7883  ?>      /**
7884         * Récupère les informations à afficher dans le tableau de suivi à l'aide
7885         * d'une requête sql. Stocke ces informations dans un tableau.
7886         * Converti le tableau au format json et renvoi le json obtenu
7887         *
7888         * @return json
7889         */
7890        protected function get_json_suivi_notification() {
7891            $valSuivi = array();
7892            // Liste des champs à afficher. Permet également la traduction des noms de colonnes.
7893            $listeChampsTrad = array(
7894                __('emetteur'),
7895                __('date_envoi'),
7896                __('destinataire'),
7897                __('date_premier_acces'),
7898                __('instruction'),
7899                __('statut'),
7900                __('commentaire')
7901            );
7902            $listeChamps = array(
7903                'emetteur',
7904                'date_envoi',
7905                'destinataire',
7906                'date_premier_acces',
7907                'instruction',
7908                'statut',
7909                'commentaire'
7910            );
7911    
7912            // Récupération des infos nécessaires à l'affichage du tableau
7913            $sql = sprintf(
7914                'SELECT
7915                    instruction_notification.instruction_notification,
7916                    CASE WHEN instruction_notification.automatique = TRUE
7917                        THEN TRIM(CONCAT(instruction_notification.emetteur, \' \', \'(automatique)\'))
7918                        ELSE instruction_notification.emetteur
7919                    END as emetteur,
7920                    date_envoi,
7921                    instruction_notification.destinataire,
7922                    instruction_notification.date_premier_acces,
7923                    evenement.libelle as instruction,
7924                    instruction_notification.statut,
7925                    instruction_notification.commentaire,
7926                    instruction_notification_document.instruction as instruction_annexe
7927                FROM
7928                    %1$sinstruction_notification
7929                    LEFT JOIN %1$sinstruction
7930                        ON instruction.instruction = instruction_notification.instruction
7931                    LEFT JOIN %1$sevenement
7932                        ON instruction.evenement = evenement.evenement
7933                    LEFT JOIN %1$sinstruction_notification_document
7934                        ON instruction_notification.instruction_notification = instruction_notification_document.instruction_notification
7935                        AND instruction_notification_document.annexe = true
7936                WHERE
7937                    instruction.instruction = %2$s
7938                ORDER BY
7939                    date_envoi ASC, instruction_notification.destinataire ASC',
7940                DB_PREFIXE,
7941                $this->getVal('instruction')
7942            );
7943            $res = $this->f->db->query($sql);
7944            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
7945            $this->f->isDatabaseError($res);
7946            // Stockage des infos de chaque notification dans un tableau
7947            while( $row =& $res->fetchrow(DB_FETCHMODE_ASSOC) ) {
7948                $valNotif = array();
7949                foreach($listeChamps as $champ) {
7950                    $valNotif[$champ] = $row[$champ];
7951                    if (($champ === 'date_envoi'
7952                        || $champ === 'date_premier_acces')
7953                        && $row[$champ] !== null
7954                        && $row[$champ] !== '') {
7955                        //
7956                        $valNotif[$champ] = date('d/m/Y H:i:s', strtotime($row[$champ]));
7957                    }
7958                }
7959                if ($row['instruction_annexe'] !== null && $row['instruction_annexe'] !== '') {
7960                    $inst_instruction = $this->f->get_inst__om_dbform(array(
7961                        "obj" => "instruction",
7962                        "idx" => $row['instruction_annexe'],
7963                    ));
7964                    $inst_evenement = $inst_instruction->get_inst_evenement();
7965                    $lienAnnexe = ' ('.$inst_evenement->getVal('libelle').')';
7966                    $valNotif['instruction'] .= $lienAnnexe;
7967                }
7968                array_push($valSuivi, $valNotif);
7969            }
7970    
7971            // Passage du tableau au format json
7972            return json_encode($valSuivi, JSON_HEX_APOS);
7973        }
7974    
7975        /**
7976         * Traitement des erreurs retournées par l'abstracteur electronicsignature.
7977         *
7978         * @param electronicsignature_exception $exception Exception retournée par l'abstracteur.
7979         *
7980         * @return void
7981         */
7982        public function handle_electronicsignature_exception(electronicsignature_exception $exception) {
7983            $this->f->displayMessage('error', $exception->getMessage());
7984        }
7985    
7986    
7987        /**
7988         * Retourne une instance du connecteur electronicsignature, et la créer si elle n'existe pas.
7989         *
7990         * @param  boolean $with_handle_error Flag pour afficher ou non le message d'erreur à l'utilisateur.
7991         * @return electronicsignature        Instance de l'abstracteur.
7992         */
7993        public function get_electronicsignature_instance($with_handle_error = true) {
7994            if(isset($this->electronicsignature_instance)) {
7995                return $this->electronicsignature_instance;
7996            }
7997            // Instanciation du connecteur electronicsignature
7998            try {
7999                require_once "electronicsignature.class.php";
8000                $collectivites = array("collectivite_idx" => $this->get_dossier_instruction_om_collectivite(), "collectivite_multi_idx" => $this->f->get_idx_collectivite_multi());
8001                $this->electronicsignature_instance = new electronicsignature($collectivites);
8002            } catch (electronicsignature_exception $e) {
8003                if ($with_handle_error === true) {
8004                    $this->handle_electronicsignature_exception($e);
8005                }
8006                return false;
8007            }
8008            return $this->electronicsignature_instance;
8009        }
8010    
8011        /**
8012         * TREATMENT - envoyer_au_controle_de_legalite
8013         *
8014         * Ajoute la tâche envoi_CL.
8015         * C'est le traitement de la tâche qui mettra à jour la date d'envoi au contrôle de légalité.
8016         *
8017         * @return [type] [description]
8018         */
8019        function envoyer_au_controle_de_legalite() {
8020            $this->begin_treatment(__METHOD__);
8021            $this->correct = true;
8022    
8023            //
8024            if ($this->can_be_sended_to_cl() === true) {
8025                // Création de la task 'envoi_CL'
8026                $inst_task = $this->f->get_inst__om_dbform(array(
8027                    "obj" => "task",
8028                    "idx" => 0,
8029                ));
8030                $task_val = array(
8031                    'type' => 'envoi_CL',
8032                    'object_id' => $this->getVal('instruction'),
8033                    'dossier' => $this->getVal('dossier'),
8034                );
8035                // Change l'état de la tâche de notification en fonction de l'état de
8036                // transmission du dossier d'instruction
8037                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
8038                if ($this->f->is_option_mode_service_consulte_enabled() === false
8039                    && ($inst_di->getVal('etat_transmission_platau') == 'non_transmissible'
8040                    || $inst_di->getVal('etat_transmission_platau') == 'transmis_mais_non_transmissible')) {
8041                    //
8042                    $task_val['state'] = $inst_task::STATUS_DRAFT;
8043                }
8044                $add_task = $inst_task->add_task(array('val' => $task_val));
8045                if ($add_task === false) {
8046                    $this->addToMessage(sprintf('%s %s',
8047                        __("Une erreur s'est produite lors de la création tâche."),
8048                        __("Veuillez contacter votre administrateur.")
8049                    ));
8050                    $this->correct = false;
8051                    return $this->end_treatment(__METHOD__, false);
8052                }
8053                // Mise à jour du champs 'envoye_cl_platau'
8054                $instr_val = array(
8055                    'envoye_cl_platau' => 't',
8056                );
8057                $res = $this->f->db->autoExecute(
8058                    DB_PREFIXE.$this->table,
8059                    $instr_val,
8060                    DB_AUTOQUERY_UPDATE,
8061                    $this->getCle($this->getVal($this->clePrimaire))
8062                );
8063                $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($instr_val, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->clePrimaire)."\");", DEBUG_MODE);
8064                if ($this->f->isDatabaseError($res, true) === true) {
8065                    $this->addToMessage(sprintf('%s %s',
8066                        __("Une erreur s'est produite lors de la mise à jour de l'instruction."),
8067                        __("Veuillez contacter votre administrateur.")
8068                    ));
8069                    $this->correct = false;
8070                    return $this->end_treatment(__METHOD__, false);
8071                }
8072                // Message de validation à l'utilisateur
8073                $this->addToMessage(__('Votre demande de transfert au contrôle de légalité à bien été prise en compte.'));
8074                $this->addToMessage(__("La date d'envoi au contrôle de légalité sera mise à jour ultérieurement."));
8075            }
8076            //
8077            return $this->end_treatment(__METHOD__, true);
8078        }
8079    
8080    
8081        /**
8082         * Retourne le lien de retour (VIEW formulaire et VIEW sousformulaire).
8083         *
8084         * @param string $view Appel dans le contexte de la vue 'formulaire' ou de
8085         *                     la vue 'sousformulaire'.
8086         *
8087         * @return string
8088         */
8089        function get_back_link($view = "formulaire") {
8090            //
8091            $href = parent::get_back_link($view);
8092            //
8093            $crud = $this->get_action_crud();
8094    
8095            // Redirection vers le formulaire de modification à la validation du
8096            // formulaire d'ajout si l'événement associé possède une lettre type
8097            if (($crud === 'create'
8098                    || ($crud === null
8099                        && $this->getParameter('maj') == 0))
8100                    && $this->correct == true
8101                    && $this->evenement_has_an_edition($this->valF['evenement']) === true) {
8102    
8103                // On instancie l'instruction
8104                $inst_instruction = $this->f->get_inst__om_dbform(array(
8105                    "obj" => "instruction",
8106                    "idx" => $this->valF[$this->clePrimaire],
8107                ));
8108    
8109                // Si l'instruction n'est pas finalisée automatiquement
8110                if ($inst_instruction->getVal('om_final_instruction') !== 't') {
8111                    $href = str_replace("&action=3", "&action=1", $href);
8112                    //
8113                    if (strpos($href, "&retour=tab") !== false) {
8114                        $href = str_replace("&retour=tab", "&retour= form", $href);
8115                    } else {
8116                        $href .= "&retour=form";
8117                    }
8118                }
8119            }
8120    
8121            //
8122            return $href;
8123        }
8124    
8125        public function view_json_data() {
8126            $this->checkAccessibility();
8127            $this->f->disableLog();
8128            $view = $this->get_json_data();
8129            printf(json_encode($view));
8130        }
8131    
8132        public function get_json_data() {
8133            $val = array_combine($this->champs, $this->val);
8134            foreach ($val as $key => $value) {
8135                $val[$key] = strip_tags($value);
8136            }
8137            $val['tacite'] = 'f';
8138            $inst_ad = $this->f->get_inst__om_dbform(array(
8139                "obj" => "avis_decision",
8140                "idx" => $val['avis_decision'],
8141            ));
8142            if (preg_match('/[tT]acite/', $inst_ad->getVal('libelle')) === 1) {
8143                $val['tacite'] = 't';
8144            }
8145            return $val;
8146        }
8147    
8148        public function get_related_instructions_next($next_type = 'retour_signature', $instruction = null) {
8149            if (in_array($next_type, array('retour_signature', 'retour_ar', 'suivant_tacite', )) === false) {
8150                return false;
8151            }
8152            $result = array();
8153            $evenements = array();
8154            if ($instruction === null) {
8155                $instruction = $this->getVal($this->clePrimaire);
8156                $evenement = $this->getVal('evenement');
8157                $dossier = $this->getVal('dossier');
8158            } else {
8159                $inst = $this->f->get_inst__om_dbform(array(
8160                    "obj" => "instruction",
8161                    "idx" => $instruction,
8162                ));
8163                $evenement = $inst->getVal('evenement');
8164                $dossier = $inst->getVal('dossier');
8165            }
8166            //
8167            $query = sprintf('
8168                SELECT evenement_%3$s
8169                FROM %1$sevenement
8170                WHERE evenement = %2$s
8171                ',
8172                DB_PREFIXE,
8173                $evenement,
8174                $next_type
8175            );
8176            $res = $this->f->get_one_result_from_db_query($query, true);
8177            if ($res['code'] === 'KO') {
8178                return false;
8179            }
8180            $ev_next = $res['result'];
8181            //
8182            $query = sprintf('
8183                SELECT MAX(instruction.instruction) as instruction
8184                FROM %1$sinstruction
8185                WHERE dossier = \'%3$s\'
8186                    AND evenement = %2$s
8187                ',
8188                DB_PREFIXE,
8189                $ev_next,
8190                $dossier
8191            );
8192            $res = $this->f->get_one_result_from_db_query($query, true);
8193            if ($res['code'] === 'KO') {
8194                return false;
8195            }
8196            //
8197            return $res['result'];
8198        }
8199    
8200        public function get_related_instructions($instruction = null) {
8201            $result = array();
8202            $evenements = array();
8203            if ($instruction === null) {
8204                $instruction = $this->getVal($this->clePrimaire);
8205                $evenement = $this->getVal('evenement');
8206                $dossier = $this->getVal('dossier');
8207            } else {
8208                $inst = $this->f->get_inst__om_dbform(array(
8209                    "obj" => "instruction",
8210                    "idx" => $instruction,
8211                ));
8212                $evenement = $inst->getVal('evenement');
8213                $dossier = $inst->getVal('dossier');
8214            }
8215            //
8216            $query = sprintf('
8217                SELECT evenement
8218                FROM %1$sevenement
8219                WHERE evenement_retour_ar = %2$s
8220                    OR evenement_retour_signature = %2$s
8221                ',
8222                DB_PREFIXE,
8223                $evenement
8224            );
8225            $res = $this->f->get_one_result_from_db_query($query, true);
8226            if ($res['code'] === 'KO') {
8227                return false;
8228            }
8229            $ev_parent = $res['result'];
8230            //
8231            $query = sprintf('
8232                SELECT MAX(instruction.instruction) as instruction
8233                FROM %1$sinstruction
8234                WHERE dossier = \'%3$s\'
8235                    AND evenement = %2$s
8236                ',
8237                DB_PREFIXE,
8238                $ev_parent,
8239                $dossier
8240            );
8241            $res = $this->f->get_one_result_from_db_query($query, true);
8242            if ($res['code'] === 'KO') {
8243                return false;
8244            }
8245            $result[] = $res['result'];
8246            //
8247            $query = sprintf('
8248                SELECT evenement_retour_ar
8249                FROM %1$sevenement
8250                WHERE evenement = %2$s
8251                    AND evenement_retour_ar != %3$s
8252                ',
8253                DB_PREFIXE,
8254                $ev_parent,
8255                $evenement
8256            );
8257            $res = $this->f->get_one_result_from_db_query($query, true);
8258            if ($res['code'] === 'KO') {
8259                return false;
8260            }
8261            $evenements[] = $res['result'];
8262            //
8263            $query = sprintf('
8264                SELECT evenement_retour_signature
8265                FROM %1$sevenement
8266                WHERE evenement = %2$s
8267                    AND evenement_retour_signature != %3$s
8268                ',
8269                DB_PREFIXE,
8270                $ev_parent,
8271                $evenement
8272            );
8273            $res = $this->f->get_one_result_from_db_query($query, true);
8274            if ($res['code'] === 'KO') {
8275                return false;
8276            }
8277            $evenements[] = $res['result'];
8278            foreach ($evenements as $value) {
8279                if ($value !== null) {
8280                    $query = sprintf('
8281                        SELECT MAX(instruction.instruction) as instruction
8282                        FROM %1$sinstruction
8283                        WHERE dossier = \'%3$s\'
8284                            AND evenement = %2$s
8285                        ',
8286                        DB_PREFIXE,
8287                        $value,
8288                        $dossier
8289                    );
8290                    $res = $this->f->get_one_result_from_db_query($query, true);
8291                    if ($res['code'] === 'KO') {
8292                        return false;
8293                    }
8294                    $result[] = $res['result'];
8295                }
8296            }
8297            return $result;
8298        }
8299    
8300        protected function getDocumentType($champ = null) {
8301            $evenementId = $this->getVal('evenement');
8302            if (! empty($evenementId)) {
8303                $evenement = $this->f->findObjectById('evenement', $evenementId);
8304                if (! empty($evenement)) {
8305                    return __("Instruction").':'.$evenement->getVal('libelle');
8306                }
8307            }
8308            return parent::getDocumentType();
8309        }
8310    
8311        /**
8312         * Récupère à l'aide d'une requête sql la liste des demandeurs
8313         * pouvant être notifié. C'est à dire les demandeurs acceptant
8314         * les notifications et pour lesquels une adresse mail existe.
8315         *
8316         * Dans le cas, d'une notification pour le portail citoyen, seul
8317         * le pétitionnaire principal doit être notifier et uniquement si
8318         * il a une adress mail et qu'il accepte les notifications.
8319         *
8320         * @param string identifiant du dossier
8321         * @param boolean true si il faut récupérer la liste des demandeurs notifiable
8322         * pour une notification de categorie portail
8323         * @return array liste des demandeurs pouvant être notifié
8324        */
8325        protected function get_demandeurs_notifiable($idDossier = null, $portail = false) {
8326            if ($idDossier === null) {
8327                $idDossier = $this->getVal('dossier');
8328            }
8329            // Ajoute une condition sur le where pour ne récupérer que le pétitionnaire principal
8330            // pour une notification depuis le portail citoyen
8331            $sqlPetitionnairePrincipal = '';
8332            if ($portail === true) {
8333                $sqlPetitionnairePrincipal = 'AND lien_dossier_demandeur.petitionnaire_principal = true';
8334            }
8335    
8336            $listeDemandeursNotifiable = array();
8337    
8338            // Requête de récupération des demandeurs
8339            $sql = sprintf(
8340                'SELECT
8341                    demandeur.demandeur,
8342                    CASE
8343                        WHEN demandeur.qualite=\'particulier\'
8344                        THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
8345                    ELSE
8346                        TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
8347                    END AS destinataire,
8348                    demandeur.courriel
8349                FROM
8350                    %1$sdossier
8351                    INNER JOIN %1$slien_dossier_demandeur
8352                        ON dossier.dossier = lien_dossier_demandeur.dossier
8353                    INNER JOIN %1$sdemandeur
8354                        ON lien_dossier_demandeur.demandeur = demandeur.demandeur
8355                WHERE
8356                    dossier.dossier = \'%2$s\' AND
8357                    notification = \'t\' AND
8358                    courriel IS NOT NULL
8359                    %3$s',
8360                DB_PREFIXE,
8361                $idDossier,
8362                $sqlPetitionnairePrincipal
8363            );
8364            $res = $this->f->db->query($sql);
8365            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
8366            $this->f->isDatabaseError($res);
8367            // Récupération des infos des demandeurs et stockage dans un tableau
8368            // ayant pour clé les id des demandeurs
8369            while($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
8370                $listeDemandeursNotifiable[$row['demandeur']] = $row;
8371            }
8372    
8373            return $listeDemandeursNotifiable;
8374        }
8375    
8376        /**
8377         * Renvoie la liste des notifications liées à l'instruction
8378         *
8379         * @param integer id de l'instruction dont on cherche les notifications
8380         * @return array liste des instruction_notification liés à l'instruction
8381         */
8382        public function get_instruction_notification($id_instruction) {
8383            $listeInstrNotif = array();
8384            $sql = sprintf('
8385                SELECT
8386                    instruction_notification.instruction_notification
8387                FROM
8388                    %1$sinstruction_notification
8389                WHERE
8390                    instruction = %2$s',
8391                DB_PREFIXE,
8392                $id_instruction
8393            );
8394            $res = $this->f->db->query($sql);
8395            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
8396            $this->f->isDatabaseError($res);
8397            while ($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
8398                $listeInstrNotif[] = $row['instruction_notification'];
8399            }
8400            return $listeInstrNotif;
8401        }
8402    
8403        /**
8404         * Crée une clé d'accès unique permettant à un utilisateur
8405         * anonyme de récupérer le document.
8406         *
8407         * @return string clé d'accès du document
8408         */
8409        protected function getCleAccesDocument() {
8410            // Initialisation d'un tableau
8411            $number_list = array();
8412    
8413            // Génération aléatoire d'un nombre sur 4 caractères, 4 fois
8414            for ($i = 0; $i < 4; $i++) {
8415                $number_list[] = str_pad(mt_rand(0, 9999), 4, 0, STR_PAD_LEFT);
8416            }
8417    
8418            // Transformation en chaîne tout en séparant les nombres par un "-"
8419            $result = implode('-', $number_list);
8420    
8421            // Vérifie si la clé existe déjà et si c'est le cas génére une nouvelle clé
8422            if ($this->getUidDocumentInstructionWithKey($result) != null) {
8423                return $this->getCleAccesDocument();
8424            }
8425    
8426            //
8427            return $result;
8428        }
8429    
8430        /**
8431         * Récupère une clé et renvoie l'uid du document liée à cette
8432         * clé. Si la clé n'existe pas renvoie null.
8433         *
8434         * @param string $cleGen clé dont on cherche l'instruction
8435         * @return integer|null
8436         */
8437        protected function getUidDocumentInstructionWithKey($cleGen) {
8438            $query = sprintf(
8439                'SELECT
8440                    instruction.om_fichier_instruction
8441                FROM
8442                    %1$sinstruction_notification_document
8443                    LEFT JOIN %1$sinstruction ON instruction_notification_document.instruction = instruction.instruction
8444                WHERE
8445                    instruction_notification_document.cle = \'%2$s\'',
8446                DB_PREFIXE,
8447                $this->f->db->escapeSimple($cleGen)
8448            );
8449    
8450            $res = $this->f->db->getOne($query);
8451            $this->addToLog(__METHOD__.": db->getOne(\"".$query."\");", VERBOSE_MODE);
8452            $this->f->isDatabaseError($res);
8453            return $res;
8454        }
8455    
8456        /**
8457         * Récupère une clé, fait une requête pour récupérer l'id de la notification liée a cette clé.
8458         * Récupère l'instance de instruction_notification dont l'id a été récupéré et la renvoie.
8459         *
8460         * @param string $cleGen
8461         * @return instruction_notification
8462         */
8463        protected function getInstanceNotificationWithKey($key) {
8464            $sql = sprintf(
8465                "SELECT
8466                    instruction_notification
8467                FROM
8468                    %1\$sinstruction_notification_document
8469                WHERE
8470                    cle = '%2\$s'",
8471                DB_PREFIXE,
8472                $this->f->db->escapeSimple($key)
8473            );
8474            $res = $this->f->db->getOne($sql);
8475            $this->addToLog(__METHOD__.": db->getOne(\"".$sql."\");", VERBOSE_MODE);
8476            $this->f->isDatabaseError($res);
8477    
8478            // Récupération de l'instance de notification
8479            $instNotif = $this->f->get_inst__om_dbform(array(
8480                "obj" => "instruction_notification",
8481                "idx" => $res,
8482            ));
8483            return $instNotif;
8484        }
8485    
8486    
8487        /**
8488         * Affiche la page de téléchargement du document de la notification.
8489         *
8490         * @param boolean $content_only Affiche le contenu seulement.
8491         *
8492         * @return void
8493         */
8494        public function view_telecharger_document_anonym() {
8495            // Par défaut on considère qu'on va afficher le formulaire
8496            $idx = 0;
8497            // Flag d'erreur
8498            $error = false;
8499            // Message d'erreur
8500            $message = '';
8501    
8502            // Paramètres GET : récupération de la clé d'accès
8503            $cle_acces_document = $this->f->get_submitted_get_value('key');
8504            $cle_acces_document = $this->f->db->escapeSimple($cle_acces_document);
8505            // Vérification de l'existence de la clé et récupération de l'uid du fichier
8506            $uidFichier = $this->getUidDocumentInstructionWithKey($cle_acces_document);
8507            if ($uidFichier != null) {
8508                // Récupération du document
8509                $file = $this->f->storage->get($uidFichier);
8510    
8511                // Headers
8512                header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
8513                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
8514                header("Content-Type: ".$file['metadata']['mimetype']);
8515                header("Accept-Ranges: bytes");
8516                header("Content-Disposition: inline; filename=\"".$file['metadata']['filename']."\";" );
8517                // Affichage du document
8518                echo $file['file_content'];
8519    
8520                // Récupération de la date de premier accès et maj du suivi uniquement
8521                // si la date de 1er accès n'a pas encore été remplis
8522                $inst_notif = $this->getInstanceNotificationWithKey($cle_acces_document);
8523                if ($inst_notif->getVal('date_premier_acces') == null ||
8524                    $inst_notif->getVal('date_premier_acces') == '') {
8525                    $notif_val = array();
8526                    foreach ($inst_notif->champs as $champ) {
8527                        $notif_val[$champ] = $inst_notif->getVal($champ);
8528                    }
8529                    $notif_val['date_premier_acces'] = date("d/m/Y H:i:s");
8530                    $notif_val['statut'] = 'vu';
8531                    $notif_val['commentaire'] = 'Le document a été vu';
8532                    $suivi_notif = $inst_notif->modifier($notif_val);
8533                }
8534    
8535            } else {
8536                // Page vide 404
8537                printf('Ressource inexistante');
8538                header('HTTP/1.0 404 Not Found');
8539            }
8540        }
8541    
8542        /**
8543         * Récupère le titre du document envoyé au parapheur
8544         */
8545        protected function getDocumentTitre($champ = null) {
8546            $title = $this->getTitle();
8547            $dossier = $this->getDossier();
8548            return $dossier.' '.$title;
8549        }
8550    
8551        /**
8552         * Compose le nom du document à transmettre au parapheur.
8553         * Le nom ets composé de cette manière :
8554         * instruction_xxx_libelle_de_la_lettre_type_associee
8555         * ou xxx correspond au numéro de l'instruction
8556         */
8557        protected function getDocumentLibelle() {
8558            // Récupère le champ instruction
8559            $instruction = $this->getVal("instruction");
8560    
8561            // Requête sql servant à récupérer le titre du document
8562            // TO_CHAR() introduit un espace avant l'affichage du nombre
8563            // comme les espaces sont remplacé par des '_' dans le retour de la fonction
8564            // il n'est pas nécessaire de mettre un '_' après le mot instruction.
8565            $sql = sprintf(
8566                'SELECT
8567                    CONCAT(
8568                        \'instruction\',
8569                        TO_CHAR(instruction.instruction, \'000\'),
8570                        \'_\',
8571                        LOWER(om_lettretype.libelle)
8572                    ) as nom_fichier
8573                FROM
8574                    %1$sinstruction
8575                    LEFT JOIN %1$som_lettretype ON om_lettretype.id = instruction.lettretype
8576                WHERE
8577                    instruction = %2$s',
8578                DB_PREFIXE,
8579                $instruction
8580            );
8581            $documentLibelle = $this->f->db->getOne($sql);
8582            $this->addToLog("getDocumentTitre(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
8583            if (database::isError($documentLibelle)) {
8584                die();
8585            }
8586    
8587            // Transforamtion des ' ' en '_', des accents en lettres sans accents et des
8588            // caractères spéciaux en '_'
8589            // La méthode normalize_string est utilisé pour gérer les accents
8590            $documentLibelle = $this->f->normalize_string($documentLibelle);
8591            // TODO : comparer cette liste et celle de la méthode normalize_string
8592            // pour éviter les doublons + vérifier qu'il n'y a pas de doublons dans cette
8593            // liste
8594            $invalid = array('Œ'=>'oe', 'œ'=>'oe', 'Ÿ'=>'y', 'ü'=>'u',
8595                '¢' => '_', 'ß' => '_', '¥' => '_', '£' => '_', '™' => '_', '©' => '_',
8596                '®' => '_', 'ª' => '_', '×' => '_', '÷' => '_', '±' => '_', '²' => '_',
8597                '³' => '_', '¼' => '_', '½' => '_', '¾' => '_', 'µ' => '_', '¿' => '_',
8598                '¶' => '_', '·' => '_', '¸' => '_', 'º' => '_', '°' => '_', '¯' => '_',
8599                '§' => '_', '…' => '_', '¤' => '_', '¦' => '_', '≠' => '_', '¬' => '_',
8600                'ˆ' => '_', '¨' => '_', '‰' => '_', '¤' => '_', '€' => '_', '$' => '_',
8601                '«' => '_', '»' => '_', '‹' => '_', '›' => '_', 'ƒ' => '_', '¥' => '_',
8602                '‘‘' => '_', '‚' => '_', '!' => '_', '¡' => '_', '¢' => '_', '£' => '_',
8603                '?' => '_', '[' => '_', ']' => '_', '´' => '_', '`' => '_', '^' => '_',
8604                '~' => '_', '˜' => '_', '#' => '_', '*' => '_', '.' => '_', ':' => '_',
8605                ';' => '_', '•' => '_', '¯' => '_', '‾' => '_', '–' => '_', '–' => '_',
8606                '—' => '_', '_' => '_', '|' => '_', '¦‌' => '_', '‡' => '_', '§' => '_',
8607                '¶' => '_', '©' => '_', '®' => '_', '™' => '_', '&' => '_', '@' => '_',
8608                '/' => '_', '\\' => '_', '◊' => '_', '♠' => '_', '♣' => '_', '♥' => '_',
8609                '♦' => '_', '←' => '_', '↑' => '_', '→' => '_', '↓' => '_', '↔' => '_',
8610                '°' => '_', 'µ' => '_', '<' => '_', '>' => '_', '≤' => '_', '≥' => '_',
8611                '=' => '_', '≈' => '_', '≠' => '_', '≡' => '_', '±' => '_', '−' => '_',
8612                '+' => '_', '×' => '_', '÷' => '_', '⁄' => '_', '%' => '_', '‰' => '_',
8613                '¼' => '_', '½' => '_', '¾' => '_', '¹' => '_', '²' => '_', '³' => '_',
8614                '' => '_', 'º' => '_', 'ª' => '_', 'ƒ' => '_', '′' => '_', '″' => '_',
8615                '∂' => '_', '∏' => '_', '∑' => '_', '√' => '_', '∞' => '_', '¬' => '_',
8616                '∩' => '_', '∫' => '_', 'α' => '_', 'Α' => '_', 'β' => '_', 'Β' => '_',
8617                'γ' => '_', 'Γ' => '_', 'δ' => '_', 'Δ' => '_', 'ε' => '_', 'Ε' => '_',
8618                'ζ' => '_', 'Ζ' => '_', 'η' => '_', 'Η' => '_', 'θ' => '_', 'Θ' => '_',
8619                'ι' => '_', 'Ι' => '_', 'κ' => '_', 'Κ' => '_', 'λ' => '_', 'Λ' => '_',
8620                'μ' => '_', 'Μ' => '_', 'ν' => '_', 'Ν' => '_', 'ξ' => '_', 'Ξ' => '_',
8621                'ο' => '_', 'Ο' => '_', 'π' => '_', 'Π' => '_', 'ρ' => '_', 'Ρ' => '_',
8622                'σ' => '_', 'ς' => '_', 'Σ' => '_', 'τ' => '_', 'Τ' => '_', 'υ' => '_',
8623                'Υ' => '_', 'φ' => '_', 'Φ' => '_', 'χ' => '_', 'Χ' => '_', 'ψ' => '_',
8624                'Ψ' => '_', 'ω' => '_', 'Ω' => '_', ',' => '_', ' ' => '_'
8625            );
8626    
8627            return str_replace(array_keys($invalid), array_values($invalid), $documentLibelle);
8628        }
8629    
8630        /**
8631         * Surcharge permettant de ne pas afficher le fil d'Ariane dans
8632         * l'overlay de notification des demandeurs.
8633         */
8634        function getSubFormTitle($ent) {
8635            if ($this->getParameter('maj') == '411') {
8636                return '';
8637            }
8638            return parent::getSubFormTitle($ent);
8639        }
8640    }// fin classe

Legend:
Removed from v.6272  
changed lines
  Added in v.11418

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26