/[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 5254 by nhaye, Fri Nov 25 10:59:14 2016 UTC revision 12654 by softime, Mon Aug 1 16:58:31 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 68  class instruction extends instruction_ge Line 68  class instruction extends instruction_ge
68              "dateEvenementDocument" => "getDateEvenementDocument",              "dateEvenementDocument" => "getDateEvenementDocument",
69              "groupeInstruction" => 'getGroupeInstruction',              "groupeInstruction" => 'getGroupeInstruction',
70              "title" => 'getTitle',              "title" => 'getTitle',
71                '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 84  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 108  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 134  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 151  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 165  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 180  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 225  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 262  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 270  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            // ACTION - 404 - Annuler l'envoi en signature
415            // Cet évenement permet d'annuler l'envoi en signature du document au parapheur
416            $this->class_actions[404] = array(
417                "identifier" => "annuler_envoi_signature",
418                "portlet" => array(
419                    "libelle" => __("Annuler l'envoi en signature"),
420                    "type" => "action-direct-with-confirmation",
421                    "class" => "annuler_envoi_signature-16",
422                ),
423                "view" => "formulaire",
424                "method" => "annuler_envoi_en_signature",
425                "condition" => array(
426                    "is_sent_for_signature",
427                    "is_parapheur_annulation_parameter_enabled"
428                ),
429                "permission_suffix" => "envoyer_a_signature",
430            );
431    
432            //
433            $this->class_actions[401] = array(
434                "identifier" => "preview_edition",
435                "view" => "formulaire",
436                "permission_suffix" => "tab",
437            );
438    
439            // ACTION - 410 - Notifier les pétitionnaires (mail ou autre)
440            $this->class_actions[410] = array(
441                "identifier" => "overlay_notification_manuelle",
442                "portlet" => array(
443                    "libelle" => __("Notifier les pétitionnaires"),
444                    "type" => "action-self",
445                    "class" => "notifier_commune-16",
446                ),
447                "condition" => array(
448                    "is_notifiable_by_task_manual",
449                    "is_not_portail_notification_sans_annexe"
450                ),
451                "view" => "view_overlay_notification_manuelle",
452                "permission_suffix" => "modifier",
453            );
454    
455            // ACTION - 411 - Notifier les pétitionnaires (portail citoyen)
456            $this->class_actions[411] = array(
457                "identifier" => "notification_manuelle_portal",
458                "portlet" => array(
459                    "libelle" => __("Notifier les pétitionnaires"),
460                    "type" => "action-direct-with-confirmation",
461                    "class" => "notifier_commune-16",
462                ),
463                "condition" => array(
464                    "is_notifiable_by_task_manual",
465                    "is_portail_notification_sans_annexe"
466                ),
467                "method" => "notifier_demandeur_principal",
468                "permission_suffix" => "modifier",
469            );
470    
471            // ACTION - 420 - Notifier les services consultés (mail)
472            $this->class_actions[420] = array(
473                "identifier" => "overlay_notification_service_consulte",
474                "portlet" => array(
475                    "libelle" => __("Notifier les services consultés"),
476                    "type" => "action-self",
477                    "class" => "notifier_commune-16",
478                ),
479                "condition" => array(
480                    "is_service_notifiable"
481                ),
482                "view" => "view_overlay_notification_service_consulte",
483                "permission_suffix" => "tab",
484            );
485    
486            // ACTION - 430 - Notifier les tiers consultés (mail)
487            $this->class_actions[430] = array(
488                "identifier" => "overlay_notification_tiers_consulte",
489                "portlet" => array(
490                    "libelle" => __("Notifier les tiers consultés"),
491                    "type" => "action-self",
492                    "class" => "notifier_commune-16",
493                ),
494                "condition" => array(
495                    "is_tiers_notifiable"
496                ),
497                "view" => "view_overlay_notification_tiers_consulte",
498                "permission_suffix" => "tab",
499            );
500    
501            //
502            $this->class_actions[403] = array(
503                "identifier" => "envoyer_au_controle_de_legalite",
504                "portlet" => array(
505                    "libelle" => __("Envoyer au contrôle de légalité"),
506                    "type" => "action-direct-with-confirmation",
507                    "class" => "envoyer_au_controle_de_legalite-16",
508                ),
509                "view" => "formulaire",
510                "method" => "envoyer_au_controle_de_legalite",
511                "condition" => array(
512                    "can_be_sended_to_cl"
513                ),
514                "permission_suffix" => "envoyer_au_controle_de_legalite",
515            );
516    
517            //
518            $this->class_actions[998] = array(
519                "identifier" => "json_data",
520                "view" => "view_json_data",
521                "permission_suffix" => "consulter",
522            );
523        }
524    
525        /**
526         * Clause select pour la requête de sélection des données de l'enregistrement.
527         *
528         * @return array
529         */
530        function get_var_sql_forminc__champs() {
531            return array(
532                "instruction",
533                "destinataire",
534                "instruction.evenement",
535                "instruction.commentaire",
536                "date_evenement",
537                "instruction.lettretype",
538                "signataire_arrete",
539                "flag_edition_integrale",
540                "om_final_instruction_utilisateur",
541                "date_finalisation_courrier",
542                "date_envoi_signature",
543                "date_envoi_rar",
544                "date_envoi_controle_legalite",
545    
546                "date_retour_signature",
547                "date_retour_rar",
548                "date_retour_controle_legalite",
549    
550                "numero_arrete",
551    
552                "complement_om_html",
553                "'' as bible_auto",
554                "'' as bible",
555                "complement2_om_html",
556                "'' as bible2",
557                "complement3_om_html",
558                "'' as bible3",
559                "complement4_om_html",
560                "'' as bible4",
561    
562                "titre_om_htmletat",
563                "corps_om_htmletatex",
564    
565                "'' as btn_preview",
566                "'' as btn_redaction",
567    
568                "'' as btn_refresh",
569                "'' as live_preview",
570    
571                "dossier",
572                "instruction.action",
573                "instruction.delai",
574                "instruction.etat",
575                "instruction.autorite_competente",
576                "instruction.accord_tacite",
577                "instruction.delai_notification",
578                "instruction.avis_decision",
579                "archive_delai",
580                "archive_accord_tacite",
581                "archive_etat",
582                "archive_avis",
583                "archive_date_complet",
584                "archive_date_rejet",
585                "archive_date_limite",
586                "archive_date_notification_delai",
587                "archive_date_decision",
588                "archive_date_validite",
589                "archive_date_achevement",
590                "archive_date_conformite",
591                "archive_date_chantier",
592                "archive_date_dernier_depot",
593                "date_depot",
594                "date_depot_mairie",
595                "complement5_om_html",
596                "'' as bible5",
597                "complement6_om_html",
598                "'' as bible6",
599                "complement7_om_html",
600                "'' as bible7",
601                "complement8_om_html",
602                "'' as bible8",
603                "complement9_om_html",
604                "'' as bible9",
605                "complement10_om_html",
606                "'' as bible10",
607                "complement11_om_html",
608                "'' as bible11",
609                "complement12_om_html",
610                "complement13_om_html",
611                "complement14_om_html",
612                "complement15_om_html",
613                "archive_incompletude",
614                "archive_incomplet_notifie",
615                "archive_evenement_suivant_tacite",
616                "archive_evenement_suivant_tacite_incompletude",
617                "archive_etat_pendant_incompletude",
618                "archive_date_limite_incompletude",
619                "archive_delai_incompletude",
620                "archive_autorite_competente",
621                "code_barres",
622                "om_fichier_instruction",
623                "om_final_instruction",
624                "om_fichier_instruction_dossier_final",
625                "document_numerise",
626                "duree_validite_parametrage",
627                "duree_validite",
628                "created_by_commune",
629                "archive_date_cloture_instruction",
630                "archive_date_premiere_visite",
631                "archive_date_derniere_visite",
632                "archive_date_contradictoire",
633                "archive_date_retour_contradictoire",
634                "archive_date_ait",
635                "archive_date_transmission_parquet",
636                "archive_dossier_instruction_type",
637                "archive_date_affichage",
638                "pec_metier",
639                "archive_pec_metier",
640                "archive_a_qualifier",
641                "id_parapheur_signature",
642                "statut_signature",
643                "commentaire_signature",
644                "historique_signature",
645                "'' as suivi_notification",
646                "'' as suivi_notification_service",
647                "'' as suivi_notification_tiers",
648                "'' as suivi_notification_commune",
649    
650                "'' as preview_edition",
651                "envoye_cl_platau",
652                "'' as log_instruction"
653            );
654        }
655    
656        /**
657         * CONDITION - is_edition_integrale_enabled
658         *
659         * Vérifie que la rédaction libre est activée sur l'instruction en cours.
660         *
661         * @return boolean
662         */
663        function is_edition_integrale_enabled() {
664            if ($this->getVal("flag_edition_integrale") == 't') {
665                return true;
666            }
667            return false;
668      }      }
669    
670      /**      /**
671       * Cette variable permet de stocker le résultat de la méthode       * CONDITION - is_edition_integrale_not_enabled
672       * getDivisionFromDossier() afin de ne pas effectuer le recalcul à chacun de       *
673       * ces appels.       * Vérifie que la rédaction libre est désactivée sur l'instruction en cours.
674       * @var string Code de la division du dossier en cours       *
675         * @return boolean
676         */
677        function is_edition_integrale_not_enabled() {
678            return !$this->is_edition_integrale_enabled();
679        }
680    
681        /**
682         * CONDITION - is_option_redaction_libre_enabled
683         *
684         * Vérifie que l'option de rédaction libre est activée.
685         *
686         * @return boolean
687       */       */
688      var $_division_from_dossier = NULL;      function is_option_redaction_libre_enabled() {
689            $collectivite_di = $this->get_dossier_instruction_om_collectivite();
690            return $this->f->is_option_redaction_libre_enabled($collectivite_di);
691        }
692    
693      /**      /**
694       * Cette méthode permet de récupérer le code de division correspondant       * CONDITION - is_option_parapheur_relecture_enabled
      * au dossier sur lequel on se trouve.  
695       *       *
696       * @return string Code de la division du dossier en cours       * Vérifie que l'option de relecture lors de l'envoi en signature est activée.
697         *
698         * @return boolean
699       */       */
700      function getDivisionFromDossier() {      function is_parapheur_relecture_parameter_enabled() {
701            //Instanciation de la classe electronicsignature
702            $inst_es = $this->get_electronicsignature_instance();
703            if ($inst_es === false) {
704                return false;
705            }
706    
707          // Cette méthode peut être appelée plusieurs fois lors d'une requête.          if ($inst_es->get_conf('is_forced_view_files') !== 'true' && $inst_es->get_conf('is_forced_view_files') !== true) {
708          // Pour éviter de refaire le traitement de recherche de la division              return false;
         // alors on vérifie si nous ne l'avons pas déjà calculé.  
         if ($this->_division_from_dossier != NULL) {  
             // Logger  
             $this->addToLog("getDivisionFromDossier(): retour de la valeur déjà calculée - '".$this->_division_from_dossier."'", EXTRA_VERBOSE_MODE);  
             // On retourne la valeur déjà calculée  
             return $this->_division_from_dossier;  
709          }          }
710    
711          // Par défaut, on définit la valeur du dossier à NULL          return true;
712          $dossier = NULL;      }
713          // Test sur le mode et le contexte du formulaire  
714          if ($this->getParameter("maj") == 0      /**
715              && ($this->getParameter("retourformulaire") == "dossier"       * CONDITION - is_parapheur_annulation_parameter_enabled
716                  || $this->getParameter("retourformulaire") == "dossier_instruction"       *
717                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"       * Vérifie que l'option d'annulation de l'envoi en signature est activée.
718                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"       *
719                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"       * @return boolean
720                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures")) {       */
721              // Si on se trouve en mode AJOUT (seul mode où l'enregistrement      function is_parapheur_annulation_parameter_enabled() {
722              // n'existe pas en base de données) ET que nous nous trouvons          //Instanciation de la classe electronicsignature
723              // dans le contexte d'un dossier d'instruction alors on récupère          $inst_es = $this->get_electronicsignature_instance();
724              // le numéro de dossier depuis le paramètre 'idxformulaire'          if ($inst_es === false) {
725              $dossier = $this->getParameter("idxformulaire");              return false;
726            }
727    
728            if ($inst_es->get_conf('cancel_send') !== 'true' && $inst_es->get_conf('cancel_send') !== true) {
729                return false;
730            }
731    
732            return true;
733        }
734    
735    
736        /**
737         * CONDITION - is_sent_for_signature
738         *
739         * Vérifie que l'instruction a été envoyé à signature
740         *
741         * @return boolean
742         */
743        function is_sent_for_signature() {
744            // Si un parapheur a été configuré
745            // et que le champ id_parapheur_signature n'est pas vide
746            // que le status est différent de "canceled" ou "expired"
747            // alors l'évènement a été envoyé en signature
748            if ($this->has_connector_electronicsignature() === true
749                && empty($this->getVal("id_parapheur_signature")) === false
750                && ($this->getVal("statut_signature") != "canceled"
751                && $this->getVal("statut_signature") != "expired"
752                && $this->getVal("statut_signature") != "finished")) {
753                //
754                return true;
755            }
756    
757            return false;
758        }
759    
760        /**
761         * CONDITION - is_not_sent_for_signature
762         *
763         * Vérifie que l'instruction n'a pas été envoyé à signature
764         *
765         * @return boolean
766         */
767        function is_not_sent_for_signature() {
768            // Contrôle si l'utilisateur possède un bypass
769            $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_definaliser_bypass");
770            if ($bypass == true) {
771                return true;
772            }
773    
774            return !$this->is_sent_for_signature();
775        }
776    
777    
778        /**
779         * CONDITION - is_signed
780         *
781         * Vérifie que l'instruction a été signé
782         *
783         * @return boolean
784         */
785        function is_signed() {
786            // Si un parapheur a été configuré
787            // et que le champ id_parapheur_signature n'est pas vide
788            //  et que le statut est égal à "finished"
789            // alors le document de l'instruciton à été signé
790            if ($this->has_connector_electronicsignature() === true
791                && empty($this->getVal("id_parapheur_signature")) === false
792                && $this->getVal("statut_signature") == "finished") {
793                //
794                return true;
795            }
796    
797            return false;
798        }
799    
800    
801        /**
802         * is_sent_to_cl
803         *
804         * Vérifie que l'instruction a été envoyé au contrôle de légalité
805         *
806         * @return boolean
807         */
808        function is_sent_to_cl() {
809            // Si la case à cocher de l'instruction envoye_cl_platau est à "t"
810            if ($this->getVal('envoye_cl_platau') === 't') {
811                //
812                return true;
813            }
814            //
815            return false;
816        }
817    
818        /**
819         * CONDITION - is_portail_notification
820         *
821         * Vérifie si la notification est une notification de catégorie portail
822         *
823         * @return boolean
824         */
825        function is_portail_notification_sans_annexe() {
826            $collectiviteDi = $this->get_dossier_instruction_om_collectivite();
827            $ev = $this->get_inst_evenement($this->getVal('evenement'));
828            if (($this->f->get_param_option_notification($collectiviteDi) === null ||
829                $this->f->get_param_option_notification($collectiviteDi) === 'portal')
830                && $ev->getVal('notification') != 'notification_manuelle_annexe'
831                && $ev->getVal('notification') != 'notification_manuelle_annexe_signature_requise'
832            ) {
833                return true;
834            }
835            return false;
836        }
837    
838        /**
839         * CONDITION - is_not_portail_notification
840         *
841         * Vérifie si la notification n'est pas une notification de catégorie portail
842         *
843         * @return boolean
844         */
845        function is_not_portail_notification_sans_annexe() {
846            return (! $this->is_portail_notification_sans_annexe());
847        }
848    
849        /**
850         * CONDITION - can_be_signed
851         *
852         * Vérifie que le document de l'instruction peut être envoyé au parapheur pour signature
853         *
854         * @return boolean
855         */
856        function can_be_signed() {
857            // Instanciation de l'objet signataire_arrete
858            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
859                "obj" => "signataire_arrete",
860                "idx" => $this->getVal("signataire_arrete"),
861            ));
862            // Si un parapheur a été configuré, que le document est finalisé, que le signataire
863            // possède une adresse email, on vérifie le champ id_parapheur_signature
864            // S'il est vide l'évènement peut être envoyé en signature
865            // S'il ne l'est pas, alors on vérifie le champ statut_signature
866            // Si la valeur de ce champ est égal à "canceled" ou "expired"
867            // alors l'évènement peut être envoyé en signature
868            if ($this->has_connector_electronicsignature() === true
869                && $this->getVal("om_final_instruction") == 't'
870                && empty($inst_signataire_arrete->getVal('email')) === false) {
871                //
872                if (empty($this->getVal("id_parapheur_signature")) === true
873                    || $this->getVal("statut_signature") == "canceled"
874                    || $this->getVal("statut_signature") == "expired") {
875                    //
876                    return true;
877                }
878            }
879    
880            $this->addToLog(__METHOD__."() has_connector_electronicsignature: ".var_export($this->has_connector_electronicsignature(), true), EXTRA_VERBOSE_MODE);
881            $this->addToLog(__METHOD__."() om_final_instruction: ".var_export($this->getVal("om_final_instruction"), true), EXTRA_VERBOSE_MODE);
882            $this->addToLog(__METHOD__."() email: ".var_export($inst_signataire_arrete->getVal('email'), true), EXTRA_VERBOSE_MODE);
883            $this->addToLog(__METHOD__."() id_parapheur_signature: ".var_export($this->getVal("id_parapheur_signature"), true), EXTRA_VERBOSE_MODE);
884            $this->addToLog(__METHOD__."() statut_signature: ".var_export($this->getVal("statut_signature"), true), EXTRA_VERBOSE_MODE);
885    
886            return false;
887        }
888    
889        /**
890         * CONDITION - has_connector_electronicsignature
891         *
892         * Vérifie qu'un parapheur est paramétré
893         *
894         * @return boolean
895         */
896        function has_connector_electronicsignature() {
897            $inst_es = $this->get_electronicsignature_instance(false);
898            if ($inst_es === false) {
899                return false;
900            }
901            return true;
902        }
903    
904        /**
905         * CONDITION - can_display_parapheur
906         *
907         * Vérifie que le fieldset "Suivi Parapheur" soit affichable
908         *
909         * @return boolean
910         */
911        function can_display_parapheur() {
912            $evenement_id = $this->getVal("evenement");
913            $inst_evenement = $this->get_inst_evenement($evenement_id);
914            if ($this->has_connector_electronicsignature() === true
915                && $inst_evenement->getVal('lettretype') !== ''
916                && $inst_evenement->getVal('lettretype') !== null
917                && (empty($this->getVal("id_parapheur_signature")) === false
918                    || empty($this->getVal("historique_signature")) === false)) {
919                //
920                return true;
921            }
922    
923            return false;
924        }
925    
926        /**
927         * CONDITION - can_display_notification
928         *
929         * Vérifie que le champs "Suivi notification" est affichable
930         *
931         * @return boolean
932         */
933        function can_display_notification_demandeur() {
934            // Le suivi des notification est affiché si l'événement est notifiable
935            // et si des notifications ont été envoyées
936            $evenement_id = $this->getVal("evenement");
937            $inst_evenement = $this->get_inst_evenement($evenement_id);
938            if ($inst_evenement->getVal('notification') != null &&
939                $inst_evenement->getVal('notification') != '') {
940                // Des notifications ont été envoyé si il existe au moins une notification
941                // liées à l'instruction
942                $idsNotifs = $this->get_instruction_notification(
943                    $this->getVal($this->clePrimaire),
944                    array(
945                        'notification_recepisse',
946                        'notification_instruction',
947                        'notification_decision',
948                    ),
949                    true
950                );
951                if (isset($idsNotifs) && $idsNotifs !== array()) {
952                    return true;
953                }
954            }
955            return false;
956        }
957    
958        /**
959         * CONDITION - can_display_notification
960         *
961         * Vérifie que le champs "suivi_notification_service" est affichable
962         *
963         * @return boolean
964         */
965        function can_display_notification_service() {
966            // Le suivi des notification est affiché si l'événement est notifiable
967            // et si des notifications ont été envoyées
968            $evenement_id = $this->getVal("evenement");
969            $inst_evenement = $this->get_inst_evenement($evenement_id);
970            if ($this->get_boolean_from_pgsql_value($inst_evenement->getVal('notification_service')) == true) {
971                // Des notifications ont été envoyé si il existe au moins une notification
972                // de type notification_service_consulte liées à l'instruction
973                $idsNotifs = $this->get_instruction_notification(
974                    $this->getVal($this->clePrimaire),
975                    'notification_service_consulte'
976                );
977                if (isset($idsNotifs) && $idsNotifs !== array()) {
978                    return true;
979                }
980            }
981            return false;
982        }
983    
984    
985        /**
986         * CONDITION - can_display_notification_tiers
987         *
988         * Vérifie que le champs "suivi_notification_tiers" est affichable
989         *
990         * @return boolean
991         */
992        function can_display_notification_tiers() {
993            // Le suivi des notification est affiché si l'événement est notifiable
994            // et si des notifications ont été envoyées
995            $evenement_id = $this->getVal("evenement");
996            $inst_evenement = $this->get_inst_evenement($evenement_id);
997            if ($this->get_boolean_from_pgsql_value($inst_evenement->getVal('notification_tiers')) == true) {
998                // Des notifications ont été envoyé si il existe au moins une notification
999                // de type notification_tiers_consulte liées à l'instruction
1000                $idsNotifs = $this->get_instruction_notification(
1001                    $this->getVal($this->clePrimaire),
1002                    'notification_tiers_consulte'
1003                );
1004                if (isset($idsNotifs) && $idsNotifs !== array()) {
1005                    return true;
1006                }
1007            }
1008            return false;
1009        }
1010    
1011        /**
1012         * CONDITION - can_display_notification_commune
1013         *
1014         * Vérifie que le champs "suivi_notification_commune" est affichable
1015         *
1016         * @return boolean
1017         */
1018        function can_display_notification_commune() {
1019            // Le suivi des notification si il existe au moins une notification
1020            // de type notification_depot_demat liées à l'instruction
1021            $idsNotifs = $this->get_instruction_notification(
1022                $this->getVal($this->clePrimaire),
1023                array('notification_depot_demat', 'notification_commune')
1024            );
1025            if (isset($idsNotifs) && $idsNotifs !== array()) {
1026                return true;
1027            }
1028            return false;
1029        }
1030    
1031        /**
1032         * TREATMENT - disable_edition_integrale.
1033         *
1034         * Cette methode permet de passer la consultation en "lu"
1035         *
1036         * @return boolean true si maj effectué false sinon
1037         */
1038        function disable_edition_integrale() {
1039            // Cette méthode permet d'exécuter une routine en début des méthodes
1040            // dites de TREATMENT.
1041            $this->begin_treatment(__METHOD__);
1042            $this->correct = true;
1043            $valF = array(
1044                "flag_edition_integrale" => false,
1045                "titre_om_htmletat" => null,
1046                "corps_om_htmletatex" => null,
1047            );
1048            $res = $this->f->db->autoExecute(
1049                DB_PREFIXE.$this->table,
1050                $valF,
1051                DB_AUTOQUERY_UPDATE,
1052                $this->clePrimaire."=".$this->getVal($this->clePrimaire)
1053            );
1054            if ($this->f->isDatabaseError($res, true)) {
1055                // Appel de la methode de recuperation des erreurs
1056                $this->erreur_db($res->getDebugInfo(), $res->getMessage(), '');
1057                $this->correct = false;
1058                // Termine le traitement
1059                return $this->end_treatment(__METHOD__, false);
1060          } else {          } else {
1061              // Sinon on récupère le numéro de dossier dans le champs dossier de              $this->addToMessage(_("Rédaction par compléments activé."));
1062              // l'enregistrement (en base de données)              return $this->end_treatment(__METHOD__, true);
             $dossier = $this->getVal("dossier");  
1063          }          }
1064    
1065          // On appelle la méthode de la classe utils qui renvoi le code de la          // Termine le traitement
1066          // division d'un dossier, on la stocke pour ne pas refaire le calcul au          return $this->end_treatment(__METHOD__, false);
1067          // prochain appel de cette méthode      }
         $this->_division_from_dossier = $this->f->getDivisionFromDossier($dossier);  
         // Logger  
         $this->addToLog("getDivisionFromDossier(): retour de la valeur nouvellement calculée - '".$this->_division_from_dossier."'", EXTRA_VERBOSE_MODE);  
         // On retourne la valeur retournée  
         return $this->_division_from_dossier;  
1068    
1069        /**
1070         * TREATMENT - enable_edition_integrale.
1071         *
1072         * Cette methode permet de passer la consultation en "lu"
1073         *
1074         * @return boolean true si maj effectué false sinon
1075         */
1076        function enable_edition_integrale() {
1077            // Cette méthode permet d'exécuter une routine en début des méthodes
1078            // dites de TREATMENT.
1079            $this->begin_treatment(__METHOD__);
1080            $this->correct = true;
1081    
1082            // Récupère la collectivite du dossier d'instruction
1083            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
1084            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
1085            //
1086            $params = array(
1087                "specific" => array(
1088                    "corps" => array(
1089                        "mode" => "get",
1090                    )
1091                ),
1092            );
1093            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
1094            $corps = $result['pdf_output'];
1095            //
1096            $params = array(
1097                "specific" => array(
1098                    "titre" => array(
1099                        "mode" => "get",
1100                    )
1101                ),
1102            );
1103            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
1104            $titre = $result['pdf_output'];
1105            //
1106            $valF = array(
1107                "flag_edition_integrale" => true,
1108                "titre_om_htmletat" => $titre,
1109                "corps_om_htmletatex" => $corps,
1110            );
1111            $res = $this->f->db->autoExecute(
1112                DB_PREFIXE.$this->table,
1113                $valF,
1114                DB_AUTOQUERY_UPDATE,
1115                $this->clePrimaire."=".$this->getVal($this->clePrimaire)
1116            );
1117            if ($this->f->isDatabaseError($res, true)) {
1118                // Appel de la methode de recuperation des erreurs
1119                $this->erreur_db($res->getDebugInfo(), $res->getMessage(), '');
1120                $this->correct = false;
1121                // Termine le traitement
1122                return $this->end_treatment(__METHOD__, false);
1123            } else {
1124                $this->addToMessage(_("Rédaction libre activé."));
1125                return $this->end_treatment(__METHOD__, true);
1126            }
1127    
1128            // Termine le traitement
1129            return $this->end_treatment(__METHOD__, false);
1130      }      }
1131    
1132      /**      /**
# Line 344  class instruction extends instruction_ge Line 1141  class instruction extends instruction_ge
1141          $sql = "select dossier_autorisation from ".DB_PREFIXE."dossier ";          $sql = "select dossier_autorisation from ".DB_PREFIXE."dossier ";
1142          $sql .= " where dossier='".$id."'";          $sql .= " where dossier='".$id."'";
1143          //          //
1144          $dossier_autorisation = $this->db->getOne($sql);          $dossier_autorisation = $this->f->db->getOne($sql);
1145          $this->addToLog("getNumDemandeAutorFromDossier(): db->getone(\"".$sql."\")", VERBOSE_MODE);          $this->addToLog("getNumDemandeAutorFromDossier(): db->getone(\"".$sql."\")", VERBOSE_MODE);
1146          database::isError($dossier_autorisation);          database::isError($dossier_autorisation);
1147          //          //
# Line 354  class instruction extends instruction_ge Line 1151  class instruction extends instruction_ge
1151      // }}}      // }}}
1152    
1153      function setType(&$form, $maj) {      function setType(&$form, $maj) {
1154          //          // Récupération du mode de l'action
1155          parent::setType($form, $maj);          $crud = $this->get_action_crud($maj);
1156          // On cache tous les champs          // Récupère la collectivité du dossier d'instruction
1157          // 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');  
1158    
1159          //          // Cache tous les champs
1160          $form->setType('duree_validite','hidden');          foreach ($this->champs as $value) {
1161          $form->setType('duree_validite_parametrage','hidden');              $form->setType($value, 'hidden');
1162            }
1163    
1164          //          // Les champs historique_signature et statut_signature ne sont pas saisissable dans tous les cas
1165          $form->setType('created_by_commune','hidden');          if ($this->can_display_parapheur() === true && $maj == 3) {
1166          //              $form->setType('statut_signature', 'selectstatic');
1167          // gestion du champ "finalisé par"              $form->setType('historique_signature', 'jsontotab');
1168          if ($this->getVal("om_final_instruction") == 't') {              if ($this->getVal('commentaire_signature') == null) {
1169              $form->setType('om_final_instruction_utilisateur', 'static');                  $form->setType('commentaire_signature', 'hidden');
1170          } else {              } else {
1171              $form->setType('om_final_instruction_utilisateur', 'hidden');                  $form->setType('commentaire_signature', 'hiddenstatic');
1172                }
1173          }          }
1174          //  
1175          if ($maj < 2 || $maj == 125) { //ajouter, modifier et suivi des dates          // Le champ de suivi des notifications des demandeurs n'est pas affichable dans tous les cas
1176              $form->setType('destinataire', 'hidden');          if ($maj == 3 && $this->can_display_notification_demandeur() === true) {
1177              $form->setType('lettretype', 'hiddenstatic');              $form->setType('suivi_notification', 'jsontotab');
1178              $form->setType('complement_om_html', 'html');          }
1179              $form->setType('complement2_om_html', 'html');          // Le champ de suivi des notifications des services n'est pas affichable dans tous les cas
1180              $form->setType('complement3_om_html', 'html');          if ($maj == 3 && $this->can_display_notification_service() === true) {
1181              $form->setType('complement4_om_html', 'html');              $form->setType('suivi_notification_service', 'jsontotab');
1182              $form->setType('bible_auto', 'httpclick');          }
1183              $form->setType('bible', 'httpclick');          // Le champ de suivi des notifications des tiers n'est pas affichable dans tous les cas
1184              $form->setType('bible2', 'httpclick');          if ($maj == 3 && $this->can_display_notification_tiers() === true) {
1185              $form->setType('bible3', 'httpclick');              $form->setType('suivi_notification_tiers', 'jsontotab');
1186              $form->setType('bible4', 'httpclick');          }
1187              $form->setType('dossier', 'hidden');            // Le champ de suivi des notifications des communes n'est pas affichable dans tous les cas
1188              $form->setType('libelle', 'hiddenstatic');          if ($maj == 3 && $this->can_display_notification_commune() === true) {
1189              $form->setType('signataire_arrete','select');              $form->setType('suivi_notification_commune', 'jsontotab');
1190              $form->setType('date_envoi_signature','datedisabled');          }
1191              $form->setType('date_retour_signature','datedisabled');  
1192              $form->setType('date_envoi_rar','datedisabled');          // MODE AJOUTER
1193              $form->setType('date_retour_rar','datedisabled');          if ($this->getParameter('maj') == 0) {
1194              $form->setType('date_envoi_controle_legalite','datedisabled');              $form->setType('commentaire', 'textareahidden');
1195              $form->setType('date_retour_controle_legalite','datedisabled');              // Si l'option est active passage du champ date en lecture seule
1196              $form->setType('date_finalisation_courrier','datedisabled');              if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1197                    $form->setType("date_evenement", "hiddenstaticdate");
1198              if($maj==0){ // ajouter              } else {
1199                  $form->setType('instruction', 'hidden');                  $form->setType("date_evenement", "date");
1200                  $form->setType('lettretype', 'hidden');              }
1201                  $form->setType('evenement', 'select');              if ($this->is_in_context_of_foreign_key("evenement", $this->getParameter("retourformulaire"))) {
1202                  $form->setType('date_evenement', 'date2');                  $form->setType("evenement", "selecthiddenstatic");
1203              }else{ // modifier et suivi des dates              } else {
1204                  $form->setType('instruction', 'hiddenstatic');                  $form->setType("evenement", "select");
1205                  $form->setType('evenement', 'selecthiddenstatic');              }
1206                  //$form->setType('date_evenement', 'hiddenstaticdate');              if ($this->is_in_context_of_foreign_key("signataire_arrete", $this->getParameter("retourformulaire"))) {
1207                  $form->setType('date_evenement', 'date2');                  $form->setType("signataire_arrete", "selecthiddenstatic");
1208                } else {
1209                    $form->setType("signataire_arrete", "select");
1210                }
1211                if ($this->is_option_redaction_libre_enabled() === true) {
1212                    $form->setType("flag_edition_integrale", "select");
1213                }
1214            }
1215    
1216            // MODE MODIFIER
1217            if ($this->getParameter('maj') == 1) {
1218                // Si l'option est active passage du champ date en lecture seule
1219                if ($this->f->is_option_date_evenement_instruction_lecture_seule($collectivite_di) === true) {
1220                    $form->setType("date_evenement", "hiddenstaticdate");
1221                } else {
1222                    $form->setType("date_evenement", "date");
1223                }
1224                $form->setType("evenement", "selecthiddenstatic");
1225                if ($this->has_an_edition() === true) {
1226                    $form->setType('lettretype', 'hiddenstatic');
1227                    if ($this->is_in_context_of_foreign_key("signataire_arrete", $this->getParameter("retourformulaire"))) {
1228                        $form->setType("signataire_arrete", "selecthiddenstatic");
1229                    } else {
1230                        $form->setType("signataire_arrete", "select");
1231                    }
1232                    if ($this->getVal("flag_edition_integrale") == "t") {
1233                        $form->setType("titre_om_htmletat", "htmlEtat");
1234                        $form->setType("corps_om_htmletatex", "htmlEtatEx");
1235                    } else {
1236                        $form->setType("complement_om_html", "html");
1237                        $form->setType("complement2_om_html", "html");
1238                        $form->setType("complement3_om_html", "html");
1239                        $form->setType("complement4_om_html", "html");
1240                        $form->setType('bible_auto', 'httpclick');
1241                        $form->setType('bible', 'httpclick');
1242                        $form->setType('bible2', 'httpclick');
1243                        $form->setType('bible3', 'httpclick');
1244                        $form->setType('bible4', 'httpclick');
1245                    }
1246                    if ($this->f->is_option_preview_pdf_enabled($collectivite_di) === true) {
1247                        //
1248                        $form->setType('btn_refresh', 'httpclickbutton');
1249                        $form->setType('btn_preview', 'httpclickbutton');
1250                        $form->setType('btn_redaction', 'httpclickbutton');
1251                        // /!\ le type du champs est utilisé dans un selecteur dans le jscript.js
1252                        // pour identifiant le champ de prévisualisation et régler sa taille à
1253                        // l'affichage du champ. En cas de modification, le selecteur doit également
1254                        // être mis à jour
1255                        $form->setType('live_preview', 'previsualiser_pdf');
1256                    }
1257    
1258                  // necessaire pour calcul de date en modification                  // necessaire pour calcul de date en modification
1259                  //$form->setType('delai', 'hiddenstatic');                  //$form->setType('delai', 'hiddenstatic');
1260                  // les administrateurs technique et fonctionnel peuvent                  // les administrateurs technique et fonctionnel peuvent
1261                  // modifier tous les champs de date                  // modifier tous les champs de date
1262                  // 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
1263                  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")
1264                            || $this->f->isAccredited(array('instruction', 'instruction_modification_dates'), "OR"))
1265                      && $this->getVal("date_finalisation_courrier") != '') {                      && $this->getVal("date_finalisation_courrier") != '') {
1266                        //
1267                      $form->setType('date_envoi_signature', 'date');                      $form->setType('date_envoi_signature', 'date');
1268                      $form->setType('date_retour_signature', 'date');                      $form->setType('date_retour_signature', 'date');
1269                        if ($this->is_sent_for_signature() === true
1270                            && $this->is_signed() === true) {
1271                            //
1272                            $form->setType("date_envoi_signature", "datereadonly");
1273                            $form->setType("date_retour_signature", "datereadonly");
1274                        }
1275                      $form->setType('date_envoi_rar', 'date');                      $form->setType('date_envoi_rar', 'date');
1276                      $form->setType('date_retour_rar', 'date');                      $form->setType('date_retour_rar', 'date');
1277                      $form->setType('date_envoi_controle_legalite', 'date');                      $form->setType('date_envoi_controle_legalite', 'date');
1278                        if ($this->is_sent_to_cl() === true) {
1279                            $form->setType("date_envoi_controle_legalite", "datedisabled");
1280                        }
1281                      $form->setType('date_retour_controle_legalite', 'date');                      $form->setType('date_retour_controle_legalite', 'date');
1282                      $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');  
                     }  
1283                  }                  }
1284              }              }
         } 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");  
1285          }          }
1286    
1287          // Pour les actions finalize, unfinalize et notifier_commune          // MODE CONSULTER + SUPPRIMER + SUIVI DES DATES 125 + NOTIFICATION MANUELLE
1288          if($maj == 100 || $maj == 110 || $maj == 210) {          if ($this->getParameter('maj') == 3
1289              //              || $this->getParameter('maj') == 2
1290              foreach ($this->champs as $value) {              || $this->getParameter('maj') == 125
1291                  // Cache tous les champs              || $this->getParameter('maj') == 410) {
1292                  $form->setType($value, 'hidden');              //
1293                $form->setType("date_evenement", "datestatic");
1294                $form->setType("evenement", "selecthiddenstatic");
1295                if ($this->has_an_edition() === true) {
1296                    $form->setType('lettretype', 'hiddenstatic');
1297                    $form->setType("signataire_arrete", "selecthiddenstatic");
1298                    if ($this->getVal("om_final_instruction") == 't') {
1299                        $form->setType('om_final_instruction_utilisateur', 'textareastatic');
1300                    } else {
1301                        $form->setType('om_final_instruction_utilisateur', 'hidden');
1302                    }
1303                }
1304                if ($this->evenement_has_a_commentaire($this->getVal('evenement')) === true ) {
1305                    $form->setType('commentaire', 'textareastatic');
1306              }              }
1307          }          }
1308    
1309            // MODE CONSULTER + SUPPRIMER + NOTIFICATION MANUELLE
1310            if ($this->getParameter('maj') == 3
1311                || $this->getParameter('maj') == 2
1312                || $this->getParameter('maj') == 410) {
1313                // Si il n'y a pas de lettre type (edition) associé à l'événement
1314                // les dates de suivi ne sont pas affichée
1315                if ($this->has_an_edition() === true) {
1316                    $form->setType('date_envoi_signature', 'datestatic');
1317                    $form->setType('date_retour_signature', 'datestatic');
1318                    $form->setType('date_envoi_rar', 'datestatic');
1319                    $form->setType('date_retour_rar', 'datestatic');
1320                    $form->setType('date_envoi_controle_legalite', 'datestatic');
1321                    $form->setType('date_retour_controle_legalite', 'datestatic');
1322                    $form->setType('date_finalisation_courrier', 'datestatic');
1323                    if ($this->getVal("flag_edition_integrale") == "t") {
1324                        $form->setType("titre_om_htmletat", "htmlstatic");
1325                        $form->setType("corps_om_htmletatex", "htmlstatic");
1326                    } else {
1327                        $form->setType("complement_om_html", "htmlstatic");
1328                        $form->setType("complement2_om_html", "htmlstatic");
1329                        $form->setType("complement3_om_html", "htmlstatic");
1330                        $form->setType("complement4_om_html", "htmlstatic");
1331                    }
1332                }
1333            }
1334    
1335            // MODE SUIVI DES DATES 125
1336            if ($this->getParameter('maj') == 125) {
1337                $form->setType("date_evenement", "hiddenstaticdate");
1338                $form->setType('om_final_instruction_utilisateur', 'hiddenstatic');
1339                $form->setType('date_envoi_signature', 'date');
1340                $form->setType('date_retour_signature', 'date');
1341                if ($this->is_sent_for_signature() === true
1342                    || $this->is_signed() === true) {
1343                    //
1344                    $form->setType("date_envoi_signature", "datereadonly");
1345                    $form->setType("date_retour_signature", "datereadonly");
1346                }
1347                $form->setType('date_envoi_rar', 'date');
1348                $form->setType('date_retour_rar', 'date');
1349                $form->setType('date_envoi_controle_legalite', 'date');
1350                if ($this->is_sent_to_cl() === true) {
1351                    $form->setType("date_envoi_controle_legalite", "datedisabled");
1352                }
1353                $form->setType('date_retour_controle_legalite', 'date');
1354                $form->setType('date_finalisation_courrier', 'date');
1355            }
1356    
1357            if ($maj == 401) {
1358                foreach ($this->champs as $champ) {
1359                    $form->setType($champ, 'hidden');
1360                }
1361                $form->setType('preview_edition', 'previsualiser');
1362            }
1363    
1364            // Si l'instruction a été envoyé au contrôle de légalité et que la
1365            // tâche envoi_cl lié n'a pas encore été traité il faut indiquer à
1366            // l'utilisateur que l'envoi au cl est en cours de traitement.
1367            if ($this->is_sent_to_cl() === true
1368                && empty($this->getVal('date_envoi_controle_legalite'))
1369                && $maj == 3) {
1370                $form->setType("date_envoi_controle_legalite", "hiddenstatic");
1371            }
1372        }
1373    
1374        function setOnchange(&$form,$maj){
1375            parent::setOnchange($form,$maj);
1376    
1377            // MODE AJOUTER
1378            if ($this->getParameter('maj') == 0) {
1379                $form->setOnchange(
1380                    "evenement",
1381                    "manage_instruction_evenement_lettretype(this.value, '".addslashes($this->getParameter('idxformulaire'))."');
1382                    manage_instruction_evenement_commentaire(this.value, '".addslashes($this->getParameter('idxformulaire'))."');"
1383                );
1384            }
1385        }
1386    
1387        function evenement_has_an_edition($evenement_id) {
1388            $evenement = $this->get_inst_evenement($evenement_id);
1389            $lettretype = $evenement->getVal('lettretype');
1390            if ($lettretype !== '' && $lettretype !== null) {
1391                return true;
1392            }
1393            return false;
1394        }
1395    
1396        function view_evenement_has_an_edition_json() {
1397            $json_return = array(
1398                "lettretype" => $this->evenement_has_an_edition($this->f->get_submitted_get_value('evenement_id')),
1399                "option_redaction_libre_enabled" => $this->is_option_redaction_libre_enabled(),
1400            );
1401            echo json_encode($json_return);
1402        }
1403    
1404        function evenement_has_a_commentaire($evenement_id) {
1405            $evenement = $this->get_inst_evenement($evenement_id);
1406            return $this->get_boolean_from_pgsql_value($evenement->getVal('commentaire'));
1407      }      }
1408    
1409      function setSelect(&$form, $maj,&$db,$debug) {      function view_evenement_has_a_commentaire_json() {
1410            $json_return = array(
1411                "commentaire" => $this->evenement_has_a_commentaire($this->f->get_submitted_get_value('evenement_id'))
1412            );
1413            echo json_encode($json_return);
1414        }
1415    
1416    
1417        /**
1418         * CONDITION - can_be_sended_to_cl
1419         *
1420         * Vérifie que le contrôle de légalité est disponible
1421         *
1422         * @return boolean
1423         */
1424        function can_be_sended_to_cl() {
1425            // Si l'instruction a une édition
1426            // et que l'événement est paramétré pour envoyer le contrôle de légalité
1427            // par Plat'AU
1428            // et que la date de retour signature est renseignée
1429            // et que la date d'envoi au contrôle légalité n'est pas renseignée
1430            // et qu'il n'existe pas de task envoi_CL en cours (!= done ou canceled)
1431            if ($this->has_an_edition() === true) {
1432                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
1433                $inst_evenement = $this->get_inst_evenement($this->getVal('evenement'));
1434                if ($inst_evenement->getVal('envoi_cl_platau') === 't'
1435                    && empty($this->getVal('date_retour_signature')) === false
1436                    && empty($this->getVal('date_envoi_controle_legalite')) === true
1437                    && $this->getVal('envoye_cl_platau') === 'f'
1438                    && $this->f->is_type_dossier_platau($inst_di->getVal('dossier_autorisation')) === true
1439                    && $inst_di->getVal('etat_transmission_platau') !== 'jamais_transmissible') {
1440                    //
1441                    return true;
1442                }
1443            }
1444            //
1445            return false;
1446        }
1447    
1448        /**
1449         *
1450         * @return string
1451         */
1452        function get_var_sql_forminc__sql_signataire_arrete() {
1453            return sprintf(
1454                "SELECT
1455                    signataire_arrete.signataire_arrete,
1456                    CONCAT_WS(
1457                        ' - ',
1458                        CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1459                        signataire_habilitation.libelle,
1460                        signataire_arrete.description
1461                    )
1462                FROM
1463                    %1\$ssignataire_arrete
1464                    LEFT JOIN %1\$ssignataire_habilitation
1465                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1466                WHERE
1467                    ((signataire_arrete.om_validite_debut IS NULL
1468                        AND (signataire_arrete.om_validite_fin IS NULL
1469                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1470                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1471                            AND (signataire_arrete.om_validite_fin IS NULL
1472                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1473                ORDER BY
1474                    signataire_arrete.prenom,
1475                    signataire_arrete.nom",
1476                DB_PREFIXE
1477            );
1478        }
1479    
1480        /**
1481         *
1482         * @return string
1483         */
1484        function get_var_sql_forminc__sql_signataire_arrete_by_id() {
1485            return sprintf(
1486                "SELECT
1487                    signataire_arrete.signataire_arrete,
1488                    CONCAT_WS(
1489                        ' - ',
1490                        CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1491                        signataire_habilitation.libelle,
1492                        signataire_arrete.description
1493                    )
1494                FROM
1495                    %1\$ssignataire_arrete
1496                    LEFT JOIN %1\$ssignataire_habilitation
1497                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1498                WHERE
1499                    signataire_arrete.signataire_arrete = <idx>",
1500                DB_PREFIXE
1501            );
1502        }
1503    
1504        /**
1505         *
1506         * @return string
1507         */
1508        function get_var_sql_forminc__sql_signataire_arrete_by_di() {
1509            return sprintf(
1510                "SELECT
1511                    signataire_arrete.signataire_arrete,
1512                    CONCAT_WS(
1513                        ' - ',
1514                        CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1515                        signataire_habilitation.libelle,
1516                        signataire_arrete.description
1517                    )
1518                FROM
1519                    %1\$ssignataire_arrete
1520                    LEFT JOIN %1\$som_collectivite
1521                        ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1522                    LEFT JOIN %1\$ssignataire_habilitation
1523                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1524                WHERE
1525                    ((signataire_arrete.om_validite_debut IS NULL
1526                        AND (signataire_arrete.om_validite_fin IS NULL
1527                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1528                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1529                            AND (signataire_arrete.om_validite_fin IS NULL
1530                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1531                    AND (om_collectivite.niveau = '2'
1532                        OR signataire_arrete.om_collectivite = <collectivite_di>)
1533                ORDER BY
1534                    signataire_arrete.prenom, signataire_arrete.nom",
1535                DB_PREFIXE
1536            );
1537        }
1538    
1539        /**
1540         *
1541         * @return string
1542         */
1543        function get_var_sql_forminc__sql_signataire_arrete_defaut() {
1544            return sprintf(
1545                "SELECT
1546                    signataire_arrete.signataire_arrete,
1547                    CONCAT_WS(
1548                        ' - ',
1549                        CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1550                        signataire_habilitation.libelle,
1551                        signataire_arrete.description
1552                    )
1553                FROM
1554                    %1\$ssignataire_arrete
1555                    LEFT JOIN %1\$ssignataire_habilitation
1556                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1557                WHERE
1558                    ((signataire_arrete.om_validite_debut IS NULL
1559                        AND (signataire_arrete.om_validite_fin IS NULL
1560                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1561                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1562                            AND (signataire_arrete.om_validite_fin IS NULL
1563                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1564                    AND signataire_arrete.defaut IS TRUE
1565                ORDER BY
1566                    signataire_arrete.prenom, signataire_arrete.nom",
1567                DB_PREFIXE
1568            );
1569        }
1570    
1571        /**
1572         *
1573         * @return string
1574         */
1575        function get_var_sql_forminc__sql_signataire_arrete_defaut_by_di() {
1576            return sprintf(
1577                "SELECT
1578                    signataire_arrete.signataire_arrete,
1579                        CONCAT_WS(
1580                            ' - ',
1581                            CONCAT_WS(' ', signataire_arrete.prenom, signataire_arrete.nom),
1582                            signataire_habilitation.libelle,
1583                            signataire_arrete.description
1584                        )
1585                FROM
1586                    %1\$ssignataire_arrete
1587                    LEFT JOIN %1\$ssignataire_habilitation
1588                        ON signataire_arrete.signataire_habilitation = signataire_habilitation.signataire_habilitation
1589                    LEFT JOIN %1\$som_collectivite
1590                        ON signataire_arrete.om_collectivite = om_collectivite.om_collectivite
1591                WHERE
1592                    ((signataire_arrete.om_validite_debut IS NULL
1593                        AND (signataire_arrete.om_validite_fin IS NULL
1594                            OR signataire_arrete.om_validite_fin > CURRENT_DATE))
1595                        OR (signataire_arrete.om_validite_debut <= CURRENT_DATE
1596                            AND (signataire_arrete.om_validite_fin IS NULL
1597                                OR signataire_arrete.om_validite_fin > CURRENT_DATE)))
1598                    AND signataire_arrete.defaut IS TRUE
1599                    AND (om_collectivite.niveau = '2'
1600                        OR signataire_arrete.om_collectivite = <collectivite_di>)
1601                ORDER BY
1602                    signataire_arrete.prenom,
1603                    signataire_arrete.nom",
1604                DB_PREFIXE
1605            );
1606        }
1607    
1608        /**
1609         * SETTER_FORM - setSelect.
1610         *
1611         * @return void
1612         */
1613        function setSelect(&$form, $maj, &$dnu1 = null, $dnu2 = null) {
1614            //parent::setSelect($form, $maj);
1615          /**          /**
1616           * 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
1617           * dossier est mauvaise pour les performances, car la requête qui           * dossier est mauvaise pour les performances, car la requête qui
# Line 548  class instruction extends instruction_ge Line 1619  class instruction extends instruction_ge
1619           * 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
1620           * select           * select
1621           */           */
         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");  
   
1622          //// action          //// action
1623          //$this->init_select($form, $db, $maj, $debug, "action",          //$this->init_select($form, $this->f->db, $maj, null, "action",
1624          //                   $sql_action, $sql_action_by_id, false);          //                   $sql_action, $sql_action_by_id, false);
1625    
1626          //// avis_decision          //// avis_decision
1627          //$this->init_select($form, $db, $maj, $debug, "avis_decision",          //$this->init_select($form, $this->f->db, $maj, null, "avis_decision",
1628          //                   $sql_avis_decision, $sql_avis_decision_by_id, false);          //                   $sql_avis_decision, $sql_avis_decision_by_id, false);
1629    
1630          //// dossier          //// dossier
1631          //$this->init_select($form, $db, $maj, $debug, "dossier",          //$this->init_select($form, $this->f->db, $maj, null, "dossier",
1632          //                   $sql_dossier, $sql_dossier_by_id, false);          //                   $sql_dossier, $sql_dossier_by_id, false);
1633    
1634          //// etat          //// etat
1635          //$this->init_select($form, $db, $maj, $debug, "etat",          //$this->init_select($form, $this->f->db, $maj, null, "etat",
1636          //                   $sql_etat, $sql_etat_by_id, false);          //                   $sql_etat, $sql_etat_by_id, false);
1637    
1638          //// evenement          //// evenement
1639          //$this->init_select($form, $db, $maj, $debug, "evenement",          //$this->init_select($form, $this->f->db, $maj, null, "evenement",
1640          //                   $sql_evenement, $sql_evenement_by_id, false);          //                   $sql_evenement, $sql_evenement_by_id, false);
1641    
1642          // signataire_arrete          // signataire_arrete
# Line 580  class instruction extends instruction_ge Line 1646  class instruction extends instruction_ge
1646                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1647                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1648                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1649                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1650                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1651                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1652                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1653                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1654              // 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
1655              require_once "../obj/dossier_instruction.class.php";              $di = $this->f->get_inst__om_dbform(array(
1656              $di = new dossier_instruction($this->getParameter('idxformulaire'), $db, $debug);                  "obj" => "dossier_instruction",
1657              $sql_signataire_arrete_by_di = str_replace('<collectivite_di>', $di->getVal("om_collectivite"), $sql_signataire_arrete_by_di);                  "idx" => $this->getParameter('idxformulaire'),
1658              $this->init_select($form, $db, $maj, $debug, "signataire_arrete",              ));
1659                  $sql_signataire_arrete_by_di, $sql_signataire_arrete_by_id, true);              $sql_signataire_arrete_by_di = str_replace(
1660                    '<collectivite_di>',
1661                    $di->getVal("om_collectivite"),
1662                    $this->get_var_sql_forminc__sql("signataire_arrete_by_di")
1663                );
1664                $this->init_select(
1665                    $form,
1666                    $this->f->db,
1667                    $maj,
1668                    null,
1669                    "signataire_arrete",
1670                    $sql_signataire_arrete_by_di,
1671                    $this->get_var_sql_forminc__sql("signataire_arrete_by_id"),
1672                    true
1673                );
1674          } else {          } else {
1675              $this->init_select($form, $db, $maj, $debug, "signataire_arrete",              $this->init_select(
1676                  $sql_signataire_arrete, $sql_signataire_arrete_by_id, true);                  $form,
1677                    $this->f->db,
1678                    $maj,
1679                    null,
1680                    "signataire_arrete",
1681                    $this->get_var_sql_forminc__sql("signataire_arrete"),
1682                    $this->get_var_sql_forminc__sql("signataire_arrete_by_id"),
1683                    true
1684                );
1685          }          }
1686    
1687          /**          /**
# Line 614  class instruction extends instruction_ge Line 1706  class instruction extends instruction_ge
1706              INNER JOIN ".DB_PREFIXE."transition              INNER JOIN ".DB_PREFIXE."transition
1707                  ON evenement.evenement = transition.evenement                  ON evenement.evenement = transition.evenement
1708                  AND dossier.etat=transition.etat                  AND dossier.etat=transition.etat
1709              WHERE dossier.dossier='".$this->idxformulaire."' ";              WHERE dossier.dossier='".$this->getParameter("idxformulaire")."' ";
1710    
1711              // Si changement de décision par instructeur commune              // Si changement de décision par instructeur commune
1712              if($this->f->isUserInstructeur() === true              if($this->f->isUserInstructeur() === true
1713                  && $this->f->getDivisionFromDossier($this->idxformulaire) != $_SESSION["division"]                  && $this->getDivisionFromDossier($this->getParameter("idxformulaire")) != $_SESSION["division"]
1714                  && $this->f->isInstrCanChangeDecision($this->idxformulaire) === true) {                  && $this->isInstrCanChangeDecision($this->getParameter("idxformulaire")) === true) {
1715                  $sql .= "AND evenement.type IN ('arrete', 'changement_decision') ";                  $sql .= "AND evenement.type IN ('arrete', 'changement_decision') ";
1716              }              }
1717              $sql .= "ORDER BY evenement.libelle, evenement.action";              $sql .= "ORDER BY evenement.libelle, evenement.action";
1718              $res = $db->query($sql);              $res = $this->f->db->query($sql);
1719              $this->addToLog("setSelect(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->query(\"".$sql."\");", VERBOSE_MODE);
1720              if (database::isError($res)) {              if (database::isError($res)) {
1721                  die($res->getMessage());                  die($res->getMessage());
# Line 638  class instruction extends instruction_ge Line 1730  class instruction extends instruction_ge
1730                  $contenu[1][] = $row[1];                  $contenu[1][] = $row[1];
1731              }              }
1732              $form->setSelect("evenement", $contenu);              $form->setSelect("evenement", $contenu);
1733    
1734          } else {          } else {
1735              $sql = "SELECT              $sql = "SELECT
1736              evenement.libelle as lib              evenement.libelle as lib
1737              FROM ".DB_PREFIXE."evenement              FROM ".DB_PREFIXE."evenement
1738              WHERE evenement.evenement=".$this->getVal("evenement")."";              WHERE evenement.evenement=".$this->getVal("evenement")."";
1739              $res = $db->getone($sql);              $res = $this->f->db->getone($sql);
1740              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1741              if (database::isError($res)) {              if (database::isError($res)) {
1742                  die($res->getMessage());                  die($res->getMessage());
# Line 674  class instruction extends instruction_ge Line 1767  class instruction extends instruction_ge
1767          // lien bible4          // lien bible4
1768          $contenu = array(_("bible"));          $contenu = array(_("bible"));
1769          $form->setSelect("bible4",$contenu);          $form->setSelect("bible4",$contenu);
1770    
1771            if ($maj == 1) {
1772                $base64 = $this->init_pdf_temp();
1773                $form->setSelect('live_preview', array('base64'=>$base64));
1774                $form->setSelect("btn_refresh", array(_('Prévisualiser')));
1775                $form->setSelect("btn_preview", array(_('Prévisualiser >>')));
1776                $form->setSelect("btn_redaction", array(_('<< Rédiger')));
1777            }
1778    
1779            // Selection du type de rédaction à l'ajout
1780            $content = array(
1781                0 => array('f', 't', ),
1782                1 => array(_('Rédaction par compléments'), _('Rédaction libre'), ),
1783            );
1784            $form->setSelect('flag_edition_integrale', $content);
1785    
1786            $contenu = array();
1787            foreach(array('waiting', 'in_progress', 'canceled', 'expired', 'finished') as $value) {
1788                $contenu[0][] = $value;
1789                $contenu[1][] = $this->get_trad_for_statut($value);
1790            }
1791            $form->setSelect('statut_signature', $contenu);
1792    
1793    
1794            if ($maj == 401) {
1795                $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
1796                $form->setSelect('preview_edition', array(
1797                    'base64' => base64_encode($file['file_content']),
1798                    'mimetype' => $file['metadata']['mimetype'],
1799                    'label' => 'instruction_'.$this->getVal($this->clePrimaire),
1800                    'href' => sprintf(
1801                        '../app/index.php?module=form&snippet=file&obj=instruction&champ=om_fichier_instruction&id=%1$s',
1802                        $this->getVal($this->clePrimaire)
1803                    )
1804                ));
1805            }
1806      }      }
1807    
1808      function cleSecondaire($id, &$db, $val, $DEBUG) {      function cleSecondaire($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
1809          //          //
1810          parent::cleSecondaire($id, $db, $val, $DEBUG);          // Vérifie uniquementla cle secondaire : demande
1811            $this->rechercheTable($this->f->db, "demande", "instruction_recepisse", $id);
1812                    
1813          $id = $this->getVal($this->clePrimaire);          $id = $this->getVal($this->clePrimaire);
1814    
# Line 690  class instruction extends instruction_ge Line 1820  class instruction extends instruction_ge
1820              LEFT JOIN ".DB_PREFIXE."demande              LEFT JOIN ".DB_PREFIXE."demande
1821              ON demande.demande_type = demande_type.demande_type              ON demande.demande_type = demande_type.demande_type
1822              WHERE demande.instruction_recepisse = ".$id;              WHERE demande.instruction_recepisse = ".$id;
1823          $res = $this->db->getOne($sql);          $res = $this->f->db->getOne($sql);
1824          $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1825          if (database::isError($res)) {          if (database::isError($res)) {
1826              die($res->getMessage());              die($res->getMessage());
# Line 706  class instruction extends instruction_ge Line 1836  class instruction extends instruction_ge
1836              $sql = "SELECT demande              $sql = "SELECT demande
1837                  FROM ".DB_PREFIXE."demande                  FROM ".DB_PREFIXE."demande
1838                  WHERE instruction_recepisse = ".$id;                  WHERE instruction_recepisse = ".$id;
1839              $res = $this->db->getOne($sql);              $res = $this->f->db->getOne($sql);
1840              $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("cleSecondaire(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1841              if (database::isError($res)) {              if (database::isError($res)) {
1842                  die($res->getMessage());                  die($res->getMessage());
# Line 714  class instruction extends instruction_ge Line 1844  class instruction extends instruction_ge
1844    
1845              //Si c'est un événement d'instruction lié à une demande              //Si c'est un événement d'instruction lié à une demande
1846              if ($res != null || $res != ""){              if ($res != null || $res != ""){
1847                                    $demande = $this->f->get_inst__om_dbform(array(
1848                  require_once "../obj/demande.class.php";                      "obj" => "demande",
1849                  $demande = new demande($res, $this->db, DEBUG);                      "idx" => $res,
1850                    ));
1851    
1852                  //On met à jour la demande en supprimant la liaison vers                  //On met à jour la demande en supprimant la liaison vers
1853                  //l'événement d'instruction                  //l'événement d'instruction
# Line 727  class instruction extends instruction_ge Line 1858  class instruction extends instruction_ge
1858                  }                  }
1859                  $valF['date_demande']=$demande->dateDBToForm($valF['date_demande']);                  $valF['date_demande']=$demande->dateDBToForm($valF['date_demande']);
1860                  $valF['instruction_recepisse']=NULL;                  $valF['instruction_recepisse']=NULL;
1861                  $ret = $demande->modifier($valF, $this->db, DEBUG);                  $ret = $demande->modifier($valF);
1862              }              }
1863                                    
1864              /**              /**
# Line 740  class instruction extends instruction_ge Line 1871  class instruction extends instruction_ge
1871              // concerne le dossier en cours              // concerne le dossier en cours
1872              $sql = "SELECT max(instruction)              $sql = "SELECT max(instruction)
1873              FROM ".DB_PREFIXE."instruction              FROM ".DB_PREFIXE."instruction
1874              WHERE dossier ='".$this->idxformulaire."'";              WHERE dossier ='".$this->getParameter("idxformulaire")."'";
1875              $dernierevenement = $db->getOne($sql);              $dernierevenement = $this->f->db->getOne($sql);
1876              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog("setSelect(): db->getone(\"".$sql."\");", VERBOSE_MODE);
1877              if (database::isError($dernierevenement)) {              if (database::isError($dernierevenement)) {
1878                  die($dernierevenement->getMessage());                  die($dernierevenement->getMessage());
# Line 771  class instruction extends instruction_ge Line 1902  class instruction extends instruction_ge
1902                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1903                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1904                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1905                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1906                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1907                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1908                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1909                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1910    
1911              // 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
1912              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {              if($this->valF[$champ] != "" AND !$this->f->user_is_admin) {
# Line 787  class instruction extends instruction_ge Line 1922  class instruction extends instruction_ge
1922          return true;          return true;
1923      }      }
1924    
1925      /*Met des valeurs par défaut dans certains des sous-formulaire*/      /**
1926      function setValsousformulaire(&$form,$maj,$validation,$idxformulaire,$retourformulaire,$typeformulaire){       * SETTER_FORM - setValsousformulaire (setVal).
1927         *
1928         * @return void
1929         */
1930        function setValsousformulaire(&$form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire, &$dnu1 = null, $dnu2 = null) {
1931            // parent::setValsousformulaire($form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire);
1932            //
1933            $this->retourformulaire = $retourformulaire;
1934          //          //
         $this->retourformulaire=$retourformulaire;  
         $this->idxformulaire=$idxformulaire;  
         // Ajout  
1935          if ($maj == 0) {          if ($maj == 0) {
1936              $form->setVal("destinataire", $idxformulaire);              $form->setVal("destinataire", $this->getParameter("idxformulaire"));
1937              $form->setVal("dossier", $idxformulaire);              $form->setVal("dossier", $this->getParameter("idxformulaire"));
1938            }
1939    
1940            // Si l'instruction a été envoyé au contrôle de légalité et que la
1941            // tâche envoi_cl lié n'a pas encore été traité il faut indiquer à
1942            // l'utilisateur que l'envoi au cl est en cours de traitement.
1943            if ($this->is_sent_to_cl() === true
1944                && empty($this->getVal('date_envoi_controle_legalite'))
1945                && $maj == 3) {
1946                $form->setVal("date_envoi_controle_legalite", __("En cours de traitement."));
1947          }          }
1948          //          //
1949          $this->set_form_default_values($form, $maj, $validation);          $this->set_form_default_values($form, $maj, $validation);
1950      }      }
1951    
1952      /**      /**
1953       *  Permet de pré-remplir les valeurs des formulaires.       * SETTER_FORM - set_form_default_values (setVal).
1954       *         *
1955       * @param [object]   $form        formulaire       * @return void
      * @param [integer]  $maj         mode  
      * @param [integer]  $validation  validation  
1956       */       */
1957      function set_form_default_values(&$form, $maj, $validation) {      function set_form_default_values(&$form, $maj, $validation) {
1958            //
         // Ajout  
1959          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");  
1960              // si contexte DI              // si contexte DI
1961              if ($this->getParameter("retourformulaire") == "dossier"              if ($this->getParameter("retourformulaire") == "dossier"
1962                  || $this->getParameter("retourformulaire") == "dossier_instruction"                  || $this->getParameter("retourformulaire") == "dossier_instruction"
1963                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_encours"
1964                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_encours"
1965                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"                  || $this->getParameter("retourformulaire") == "dossier_instruction_mes_clotures"
1966                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures") {                  || $this->getParameter("retourformulaire") == "dossier_instruction_tous_clotures"
1967                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_infractions"
1968                    || $this->getParameter("retourformulaire") == "dossier_contentieux_toutes_infractions"
1969                    || $this->getParameter("retourformulaire") == "dossier_contentieux_mes_recours"
1970                    || $this->getParameter("retourformulaire") == "dossier_contentieux_tous_recours") {
1971                  // 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
1972                  require_once "../obj/dossier_instruction.class.php";                  $di = $this->f->get_inst__om_dbform(array(
1973                  $di = new dossier_instruction($this->getParameter('idxformulaire'), $db, DEBUG);                      "obj" => "dossier_instruction",
1974                  $sql = str_replace('<collectivite_di>', $di->getVal("om_collectivite"), $sql_signataire_arrete_defaut_by_di);                      "idx" => $this->getParameter("idxformulaire"),
1975                    ));
1976                    $sql = str_replace(
1977                        "<collectivite_di>",
1978                        $di->getVal("om_collectivite"),
1979                        $this->get_var_sql_forminc__sql("signataire_arrete_defaut_by_di")
1980                    );
1981              } else {              } else {
1982                  $sql = $sql_signataire_arrete_defaut;                  $sql = $this->get_var_sql_forminc__sql("signataire_arrete_defaut");
1983              }              }
             // Date du jour  
             $form->setVal("date_evenement", date('Y-m-d'));  
   
             // Exécution de la requête  
1984              $res = $this->f->db->query($sql);              $res = $this->f->db->query($sql);
1985              $this->f->addToLog("setVal(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
1986              if ( database::isError($res)){              $this->f->isDatabaseError($res);
                 die();  
             }  
           
1987              $row = $res->fetchrow(DB_FETCHMODE_ASSOC);              $row = $res->fetchrow(DB_FETCHMODE_ASSOC);
1988                            if (isset($row["signataire_arrete"])
1989              if (isset($row['signataire_arrete']) && is_numeric($row['signataire_arrete'])){                  && is_numeric($row["signataire_arrete"])) {
1990                  $form->setVal("signataire_arrete",$row['signataire_arrete']);                  //
1991                    $form->setVal("signataire_arrete", $row["signataire_arrete"]);
1992              }              }
1993                // Date du jour
1994                $form->setVal("date_evenement", date("Y-m-d"));
1995          }          }
1996            //
         // Ajout et modification  
1997          if ($maj == 0 || $maj == 1 || $maj == 125) {          if ($maj == 0 || $maj == 1 || $maj == 125) {
1998              $form->setVal("bible_auto","bible_auto()");              $form->setVal("bible_auto", "bible_auto()");
1999              $form->setVal("bible","bible(1)");              $form->setVal("bible", "bible(1)");
2000              $form->setVal("bible2","bible(2)");              $form->setVal("bible2", "bible(2)");
2001              $form->setVal("bible3","bible(3)");              $form->setVal("bible3", "bible(3)");
2002              $form->setVal("bible4","bible(4)");              $form->setVal("bible4", "bible(4)");
2003            }
2004            //
2005            $collectivite_di = $this->get_dossier_instruction_om_collectivite();
2006            if ($maj == 1
2007                && $this->f->is_option_preview_pdf_enabled($collectivite_di) === true
2008                && $this->has_an_edition() === true) {
2009                //
2010                $form->setVal("live_preview", $this->getVal($this->clePrimaire));
2011                $form->setVal("btn_refresh", "reload_pdf_viewer()");
2012                $form->setVal("btn_preview", "show_instr_preview()");
2013                $form->setVal("btn_redaction", "show_instr_redaction()");
2014            }
2015    
2016            // Gestion de l'affichage des suivis de notification des demandeurs, des services, des tiers et
2017            // des communes
2018            if ($maj == 3) {
2019                if ($this->can_display_notification_demandeur()) {
2020                    $typeNotification = array(
2021                        'notification_recepisse',
2022                        'notification_instruction',
2023                        'notification_decision',
2024                    );
2025                    $form->setVal("suivi_notification", $this->get_json_suivi_notification($typeNotification, true));
2026                }
2027                if ($this->can_display_notification_service()) {
2028                    $form->setVal("suivi_notification_service", $this->get_json_suivi_notification(array('notification_service_consulte')));
2029                }
2030                if ($this->can_display_notification_tiers()) {
2031                    $form->setVal("suivi_notification_tiers", $this->get_json_suivi_notification(array('notification_tiers_consulte')));
2032                }
2033                if ($this->can_display_notification_commune()) {
2034                    $form->setVal("suivi_notification_commune", $this->get_json_suivi_notification(array('notification_depot_demat', 'notification_commune')));
2035                }
2036          }          }
2037      }      }
2038    
   
2039      function setLayout(&$form, $maj){      function setLayout(&$form, $maj){
2040          if ( $maj < 2 OR $maj == 3 OR $maj == 125 ) {          // En consultation, pour les dossiers qui n'ont pas été transmis par le portail
2041                          /*Champ sur lequel s'ouvre le bloc 1 */          // citoyen, si la notification des demandeurs est activée sur l'évenement
2042              $form->setBloc('evenement','D',"","col_12");          // d'instruction et que le paramétrage du demandeur principal n'est pas
2043            // correct alors un message a destination de l'instructeur est affiché.
2044            if ($maj == 3) {
2045                // Si le dossier n'a pas été déposé sur le portail citoyen ou si
2046                // la requête permettant de savoir le type de demande à échouée, on
2047                // vérifie si il y a des erreurs de paramétrage et si c'est le cas
2048                // on affiche un message d'information
2049                if ($this->dossier_depose_sur_portail() == null ||
2050                    ! $this->dossier_depose_sur_portail()) {
2051                    $erreurParam = $this->get_info_notification_fail();
2052                    // Récupération de l'évenement d'instruction
2053                    $instEV = $this->get_inst_evenement();
2054                    if (! empty($instEV->getVal('notification')) && $erreurParam != array()) {
2055                        $class = 'text-info ui-state-highlight ui-state-info';
2056                        $message = __("Attention l'envoi de notification automatique n'est pas possible.");
2057                        $this->f->display_panel_information(
2058                            $class,
2059                            $message,
2060                            $erreurParam,
2061                            __('Veuillez corriger les informations suivantes.'),
2062                            'erreur_param_notif'
2063                        );
2064                    }
2065                }
2066            }
2067            $form->setBloc('evenement','D',"","sousform-instruction-action-".$maj);
2068    
2069              $form->setFieldset('evenement','D',_('Evenement'));          $form->setFieldset('evenement','D',_('Evenement'));
2070              $form->setFieldset('om_final_instruction_utilisateur','F','');          $form->setFieldset('om_final_instruction_utilisateur','F','');
2071                        
2072              $form->setBloc('om_final_instruction_utilisateur','F');          $form->setBloc('om_final_instruction_utilisateur','F');
2073    
2074              $form->setBloc('date_finalisation_courrier','D',"","col_12");          $form->setBloc('date_finalisation_courrier','D',"","");
2075    
2076              $form->setFieldset('date_finalisation_courrier','D',_('Dates'));          $form->setFieldset('date_finalisation_courrier','D',_('Dates'));
2077              $form->setBloc('date_finalisation_courrier','D',"","col_6");          $form->setBloc('date_finalisation_courrier','D',"","col_6");
2078              $form->setBloc('date_envoi_controle_legalite','F');          $form->setBloc('date_envoi_controle_legalite','F');
2079    
2080              $form->setBloc('signataire_arrete','D',"","col_6");          $form->setBloc('date_retour_signature','D',"","col_6");
2081              $form->setBloc('date_retour_controle_legalite','F');          $form->setBloc('date_retour_controle_legalite','F');
2082              $form->setFieldset('date_retour_controle_legalite','F','');          $form->setFieldset('date_retour_controle_legalite','F','');
2083                        
2084              $form->setBloc('date_retour_controle_legalite','F');          $form->setBloc('date_retour_controle_legalite','F');
2085    
2086              $form->setBloc('complement_om_html','D',"","col_12");          $form->setBloc('statut_signature','D');
2087            $form->setFieldset('statut_signature','D','Suivi Parapheur');
2088            $form->setBloc('commentaire_signature','F');
2089            $form->setBloc('historique_signature','D');
2090            $form->setFieldset('historique_signature', 'DF', __("Historique"), "collapsible, startClosed");
2091            $form->setBloc('historique_signature','F');
2092            $form->setFieldset('historique_signature','F');
2093    
2094            $form->setFieldset('suivi_notification', 'D', __("Suivi notification"), "collapsible");
2095            $form->setFieldset('suivi_notification','F');
2096            $form->setFieldset('suivi_notification_service', 'D', __("Suivi notification service"), "collapsible");
2097            $form->setFieldset('suivi_notification_service','F');
2098            $form->setFieldset('suivi_notification_tiers', 'D', __("Suivi notification tiers"), "collapsible");
2099            $form->setFieldset('suivi_notification_tiers','F');
2100            $form->setFieldset('suivi_notification_commune', 'D', __("Suivi notification commune"), "collapsible");
2101            $form->setFieldset('suivi_notification_commune','F');
2102    
2103            if ($maj == 1) {
2104                // Récupère la collectivité du dossier d'instruction
2105                $collectivite_di = $this->get_dossier_instruction_om_collectivite();
2106    
2107                //
2108                if ($this->f->is_option_preview_pdf_enabled($collectivite_di) === true
2109                    && $this->has_an_edition() === true) {
2110                    //
2111                    $form->setBloc('complement_om_html','D',"","container_instr_edition");
2112                    $form->setBloc('complement_om_html','D',"","hidelabel box_instr_edition redaction_instr_edition");
2113                    $form->setBloc('complement_om_html','D',"","box_instr_edition_main");
2114                    $form->setFieldset('complement_om_html','D',_('Complement'));
2115                    $form->setFieldset('bible','F','');
2116                    $form->setFieldset('complement2_om_html','D',_('Complement 2'));
2117                    $form->setFieldset('bible2','F','');
2118                    $form->setFieldset('complement3_om_html','D',_('Complement 3'));
2119                    $form->setFieldset('bible3','F','');
2120                    $form->setFieldset('complement4_om_html','D',_('Complement 4'));
2121                    $form->setFieldset('bible4','F','');
2122                    $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
2123                    $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
2124                    $form->setBloc('corps_om_htmletatex','F');
2125                    $form->setBloc('btn_preview','DF',"","box_instr_edition_btn");
2126                    $form->setBloc('btn_preview','F');
2127                    $form->setBloc('btn_redaction','D', '',"hidelabel box_instr_edition preview_instr_edition");
2128                    $form->setBloc('btn_redaction','DF',"","box_instr_edition_btn");
2129                    $form->setFieldset('btn_refresh','D',_('Prévisualisation'), "box_instr_edition_main");
2130                    $form->setFieldset('live_preview','F');
2131                    $form->setBloc('live_preview','F');
2132                    $form->setBloc('live_preview','F');
2133                } else {
2134                    $form->setBloc('complement_om_html','D',"","hidelabel");
2135                    $form->setFieldset('complement_om_html','D',_('Complement'));
2136                    $form->setFieldset('bible','F','');
2137                    $form->setFieldset('complement2_om_html','D',_('Complement 2'));
2138                    $form->setFieldset('bible2','F','');
2139                    $form->setFieldset('complement3_om_html','D',_('Complement 3'));
2140                    $form->setFieldset('bible3','F','');
2141                    $form->setFieldset('complement4_om_html','D',_('Complement 4'));
2142                    $form->setFieldset('bible4','F','');
2143                    $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
2144                    $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
2145                    $form->setBloc('corps_om_htmletatex','F');
2146                }
2147            } else {
2148                $form->setBloc('complement_om_html','D',"","hidelabel");
2149              $form->setFieldset('complement_om_html','D',_('Complement'));              $form->setFieldset('complement_om_html','D',_('Complement'));
2150              $form->setFieldset('bible','F','');              $form->setFieldset('bible','F','');
             $form->setBloc('bible','F');  
   
             $form->setBloc('complement2_om_html','D',"","col_12");  
2151              $form->setFieldset('complement2_om_html','D',_('Complement 2'));              $form->setFieldset('complement2_om_html','D',_('Complement 2'));
2152              $form->setFieldset('bible2','F','');              $form->setFieldset('bible2','F','');
             $form->setBloc('bible2','F');  
               
             $form->setBloc('complement3_om_html','D',"","col_12");  
2153              $form->setFieldset('complement3_om_html','D',_('Complement 3'));              $form->setFieldset('complement3_om_html','D',_('Complement 3'));
2154              $form->setFieldset('bible3','F','');              $form->setFieldset('bible3','F','');
             $form->setBloc('bible3','F');  
               
             $form->setBloc('complement4_om_html','D',"","col_12");  
2155              $form->setFieldset('complement4_om_html','D',_('Complement 4'));              $form->setFieldset('complement4_om_html','D',_('Complement 4'));
2156              $form->setFieldset('bible4','F','');              $form->setFieldset('bible4','F','');
2157              $form->setBloc('bible4','F');              $form->setFieldset('titre_om_htmletat','DF',_('Titre'), 'startClosed');
2158                $form->setFieldset('corps_om_htmletatex','DF',_('Corps'));
2159                $form->setBloc('corps_om_htmletatex','F');
2160          }          }
2161      }      }
2162            
# Line 912  class instruction extends instruction_ge Line 2169  class instruction extends instruction_ge
2169          $form->setLib('bible2', "");          $form->setLib('bible2', "");
2170          $form->setLib('bible3', "");          $form->setLib('bible3', "");
2171          $form->setLib('bible4', "");          $form->setLib('bible4', "");
2172            $form->setLib('btn_refresh', "");
2173            $form->setLib('btn_preview', "");
2174            $form->setLib('btn_redaction', "");
2175            $form->setLib('live_preview', "");
2176          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));          $form->setLib('om_final_instruction_utilisateur', _("finalise par"));
2177            $form->setLib('date_envoi_rar', __("date_envoi_ar"));
2178            $form->setLib('date_retour_rar', __("date_notification"));
2179            $form->setLib('statut_signature', __("statut"));
2180            $form->setLib('commentaire_signature', __("commentaire"));
2181            $form->setLib('historique_signature', '');
2182            $form->setLib('suivi_notification', '');
2183            $form->setLib('suivi_notification_service', '');
2184            $form->setLib('suivi_notification_tiers', '');
2185            $form->setLib('suivi_notification_commune', '');
2186            $form->setLib('preview_edition', "");
2187    
2188            // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
2189            // ajout et que l'option de rédaction libre est activée sur la
2190            // collectivité du dossier
2191            if ($maj === '0' && $this->is_option_redaction_libre_enabled() === true) {
2192                //
2193                $help_text_template = '%s <span class="info-16" title="%s"></span>';
2194                $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.");
2195                $form->setLib('flag_edition_integrale', sprintf($help_text_template, _("Type de rédaction"), $help_text));
2196            }
2197            else {
2198                $form->setLib('flag_edition_integrale', _("Type de rédaction"));
2199            }
2200    
2201            // Ajout d'une infobulle d'aide lorsque le formulaire est en mode
2202            // modification et que l'option de prévisualisation de l'édition est
2203            // activée sur la collectivité du dossier
2204            if ($maj === '1'
2205                && $this->f->is_option_preview_pdf_enabled($this->get_dossier_instruction_om_collectivite()) === true) {
2206                //
2207                $help_text_template = '%s <span class="info-16" title="%s"></span>';
2208                $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.");
2209                $form->setLib('date_evenement', sprintf($help_text_template, _('date_evenement'), $help_text));
2210                $form->setLib('signataire_arrete', sprintf($help_text_template, _('signataire_arrete'), $help_text));
2211            }
2212      }      }
2213    
2214      function triggerajouter($id, &$db, $val, $DEBUG) {      /**
2215         * TRIGGER - triggerajouter.
2216         *
2217         * @return boolean
2218         */
2219        function triggerajouter($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
2220            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
2221          /**          /**
2222           * 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
2223           * et dossier pour les stocker dans l'instruction :           * et dossier pour les stocker dans l'instruction :
# Line 928  class instruction extends instruction_ge Line 2230  class instruction extends instruction_ge
2230           * - delai_notification           * - delai_notification
2231           * - lettretype           * - lettretype
2232           * - autorite_competente           * - autorite_competente
2233             * - pec_metier
2234             * - complement_om_html
2235             * - complement2_om_html
2236             * - complement3_om_html
2237             * - complement4_om_html
2238             * - complement5_om_html
2239           * DEPUIS LE DOSSIER D'INSTRUCTION           * DEPUIS LE DOSSIER D'INSTRUCTION
2240           * - archive_delai           * - archive_delai
2241           * - archive_accord_tacite           * - archive_accord_tacite
# Line 947  class instruction extends instruction_ge Line 2255  class instruction extends instruction_ge
2255          // 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é
2256          $sql = "SELECT * FROM ".DB_PREFIXE."evenement          $sql = "SELECT * FROM ".DB_PREFIXE."evenement
2257          WHERE evenement=".$this->valF['evenement'];          WHERE evenement=".$this->valF['evenement'];
2258          $res = $db->query($sql);          $res = $this->f->db->query($sql);
2259          $this->addToLog("triggerajouter(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
2260          if (database::isError($res)) {          if (database::isError($res)) {
2261              die($res->getMessage());              die($res->getMessage());
2262          }          }
# Line 985  class instruction extends instruction_ge Line 2293  class instruction extends instruction_ge
2293              }              }
2294              // Récupération de la valeur de la lettre type              // Récupération de la valeur de la lettre type
2295              $this->valF['lettretype']=$row['lettretype'];              $this->valF['lettretype']=$row['lettretype'];
2296                // Récupération de la valeur de la prise en compte métier
2297                // si la prise en compte métier est paramétrée dans l'événement
2298                $this->valF['pec_metier'] = NULL;
2299                if(isset($row['pec_metier']) === true and empty($row['pec_metier']) === false) {
2300                    $this->valF['pec_metier'] = $row['pec_metier'];
2301                }
2302          }          }
2303          // 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
2304          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          $sql = "SELECT * FROM ".DB_PREFIXE."dossier
2305          WHERE dossier='".$this->valF['dossier']."'";          WHERE dossier='".$this->valF['dossier']."'";
2306          $res = $db->query($sql);          $res = $this->f->db->query($sql);
2307          $this->addToLog("triggerajouter(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
2308          if (database::isError($res)) {          if (database::isError($res)) {
2309              die($res->getMessage());              die($res->getMessage());
2310          }          }
# Line 1005  class instruction extends instruction_ge Line 2319  class instruction extends instruction_ge
2319                  LEFT JOIN ".DB_PREFIXE."dossier                  LEFT JOIN ".DB_PREFIXE."dossier
2320                      ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation                      ON dossier.dossier_autorisation = dossier_autorisation.dossier_autorisation
2321          WHERE dossier.dossier='".$this->valF['dossier']."'";          WHERE dossier.dossier='".$this->valF['dossier']."'";
2322          $duree_validite_parametrage = $db->getOne($sql);          $duree_validite_parametrage = $this->f->db->getOne($sql);
2323          $this->addToLog("triggerajouter(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
2324          database::isError($duree_validite_parametrage);          database::isError($duree_validite_parametrage);
2325          if ($duree_validite_parametrage != '') {          if ($duree_validite_parametrage != '') {
2326              $this->valF['duree_validite_parametrage']= $duree_validite_parametrage;              $this->valF['duree_validite_parametrage']= $duree_validite_parametrage;
# Line 1019  class instruction extends instruction_ge Line 2333  class instruction extends instruction_ge
2333          $this->valF["code_barres"] = $idTypeCourrier . $idCourrier;          $this->valF["code_barres"] = $idTypeCourrier . $idCourrier;
2334      }      }
2335            
2336      // Test si une restriction est valide      /**
2337      // return boolean       * Test si une restriction est valide.
2338         *
2339         * @return boolean
2340         */
2341      function restrictionIsValid($restriction){      function restrictionIsValid($restriction){
2342          if($this->restriction_valid != null) {          if($this->restriction_valid != null) {
2343              return $this->restriction_valid;              return $this->restriction_valid;
# Line 1205  class instruction extends instruction_ge Line 2522  class instruction extends instruction_ge
2522          $sql = "SELECT retour          $sql = "SELECT retour
2523              FROM ".DB_PREFIXE."evenement              FROM ".DB_PREFIXE."evenement
2524              WHERE evenement = ".$evenement;              WHERE evenement = ".$evenement;
2525          $retour = $this->db->getOne($sql);          $retour = $this->f->db->getOne($sql);
2526          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);
2527          if (database::isError($retour)) {          if (database::isError($retour)) {
2528              die($retour->getMessage());              die($retour->getMessage());
# Line 1236  class instruction extends instruction_ge Line 2553  class instruction extends instruction_ge
2553                WHERE                WHERE
2554                    evenement =".$evenement;                    evenement =".$evenement;
2555    
2556          $restriction = $this->db->getOne($sql);          $restriction = $this->f->db->getOne($sql);
2557          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("verifier(): db->query(\"".$sql."\");", VERBOSE_MODE);
2558          if (database::isError($restriction)) {          if (database::isError($restriction)) {
2559              die($restriction->getMessage());              die($restriction->getMessage());
# Line 1270  class instruction extends instruction_ge Line 2587  class instruction extends instruction_ge
2587          return $return;          return $return;
2588      }      }
2589    
2590    
2591      /**      /**
2592       * Calcul des règle d'action.       * Calcul des règle d'action selon leur type.
2593       * @param string $rule      Règle d'action       *
2594       * @param string $rule_name Nom de la règle       * Types de règle :
2595       * @param string $type      Type de la règle       * - date
2596         * - numeric
2597         * - text
2598         * - bool
2599         * - specific
2600         * - technical_data
2601         *
2602         * @param string $rule      Règle d'action.
2603         * @param string $rule_name Nom de la règle.
2604         * @param string $type      Type de la règle.
2605       *       *
2606       * @return mixed            Résultat de la règle       * @return mixed            Résultat de la règle
2607       */       */
2608      function regle($rule, $rule_name, $type = null) {      public function regle($rule, $rule_name, $type = null) {
2609    
2610          // Supprime tous les espaces de la chaîne de caractère          // Supprime tous les espaces de la chaîne de caractère
2611          $rule = str_replace(' ', '', $rule);          $rule = str_replace(' ', '', $rule);
# Line 1292  class instruction extends instruction_ge Line 2619  class instruction extends instruction_ge
2619              return null;              return null;
2620          }          }
2621    
         // 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];  
         }  
   
2622          // Tableau des champs de type date          // Tableau des champs de type date
2623          $rule_type_date = array(          $rule_type_date = array(
2624              "regle_date_limite",              "regle_date_limite",
# Line 1314  class instruction extends instruction_ge Line 2632  class instruction extends instruction_ge
2632              "regle_date_rejet",              "regle_date_rejet",
2633              "regle_date_dernier_depot",              "regle_date_dernier_depot",
2634              "regle_date_limite_incompletude",              "regle_date_limite_incompletude",
2635                "regle_date_cloture_instruction",
2636                "regle_date_premiere_visite",
2637                "regle_date_derniere_visite",
2638                "regle_date_contradictoire",
2639                "regle_date_retour_contradictoire",
2640                "regle_date_ait",
2641                "regle_date_transmission_parquet",
2642                "regle_date_affichage",
2643          );          );
2644          // Tableau des champs de type numérique          // Tableau des champs de type numérique
2645          $rule_type_numeric = array(          $rule_type_numeric = array(
2646              "regle_delai",              "regle_delai",
2647              "regle_delai_incompletude",              "regle_delai_incompletude",
2648          );          );
2649            // Tableau des champs de type text
2650            $rule_type_text = array(
2651            );
2652            // Tableau des champs de type booléen
2653            $rule_type_bool = array(
2654                "regle_a_qualifier",
2655                "regle_incompletude",
2656                "regle_incomplet_notifie",
2657                "regle_evenement_suivant_tacite_incompletude",
2658            );
2659            // Tableau des champs spécifiques
2660            $rule_type_specific = array(
2661                "regle_autorite_competente",
2662                "regle_etat",
2663                "regle_accord_tacite",
2664                "regle_avis",
2665                "regle_pec_metier",
2666                "regle_etat_pendant_incompletude",
2667            );
2668            // Tableau des champs de données techniques
2669            $rule_type_technical_data = array(
2670                'regle_donnees_techniques1',
2671                'regle_donnees_techniques2',
2672                'regle_donnees_techniques3',
2673                'regle_donnees_techniques4',
2674                'regle_donnees_techniques5',
2675            );
2676            // Tableau des champs simple
2677            $rule_type_simple = array(
2678                "regle_dossier_instruction_type",
2679            );
2680    
2681          // Définit le type du champ          // Définit le type du champ
2682          if (in_array($rule_name, $rule_type_date) == true) {          if (in_array($rule_name, $rule_type_date) == true) {
# Line 1328  class instruction extends instruction_ge Line 2685  class instruction extends instruction_ge
2685          if (in_array($rule_name, $rule_type_numeric) == true) {          if (in_array($rule_name, $rule_type_numeric) == true) {
2686              $type = "numeric";              $type = "numeric";
2687          }          }
2688            if (in_array($rule_name, $rule_type_text) === true) {
2689                $type = "text";
2690            }
2691            if (in_array($rule_name, $rule_type_bool) === true) {
2692                $type = "bool";
2693            }
2694            if (in_array($rule_name, $rule_type_specific) === true) {
2695                $type = "specific";
2696            }
2697            if (in_array($rule_name, $rule_type_technical_data) === true) {
2698                $type = 'text';
2699            }
2700            if (in_array($rule_name, $rule_type_simple) === true) {
2701                $type = 'simple';
2702            }
2703    
2704            // Si c'est un type spécifique ou booléen alors il n'a qu'un opérande
2705            // Récupère directement la valeur de l'opérande
2706            if ($type === 'specific') {
2707                //
2708                return $this->get_value_for_rule($rule);
2709            }
2710    
2711          // Initialisation des variables          // Initialisation des variables
2712          $key_date = 0;          $key_date = 0;
2713          $total_numeric = 0;          $total_numeric = 0;
2714            $res_text = '';
2715    
2716          // Pour chaque opérande          // Pour chaque opérande
2717          foreach ($operands as $key => $operand) {          foreach ($operands as $key => $operand) {
# Line 1339  class instruction extends instruction_ge Line 2719  class instruction extends instruction_ge
2719              // Si c'est une règle de type date              // Si c'est une règle de type date
2720              if ($type == 'date') {              if ($type == 'date') {
2721                  // Vérifie si au moins une des opérandes est une date                  // Vérifie si au moins une des opérandes est une date
2722                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2723                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2724                      && $this->f->check_date($this->valF[$operand]) == true) {                      && $this->f->check_date($this->get_value_for_rule($operand)) == true) {
2725                      // Récupère la position de la date                      // Récupère la position de la date
2726                      $key_date = $key;                      $key_date = $key;
2727                  }                  }
# Line 1350  class instruction extends instruction_ge Line 2730  class instruction extends instruction_ge
2730                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2731                      $total_numeric += $operand;                      $total_numeric += $operand;
2732                  }                  }
2733                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2734                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2735                      && is_numeric($this->valF[$operand]) == true) {                      && is_numeric($this->get_value_for_rule($operand)) == true) {
2736                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2737                      $total_numeric += $this->valF[$operand];                      $total_numeric += $this->get_value_for_rule($operand);
2738                  }                  }
2739              }              }
2740    
# Line 1365  class instruction extends instruction_ge Line 2745  class instruction extends instruction_ge
2745                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2746                      $total_numeric += $operand;                      $total_numeric += $operand;
2747                  }                  }
2748                  if (!is_numeric($operand)                  if (is_numeric($operand) === false
2749                      && isset($this->valF[$operand])                      && $this->get_value_for_rule($operand) !== null
2750                      && is_numeric($this->valF[$operand]) == true) {                      && is_numeric($this->get_value_for_rule($operand)) == true) {
2751                      // Ajoute l'opérande au total                      // Ajoute l'opérande au total
2752                      $total_numeric += $this->valF[$operand];                      $total_numeric += $this->get_value_for_rule($operand);
2753                  }                  }
2754              }              }
2755    
2756                // Si c'est une règle de type text
2757                if ($type === 'text') {
2758                    // Concatène toutes les chaînes de caractère
2759                    $res_text .= $this->get_value_for_rule($operand);
2760                }
2761          }          }
2762    
2763          // Résultat pour une règle de type date          // Résultat pour une règle de type date
# Line 1386  class instruction extends instruction_ge Line 2772  class instruction extends instruction_ge
2772              // Retourne le calcul              // Retourne le calcul
2773              return $total_numeric;              return $total_numeric;
2774          }          }
2775    
2776            // Résultat pour une règle de type text
2777            if ($type === 'text') {
2778                // Retourne la chaîne de caractère
2779                return $res_text;
2780            }
2781            if ($type === 'simple' || $type === 'bool') {
2782                // Retourne la valeur du champs rule
2783                return $rule;
2784            }
2785        }
2786    
2787    
2788        /**
2789         * Récupère la valeur du champs dans l'instruction ou dans les données
2790         * techniques.
2791         * Spécifique au calcul des règles.
2792         *
2793         * @param string $field Champ
2794         *
2795         * @return mixed Valeur du champ
2796         */
2797        private function get_value_for_rule($field) {
2798            // Si le champ n'existe pas dans la table instruction
2799            if (array_key_exists($field, $this->valF) === false) {
2800                // Récupère l'instance de la classe donnees_techniques
2801                $inst_donnees_techniques = $this->get_inst_donnees_techniques();
2802                // Retourne la valeur de la donnée technique
2803                return $inst_donnees_techniques->getVal($field);
2804            }
2805    
2806            //
2807            return $this->valF[$field];
2808        }
2809    
2810    
2811        /**
2812         * [get_inst_donnees_techniques description]
2813         *
2814         * @param [type] $donnees_techniques [description]
2815         *
2816         * @return [type] [description]
2817         */
2818        function get_inst_donnees_techniques($donnees_techniques = null) {
2819            //
2820            if (isset($this->inst_donnees_techniques) === false or
2821                $this->inst_donnees_techniques === null) {
2822                //
2823                if (is_null($donnees_techniques)) {
2824                    $donnees_techniques = $this->getDonneesTechniques();
2825                }
2826                //
2827                $this->inst_donnees_techniques = $this->f->get_inst__om_dbform(array(
2828                    "obj" => "donnees_techniques",
2829                    "idx" => $donnees_techniques,
2830                ));
2831            }
2832            //
2833            return $this->inst_donnees_techniques;
2834        }
2835    
2836    
2837        /**
2838         * Retourne l'identifiant des données techniques liées du dossier
2839         * @return string L'identifiant des données techniques liées du dossier
2840         */
2841        function getDonneesTechniques() {
2842                    
2843            $donnees_techniques = '';
2844    
2845            $sql = "SELECT donnees_techniques
2846                FROM ".DB_PREFIXE."donnees_techniques
2847                WHERE dossier_instruction ='".$this->valF["dossier"]."'";
2848            $donnees_techniques = $this->f->db->getOne($sql);
2849            $this->f->addToLog("getStatut() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
2850            if ( database::isError($donnees_techniques)){
2851                die();
2852            }
2853    
2854            return $donnees_techniques;
2855      }      }
2856    
2857      /**      /**
# Line 1399  class instruction extends instruction_ge Line 2864  class instruction extends instruction_ge
2864       *       *
2865       * @return boolean       * @return boolean
2866       */       */
2867      function triggerajouterapres($id, &$db, $val, $DEBUG) {      function triggerajouterapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
2868            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
2869    
2870          // 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
2871          $inst_di = $this->get_inst_dossier($this->valF['dossier']);          $inst_di = $this->get_inst_dossier($this->valF['dossier']);
   
2872          // Instance de la classe evenement          // Instance de la classe evenement
2873          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);          $inst_evenement = $this->get_inst_evenement($this->valF['evenement']);
2874            // Instance de l'état courant du dossier d'instruction
2875            $inst_current_etat = $this->f->get_inst__om_dbform(array(
2876                "obj" => "etat",
2877                "idx" => $inst_di->get_id_etat(),
2878            ));
2879    
2880          /**          /**
2881           * 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 1413  class instruction extends instruction_ge Line 2883  class instruction extends instruction_ge
2883           */           */
2884          // état de complétude actuel du dossier          // état de complétude actuel du dossier
2885          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);          $incompletude = ($inst_di->getVal('incompletude') == 't' ? true : false);
2886            // L'événement suivant tacite paramétré est destiné à la gestion de l'incomplétude
2887            $ev_suiv_tacite_incompletude = false;
2888          // Initialisation          // Initialisation
2889          $valF = "";          $valF = array();
2890            $valF_dt = array();
2891          //          //
         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;  
             }  
         }  
2892          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
2893          $sql = "SELECT * FROM ".DB_PREFIXE."action          $sql = "SELECT * FROM ".DB_PREFIXE."action
2894          WHERE action='".$this->valF['action']."'";          WHERE action='".$this->valF['action']."'";
2895          $res = $db->query($sql);          $res = $this->f->db->query($sql);
2896          $this->addToLog("triggerajouterapres(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
2897          if (database::isError($res)) {          if (database::isError($res)) {
2898              die($res->getMessage());              die($res->getMessage());
2899          }          }
2900          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
2901    
2902              // pour chacune des regles, on applique la regle              // pour chacune des regles, on applique la regle
2903              if($row['regle_delai']!=''){              if ($row['regle_delai'] != '') {
2904                  $valF['delai'] = $this->regle($row['regle_delai'], 'regle_delai');                  $valF['delai'] = $this->regle($row['regle_delai'], 'regle_delai');
2905              }              }
2906              if($row['regle_accord_tacite']!=''){              if ($row['regle_accord_tacite'] != '') {
2907                  $valF['accord_tacite'] = $this->regle($row['regle_accord_tacite'], 'regle_accord_tacite');                  $valF['accord_tacite'] = $this->regle($row['regle_accord_tacite'], 'regle_accord_tacite');
2908              }              }
2909              if($row['regle_avis']!=''){              if ($row['regle_avis'] != '') {
2910                  $valF['avis_decision'] = $this->regle($row['regle_avis'], 'regle_avis');                  $valF['avis_decision'] = $this->regle($row['regle_avis'], 'regle_avis');
2911              }              }
2912              if($row['regle_date_limite']!=''){              if ($row['regle_date_limite'] != '') {
2913                  $valF['date_limite']= $this->regle($row['regle_date_limite'], 'regle_date_limite');                  $valF['date_limite'] = $this->regle($row['regle_date_limite'], 'regle_date_limite');
2914              }              }
2915              if($row['regle_date_complet']!=''){              if ($row['regle_date_complet'] != '') {
2916                  $valF['date_complet']= $this->regle($row['regle_date_complet'], 'regle_date_complet');                  $valF['date_complet'] = $this->regle($row['regle_date_complet'], 'regle_date_complet');
2917              }              }
2918              if($row['regle_date_dernier_depot']!=''){              if ($row['regle_date_dernier_depot'] != '') {
2919                  $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');
2920              }              }
2921              if($row['regle_date_notification_delai']!=''){              if ($row['regle_date_notification_delai'] != '') {
2922                  $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');
2923              }              }
2924              if($row['regle_date_decision']!=''){              if ($row['regle_date_decision'] != '') {
2925                  $valF['date_decision']= $this->regle($row['regle_date_decision'], 'regle_date_decision');                  $valF['date_decision'] = $this->regle($row['regle_date_decision'], 'regle_date_decision');
2926              }              }
2927              if($row['regle_date_rejet']!=''){              if ($row['regle_date_rejet'] != '') {
2928                  $valF['date_rejet']= $this->regle($row['regle_date_rejet'], 'regle_date_rejet');                  $valF['date_rejet'] = $this->regle($row['regle_date_rejet'], 'regle_date_rejet');
2929              }              }
2930              if($row['regle_date_validite']!=''){              if ($row['regle_date_validite'] != '') {
2931                  $valF['date_validite']= $this->regle($row['regle_date_validite'], 'regle_date_validite');                  $valF['date_validite'] = $this->regle($row['regle_date_validite'], 'regle_date_validite');
2932              }              }
2933              if($row['regle_date_chantier']!=''){              if ($row['regle_date_chantier'] != '') {
2934                  $valF['date_chantier']= $this->regle($row['regle_date_chantier'], 'regle_date_chantier');                  $valF['date_chantier'] = $this->regle($row['regle_date_chantier'], 'regle_date_chantier');
2935              }              }
2936              if($row['regle_date_achevement']!=''){              if ($row['regle_date_achevement'] != '') {
2937                  $valF['date_achevement']= $this->regle($row['regle_date_achevement'], 'regle_date_achevement');                  $valF['date_achevement'] = $this->regle($row['regle_date_achevement'], 'regle_date_achevement');
2938              }              }
2939              if($row['regle_date_conformite']!=''){              if ($row['regle_date_conformite'] != '') {
2940                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');                  $valF['date_conformite'] = $this->regle($row['regle_date_conformite'], 'regle_date_conformite');
2941              }              }
2942              if($row['regle_date_limite_incompletude']!=''){              if ($row['regle_date_limite_incompletude'] != '') {
2943                  $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');
2944              }              }
2945              if($row['regle_delai_incompletude']!=''){              if ($row['regle_delai_incompletude'] != '') {
2946                  $valF['delai_incompletude']= $this->regle($row['regle_delai_incompletude'], 'regle_delai_incompletude');                  $valF['delai_incompletude'] = $this->regle($row['regle_delai_incompletude'], 'regle_delai_incompletude');
2947              }              }
2948              if($row['regle_autorite_competente']!=''){              if ($row['regle_autorite_competente'] != '') {
2949                  $valF['autorite_competente']= $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');                  $valF['autorite_competente'] = $this->regle($row['regle_autorite_competente'], 'regle_autorite_competente');
2950              }              }
2951              if($row['regle_etat']!=''){              if ($row['regle_etat'] != '') {
2952                  // 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');
2953                  // qu'on a un événement de type incomplétude alors : on stocke              }
2954                  // l'état dans la variable courante              if ($row['regle_date_cloture_instruction'] !== '') {
2955                  if ($incompletude == FALSE OR $inst_evenement->getVal('type') == "incompletude") {                  $valF['date_cloture_instruction'] = $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
2956                      $valF['etat'] = $this->regle($row['regle_etat'], 'regle_etat');              }
2957                  } else {              if ($row['regle_date_premiere_visite'] !== '') {
2958                      $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');
2959                }
2960                if ($row['regle_date_derniere_visite'] !== '') {
2961                    $valF['date_derniere_visite'] = $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');
2962                }
2963                if ($row['regle_date_contradictoire'] !== '') {
2964                    $valF['date_contradictoire'] = $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');
2965                }
2966                if ($row['regle_date_retour_contradictoire'] !== '') {
2967                    $valF['date_retour_contradictoire'] = $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');
2968                }
2969                if ($row['regle_date_ait'] !== '') {
2970                    $valF['date_ait'] = $this->regle($row['regle_date_ait'], 'regle_date_ait');
2971                }
2972                if ($row['regle_donnees_techniques1'] !== '') {
2973                    $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');
2974                }
2975                if ($row['regle_donnees_techniques2'] !== '') {
2976                    $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');
2977                }
2978                if ($row['regle_donnees_techniques3'] !== '') {
2979                    $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');
2980                }
2981                if ($row['regle_donnees_techniques4'] !== '') {
2982                    $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');
2983                }
2984                if ($row['regle_donnees_techniques5'] !== '') {
2985                    $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');
2986                }
2987                if ($row['regle_date_transmission_parquet'] !== '') {
2988                    $valF['date_transmission_parquet'] = $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');
2989                }
2990                if ($row['regle_dossier_instruction_type'] !== '') {
2991                    $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');
2992                }
2993                // La date d'affichage est modifiée seulement si le champ n'est pas
2994                // renseigné
2995                if ($row['regle_date_affichage'] !== ''
2996                    && ($inst_di->getVal('date_affichage') === ''
2997                        || $inst_di->getVal('date_affichage') === null)) {
2998                    //
2999                    $valF['date_affichage'] = $this->regle($row['regle_date_affichage'], 'regle_date_affichage');
3000                }
3001                //
3002                if ($row['regle_pec_metier'] != '') {
3003                    $valF['pec_metier'] = $this->regle($row['regle_pec_metier'], 'regle_pec_metier');
3004                }
3005                if ($row['regle_a_qualifier'] != '') {
3006                    $valF['a_qualifier'] = $this->regle($row['regle_a_qualifier'], 'regle_a_qualifier');
3007                }
3008                //
3009                if ($row['regle_incompletude'] != '') {
3010                    $valF['incompletude'] = $this->regle($row['regle_incompletude'], 'regle_incompletude');
3011                }
3012                if ($row['regle_incomplet_notifie'] != '') {
3013                    $valF['incomplet_notifie'] = $this->regle($row['regle_incomplet_notifie'], 'regle_incomplet_notifie');
3014                }
3015                if ($row['regle_etat_pendant_incompletude'] != '') {
3016                    $valF['etat_pendant_incompletude'] = $this->regle($row['regle_etat_pendant_incompletude'], 'regle_etat_pendant_incompletude');
3017                }
3018                if ($row['regle_evenement_suivant_tacite_incompletude'] != '') {
3019                    $resti = $this->regle($row['regle_evenement_suivant_tacite_incompletude'], 'regle_evenement_suivant_tacite_incompletude');
3020                    if (strtolower($resti) === 't' || strtolower($resti) === 'true') {
3021                        $ev_suiv_tacite_incompletude = true;
3022                  }                  }
3023              }              }
3024          }          }
3025          if($this->valEvenement['evenement_suivant_tacite'] != '') {  
3026              // Si on est pas en incomplétude on stocke l'événement tacite          // Si l'événement a un événement suivant tacite
3027              //de l'événement dans la variable courante          if($inst_evenement->getVal('evenement_suivant_tacite') != '') {
3028                            // En fonction de l'action de l'événement, l'événement suivant tacite ne sera
3029              if ($incompletude == FALSE OR $this->valEvenement['type'] != "incompletude") {              // pas associé de le même façon au dossier d'instruction
3030                  $valF['evenement_suivant_tacite'] = $this->valEvenement['evenement_suivant_tacite'];              if ($ev_suiv_tacite_incompletude === false) {
3031              } else {                  $valF['evenement_suivant_tacite'] = $inst_evenement->getVal('evenement_suivant_tacite');
3032                  $valF['evenement_suivant_tacite_incompletude'] = $this->valEvenement['evenement_suivant_tacite'];              }
3033                if ($ev_suiv_tacite_incompletude === true) {
3034                    $valF['evenement_suivant_tacite_incompletude'] = $inst_evenement->getVal('evenement_suivant_tacite');
3035              }              }
3036          }          }
3037          // 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
3038          if ($valF != "") {          if (count($valF_dt) > 0) {
3039                $dt_id = $this->getDonneesTechniques();
3040              // On met à jour le dossier              // On met à jour le dossier
3041              $cle = " dossier='".$this->valF['dossier']."'";              $cle = " donnees_techniques='".$dt_id."'";
3042              $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);
3043              $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);
3044              if (database::isError($res1)) {              if (database::isError($res1)) {
3045                  die($res->getMessage());                  die($res->getMessage());
3046              }              }
3047              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
3048              $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')."]");
3049            }
3050            // Si des valeurs ont été calculées alors on met à jour l'enregistrement
3051            if (count($valF) > 0) {
3052                //
3053                $inst_dossier = $this->f->get_inst__om_dbform(array(
3054                    "obj" => "dossier",
3055                    "idx" => $this->valF['dossier'],
3056                ));
3057                $valF['instruction'] = $id;
3058                $valF['crud'] = 'create';
3059                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
3060                if ($update_by_instruction === false) {
3061                    $this->cleanMessage();
3062                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
3063                    return false;
3064                }
3065                // Affichage d'informations à l'utilisateur
3066                $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
3067          }          }
3068    
3069          /**          /**
# Line 1572  class instruction extends instruction_ge Line 3099  class instruction extends instruction_ge
3099              $this->addToMessage(_("Notification (105) du référentiel ERP OK."));              $this->addToMessage(_("Notification (105) du référentiel ERP OK."));
3100          }          }
3101    
3102            // Si le mode en rédaction intégrale est activé
3103            if (isset($this->valF['flag_edition_integrale']) === true
3104                && $this->valF['flag_edition_integrale'] === true) {
3105                $redactionIntegraleValF = array();
3106    
3107                // Récupère la collectivite du dossier d'instruction
3108                $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
3109                $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
3110                // Récupère le corps de la lettre type
3111                $params = array(
3112                    "specific" => array(
3113                        "corps" => array(
3114                            "mode" => "get",
3115                        )
3116                    ),
3117                );
3118                $result = $this->compute_pdf_output('lettretype', $this->valF['lettretype'], $collectivite, $id, $params);
3119                $redactionIntegraleValF['corps_om_htmletatex'] = $result['pdf_output'];
3120                // Récupère le titre de la lettre type
3121                $params = array(
3122                    "specific" => array(
3123                        "titre" => array(
3124                            "mode" => "get",
3125                        )
3126                    ),
3127                );
3128                $result = $this->compute_pdf_output('lettretype', $this->valF['lettretype'], $collectivite, $id, $params);
3129                $redactionIntegraleValF['titre_om_htmletat'] = $result['pdf_output'];
3130    
3131                // mise à jour en base de données
3132                $res = $this->f->db->autoExecute(
3133                    DB_PREFIXE.$this->table,
3134                    $redactionIntegraleValF,
3135                    DB_AUTOQUERY_UPDATE,
3136                    $this->clePrimaire."=".$id
3137                );
3138                $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($redactionIntegraleValF, true).", DB_AUTOQUERY_UPDATE, \"".$this->clePrimaire."=".$id."\");", VERBOSE_MODE);
3139                if ($this->f->isDatabaseError($res, true) === true) {
3140                    return false;
3141                }
3142            }
3143    
3144            /**
3145             * Finalisation automatique de l'instruction si le paramétrage de l'événement l'autorise
3146             */
3147            // Si la finalisation automatique de l'événement est activée
3148            // ET si l'instruction n'a pas déjà été finalisée
3149            // ET s'il existe une lettre type associée
3150            if ($inst_evenement->getVal('finaliser_automatiquement') === 't'
3151                && $inst_evenement->getVal('om_final_instruction') !== 't'
3152                && $inst_evenement->getVal('lettretype') !== ''
3153                && $inst_evenement->getVal('lettretype') !== null) {
3154    
3155                 // On instancie l'instruction
3156                $inst_instruction = $this->f->get_inst__om_dbform(array(
3157                    "obj" => "instruction",
3158                    "idx" => $this->valF[$this->clePrimaire],
3159                ));
3160    
3161                // On finalise l'instruction dans le contexte de finalisation : action 100
3162                $inst_instruction->setParameter('maj', 100);
3163                $finalize = $inst_instruction->finalize($inst_instruction->valF);
3164    
3165                // Une erreur de finalisation renvoie 'false' : ajout dans les logs
3166                // et dans le message d'erreur
3167                if ($finalize === false) {
3168                    $this->f->addToLog(__METHOD__."() : ERROR - Impossible de finaliser l'instruction.", DEBUG_MODE);
3169                    $this->addToMessage(_("Erreur lors de la finalisation de l'instruction. Contactez votre administrateur."));
3170                    return false;
3171                }
3172            }
3173    
3174            /**
3175             * Finalisation automatique des instructions tacites ou retours.
3176             */
3177            // Si l'option de finalisation automatique des instructions tacites ou
3178            // retours est activée et l'événement d'instruction a une lettre type
3179            // associée
3180            $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
3181            if ($this->f->is_option_finalisation_auto_enabled($collectivite_di) === true
3182                && $inst_evenement->getVal('lettretype') !== ''
3183                && $inst_evenement->getVal('lettretype') !== null) {
3184    
3185                // Rècupère l'identifiant de l'événement
3186                $evenement_id = $inst_evenement->getVal($inst_evenement->clePrimaire);
3187    
3188                // Si l'événement d'instruction est identifié comme un événement
3189                // retour
3190                // OU l'événement d'instruction est l'événement suivant tacite du
3191                // dossier d'instruction (incomplétude prise en compte)
3192                // ET l'événement d'instruction n'a pas déjà été finalisé
3193                if (($inst_evenement->getVal("retour") === 't'
3194                    || ($inst_di->getVal('evenement_suivant_tacite_incompletude') === $evenement_id
3195                        || $inst_di->getVal('evenement_suivant_tacite') === $evenement_id))
3196                        && ($inst_evenement->getVal('om_final_instruction') !== 't')) {
3197    
3198                    // Finalise l'instruction
3199                    $inst_instruction = $this->f->get_inst__om_dbform(array(
3200                        "obj" => "instruction",
3201                        "idx" => $this->valF[$this->clePrimaire],
3202                    ));
3203                    $inst_instruction->setParameter('maj', 100);
3204                    $finalize = $inst_instruction->finalize($inst_instruction->valF);
3205                    if ($finalize === false) {
3206                        //
3207                        return false;
3208                    }
3209                }
3210            }
3211    
3212            /**
3213             * Mise à jour de la version de clôture *version_clos* du dossier si et
3214             * seulement si l'instruction met à jour l'état du dossier.
3215             */
3216            if (isset($valF['etat']) === true
3217                && $valF['etat'] !== null
3218                && $valF['etat'] !== '') {
3219                // Instanciation de l'état appliqué sur le dossier par l'instruction
3220                $inst_etat = $this->f->get_inst__om_dbform(array(
3221                    "obj" => "etat",
3222                    "idx" => $valF['etat'],
3223                ));
3224                //
3225                $update_version_clos = null;
3226                // En cas d'instruction qui clôture le dossier
3227                if ($inst_etat->getVal('statut') === 'cloture') {
3228                    $update_version_clos = $inst_di->update_version_clos('up');
3229                }
3230                // En cas d'instruction qui rouvre le dossier
3231                if ($inst_current_etat->getVal('statut') === 'cloture'
3232                    && $inst_etat->getVal('statut') !== 'cloture') {
3233                    //
3234                    $update_version_clos = $inst_di->update_version_clos('down');
3235                    //
3236                    $params = array(
3237                        'di_reopened' => true,
3238                    );
3239                }
3240                //
3241                if ($update_version_clos === false) {
3242                    $this->f->addToLog(sprintf(
3243                        "%s() : ERREUR - %s %s",
3244                        __METHOD__,
3245                        sprintf(
3246                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
3247                            $inst_di->getVal($inst_di->clePrimaire)
3248                        ),
3249                        sprintf(
3250                            __("L'instruction tente d'appliquer l'état %s."),
3251                            $inst_etat->getVal($inst_etat->clePrimaire)
3252                        )
3253                    ));
3254                    $this->addToMessage(sprintf(
3255                        "%s %s",
3256                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
3257                        __("Veuillez contacter votre administrateur.")
3258                    ));
3259                    return false;
3260                }
3261            }
3262    
3263            /**
3264             * Notification automatique
3265             */
3266            // Notification automatique à l'ajout de l'instruction si la notification
3267            // automatique est choisie et qu'il n'y a pas de lettretype associée à l'événement
3268            if ($inst_evenement->getVal('notification') === 'notification_automatique' &&
3269                ($inst_evenement->getVal('lettretype') === null ||
3270                $inst_evenement->getVal('lettretype') === '')) {
3271                // Récupération de la liste des demandeurs à notifier et de la catégorie
3272                $categorie = $this->f->get_param_option_notification($collectivite_di);
3273                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
3274                $demandeursANotifie = $this->get_demandeurs_notifiable(
3275                    $this->valF['dossier'],
3276                    $isPortal
3277                );
3278    
3279                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
3280                $demandeurPrincipalNotifie = false;
3281                foreach ($demandeursANotifie as $demandeur) {
3282                    // Identifie si le demandeur principal a été notifié ou pas
3283                    // et récupère ses informations
3284                    if ($demandeur['petitionnaire_principal'] == 't') {
3285                        $demandeurPrincipalNotifie = true;
3286                        // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
3287                        // son paramétrage, on effectue pas le traitement et on passe à l'itération
3288                        // suivante. On le considère également comme non notifié pour gérer l'envoie
3289                        // des messages d'erreurs
3290                        // Si la demande a été déposée via le portail alors le paramétrage n'a pas
3291                        // d'impact sur la notification
3292                        $erreursParam = $this->get_info_notification_fail($val['dossier']);
3293                        if (! $this->dossier_depose_sur_portail($val['dossier']) && $erreursParam != array()) {
3294                            $demandeurPrincipalNotifie = false;
3295                            continue;
3296                        }
3297                    }
3298                    // Ajout de la notif et récupération de son id
3299                    $idNotif = $this->ajouter_notification(
3300                        $this->valF[$this->clePrimaire],
3301                        $this->f->get_connected_user_login_name(),
3302                        $demandeur,
3303                        $collectivite_di,
3304                        array(),
3305                        true
3306                    );
3307                    if ($idNotif === false) {
3308                        return false;
3309                    }
3310                    // Création de la tache en lui donnant l'id de la notification
3311                    $notification_by_task = $this->notification_by_task(
3312                        $idNotif,
3313                        $this->valF['dossier'],
3314                        $categorie
3315                    );
3316                    if ($notification_by_task === false) {
3317                        $this->addToMessage(
3318                            __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3319                        );
3320                        return false;
3321                    }
3322                }
3323                // Si le demandeur principal n'est pas notifiable, on créé une nouvelle notification
3324                // en erreur avec en commentaire la raison pour laquelle le demandeur principal
3325                // n'a pas pu être notifié
3326                if (! $demandeurPrincipalNotifie) {
3327                    // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
3328                    $erreursParam = $this->get_info_notification_fail($val['dossier']);
3329                    $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($val['dossier']);
3330                    // Ajout de la notif et récupération de son id
3331                    $idNotif = $this->ajouter_notification(
3332                        $this->valF[$this->clePrimaire],
3333                        $this->f->get_connected_user_login_name(),
3334                        $demandeurPrincipal,
3335                        $collectivite_di,
3336                        array(),
3337                        true,
3338                        'Echec',
3339                        implode(' ', $erreursParam)
3340                    );
3341                    if ($idNotif === false) {
3342                        $this->addToMessage(
3343                            __('Erreur : la création de la notification a échouée.').
3344                            __("Veuillez contacter votre administrateur.")
3345                        );
3346                        return false;
3347                    }
3348                    // Prépare un message d'alerte à destination de l'instructeur pour l'informer
3349                    // de l'échec de la notification
3350                    $dossier_message = $this->get_inst_dossier_message(0);
3351                    $dossier_message_val = array(
3352                        'dossier' => $val['dossier'],
3353                        'type' => _('erreur expedition'),
3354                        'emetteur' => $this->f->get_connected_user_login_name().' (automatique)',
3355                        'login' => $_SESSION['login'],
3356                        'date_emission' => date('Y-m-d H:i:s'),
3357                        'contenu' => _('Échec lors de la notification de l\'instruction ').
3358                            $inst_evenement->getVal('libelle').
3359                            '.<br>'.
3360                            implode("\n", $erreursParam).
3361                            '<br>'.
3362                            _('Veuillez corriger ces informations avant de renvoyer la notification.')
3363                    );
3364                    $add = $dossier_message->add_notification_message($dossier_message_val, true);
3365                    // Si une erreur se produit pendant l'ajout
3366                    if ($add !== true) {
3367                        $this->addToLog(__METHOD__."(): Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.", DEBUG_MODE);
3368                        return false;
3369                    }
3370                }
3371                $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.")));
3372            }
3373    
3374            // Notification automatique en cas de dépôt de dossier dématérialisé
3375            // Vérifie si l'option de notification est active et si il s'agit bien d'une
3376            // instruction de récépissé
3377            if (
3378                $this->f->is_option_notification_depot_demat_enabled($collectivite_di)
3379                && $this->is_instruction_recepisse()
3380            ) {
3381                // Récupère l'instance de la demande
3382                $demande = $inst_di->get_inst_demande();
3383                // Récupère la liste des mails fournis en paramètre
3384                $listeEmails = $this->f->get_param_courriel_de_notification_commune($collectivite_di);
3385                // Vérifie que le dossier a été déposé via platau ou ideau et qu'il y a
3386                // des adresses à notifier
3387                if (
3388                    ($demande->getVal('source_depot') == 'platau' ||
3389                    $demande->getVal('source_depot') == 'ideau') &&
3390                    ! empty($listeEmails)
3391                ) {
3392                    foreach ($listeEmails as $email) {
3393                        // Ajout de la notif et récupération de son id
3394                        $destinataire = array(
3395                            'destinataire' => $email,
3396                            'courriel' => $email
3397                        );
3398                        $idNotif = $this->ajouter_notification(
3399                            $this->valF[$this->clePrimaire],
3400                            $this->f->get_connected_user_login_name(),
3401                            $destinataire,
3402                            $collectivite_di,
3403                            array(),
3404                            true
3405                        );
3406                        if ($idNotif === false) {
3407                            return false;
3408                        }
3409                        // Création de la tache en lui donnant l'id de la notification
3410                        $notification_by_task = $this->notification_by_task(
3411                            $idNotif,
3412                            $this->valF['dossier'],
3413                            'mail',
3414                            'notification_depot_demat'
3415                        );
3416                        if ($notification_by_task === false) {
3417                            $this->addToMessage(
3418                                __("Erreur lors de la génération de la notification de dépot de dossier par voie dématérialisée.")
3419                            );
3420                            return false;
3421                        }
3422                    }
3423                }
3424            }
3425    
3426            /**
3427             * Mise à jour de la date de dernière modification du dossier
3428             */
3429            $inst_di->update_last_modification_date();
3430    
3431          /**          /**
3432           * Mise à jour des données du DA.           * Mise à jour des données du DA.
3433           */           */
         //  
3434          $inst_da = $inst_di->get_inst_dossier_autorisation();          $inst_da = $inst_di->get_inst_dossier_autorisation();
3435          //          $params['di_id'] = $this->valF['dossier'];
3436          if ($inst_da->majDossierAutorisation() === false) {          if ($inst_da->majDossierAutorisation($params) === false) {
3437              $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."));
3438              $this->correct = false;              $this->correct = false;
3439              return false;              return false;
# Line 1591  class instruction extends instruction_ge Line 3446  class instruction extends instruction_ge
3446          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));          return $this->add_log_to_dossier($id, array_merge($val, $this->valF));
3447      }      }
3448    
3449      function triggermodifierapres($id,&$db,$val,$DEBUG) {      /**
3450         * Cette méthode vérifie si toutes les conditions de l'envoi de la notification
3451         * sont remplies.
3452         * Les conditions vérifiées sont les suivantes :
3453         *  - Le petitionnaire principal doit accepter les notifications
3454         *  - Le pétitionnaire principal doit avoir une adresse mail renseignée
3455         *  - Le pétitionnaire principal doit avoir une adresse mail correcte
3456         * Pour chaque vérification effectué un message d'erreur est ajouté si la
3457         * condition n'est pas remplie.
3458         * Renvoie le message d'erreur en sortie.
3459         *
3460         * @param string identifiant du dossier sur lequel les notifications ont échouée
3461         * @return string
3462         */
3463        protected function get_info_notification_fail($dossier = null) {
3464            // Utilise l'identifiant du dossier passé en paramètre et si aucun dossier n'a été récupéré
3465            // utilise celui associé à l'instruction
3466            if ($dossier == null) {
3467                $dossier = $this->getVal('dossier');
3468            }
3469            // Tableau contenant la liste des messages d'erreur
3470            $errorMessage = array();
3471            // Récupère les informations du demandeurs principal
3472            $infoPetitionnaire = $this->get_info_petitionnaire_principal_dossier($dossier);
3473            // Vérifie si le pétitionnaire principal à bien la case "accepte les notification" cochée
3474            if (isset($infoPetitionnaire['notification']) && $infoPetitionnaire['notification'] != 't') {
3475                $errorMessage[] = __('Le pétitionnaire principal n\'accepte pas les notifications.');
3476            }
3477            // Vérifie si l'adresse mail du pétitionnaire principale est renseignée
3478            if (isset($infoPetitionnaire['courriel']) && ! empty($infoPetitionnaire['courriel'])) {
3479                // Vérifie si le format de l'adresse mail est pas correct et, si ce n'est pas le cas, informe l'utilisateur
3480                // qu'il doit le corriger avant de pouvoir ajouter l'nstruction
3481                if (! $this->f->checkValidEmailAddress($infoPetitionnaire['courriel'])) {
3482                    $errorMessage[] = __('Le courriel du pétitionnaire principal n\'est pas correct : ').
3483                        $infoPetitionnaire['courriel'].
3484                        '.';
3485                }
3486            } else {
3487                // Si le courriel du pétitionnaire principal
3488                $errorMessage[] = __('Le courriel du pétitionnaire principal n\'est pas renseigné.');
3489            }
3490    
3491            return $errorMessage;
3492        }
3493    
3494        /**
3495         * Méthode servant à vérifier si un dossier a été déposé sur
3496         * le portail citoyen ou pas.
3497         * La verification se fait via une requête sql dans laquelle
3498         * on va chercher un dossier ayant pour id l'identifiant de
3499         * dossier associé à l'instruction et pour lequel la demande
3500         * associée la plus ancienne est une demande de création de
3501         * dossier via portail
3502         *
3503         * @param string identifiant du dossier. Si non renseigné c'est le dossier
3504         * associé à l'instruction qui est utilisé
3505         * @return boolean|void true : dossier déposé via portail, false : dossier
3506         * non déposé via portail et null : erreur de base de données.
3507         */
3508        protected function dossier_depose_sur_portail($dossier = null) {
3509            if (empty($dossier)) {
3510                $dossier = $this->getVal('dossier');
3511            }
3512            $sql = sprintf(
3513                'SELECT
3514                    dossier
3515                FROM
3516                    %1$sdossier
3517                    -- Récuperation de la première demande associée au dossier
3518                    LEFT JOIN (
3519                        SELECT
3520                            demande,
3521                            dossier_instruction,
3522                            source_depot
3523                            FROM
3524                            %1$sdemande
3525                            WHERE
3526                           dossier_instruction = \'%2$s\'
3527                                ORDER BY
3528                           demande ASC
3529                                LIMIT 1
3530                            ) as demande ON dossier.dossier = demande.dossier_instruction
3531                WHERE
3532                    dossier.dossier = \'%2$s\'
3533                    AND demande.source_depot = \'portal\'',
3534                DB_PREFIXE,
3535                $dossier
3536            );
3537            $res = $this->f->get_one_result_from_db_query($sql, true);
3538            if ($res['code'] === 'KO') {
3539                $this->addToMessage(__('Erreur : La vérification du mode de dépôt du dossier à échoué'));
3540                return;
3541            }
3542            // Si on a un résultat c'est que le dossier a été déposé via le portail
3543            return ! empty($res['result']);
3544        }
3545    
3546        public function is_service_notifiable() {
3547            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
3548    
3549            // Si l'instruction a une édition non finalisé quel que soit
3550            // le type de notification, il n'est pas notifiable
3551            if ($this->has_an_edition() === true) {
3552                if ($this->is_unfinalizable_without_bypass() === false) {
3553                    return false;
3554                }
3555            }
3556            // Vérifie si la notification des tiers est active pour l'évènement
3557            return $this->get_boolean_from_pgsql_value($evenement->getVal('notification_service'));
3558        }
3559    
3560        public function is_tiers_notifiable() {
3561            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
3562    
3563            // Si l'instruction a une édition non finalisé quel que soit
3564            // le type de notification, il n'est pas notifiable
3565            if ($this->has_an_edition() === true) {
3566                if ($this->is_unfinalizable_without_bypass() === false) {
3567                    return false;
3568                }
3569            }
3570            // Vérifie si la notification des tiers est active pour l'évènement
3571            return $this->get_boolean_from_pgsql_value($evenement->getVal('notification_tiers'));
3572        }
3573    
3574        /**
3575         * Méthode permettant de savoir si une instruction peut
3576         * être notifiée manuellement selon les différents types
3577         * de notification.
3578         *
3579         * Si l'instruction a une édition non finalisée alors elle n'est pas
3580         * manuellement notifiable.
3581         * Si l'instruction est associé à un événement de notification pour
3582         * lequel un retour signature est recquis, elle n'est notifiable que
3583         * si la date de retour de signature est remplie.
3584         * Par défaut si le type de notification n'est pas connu alors l'instruction
3585         * n'est pas notifiable.
3586         * Pour tous les autres cas l'instruction est manuellement notifiable.
3587         *
3588         * @return boolean true : notifiable | false : non notifiable
3589         */
3590        public function is_notifiable_by_task_manual() {
3591            $ev = $this->get_inst_evenement($this->getVal('evenement'));
3592    
3593            // Si l'instruction a une édition non finalisé quel que soit
3594            // le type de notification, il n'est pas notifiable
3595            if ($this->has_an_edition() === true) {
3596                if ($this->is_unfinalizable_without_bypass() === false) {
3597                    return false;
3598                }
3599            }
3600    
3601            // Gestion des différents cas selon la valeur du champs notification
3602            if ($ev->getVal('notification') == 'notification_manuelle' ||
3603                $ev->getVal('notification') == 'notification_manuelle_annexe' ||
3604                $ev->getVal('notification') == 'notification_automatique'
3605            ) {
3606                return true;
3607            } elseif (($ev->getVal('notification') == 'notification_auto_signature_requise' ||
3608                $ev->getVal('notification') == 'notification_manuelle_signature_requise' ||
3609                $ev->getVal('notification') == 'notification_manuelle_annexe_signature_requise') &&
3610                $this->getVal('date_retour_signature') != null &&
3611                $this->getVal('date_retour_signature') != ''
3612            ) {
3613                return true ;
3614            }
3615            return false;
3616        }
3617    
3618        /**
3619         * Crée une instance et une tache de notification pour le demandeur
3620         * principal.
3621         *
3622         * @return boolean true si le traitement à réussi
3623         */
3624        protected function notifier_demandeur_principal() {
3625            $this->begin_treatment(__METHOD__);
3626            $message = '';
3627            // Récupération des informations concernant le demandeur
3628            $dossier = $this->getVal('dossier');
3629            $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
3630            $demandeur = $this->get_demandeurs_notifiable(
3631                $dossier,
3632                true
3633            );
3634            if ($demandeur !== array()) {
3635                $destinataire = array_values($demandeur);
3636                // Ajout de la notif et récupération de son id
3637                $idNotification = $this->ajouter_notification(
3638                    $this->getVal($this->clePrimaire),
3639                    $this->f->get_connected_user_login_name(),
3640                    $destinataire[0],
3641                    $collectivite_di,
3642                    array(),
3643                    true
3644                );
3645                if ($idNotification === false) {
3646                    return $this->end_treatment(__METHOD__, false);
3647                }
3648                // Création de la tâche en lui donnant l'id de la notification
3649                $notification_by_task = $this->notification_by_task($idNotification, $dossier);
3650                if ($notification_by_task === false) {
3651                    $this->addToMessage(
3652                        __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
3653                    );
3654                    return $this->end_treatment(__METHOD__, false);
3655                }
3656                $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.")));
3657                return $this->end_treatment(__METHOD__, true);
3658            }
3659            $this->addToMessage( __("Le demandeur principal n'est pas notifiable."));
3660            return $this->end_treatment(__METHOD__, false);
3661        }
3662    
3663        public function notification_by_task($object_id, $dossier, $category = null, $type = null) {
3664            // Par défaut le type est portal
3665            if ($category === null) {
3666                $category = 'portal';
3667            }
3668            // Si le type n'est pas correctement spécifié, alors il est calculé
3669            if ($type !== 'notification_recepisse'
3670                && $type !== 'notification_instruction'
3671                && $type !== 'notification_decision'
3672                && $type !== 'notification_service_consulte'
3673                && $type !== 'notification_tiers_consulte'
3674                && $type !== 'notification_depot_demat'
3675                && $type !== 'notification_commune') {
3676                //
3677                $type = 'notification_instruction';
3678                // Vérifie si l'instruction est un récépissé
3679                if ($this->is_instruction_recepisse()) {
3680                    $type = 'notification_recepisse';
3681    
3682                }
3683                // Vérifie si l'instruction est une décision
3684                if ($type !== 'notification_recepisse') {
3685                    $avis_decision = $this->getVal('avis_decision') !== null ? $this->getVal('avis_decision') : $this->valF['avis_decision'];
3686                    if ($avis_decision !== null && $avis_decision !== '') {
3687                        $type = 'notification_decision';
3688                    }
3689                }
3690            }
3691            // Préparation de la tache de notification
3692            $inst_task = $this->f->get_inst__om_dbform(array(
3693                "obj" => "task",
3694                "idx" => 0,
3695            ));
3696            $task_val = array(
3697                'type' => $type,
3698                'object_id' => $object_id,
3699                'dossier' => $dossier,
3700                'category' => $category,
3701            );
3702    
3703            $add_task = $inst_task->add_task(array('val' => $task_val));
3704            if ($add_task === false) {
3705                return false;
3706            }
3707    
3708            return true;
3709        }
3710    
3711        /**
3712         * Cette méthode permet de savoir si l'instruction est une instruction
3713         * de recepisse (instruction lié à l'ajout du dossier).
3714         *
3715         * Pour cela, on récupère la liste des actions qui ont menées à la création
3716         * de l'instruction. Si une de ces actions est lié à un objet "demande" on
3717         * en deduis que c'est l'ajout d'une demande qui a déclenché la création de
3718         * l'instruction et donc qu'il s'agit d'un recepisse.
3719         *
3720         * @return boolean
3721         */
3722        protected function is_instruction_recepisse() {
3723            // Récupère la liste des actions qui ont mené à la création de
3724            // l'instruction
3725            $trace = debug_backtrace();
3726            // Parcours la liste des actions et si une de ces actions est lié
3727            // à la classe demande on cosidère que l'instruction est un recepisse
3728            foreach ($trace as $key => $value) {
3729                if (isset($trace[$key]['class']) === true
3730                    && empty($trace[$key]['class']) === false) {
3731                    if (strtolower($trace[$key]['class']) === 'demande') {
3732                        return true;
3733                    }
3734                }
3735            }
3736            return false;
3737        }
3738    
3739        /**
3740         * A partir des informations passée en argument ajoute un nouvel élément
3741         * dans la table instruction_notification.
3742         * Avant l'ajout vérifie en utilisant l'id de la collectivité passée en
3743         * paramètre si le paramétrage attendus est ok.
3744         * Ajoute également un nouvel élement dans instruction_notification_document
3745         * si l'instruction possède une lettretype.
3746         * Si un identifiant d'une instruction annexe est donnée ajoute un deuxième
3747         * élement dans la table instruction_notification_document qui correspondra
3748         * à l'annexe de la notification.
3749         *
3750         * @param integer identifiant de l'instruction notifiée
3751         * @param string information concernant l'emetteur
3752         * @param array tableau contenant 2 entrées
3753         *  - destinatire : nom, prenom ou raison sociale, dénomination et courriel
3754         *  - courriel : adresse mail de la personne à notifier
3755         * @param integer identifiant de la collectivité permettant de récupèrer les
3756         * paramètres à valider
3757         * @param boolean indique si la notification est automatique ou manuelle
3758         * @param integer identifiant d'une instruction dont l'édition sera annexé
3759         * à la notification
3760         *
3761         * @return integer|boolean identifiant de la notification créée si le traitement
3762         * a réussie, false sinon.
3763         */
3764        protected function ajouter_notification(
3765            $idInstruction,
3766            $emetteur,
3767            $destinataire,
3768            $collectiviteId,
3769            $annexes = array(),
3770            $demandeAuto = false,
3771            $statut = 'en cours d\'envoi',
3772            $commentaire = 'Notification en cours de traitement'
3773        ) {
3774            // Vérification que les paramètres nécessaires à l'envoi de la notification existe avant
3775            // de créer la notification
3776            if (! $this->is_parametrage_notification_correct($collectiviteId)) {
3777                $this->addToMessage(__("Erreur de paramétrage. L'url d'accès au(x) document(s) notifié(s) n'est pas paramétrée."));
3778                return false;
3779            }
3780            // Préparation de la notification
3781            $inst_notif = $this->f->get_inst__om_dbform(array(
3782                "obj" => "instruction_notification",
3783                "idx" => "]",
3784            ));
3785            $notif_val = array(
3786                'instruction_notification' => null,
3787                'instruction' => $idInstruction,
3788                'automatique' => $demandeAuto,
3789                'emetteur' => $emetteur,
3790                'date_envoi' => null,
3791                'destinataire' => $destinataire['destinataire'],
3792                'courriel' => $destinataire['courriel'],
3793                'date_premier_acces' => null,
3794                'statut' => $statut,
3795                'commentaire' => $commentaire
3796            );
3797    
3798            // Création de la notification
3799            $add_notif = $inst_notif->ajouter($notif_val);
3800            if ($add_notif === false) {
3801                $this->addToMessage(__("Erreur lors de la génération de la notification au(x) pétitionnaire(s)."));
3802                return false;
3803            }
3804    
3805            // Si il y a une lettretype finalisé stockage de la clé d'accès au documents
3806            if ($this->evenement_has_an_edition($this->getVal('evenement')) === true) {
3807                $add_notif_doc = $this->ajouter_notification_document(
3808                    $inst_notif->getVal($inst_notif->clePrimaire),
3809                    $this->getVal($this->clePrimaire),
3810                    'instruction'
3811                );
3812                if ($add_notif_doc === false) {
3813                    $this->addToMessage(__("Erreur lors de la génération de la notification du document."));
3814                    return false;
3815                }
3816            }
3817            // Si une annexe a été choisie stockage de la clé d'accès à l'annexe
3818            if (! empty($annexes) && is_array($annexes)) {
3819                $add_notif_annexe = $this->ajouter_notification_document_multiple(
3820                    $inst_notif->getVal($inst_notif->clePrimaire),
3821                    $annexes
3822                );
3823                if ($add_notif_annexe === false) {
3824                    $this->addToMessage(__("Erreur lors de la génération de la notification de l'annexe."));
3825                    return false;
3826                }
3827            }
3828    
3829            // Renvoie l'id de la nouvelle instance de instruction_notification
3830            return $inst_notif->getVal($inst_notif->clePrimaire);
3831        }
3832    
3833        /**
3834         * Pour chaque élément du tableau passé en paramètre ajoute une nouvelle
3835         * instance dans la table instruction_notification_document lié a la
3836         * notification dont l'id est passé en paramètre.
3837         *
3838         * @param array tableau contenant les informations nécessaires pour créer les annexes
3839         *
3840         * @return integer|boolean identifiant de la notification créée si le traitement
3841         * a réussie, false sinon.
3842         */
3843        protected function ajouter_notification_document_multiple($idNotification, $listeDocument) {
3844            foreach ($listeDocument as $paramDoc) {
3845                if (! $this->ajouter_notification_document($idNotification, $paramDoc['id'], $paramDoc['tableDocument'], $paramDoc['isAnnexe'])) {
3846                    $this->addToMessage(__("Erreur lors de la génération des documents à notifier."));
3847                    return false;
3848                }
3849            }
3850            return true;
3851        }
3852    
3853        /**
3854         * Ajoute un élément dans la table instruction_notification_document en utilisant
3855         * les éléments fourni en paramètre
3856         *
3857         * @param integer $idNotification : id de la notification à laquelle on associe le document
3858         * @param integer $idDocument : id de l'objet auquel est rattaché le document
3859         * @param string $tableDocument : nom de la table a laquelle est rattaché le document
3860         * @param boolean $isAnnexe : indique si le document est une annexe ou pas
3861         *
3862         * @return boolean indique si le traitement a réussi
3863         */
3864        protected function ajouter_notification_document($idNotification, $idDocument, $tableDocument, $isAnnexe = false) {
3865            $inst_notif_doc = $this->f->get_inst__om_dbform(array(
3866                "obj" => "instruction_notification_document",
3867                "idx" => "]",
3868            ));
3869            // l'attribut instruction doit obligatoirement être renseigné
3870            // pour éviter toutes confusion avec d'autres instruction l'id
3871            // 0 est donné au document n'appartenant pas aux instructions
3872            $notif_doc_val = array(
3873                'instruction_notification_document' => null,
3874                'instruction_notification' => $idNotification,
3875                'instruction' => $tableDocument == 'instruction' ? $idDocument : 0,
3876                'document_type' => $tableDocument,
3877                'document_id' => $idDocument,
3878                'cle' => $this->getCleAccesDocument(),
3879                'annexe' => $isAnnexe
3880            );
3881    
3882            $add_notif_doc = $inst_notif_doc->ajouter($notif_doc_val);
3883            if ($add_notif_doc === false) {
3884                return false;
3885            }
3886            return true;
3887        }
3888        
3889        /**
3890         * Vérifie si le paramétrage de la notification des demandeurs est correct.
3891         *
3892         * @param integer identifiant de la collectivité
3893         * @return boolean
3894         */
3895        protected function is_parametrage_notification_correct($collectiviteId) {
3896            $categorie = $this->f->get_param_option_notification($collectiviteId);
3897            $urlAccesNotif = $this->f->get_parametre_notification_url_acces($collectiviteId);
3898            if ($categorie == 'mail' && $urlAccesNotif == null) {
3899                return false;
3900            }
3901            return true;
3902        }
3903    
3904        /**
3905         * TRIGGER - triggermodifierapres.
3906         *
3907         * @return boolean
3908         */
3909        function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
3910            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
3911            $collectivite_di = $this->get_dossier_instruction_om_collectivite($val['dossier']);
3912            $message = '';
3913          /**          /**
3914           * 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
3915           * si la date de l'evenement est modifiee           * si la date de l'evenement est modifiee
3916           */           */
3917          // Initialisation          // Initialisation
3918          $valF = "";          $valF = array();
3919            $valF_dt = array();
3920          // Initialisation du type d'événement          // Initialisation du type d'événement
3921          $type_evmt = "";          $type_evmt = "";
3922          // Récupération de l'action correspondante à l'événement          // Récupération de l'action correspondante à l'événement
3923          $sql = "SELECT action          $sql = "SELECT action
3924          FROM ".DB_PREFIXE."evenement          FROM ".DB_PREFIXE."evenement
3925          WHERE evenement=".$this->valF['evenement'];          WHERE evenement=".$this->valF['evenement'];
3926          $action = $db->getOne($sql);          $action = $this->f->db->getOne($sql);
3927          $this->addToLog("triggermodifierapres(): db->getone(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->getone(\"".$sql."\");", VERBOSE_MODE);
3928          if (database::isError($action)) {          if (database::isError($action)) {
3929              die($action->getMessage());              die($action->getMessage());
3930          }          }
# Line 1613  class instruction extends instruction_ge Line 3932  class instruction extends instruction_ge
3932          // Récupération des paramètres de l'action          // Récupération des paramètres de l'action
3933          $sql = "SELECT * FROM ".DB_PREFIXE."action          $sql = "SELECT * FROM ".DB_PREFIXE."action
3934          WHERE action='".$action."'";          WHERE action='".$action."'";
3935          $res = $db->query($sql);          $res = $this->f->db->query($sql);
3936          $this->addToLog("triggermodifierapres(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
3937          if (database::isError($res)) {          if (database::isError($res)) {
3938              die($res->getMessage());              die($res->getMessage());
3939          }          }
# Line 1650  class instruction extends instruction_ge Line 3969  class instruction extends instruction_ge
3969              if(preg_match("/date_evenement/",$row['regle_date_conformite'])){              if(preg_match("/date_evenement/",$row['regle_date_conformite'])){
3970                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');                  $valF['date_conformite']= $this->regle($row['regle_date_conformite'], 'regle_date_conformite');
3971              }              }
3972                if(preg_match("/date_evenement/",$row['regle_date_cloture_instruction'])){
3973                    $valF['date_cloture_instruction']= $this->regle($row['regle_date_cloture_instruction'], 'regle_date_cloture_instruction');
3974                }
3975                if(preg_match("/date_evenement/",$row['regle_date_premiere_visite'])){
3976                    $valF['date_premiere_visite']= $this->regle($row['regle_date_premiere_visite'], 'regle_date_premiere_visite');
3977                }
3978                if(preg_match("/date_evenement/",$row['regle_date_derniere_visite'])){
3979                    $valF['date_derniere_visite']= $this->regle($row['regle_date_derniere_visite'], 'regle_date_derniere_visite');
3980                }
3981                if(preg_match("/date_evenement/",$row['regle_date_contradictoire'])){
3982                    $valF['date_contradictoire']= $this->regle($row['regle_date_contradictoire'], 'regle_date_contradictoire');
3983                }
3984                if(preg_match("/date_evenement/",$row['regle_date_retour_contradictoire'])){
3985                    $valF['date_retour_contradictoire']= $this->regle($row['regle_date_retour_contradictoire'], 'regle_date_retour_contradictoire');
3986                }
3987                if(preg_match("/date_evenement/",$row['regle_date_ait'])){
3988                    $valF['date_ait']= $this->regle($row['regle_date_ait'], 'regle_date_ait');
3989                }
3990                if(preg_match("/date_evenement/",$row['regle_date_transmission_parquet'])){
3991                    $valF['date_transmission_parquet']= $this->regle($row['regle_date_transmission_parquet'], 'regle_date_transmission_parquet');
3992                }
3993                if ($row['regle_donnees_techniques1'] !== '') {
3994                    $valF_dt[$row['cible_regle_donnees_techniques1']] = $this->regle($row['regle_donnees_techniques1'], 'regle_donnees_techniques1');
3995                }
3996                if ($row['regle_donnees_techniques2'] !== '') {
3997                    $valF_dt[$row['cible_regle_donnees_techniques2']] = $this->regle($row['regle_donnees_techniques2'], 'regle_donnees_techniques2');
3998                }
3999                if ($row['regle_donnees_techniques3'] !== '') {
4000                    $valF_dt[$row['cible_regle_donnees_techniques3']] = $this->regle($row['regle_donnees_techniques3'], 'regle_donnees_techniques3');
4001                }
4002                if ($row['regle_donnees_techniques4'] !== '') {
4003                    $valF_dt[$row['cible_regle_donnees_techniques4']] = $this->regle($row['regle_donnees_techniques4'], 'regle_donnees_techniques4');
4004                }
4005                if ($row['regle_donnees_techniques5'] !== '') {
4006                    $valF_dt[$row['cible_regle_donnees_techniques5']] = $this->regle($row['regle_donnees_techniques5'], 'regle_donnees_techniques5');
4007                }
4008                if ($row['regle_dossier_instruction_type'] !== '') {
4009                    $valF['dossier_instruction_type'] = $this->regle($row['regle_dossier_instruction_type'], 'regle_dossier_instruction_type');
4010                }
4011          }          }
4012          // 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
4013          if ($valF != "") {          if (count($valF_dt) > 0) {
4014                $dt_id = $this->getDonneesTechniques();
4015              // On met à jour le dossier              // On met à jour le dossier
4016              $cle = " dossier='".$this->valF['dossier']."'";              $cle = " donnees_techniques='".$dt_id."'";
4017              $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);
4018              $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);
4019              if (database::isError($res1)) {              if (database::isError($res1)) {
4020                  die($res->getMessage());                  die($res->getMessage());
4021              }              }
4022              // Affichage d'informations à l'utilisateur              // Affichage d'informations à l'utilisateur
4023              $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')."]");
4024            }
4025            // Si des valeurs ont été calculées alors on met à jour l'enregistrement
4026            if (count($valF) > 0) {
4027                //
4028                $inst_dossier = $this->f->get_inst__om_dbform(array(
4029                    "obj" => "dossier",
4030                    "idx" => $this->valF['dossier'],
4031                ));
4032                $valF['instruction'] = $id;
4033                $valF['crud'] = 'update';
4034                $update_by_instruction = $inst_dossier->update_by_instruction($valF);
4035                if ($update_by_instruction === false) {
4036                    $this->cleanMessage();
4037                    $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
4038                    return false;
4039                }
4040                // Affichage d'informations à l'utilisateur
4041                $this->addToMessage(_('enregistrement')." ".$this->valF['dossier']." "._('table')." dossier [".$this->f->db->affectedRows()." "._('enregistrement')." "._('mis_a_jour')."]");
4042          }          }
4043    
4044          $restriction = $this->get_restriction($val['evenement']);          $restriction = $this->get_restriction($val['evenement']);
# Line 1671  class instruction extends instruction_ge Line 4048  class instruction extends instruction_ge
4048              // 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é
4049              $sql = "SELECT * FROM ".DB_PREFIXE."evenement              $sql = "SELECT * FROM ".DB_PREFIXE."evenement
4050              WHERE evenement=".$this->valF['evenement'];              WHERE evenement=".$this->valF['evenement'];
4051              $res = $db->query($sql);              $res = $this->f->db->query($sql);
4052              $this->addToLog("triggermodifierapres(): db->query(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
4053              if (database::isError($res)) {              if (database::isError($res)) {
4054                  die($res->getMessage());                  die($res->getMessage());
4055              }              }
# Line 1682  class instruction extends instruction_ge Line 4059  class instruction extends instruction_ge
4059                  if ($this->getVal('date_retour_signature') == "" AND                  if ($this->getVal('date_retour_signature') == "" AND
4060                      $this->valF['date_retour_signature'] != "" AND                      $this->valF['date_retour_signature'] != "" AND
4061                      $row['evenement_retour_signature'] != "") {                      $row['evenement_retour_signature'] != "") {
4062                      $new_instruction = new instruction("]", $db, $DEBUG);                      $new_instruction = $this->f->get_inst__om_dbform(array(
4063                            "obj" => "instruction",
4064                            "idx" => "]",
4065                        ));
4066                      // 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
4067                      foreach($new_instruction->champs as $champ) {                      foreach($new_instruction->champs as $champ) {
4068                          $valNewInstr[$champ] = "";                          $valNewInstr[$champ] = "";
# Line 1701  class instruction extends instruction_ge Line 4081  class instruction extends instruction_ge
4081                      $new_instruction->setParameter("maj", 0);                      $new_instruction->setParameter("maj", 0);
4082                      $new_instruction->class_actions[0]["identifier"] =                      $new_instruction->class_actions[0]["identifier"] =
4083                          "retour signature de l'instruction $current_id";                          "retour signature de l'instruction $current_id";
4084                      $retour = $new_instruction->ajouter($valNewInstr,$db, $DEBUG);                      $retour = $new_instruction->ajouter($valNewInstr);
4085                                            
4086                      //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
4087                      //de restriction                      //de restriction
4088                      if ($retour == false && !$new_instruction->restriction_valid){                      if ($retour == false && !$new_instruction->restriction_valid){
4089                          $error_message = $this->get_restriction_error_message($restriction);                          $error_message = $this->get_restriction_error_message($restriction);
4090                          $this->f->displayMessage("error", $error_message);                          $this->f->displayMessage("error", $error_message);
4091                          $this->addToLog("triggermodifierapres() : evenement retour ".                          $this->addToLog(__METHOD__."(): evenement retour ".
4092                              "instruction ".$this->valF[$this->clePrimaire]." : ".                              "instruction ".$this->valF[$this->clePrimaire]." : ".
4093                              $new_instruction->msg);                              $new_instruction->msg);
4094                      }                      }
# Line 1724  class instruction extends instruction_ge Line 4104  class instruction extends instruction_ge
4104                      $this->valF['date_retour_rar'] != "") {                      $this->valF['date_retour_rar'] != "") {
4105                                            
4106                      if($row['evenement_retour_ar'] != "") {                      if($row['evenement_retour_ar'] != "") {
4107                          $new_instruction = new instruction("]", $db, $DEBUG);                          $new_instruction = $this->f->get_inst__om_dbform(array(
4108                                "obj" => "instruction",
4109                                "idx" => "]",
4110                            ));
4111                          // 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
4112                          foreach($new_instruction->champs as $champ) {                          foreach($new_instruction->champs as $champ) {
4113                              $valNewInstr[$champ] = "";                              $valNewInstr[$champ] = "";
# Line 1742  class instruction extends instruction_ge Line 4125  class instruction extends instruction_ge
4125                          $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']);
4126                          $new_instruction->setParameter("maj", 0);                          $new_instruction->setParameter("maj", 0);
4127                          $new_instruction->class_actions[0]["identifier"] =                          $new_instruction->class_actions[0]["identifier"] =
4128                              "retour RAR de l'instruction $current_id";                              "notification de l'instruction $current_id";
4129                          $retour = $new_instruction->ajouter($valNewInstr,$db, $DEBUG);                          $retour = $new_instruction->ajouter($valNewInstr);
4130    
4131                          //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
4132                          //de restriction                          //de restriction
# Line 1751  class instruction extends instruction_ge Line 4134  class instruction extends instruction_ge
4134                              $error_message = $this->get_restriction_error_message($restriction);                              $error_message = $this->get_restriction_error_message($restriction);
4135                              $this->f->displayMessage("error", $error_message);                              $this->f->displayMessage("error", $error_message);
4136                              $this->addToLog(                              $this->addToLog(
4137                                  "triggermodifierapres() : evenement retour instruction ".                                  __METHOD__."(): evenement retour instruction ".
4138                                  $this->valF[$this->clePrimaire]." : ".                                  $this->valF[$this->clePrimaire]." : ".
4139                                  $new_instruction->msg                                  $new_instruction->msg
4140                              );                              );
# Line 1763  class instruction extends instruction_ge Line 4146  class instruction extends instruction_ge
4146                              return false;                              return false;
4147                          }                          }
4148                      }                      }
                     // 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());  
                         }  
                     }  
4149                  }                  }
4150              }              }
4151          }          }
4152    
4153            /**
4154             * Mise à jour de la date de dernière modification du dossier
4155             * d'instruction
4156             */
4157            $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
4158            $inst_di->update_last_modification_date();
4159    
4160          // Mise à jour des données du dossier d'autorisation          // Mise à jour des données du dossier d'autorisation
4161          require_once "../obj/dossier_autorisation.class.php";          $da = $this->f->get_inst__om_dbform(array(
4162          $da = new dossier_autorisation($this->getNumDemandeAutorFromDossier($this->valF['dossier']), $this->db, DEBUG);              "obj" => "dossier_autorisation",
4163          if($da->majDossierAutorisation() === false) {              "idx" => $this->getNumDemandeAutorFromDossier($this->valF['dossier']),
4164            ));
4165            $params = array(
4166                'di_id' => $this->getVal('dossier'),
4167            );
4168            if($da->majDossierAutorisation($params) === false) {
4169              $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."));
4170              $this->correct = false;              $this->correct = false;
4171              return false;              return false;
4172          }          }
4173    
4174            // mise à jour des métadonnées issues des dates de suivi
4175            $dateRetourSignatureModified = ($this->valF['date_retour_signature'] != $this->getVal('date_retour_signature'));
4176            $dateRetourRARModified = ($this->valF['date_retour_rar'] != $this->getVal('date_retour_rar'));
4177            if ($dateRetourSignatureModified || $dateRetourRARModified) {
4178    
4179                // Calculs des nouvelles métadonnées
4180                $metadata = $this->getMetadata("om_fichier_instruction");
4181    
4182                // On vérifie si l'instruction à finaliser a un événement de type arrete
4183                $sql = "SELECT type FROM ".DB_PREFIXE."evenement WHERE evenement = ".$this->getVal("evenement");
4184                $typeEvenement = $this->f->db->getOne($sql);
4185                $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
4186                if ($this->f->isDatabaseError($typeEvenement, true) === true) {
4187                    $this->correct = false;
4188                    $this->addToMessage(__("Erreur de traitement de fichier."));
4189                    $this->addToLog(__METHOD__."() erreur BDD: ".var_export($typeEvenement->getMessage(), true), DEBUG_MODE);
4190                    return false;
4191                }
4192    
4193                // Si l'événement est de type arrete, on ajoute les métadonnées spécifiques
4194                if ($typeEvenement == 'arrete'){
4195                    $metadata = array_merge($metadata, $this->getMetadata("arrete"));
4196                }
4197    
4198                // Filtre pour conserver uniquement les métadonnées liées aux dates
4199                $metadataToKeep = array(
4200                    "statutAutorisation",
4201                    "dateEvenementDocument",
4202                    'date_cloture_metier',
4203                    "NotificationArrete",
4204                    "dateNotificationArrete",
4205                    "controleLegalite",
4206                    "dateSignature",
4207                    "nomSignataire",
4208                    "qualiteSignataire",
4209                    "dateControleLegalite",
4210                );
4211                $metadata = array_filter(
4212                    $metadata,
4213                    function($key) use ($metadataToKeep) { return in_array($key, $metadataToKeep); },
4214                    ARRAY_FILTER_USE_KEY
4215                );
4216    
4217                // Mise à jour des métadonnées du document en GED
4218                $docUid = $this->getVal("om_fichier_instruction");
4219                $operationOrUID = $this->f->storage->update_metadata($docUid, $metadata);
4220                if ($operationOrUID == 'OP_FAILURE') {
4221                    $this->correct = false;
4222                    $this->addToMessage(__("Erreur de traitement de fichier."));
4223                    $this->addToLog(__METHOD__."() failed to update metadata: ".var_export($operationOrUID, true), DEBUG_MODE);
4224                    return false;
4225                }
4226    
4227                // mise à jour de l'UID du document en BDD
4228                else {
4229                    $valF = array('om_fichier_instruction' => $operationOrUID);
4230                    $res = $this->f->db->autoExecute(DB_PREFIXE.$this->table, $valF, DB_AUTOQUERY_UPDATE, $this->getCle($id));
4231                    $this->addToLog(__METHOD__.'() : db->autoExecute("'.DB_PREFIXE.$this->table.'", '.print_r($valF, true).', DB_AUTOQUERY_UPDATE, "'.$this->getCle($id).'")', VERBOSE_MODE);
4232                    if ($this->f->isDatabaseError($res, true) === true) {
4233                        $this->correct = false;
4234                        $this->addToMessage(__("Erreur de traitement de fichier."));
4235                        $this->addToLog(__METHOD__."() erreur BDD: ".var_export($res->getMessage(), true), DEBUG_MODE);
4236                        return false;
4237                    }
4238                    $this->addToMessage(__("La mise a jour du document s'est effectuee avec succes."));
4239                }
4240            }
4241    
4242            // Notification auto des demandeurs
4243            if ($dateRetourSignatureModified === true
4244                && $this->valF['date_retour_signature'] !== ''
4245                && $this->valF['date_retour_signature'] !== null) {
4246                //
4247                $ev = $this->get_inst_evenement($this->valF['evenement']);
4248                if ($ev->getVal('notification') === 'notification_auto_signature_requise') {
4249                    // Récupération de la liste des demandeurs à notifier et de la catégorie
4250                    $categorie = $this->f->get_param_option_notification($collectivite_di);
4251                    $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
4252                    $demandeursANotifie = $this->get_demandeurs_notifiable(
4253                        $this->valF['dossier'],
4254                        $isPortal
4255                    );
4256    
4257                    // Création d'une notification et d'une tâche pour chaque demandeur à notifier
4258                    $demandeurPrincipalNotifie = false;
4259                    foreach ($demandeursANotifie as $demandeur) {
4260                        // Identifie si le demandeur principal a été notifié ou pas
4261                        // et récupère ses informations
4262                        if ($demandeur['petitionnaire_principal'] == 't') {
4263                            $demandeurPrincipalNotifie = true;
4264                            // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
4265                            // son paramétrage, on effectue pas le traitement et on passe à l'itération
4266                            // suivante. On le considère également comme non notifié pour gérer l'envoie
4267                            // des messages d'erreurs
4268                            // Si la demande a été déposée via le portail alors le paramétrage n'a pas
4269                            // d'impact sur la notification
4270                            $erreursParam = $this->get_info_notification_fail();
4271                            if (! $this->dossier_depose_sur_portail() && $erreursParam != array()) {
4272                                $demandeurPrincipalNotifie = false;
4273                                continue;
4274                            }
4275                        }
4276                        // Ajout de la notif et récupération de son id
4277                        $idNotif = $this->ajouter_notification(
4278                            $this->valF[$this->clePrimaire],
4279                            $this->f->get_connected_user_login_name(),
4280                            $demandeur,
4281                            $collectivite_di,
4282                            array(),
4283                            true
4284                        );
4285                        if ($idNotif === false) {
4286                            return false;
4287                        }
4288                        // Création de la tache en lui donnant l'id de la notification
4289                        $notification_by_task = $this->notification_by_task(
4290                            $idNotif,
4291                            $this->valF['dossier'],
4292                            $categorie
4293                        );
4294                        if ($notification_by_task === false) {
4295                            $this->addToMessage(
4296                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
4297                            );
4298                            return false;
4299                        }
4300                    }
4301                    // Si le demandeur principal n'est pas notifiable, on créé une nouvelle notification
4302                    // en erreur avec en commentaire la raison pour laquelle le demandeur principal
4303                    // n'a pas pu être notifié
4304                    if (! $demandeurPrincipalNotifie) {
4305                        // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
4306                        $erreursParam = $this->get_info_notification_fail();
4307                        $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($this->getVal('dossier'));
4308                        // Ajout de la notif et récupération de son id
4309                        $idNotif = $this->ajouter_notification(
4310                            $this->valF[$this->clePrimaire],
4311                            $this->f->get_connected_user_login_name(),
4312                            $demandeurPrincipal,
4313                            $collectivite_di,
4314                            array(),
4315                            true,
4316                            'Echec',
4317                            implode(' ', $erreursParam)
4318                        );
4319                        if ($idNotif === false) {
4320                            $this->addToMessage(
4321                                __('Erreur : la création de la notification a échouée.').
4322                                __("Veuillez contacter votre administrateur.")
4323                            );
4324                            return false;
4325                        }
4326                        // Prépare un message d'alerte à destination de l'instructeur pour l'informer
4327                        // de l'échec de la notification
4328                        $dossier_message = $this->get_inst_dossier_message(0);
4329                        $dossier_message_val = array(
4330                            'dossier' => $this->getVal('dossier'),
4331                            'type' => _('erreur expedition'),
4332                            'emetteur' => $this->f->get_connected_user_login_name(),
4333                            'login' => $_SESSION['login'],
4334                            'date_emission' => date('Y-m-d H:i:s'),
4335                            'contenu' => _('Échec lors de la notification de l\'instruction ').
4336                                $ev->getVal('libelle').
4337                                '.<br>'.
4338                                implode("\n", $erreursParam).
4339                                '<br>'.
4340                                _('Veuillez corriger ces informations avant de renvoyer la notification.')
4341                        );
4342                        $add = $dossier_message->add_notification_message($dossier_message_val, true);
4343                        // Si une erreur se produit pendant l'ajout
4344                        if ($add !== true) {
4345                            $this->addToLog(__METHOD__."(): Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.", DEBUG_MODE);
4346                            return false;
4347                        }
4348                    }
4349                    $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.")));
4350                }
4351            }
4352    
4353          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
4354      }      }
4355    
4356      function triggersupprimer($id,&$db,$val,$DEBUG) {      /**
4357         * TRIGGER - triggersupprimer.
4358         *
4359         * @return boolean
4360         */
4361        function triggersupprimer($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
4362            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
4363          /**          /**
4364           * 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
4365           * archive dans le dossier d'instruction avant de supprimer l'événement           * archive dans le dossier d'instruction avant de supprimer l'événement
4366           * d'instruction           * d'instruction si les valeurs du dossier sont différentes
4367           */           */
4368                    $valF = array();
4369          // Mise à jour des 4 valeurs modifiées par l'action          $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
4370          $valF['delai'] = $val['archive_delai'];          foreach ($inst_di->champs as $key => $champ) {
4371          $valF['accord_tacite'] = $val['archive_accord_tacite'];              // Si le champ du DI à une archive dans l'instruction
4372          $valF['etat'] = $val['archive_etat'];              if (isset($val[sprintf('archive_%s', $champ)]) === true) {
4373          if ($val['archive_avis'] != '') {                  // Si la valeur entre le champ du DI et son archive dans instruction
4374              $valF['avis_decision'] = $val['archive_avis'];                  // est différente
4375          } else {                  if ($inst_di->getVal($champ) !== $val[sprintf('archive_%s', $champ)]) {
4376              $valF['avis_decision'] = NULL;                      $val[sprintf('archive_%s', $champ)] === '' ? $valF[$champ] = null : $valF[$champ] = $val[sprintf('archive_%s', $champ)];
4377          }                  }
4378          // 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;  
4379          }          }
4380          if ($val['archive_delai_incompletude'] != '') {          // Spécificité du champ avis_decision dont le champ archive est nommé
4381              $valF['delai_incompletude'] = $val['archive_delai_incompletude'];          // différemment
4382          } else {          if ($inst_di->getVal('avis_decision') !== $val['archive_avis']) {
4383              $valF['delai_incompletude'] = NULL;              $val['archive_avis'] === '' ? $valF['avis_decision'] = null : $valF['avis_decision'] = $val['archive_avis'];
4384            }
4385            // Spécificité de la date d'affichage dont la valeur n'ai jamais modifiée
4386            // par l'archive
4387            unset($valF['date_affichage']);
4388    
4389            /**
4390             * Mise à jour de la version de clôture *version_clos* du dossier si et
4391             * seulement si l'instruction met à jour l'état du dossier.
4392             */
4393            if (isset($valF['etat']) === true
4394                && $valF['etat'] !== null
4395                && $valF['etat'] !== '') {
4396                // Récupère l'état actuel du dossier d'instruction
4397                $inst_current_etat = $this->f->get_inst__om_dbform(array(
4398                    "obj" => "etat",
4399                    "idx" => $inst_di->get_id_etat(),
4400                ));
4401                // Instanciation de l'état archivé appliqué sur le dossier
4402                $inst_etat = $this->f->get_inst__om_dbform(array(
4403                    "obj" => "etat",
4404                    "idx" => $valF['etat'],
4405                ));
4406                //
4407                $update_version_clos = null;
4408                // En cas de clôture du dossier par l'état archivé
4409                if ($inst_etat->getVal('statut') === 'cloture') {
4410                    $update_version_clos = $inst_di->update_version_clos('up');
4411                }
4412                // En cas de réouverture du dossier par l'état archivé
4413                if ($inst_current_etat->getVal('statut') === 'cloture'
4414                    && $inst_etat->getVal('statut') !== 'cloture') {
4415                    //
4416                    $update_version_clos = $inst_di->update_version_clos('down');
4417                    //
4418                    $this->set_att_di_reopened(true);
4419                }
4420                //
4421                if ($update_version_clos === false) {
4422                    $this->f->addToLog(sprintf(
4423                        "%s() : ERREUR - %s %s",
4424                        __METHOD__,
4425                        sprintf(
4426                            __("Impossible de mettre à jour la version de clôture du dossier d'instruction %s."),
4427                            $inst_di->getVal($inst_di->clePrimaire)
4428                        ),
4429                        sprintf(
4430                            __("L'instruction tente d'appliquer l'état %s."),
4431                            $inst_etat->getVal($inst_etat->clePrimaire)
4432                        )
4433                    ));
4434                    $this->addToMessage(sprintf(
4435                        "%s %s",
4436                        __("Erreur lors de la mise à jour de la version de clôture du dossier d'instruction."),
4437                        __("Veuillez contacter votre administrateur.")
4438                    ));
4439                    return false;
4440                }
4441          }          }
4442          if ($val['archive_autorite_competente'] != '') {          // On supprime toutes les notications liées à l'instruction
4443              $valF['autorite_competente'] = $val['archive_autorite_competente'];          $notifASupprimer = $this->get_instruction_notification(
4444          } else {              $this->getVal($this->clePrimaire),
4445              $valF['autorite_competente'] = NULL;              array(
4446                    'notification_recepisse',
4447                    'notification_instruction',
4448                    'notification_decision',
4449                    'notification_service_consulte',
4450                    'notification_tiers_consulte',
4451                ),
4452                true
4453            );
4454                
4455            foreach ($notifASupprimer as $idNotif) {
4456                $inst_notif = $this->f->get_inst__om_dbform(array(
4457                    "obj" => "instruction_notification",
4458                    "idx" => $idNotif,
4459                ));
4460                $val_notif = array();
4461                foreach ($inst_notif->champs as $champ) {
4462                    $val_notif[$champ] = $inst_notif->getVal($champ);
4463                }
4464                // La suppression des notifications entrainera la suppression des tâches qui y sont
4465                // liées
4466                $supprNotif = $inst_notif->supprimer($val_notif);
4467                if ($supprNotif == false) {
4468                    $this->addToMessage(sprintf(
4469                        "%s %s",
4470                        __("Erreur lors de la suppression des notifications de l'instruction."),
4471                        __("Veuillez contacter votre administrateur.")
4472                    ));
4473                    return false;
4474                }
4475          }          }
4476    
4477          // On met à jour le dossier          // On met à jour le dossier
4478          $cle = " dossier='".$val['dossier']."'";          $valF['instruction'] = $id;
4479          $res = $db->autoExecute(DB_PREFIXE.'dossier', $valF, DB_AUTOQUERY_UPDATE, $cle);          $valF['crud'] = 'delete';
4480          $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);
4481          if (database::isError($res)) {          if ($update_by_instruction === false) {
4482              die($res->getMessage());              $this->cleanMessage();
4483                $this->addToMessage(sprintf('%s %s', __("Une erreur s'est produite lors de la mise à jour du dossier d'instruction."), __("Veuillez contacter votre administrateur.")));
4484                return false;
4485          }          }
4486    
4487          // Affichage d'informations à l'utilisateur          // Affichage d'informations à l'utilisateur
4488          $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')."]");
4489    
4490          // 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
4491      }      }
4492    
4493      function triggersupprimerapres($id,&$db,$val,$DEBUG) {      /**
4494         * TRIGGER - triggersupprimerapres.
4495         *
4496         * @return boolean
4497         */
4498        function triggersupprimerapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
4499            $this->addToLog(__METHOD__."(): start", EXTRA_VERBOSE_MODE);
4500            /**
4501             * Mise à jour de la date de dernière modification du dossier
4502             * d'instruction
4503             */
4504            $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
4505            $inst_di->update_last_modification_date();
4506    
4507          // Mise à jour des données du dossier d'autorisation          /**
4508          require_once "../obj/dossier_autorisation.class.php";           * Mise à jour des données du dossier d'autorisation
4509          $da = new dossier_autorisation($this->getNumDemandeAutorFromDossier($val["dossier"]), $this->db, DEBUG);           */
4510          if($da->majDossierAutorisation() === false) {          $da = $this->f->get_inst__om_dbform(array(
4511                "obj" => "dossier_autorisation",
4512                "idx" => $this->getNumDemandeAutorFromDossier($val["dossier"]),
4513            ));
4514            $params = array(
4515                'di_id' => $this->getVal('dossier'),
4516                'di_reopened' => $this->get_att_di_reopened(),
4517            );
4518            if($da->majDossierAutorisation($params) === false) {
4519              $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."));
4520              $this->correct = false;              $this->correct = false;
4521              return false;              return false;
4522          }          }
4523    
4524            /**
4525             * Gestion des tâches pour la dématérialisation
4526             */
4527            $inst_task_empty = $this->f->get_inst__om_dbform(array(
4528                "obj" => "task",
4529                "idx" => 0,
4530            ));
4531            foreach ($inst_di->task_types as $task_type) {
4532                $task_exists = $inst_task_empty->task_exists($task_type, $id);
4533                if ($task_exists !== false) {
4534                    $inst_task = $this->f->get_inst__om_dbform(array(
4535                        "obj" => "task",
4536                        "idx" => $task_exists,
4537                    ));
4538                    if ($inst_task->getVal('state') === $inst_task::STATUS_NEW || $inst_task->getVal('state') === $inst_task::STATUS_DRAFT) {
4539                        $task_val = array(
4540                            'state' => $inst_task::STATUS_CANCELED,
4541                        );
4542                        $update_task = $inst_task->update_task(array('val' => $task_val));
4543                        if ($update_task === false) {
4544                            $this->addToMessage(sprintf('%s %s',
4545                                sprintf(__("Une erreur s'est produite lors de la modification de la tâche %."), $inst_task->getVal($inst_task->clePrimaire)),
4546                                __("Veuillez contacter votre administrateur.")
4547                            ));
4548                            $this->correct = false;
4549                            return false;
4550                        }
4551                    }
4552                }
4553            }
4554    
4555            //
4556          $val['evenement'] = $this->getVal('evenement');          $val['evenement'] = $this->getVal('evenement');
4557          return $this->add_log_to_dossier($id, $val);          return $this->add_log_to_dossier($id, $val);
4558      }      }
4559    
4560      /**      /**
4561         * Permet de mettre la valeur passée en paramètre dans l'attribut de classe
4562         * "di_reopened".
4563         *
4564         * @param boolean $val
4565         */
4566        function set_att_di_reopened($val) {
4567            $this->di_reopened = $val;
4568        }
4569    
4570        /**
4571         * Permet de récupérer la valeur de l'attribut de classe "di_reopened".
4572         *
4573         * @return boolean
4574         */
4575        function get_att_di_reopened() {
4576            return $this->di_reopened;
4577        }
4578    
4579        /**
4580       * Permet de composer un message d'erreur sur restriction non valide en       * Permet de composer un message d'erreur sur restriction non valide en
4581       * fonction du contexte.       * fonction du contexte.
4582       *       *
# Line 1977  class instruction extends instruction_ge Line 4615  class instruction extends instruction_ge
4615      }      }
4616    
4617      /**      /**
4618       * Vérifie la restriction sur l'événement.       * Surcharge de la méthode verifier() de la classe om_dbform pour y ajouter
4619       *       * les vérifications suivantes :
4620       * @param array    $val   valeurs du formulaire       *   - Si l'instruction à un événement associé et que cet événement à des restrictions :
4621       * @param database $db    handler database       *       1. vérifie si la restriction est valide, si ce n'est pas le cas récupère et affiche
4622       * @param boolean  $DEBUG NA       *          le message d'erreur associé à la restriction
4623         *       2. vérifie si les restrictions sont respectées. Si ce n'est pas le cas bloque l'ajout
4624         *          et / ou la modification et affiche un message d'erreur
4625         *   -
4626         *   -
4627         *   -
4628         *   -
4629         *   -
4630         *   -
4631         *
4632         * @param array val : tableau contenant les valeurs issues du formulaire.
4633         * @param - dnu1 : Paramètre déprécié et non utilisé.
4634         * @param - dnu2 : Paramètre déprécié et non utilisé.
4635       *       *
4636       * @return [type] [description]       * @return void
4637       */       */
4638      function verifier($val = array(), &$db, $DEBUG) {      function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {
4639          parent::verifier($val, $db, $DEBUG);          parent::verifier($val);
4640            //
4641          if ( isset($val['evenement']) && is_numeric($val['evenement'])){          if ( isset($val['evenement']) && is_numeric($val['evenement'])){
4642              $restriction = $this->get_restriction($val['evenement']);              $restriction = $this->get_restriction($val['evenement']);
4643            
# Line 2064  class instruction extends instruction_ge Line 4714  class instruction extends instruction_ge
4714          }          }
4715    
4716      }      }
4717    
4718        /**
4719         * Récupère et stocket dans un tableau toutes les infos du pétitionnaire
4720         * principal du dossier auquel appartiens l'instruction.
4721         * Renvoie un tableau contenant les informations du pétitionnaire principal.
4722         *
4723         * Si l'identifiant de l'instruction n'a pas pu etre récupéré renvoie false
4724         * et affiche un message dans les logs.
4725         * En cas d'erreur de base de donnée renvoie false et affiche un message d'erreur.
4726         *
4727         * @param string identifiant du dossier
4728         * @return array|boolean
4729         */
4730        protected function get_info_petitionnaire_principal_dossier($dossier = null) {
4731            // Si l'identifiant de l'instruction n'a pas été fournit on récupère celui de
4732            // l'objet courant
4733            if (empty($dossier)) {
4734                $dossier = $this->getVal('dossier');
4735                // Si la récupération de l'identifiant de l'instruction a échoué la méthode renvoie
4736                // false et on affiche un message d'erreur dans les logs
4737                if (empty($dossier)) {
4738                    $this->addToLog(__METHOD__.' : L\'identifiant du dossier n\'a pas pu être récupéré');
4739                    return false;
4740                }
4741            }
4742    
4743            // Requête sql servant à récupérer toutes les informations relatives au demandeurs
4744            // principal
4745            $sql = sprintf(
4746                'SELECT
4747                    -- Récupère toutes les informations du demandeur principal
4748                    demandeur.*,
4749                    CASE
4750                        WHEN demandeur.qualite=\'particulier\'
4751                        THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
4752                    ELSE
4753                        TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
4754                    END AS destinataire
4755                FROM
4756                    %1$sdossier
4757                    LEFT JOIN %1$slien_dossier_demandeur
4758                        ON lien_dossier_demandeur.dossier = dossier.dossier
4759                    LEFT JOIN %1$sdemandeur
4760                        ON demandeur.demandeur = lien_dossier_demandeur.demandeur
4761                WHERE
4762                    dossier.dossier = \'%2$s\'
4763                    AND lien_dossier_demandeur.petitionnaire_principal IS TRUE',
4764                DB_PREFIXE,
4765                $dossier
4766            );
4767    
4768            $res = $this->f->get_one_row_result_from_db_query($sql);
4769            if ($res['code'] === 'KO') {
4770                return false;
4771            }
4772            return $res['result'];
4773        }
4774    
4775    
4776            
4777      /**      /**
4778       * Finalisation des documents.       * Finalisation des documents.
# Line 2096  class instruction extends instruction_ge Line 4805  class instruction extends instruction_ge
4805    
4806              //              //
4807              $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);              $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
4808                
4809                //
4810                $params = array(
4811                    "specific" => array(),
4812                );
4813                // Si la rédaction libre est activée sur l'instruction
4814                if ($this->getVal("flag_edition_integrale") == 't') {
4815                    $params["specific"]["corps"] = array(
4816                        "mode" => "set",
4817                        "value" => $this->getVal("corps_om_htmletatex"),
4818                    );
4819                    $params["specific"]["titre"] = array(
4820                        "mode" => "set",
4821                        "value" => $this->getVal("titre_om_htmletat"),
4822                    );
4823                }
4824              // Génération du PDF              // Génération du PDF
4825              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite);              $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
4826              $pdf_output = $result['pdf_output'];              $pdf_output = $result['pdf_output'];
4827                
4828              //Métadonnées du document              //Métadonnées du document
4829              $metadata = array(              $metadata = array(
4830                  'filename' => 'instruction_'.$id_inst.'.pdf',                  'filename' => 'instruction_'.$id_inst.'.pdf',
# Line 2115  class instruction extends instruction_ge Line 4839  class instruction extends instruction_ge
4839              $sql = "SELECT type              $sql = "SELECT type
4840                  FROM ".DB_PREFIXE."evenement                  FROM ".DB_PREFIXE."evenement
4841                  WHERE evenement = ".$this->getVal("evenement");                  WHERE evenement = ".$this->getVal("evenement");
4842              $typeEvenement = $this->db->getOne($sql);              $typeEvenement = $this->f->db->getOne($sql);
4843              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);              $this->addToLog(__METHOD__."(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
4844              if ($this->f->isDatabaseError($typeEvenement, true) === true) {              if ($this->f->isDatabaseError($typeEvenement, true) === true) {
4845                  $this->correct = false;                  $this->correct = false;
# Line 2132  class instruction extends instruction_ge Line 4856  class instruction extends instruction_ge
4856    
4857              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);              $metadata = array_merge($metadata, $spe_metadata, $arrete_metadata);
4858    
4859                /*
4860                // transforme le tableau de métadonnées en objet
4861                $mdf = new MetadataFactory();
4862                $md = $mdf->build('Instruction', $metadata);
4863                */
4864    
4865              // Si le document a déjà été finalisé on le met à jour              // Si le document a déjà été finalisé on le met à jour
4866              // en conservant son UID              // en conservant son UID
4867              if ($this->getVal("om_fichier_instruction") != ''){              if ($this->getVal("om_fichier_instruction") != ''){
# Line 2140  class instruction extends instruction_ge Line 4870  class instruction extends instruction_ge
4870              }              }
4871              // 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
4872              else {              else {
4873                  $uid = $this->f->storage->create($pdf_output, $metadata);                  $uid = $this->f->storage->create($pdf_output, $metadata, "from_content", $this->table.".om_fichier_instruction");
4874              }              }
4875          }          }
4876    
# Line 2157  class instruction extends instruction_ge Line 4887  class instruction extends instruction_ge
4887          if ($uid == '' || $uid == 'OP_FAILURE' ) {          if ($uid == '' || $uid == 'OP_FAILURE' ) {
4888              $this->correct = false;              $this->correct = false;
4889              $this->addToMessage($file_msg_error);              $this->addToMessage($file_msg_error);
4890              $this->addToLog(sprintf($log_msg_error, $id_inst, $uid));              $this->addToLog(sprintf($log_msg_error, $id_inst, $uid), DEBUG_MODE);
4891              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
4892          }          }
4893    
# Line 2168  class instruction extends instruction_ge Line 4898  class instruction extends instruction_ge
4898          }          }
4899    
4900          //          //
4901          $val['date_evenement']=$this->dateDBToForm($val['date_evenement']);          $val['date_evenement'] = $this->dateDBToForm($val['date_evenement']);
4902          $val['archive_date_complet']=$this->dateDBToForm($val['archive_date_complet']);          $val['archive_date_complet'] = $this->dateDBToForm($val['archive_date_complet']);
4903          $val['archive_date_rejet']=$this->dateDBToForm($val['archive_date_rejet']);          $val['archive_date_rejet'] = $this->dateDBToForm($val['archive_date_rejet']);
4904          $val['archive_date_limite']=$this->dateDBToForm($val['archive_date_limite']);          $val['archive_date_limite'] = $this->dateDBToForm($val['archive_date_limite']);
4905          $val['archive_date_notification_delai']=$this->dateDBToForm($val['archive_date_notification_delai']);          $val['archive_date_notification_delai'] = $this->dateDBToForm($val['archive_date_notification_delai']);
4906          $val['archive_date_decision']=$this->dateDBToForm($val['archive_date_decision']);          $val['archive_date_decision'] = $this->dateDBToForm($val['archive_date_decision']);
4907          $val['archive_date_validite']=$this->dateDBToForm($val['archive_date_validite']);          $val['archive_date_validite'] = $this->dateDBToForm($val['archive_date_validite']);
4908          $val['archive_date_achevement']=$this->dateDBToForm($val['archive_date_achevement']);          $val['archive_date_achevement'] = $this->dateDBToForm($val['archive_date_achevement']);
4909          $val['archive_date_chantier']=$this->dateDBToForm($val['archive_date_chantier']);          $val['archive_date_chantier'] = $this->dateDBToForm($val['archive_date_chantier']);
4910          $val['archive_date_conformite']=$this->dateDBToForm($val['archive_date_conformite']);          $val['archive_date_conformite'] = $this->dateDBToForm($val['archive_date_conformite']);
4911          $val['archive_date_dernier_depot']=$this->dateDBToForm($val['archive_date_dernier_depot']);          $val['archive_date_dernier_depot'] = $this->dateDBToForm($val['archive_date_dernier_depot']);
4912          $val['archive_date_limite_incompletude']=$this->dateDBToForm($val['archive_date_limite_incompletude']);          $val['archive_date_limite_incompletude'] = $this->dateDBToForm($val['archive_date_limite_incompletude']);
4913          $val['date_finalisation_courrier']=$this->dateDBToForm($val['date_finalisation_courrier']);          $val['date_finalisation_courrier'] = $this->dateDBToForm($val['date_finalisation_courrier']);
4914          $val['date_envoi_signature']=$this->dateDBToForm($val['date_envoi_signature']);          $val['date_envoi_signature'] = $this->dateDBToForm($val['date_envoi_signature']);
4915          $val['date_retour_signature']=$this->dateDBToForm($val['date_retour_signature']);          $val['date_retour_signature'] = $this->dateDBToForm($val['date_retour_signature']);
4916          $val['date_envoi_rar']=$this->dateDBToForm($val['date_envoi_rar']);          $val['date_envoi_rar'] = $this->dateDBToForm($val['date_envoi_rar']);
4917          $val['date_retour_rar']=$this->dateDBToForm($val['date_retour_rar']);          $val['date_retour_rar'] = $this->dateDBToForm($val['date_retour_rar']);
4918          $val['date_envoi_controle_legalite']=$this->dateDBToForm($val['date_envoi_controle_legalite']);          $val['date_envoi_controle_legalite'] = $this->dateDBToForm($val['date_envoi_controle_legalite']);
4919          $val['date_retour_controle_legalite']=$this->dateDBToForm($val['date_retour_controle_legalite']);          $val['date_retour_controle_legalite'] = $this->dateDBToForm($val['date_retour_controle_legalite']);
4920            $val['archive_date_cloture_instruction'] = $this->dateDBToForm($val['archive_date_cloture_instruction']);
4921            $val['archive_date_premiere_visite'] = $this->dateDBToForm($val['archive_date_premiere_visite']);
4922            $val['archive_date_derniere_visite'] = $this->dateDBToForm($val['archive_date_derniere_visite']);
4923            $val['archive_date_contradictoire'] = $this->dateDBToForm($val['archive_date_contradictoire']);
4924            $val['archive_date_retour_contradictoire'] = $this->dateDBToForm($val['archive_date_retour_contradictoire']);
4925            $val['archive_date_ait'] = $this->dateDBToForm($val['archive_date_ait']);
4926            $val['archive_date_transmission_parquet'] = $this->dateDBToForm($val['archive_date_transmission_parquet']);
4927            $val['archive_date_affichage'] = $this->dateDBToForm($val['archive_date_affichage']);
4928          $this->setvalF($val);          $this->setvalF($val);
4929    
4930          // Verification de la validite des donnees          // Verification de la validite des donnees
4931          $this->verifier($this->val, $this->db, DEBUG);          $this->verifier($this->val);
4932          // Si les verifications precedentes sont correctes, on procede a          // Si les verifications precedentes sont correctes, on procede a
4933          // la modification, sinon on ne fait rien et on retourne une erreur          // la modification, sinon on ne fait rien et on retourne une erreur
4934          if ($this->correct === true) {          if ($this->correct === true) {
# Line 2224  class instruction extends instruction_ge Line 4962  class instruction extends instruction_ge
4962    
4963              // Execution de la requête de modification des donnees de l'attribut              // Execution de la requête de modification des donnees de l'attribut
4964              // valF de l'objet dans l'attribut table de l'objet              // valF de l'objet dans l'attribut table de l'objet
4965              $res = $this->db->autoExecute(DB_PREFIXE.$this->table, $valF,              $res = $this->f->db->autoExecute(DB_PREFIXE.$this->table, $valF,
4966                  DB_AUTOQUERY_UPDATE, $this->getCle($id_inst));                  DB_AUTOQUERY_UPDATE, $this->getCle($id_inst));
4967               $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);
4968              //              //
# Line 2245  class instruction extends instruction_ge Line 4983  class instruction extends instruction_ge
4983          }          }
4984          // L'appel de verifier() a déjà positionné correct à false          // L'appel de verifier() a déjà positionné correct à false
4985          // et défini un message d'erreur.          // et défini un message d'erreur.
4986          $this->addToLog(sprintf($log_msg_error, $id_inst, $uid));          $this->addToLog(sprintf($log_msg_error, $id_inst, $uid), DEBUG_MODE);
4987          return $this->end_treatment(__METHOD__, false);          return $this->end_treatment(__METHOD__, false);
4988      }      }
4989    
# Line 2253  class instruction extends instruction_ge Line 4991  class instruction extends instruction_ge
4991       * 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
4992       * @return string numéro de dossier d'instruction       * @return string numéro de dossier d'instruction
4993       */       */
4994      protected function getDossier() {      protected function getDossier($champ = null) {
4995          if(empty($this->specificMetadata)) {          if(empty($this->specificMetadata)) {
4996              $this->getSpecificMetadata();              $this->getSpecificMetadata();
4997          }          }
# Line 2352  class instruction extends instruction_ge Line 5090  class instruction extends instruction_ge
5090          // Requête sql          // Requête sql
5091          $sql = "SELECT libelle FROM ".DB_PREFIXE."evenement          $sql = "SELECT libelle FROM ".DB_PREFIXE."evenement
5092                  WHERE evenement=".$evenement;                  WHERE evenement=".$evenement;
5093          $evenement_libelle = $this->db->getOne($sql);          $evenement_libelle = $this->f->db->getOne($sql);
5094          $this->addToLog("getTitle(): db->getOne(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("getTitle(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
5095          if (database::isError($evenement_libelle)) {          if (database::isError($evenement_libelle)) {
5096              die();              die();
# Line 2362  class instruction extends instruction_ge Line 5100  class instruction extends instruction_ge
5100          return $evenement_libelle;          return $evenement_libelle;
5101      }      }
5102    
5103    
5104        /**
5105         * Récupération du champ ERP du dossier d'instruction.
5106         *
5107         * @return boolean
5108         */
5109        public function get_concerne_erp() {
5110            //
5111            if(empty($this->specificMetadata)) {
5112                $this->getSpecificMetadata();
5113            }
5114            //
5115            return $this->specificMetadata->erp;
5116        }
5117    
5118    
5119      /**      /**
5120       * Cette méthode permet de stocker en attribut toutes les métadonnées       * Cette méthode permet de stocker en attribut toutes les métadonnées
5121       * nécessaire à l'ajout d'un document.       * nécessaire à l'ajout d'un document.
# Line 2379  class instruction extends instruction_ge Line 5133  class instruction extends instruction_ge
5133                          dossier_instruction_type.code as dossier_instruction_type,                          dossier_instruction_type.code as dossier_instruction_type,
5134                          etat_dossier_autorisation.libelle as statut,                          etat_dossier_autorisation.libelle as statut,
5135                          dossier_autorisation_type.code as dossier_autorisation_type,                          dossier_autorisation_type.code as dossier_autorisation_type,
5136                          groupe.code as groupe_instruction                          groupe.code as groupe_instruction,
5137                            CASE WHEN dossier.erp IS TRUE
5138                                THEN 'true'
5139                                ELSE 'false'
5140                            END as erp
5141                  FROM ".DB_PREFIXE."dossier                  FROM ".DB_PREFIXE."dossier
5142                      LEFT JOIN ".DB_PREFIXE."dossier_instruction_type                        LEFT JOIN ".DB_PREFIXE."dossier_instruction_type  
5143                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type                          ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
# Line 2394  class instruction extends instruction_ge Line 5152  class instruction extends instruction_ge
5152                      LEFT JOIN ".DB_PREFIXE."groupe                      LEFT JOIN ".DB_PREFIXE."groupe
5153                          ON dossier_autorisation_type.groupe = groupe.groupe                          ON dossier_autorisation_type.groupe = groupe.groupe
5154                  WHERE dossier.dossier = '".$dossier."'";                  WHERE dossier.dossier = '".$dossier."'";
5155          $res = $this->db->query($sql);          $res = $this->f->db->query($sql);
5156          $this->f->addToLog("getSpecificMetadata() : db->query(".$sql.")", VERBOSE_MODE);          $this->f->addToLog("getSpecificMetadata() : db->query(".$sql.")", VERBOSE_MODE);
5157          if ( database::isError($res)){          if ( database::isError($res)){
5158              die();              die();
# Line 2439  class instruction extends instruction_ge Line 5197  class instruction extends instruction_ge
5197                      ON                      ON
5198                          dossier.etat = etat.etat                          dossier.etat = etat.etat
5199                  WHERE dossier ='".$idx."'";                  WHERE dossier ='".$idx."'";
5200              $statut = $this->db->getOne($sql);              $statut = $this->f->db->getOne($sql);
5201              $this->f->addToLog("getStatutAutorisationDossier() : db->getOne(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog("getStatutAutorisationDossier() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
5202              if ( database::isError($statut)){              if ( database::isError($statut)){
5203                  die();                  die();
# Line 2460  class instruction extends instruction_ge Line 5218  class instruction extends instruction_ge
5218          // 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
5219          $sql = "SELECT * FROM ".DB_PREFIXE."dossier          $sql = "SELECT * FROM ".DB_PREFIXE."dossier
5220          WHERE dossier='".$this->valF['dossier']."'";          WHERE dossier='".$this->valF['dossier']."'";
5221          $res = $this->db->query($sql);          $res = $this->f->db->query($sql);
5222          $this->addToLog("get_dossier_actual(): db->query(\"".$sql."\");", VERBOSE_MODE);          $this->addToLog("get_dossier_actual(): db->query(\"".$sql."\");", VERBOSE_MODE);
5223          $this->f->isDatabaseError($res);          $this->f->isDatabaseError($res);
5224    
# Line 2469  class instruction extends instruction_ge Line 5227  class instruction extends instruction_ge
5227    
5228              // 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,
5229              // de l'état et de l'avis du dossier d'instruction              // de l'état et de l'avis du dossier d'instruction
5230              $return['archive_delai']=$row['delai'];              $return['archive_delai'] = $row['delai'];
5231              $return['archive_accord_tacite']=$row['accord_tacite'];              $return['archive_accord_tacite'] = $row['accord_tacite'];
5232              $return['archive_etat']=$row['etat'];              $return['archive_etat'] = $row['etat'];
5233              $return['archive_avis']=$row['avis_decision'];              $return['archive_avis'] = $row['avis_decision'];
5234              // Récupération de la valeur actuelle des 9 dates du dossier              // Récupération de la valeur actuelle des dates du dossier
5235              // d'instruction              // d'instruction
5236              $return['archive_date_complet']=$row['date_complet'];              $return['archive_date_complet'] = $row['date_complet'];
5237              $return['archive_date_dernier_depot']=$row['date_dernier_depot'];              $return['archive_date_dernier_depot'] = $row['date_dernier_depot'];
5238              $return['archive_date_rejet']= $row['date_rejet'];              $return['archive_date_rejet'] = $row['date_rejet'];
5239              $return['archive_date_limite']= $row['date_limite'];              $return['archive_date_limite'] = $row['date_limite'];
5240              $return['archive_date_notification_delai']= $row['date_notification_delai'];              $return['archive_date_notification_delai'] = $row['date_notification_delai'];
5241              $return['archive_date_decision']= $row['date_decision'];              $return['archive_date_decision'] = $row['date_decision'];
5242              $return['archive_date_validite']= $row['date_validite'];              $return['archive_date_validite'] = $row['date_validite'];
5243              $return['archive_date_achevement']= $row['date_achevement'];              $return['archive_date_achevement'] = $row['date_achevement'];
5244              $return['archive_date_chantier']= $row['date_chantier'];              $return['archive_date_chantier'] = $row['date_chantier'];
5245              $return['archive_date_conformite']= $row['date_conformite'];              $return['archive_date_conformite'] = $row['date_conformite'];
5246              $return['archive_incompletude']= $row['incompletude'];              $return['archive_incompletude'] = $row['incompletude'];
5247              $return['archive_incomplet_notifie']= $row['incomplet_notifie'];              $return['archive_incomplet_notifie'] = $row['incomplet_notifie'];
5248              $return['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];              $return['archive_evenement_suivant_tacite'] = $row['evenement_suivant_tacite'];
5249              $return['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];              $return['archive_evenement_suivant_tacite_incompletude'] = $row['evenement_suivant_tacite_incompletude'];
5250              $return['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];              $return['archive_etat_pendant_incompletude'] = $row['etat_pendant_incompletude'];
5251              $return['archive_date_limite_incompletude']= $row['date_limite_incompletude'];              $return['archive_date_limite_incompletude'] = $row['date_limite_incompletude'];
5252              $return['archive_delai_incompletude']= $row['delai_incompletude'];              $return['archive_delai_incompletude'] = $row['delai_incompletude'];
5253              $return['archive_autorite_competente']= $row['autorite_competente'];              $return['archive_autorite_competente'] = $row['autorite_competente'];
5254              $return['duree_validite']= $row['duree_validite'];              $return['archive_dossier_instruction_type'] = $row['dossier_instruction_type'];
5255              $return['date_depot']= $row['date_depot'];              $return['duree_validite'] = $row['duree_validite'];
5256                $return['date_depot'] = $row['date_depot'];
5257                $return['date_depot_mairie'] = $row['date_depot_mairie'];
5258                $return['archive_date_cloture_instruction'] = $row['date_cloture_instruction'];
5259                $return['archive_date_premiere_visite'] = $row['date_premiere_visite'];
5260                $return['archive_date_derniere_visite'] = $row['date_derniere_visite'];
5261                $return['archive_date_contradictoire'] = $row['date_contradictoire'];
5262                $return['archive_date_retour_contradictoire'] = $row['date_retour_contradictoire'];
5263                $return['archive_date_ait'] = $row['date_ait'];
5264                $return['archive_date_transmission_parquet'] = $row['date_transmission_parquet'];
5265                $return['archive_date_affichage'] = $row['date_affichage'];
5266                $return['archive_pec_metier'] = $row['pec_metier'];
5267                $return['archive_a_qualifier'] = $row['a_qualifier'];
5268          }          }
5269    
5270          // Retour de la fonction          // Retour de la fonction
# Line 2522  class instruction extends instruction_ge Line 5292  class instruction extends instruction_ge
5292                          ON instruction.evenement = evenement.evenement                          ON instruction.evenement = evenement.evenement
5293                      WHERE instruction.instruction = $idx";                      WHERE instruction.instruction = $idx";
5294              $this->f->addToLog("checkEvenementNonVerrouillable() : db->getOne(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog("checkEvenementNonVerrouillable() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
5295              $res = $this->db->getOne($sql);              $res = $this->f->db->getOne($sql);
5296              $this->f->isDatabaseError($res);              $this->f->isDatabaseError($res);
5297    
5298              // Si le retour de la requête est true              // Si le retour de la requête est true
# Line 2556  class instruction extends instruction_ge Line 5326  class instruction extends instruction_ge
5326          if ($row['date_dernier_depot'] != '') {          if ($row['date_dernier_depot'] != '') {
5327              $this->valF['archive_date_dernier_depot']=$row['date_dernier_depot'];              $this->valF['archive_date_dernier_depot']=$row['date_dernier_depot'];
5328          }          }
5329          if ($row['date_rejet']!='') {          if ($row['date_rejet'] != '') {
5330              $this->valF['archive_date_rejet']= $row['date_rejet'];              $this->valF['archive_date_rejet']= $row['date_rejet'];
5331          }          }
5332          if ($row['date_limite']!='') {          if ($row['date_limite'] != '') {
5333              $this->valF['archive_date_limite']= $row['date_limite'];              $this->valF['archive_date_limite']= $row['date_limite'];
5334          }          }
5335          if ($row['date_notification_delai']!='') {          if ($row['date_notification_delai'] != '') {
5336              $this->valF['archive_date_notification_delai']= $row['date_notification_delai'];              $this->valF['archive_date_notification_delai']= $row['date_notification_delai'];
5337          }          }
5338          if ($row['date_decision']!='') {          if ($row['date_decision'] != '') {
5339              $this->valF['archive_date_decision']= $row['date_decision'];              $this->valF['archive_date_decision']= $row['date_decision'];
5340          }          }
5341          if ($row['date_validite']!='') {          if ($row['date_validite'] != '') {
5342              $this->valF['archive_date_validite']= $row['date_validite'];              $this->valF['archive_date_validite']= $row['date_validite'];
5343          }          }
5344          if ($row['date_achevement']!='') {          if ($row['date_achevement'] != '') {
5345              $this->valF['archive_date_achevement']= $row['date_achevement'];              $this->valF['archive_date_achevement']= $row['date_achevement'];
5346          }          }
5347          if ($row['date_chantier']!='') {          if ($row['date_chantier'] != '') {
5348              $this->valF['archive_date_chantier']= $row['date_chantier'];              $this->valF['archive_date_chantier']= $row['date_chantier'];
5349          }          }
5350          if ($row['date_conformite']!='') {          if ($row['date_conformite'] != '') {
5351              $this->valF['archive_date_conformite']= $row['date_conformite'];                $this->valF['archive_date_conformite']= $row['date_conformite'];  
5352          }          }
5353          if ($row['incompletude']!='') {          if ($row['incompletude'] != '') {
5354              $this->valF['archive_incompletude']= $row['incompletude'];                $this->valF['archive_incompletude']= $row['incompletude'];  
5355          }          }
5356          if ($row['incomplet_notifie']!='') {          if ($row['incomplet_notifie'] != '') {
5357              $this->valF['archive_incomplet_notifie']= $row['incomplet_notifie'];                $this->valF['archive_incomplet_notifie']= $row['incomplet_notifie'];  
5358          }          }
5359          if ($row['evenement_suivant_tacite']!='') {          if ($row['evenement_suivant_tacite'] != '') {
5360              $this->valF['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];                $this->valF['archive_evenement_suivant_tacite']= $row['evenement_suivant_tacite'];  
5361          }          }
5362          if ($row['evenement_suivant_tacite_incompletude']!='') {          if ($row['evenement_suivant_tacite_incompletude'] != '') {
5363              $this->valF['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];                $this->valF['archive_evenement_suivant_tacite_incompletude']= $row['evenement_suivant_tacite_incompletude'];  
5364          }          }
5365          if ($row['etat_pendant_incompletude']!='') {          if ($row['etat_pendant_incompletude'] != '') {
5366              $this->valF['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];                $this->valF['archive_etat_pendant_incompletude']= $row['etat_pendant_incompletude'];  
5367          }          }
5368          if ($row['date_limite_incompletude']!='') {          if ($row['date_limite_incompletude'] != '') {
5369              $this->valF['archive_date_limite_incompletude']= $row['date_limite_incompletude'];                $this->valF['archive_date_limite_incompletude']= $row['date_limite_incompletude'];  
5370          }          }
5371          if ($row['delai_incompletude']!='') {          if ($row['delai_incompletude'] != '') {
5372              $this->valF['archive_delai_incompletude']= $row['delai_incompletude'];                $this->valF['archive_delai_incompletude']= $row['delai_incompletude'];  
5373          }          }
5374          if ($row['autorite_competente']!='') {          if ($row['autorite_competente'] != '') {
5375              $this->valF['archive_autorite_competente']= $row['autorite_competente'];                $this->valF['archive_autorite_competente']= $row['autorite_competente'];  
5376          }          }
5377          if ($row['duree_validite']!='') {          if ($row['duree_validite'] != '') {
5378              $this->valF['duree_validite']= $row['duree_validite'];                $this->valF['duree_validite']= $row['duree_validite'];  
5379          }          }
5380          if ($row['date_depot']!='') {          if ($row['date_depot'] != '') {
5381              $this->valF['date_depot']= $row['date_depot'];                $this->valF['date_depot']= $row['date_depot'];  
5382          }          }
5383            if ($row['date_depot_mairie'] != '') {
5384                $this->valF['date_depot_mairie']= $row['date_depot_mairie'];  
5385            }
5386            // Dates concernant les dossiers contentieux
5387            if ($row['date_cloture_instruction'] != '') {
5388                $this->valF['archive_date_cloture_instruction']= $row['date_cloture_instruction'];  
5389            }
5390            if ($row['date_premiere_visite'] != '') {
5391                $this->valF['archive_date_premiere_visite']= $row['date_premiere_visite'];  
5392            }
5393            if ($row['date_derniere_visite'] != '') {
5394                $this->valF['archive_date_derniere_visite']= $row['date_derniere_visite'];  
5395            }
5396            if ($row['date_contradictoire'] != '') {
5397                $this->valF['archive_date_contradictoire']= $row['date_contradictoire'];  
5398            }
5399            if ($row['date_retour_contradictoire'] != '') {
5400                $this->valF['archive_date_retour_contradictoire']= $row['date_retour_contradictoire'];  
5401            }
5402            if ($row['date_ait'] != '') {
5403                $this->valF['archive_date_ait']= $row['date_ait'];  
5404            }
5405            if ($row['date_transmission_parquet'] != '') {
5406                $this->valF['archive_date_transmission_parquet']= $row['date_transmission_parquet'];  
5407            }
5408            //
5409            if ($row['dossier_instruction_type'] != '') {
5410                $this->valF['archive_dossier_instruction_type']= $row['dossier_instruction_type'];  
5411            }
5412            if ($row['date_affichage'] != '') {
5413                $this->valF['archive_date_affichage']= $row['date_affichage'];  
5414            }
5415            if (isset($row['pec_metier']) === true && $row['pec_metier'] != '') {
5416                $this->valF['archive_pec_metier']= $row['pec_metier'];  
5417            }
5418            if (isset($row['a_qualifier']) === true && $row['a_qualifier'] != '') {
5419                $this->valF['archive_a_qualifier']= $row['a_qualifier'];  
5420            }
5421      }      }
5422    
5423      // {{{      // {{{
# Line 2741  class instruction extends instruction_ge Line 5549  class instruction extends instruction_ge
5549          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",          "datecontrolelegalite"=>"", "ap_numrue"=>"", "ap_nomdelavoie"=>"",
5550          "ap_codepostal"=>"", "ap_ville"=>"");          "ap_codepostal"=>"", "ap_ville"=>"");
5551    
5552          $sqlArrete = "SELECT    signataire_arrete.nom as \"nomsignataire\",          $sqlArrete = "SELECT
5553                    signataire_arrete.prenom || ' ' ||signataire_arrete.nom as \"nomsignataire\",
5554                  signataire_arrete.qualite as \"qualitesignataire\",                  signataire_arrete.qualite as \"qualitesignataire\",
5555                  instruction.etat as \"decisionarrete\",                  instruction.etat as \"decisionarrete\",
5556                  instruction.date_retour_rar as \"datenotification\",                  instruction.date_retour_rar as \"datenotification\",
# Line 2759  class instruction extends instruction_ge Line 5568  class instruction extends instruction_ge
5568              LEFT JOIN ".DB_PREFIXE."donnees_techniques ON              LEFT JOIN ".DB_PREFIXE."donnees_techniques ON
5569                      donnees_techniques.dossier_instruction = dossier.dossier                      donnees_techniques.dossier_instruction = dossier.dossier
5570              WHERE instruction.instruction = ".$this->getVal("instruction");              WHERE instruction.instruction = ".$this->getVal("instruction");
5571          $resArrete = $this->db->query($sqlArrete);          $resArrete = $this->f->db->query($sqlArrete);
5572          $this->f->addToLog("getArreteMetadata(): db->query(\"".$sqlArrete."\");", VERBOSE_MODE);          $this->f->addToLog("getArreteMetadata(): db->query(\"".$sqlArrete."\");", VERBOSE_MODE);
5573          if ( database::isError($resArrete)){          if ( database::isError($resArrete)){
5574              die();              die();
# Line 2779  class instruction extends instruction_ge Line 5588  class instruction extends instruction_ge
5588          // Récupère la valeur du champ lettretype          // Récupère la valeur du champ lettretype
5589          $lettretype = $this->getVal("lettretype");          $lettretype = $this->getVal("lettretype");
5590          // Si le champ est vide          // Si le champ est vide
5591          if (empty($lettretype)) {          if ($lettretype !== '' && $lettretype !== null) {
5592              //              //
5593              return false;              return true;
5594          }          }
5595    
5596          //          //
5597          return true;          return false;
5598        }
5599    
5600        /**
5601         * CONDITION - is_modifiable.
5602         *
5603         * Controle si l'évenement est modifiable.
5604         *
5605         * @return boolean
5606         */
5607        function is_evenement_modifiable() {
5608            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
5609            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_modifiable'));
5610      }      }
5611    
5612      /**      /**
# Line 2796  class instruction extends instruction_ge Line 5617  class instruction extends instruction_ge
5617       * @return boolean       * @return boolean
5618       */       */
5619      function is_editable() {      function is_editable() {
5620    
5621            // XXX
5622            // 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é)
5623            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
5624    
5625          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5626          $bypass = $this->f->isAccredited(get_class()."_modifier_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modifier_bypass");
5627          //          //
5628          if ($bypass == true) {          if ($bypass == true) {
   
5629              //              //
5630              return true;              return true;
5631          }          }
5632            
         // 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;  
         }  
5633          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
5634          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
5635          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
5636              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
5637              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
5638              //              //
5639              return false;              return false;
5640          }          }
5641    
5642            // Si l'utilisateur est un intructeur qui correspond à la division du
5643            // dossier
5644            if ($this->is_instructeur_from_division_dossier() === true) {
5645                //
5646                return true;
5647            }
5648    
5649            // Si l'utilisateur est instructeur de la commune du dossier et que
5650            // l'instruction est créée par un instructeur de la commune
5651            if ($this->is_instructeur_from_collectivite_dossier() === true and
5652                $this->getVal('created_by_commune') === 't') {
5653                return true;
5654            }
5655    
5656          //          //
5657          return true;          return false;
5658        }
5659    
5660        /**
5661         * Vérifie si l'événement est supprimable ou pas.
5662         *
5663         * @return boolean
5664         */
5665        function is_evenement_supprimable() {
5666            // Controle si l'évenement est supprimable
5667            $evenement = $this->get_inst_evenement($this->getVal('evenement'));
5668            return ! $this->get_boolean_from_pgsql_value($evenement->getVal('non_supprimable'));
5669      }      }
5670    
5671      /**      /**
5672       * CONDITION - is_deletable.       * CONDITION - is_deletable.
5673       *       *
5674       * Condition pour lma modification.       * Condition pour la suppression.
5675       *       *
5676       * @return boolean       * @return boolean
5677       */       */
5678      function is_deletable() {      function is_deletable() {
5679          // Contrôle si l'utilisateur possède un bypass  
5680          $bypass = $this->f->isAccredited(get_class()."_supprimer_bypass");          // XXX
5681            // 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é)
5682            // Si cette tâche identifiée est DONE alors la suppression/modification de cette intruction est impossible
5683    
5684            // Contrôle si l'utilisateur possède un bypass intégral
5685            $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass");
5686          //          //
5687          if ($bypass == true) {          if ($bypass == true) {
5688    
# Line 2854  class instruction extends instruction_ge Line 5691  class instruction extends instruction_ge
5691          }          }
5692    
5693          // Si l'utilisateur est un intructeur qui ne correspond pas à la          // Si l'utilisateur est un intructeur qui ne correspond pas à la
5694          // division du dossier          // division du dossier et si l'utilisateur n'a pas la permission bypass
5695          if ($this->f->isUserInstructeur()          // de la division
5696              && $this->f->om_utilisateur["division"] != $this->getDivisionFromDossier()) {          if ($this->is_instructeur_from_division_dossier() === false
5697                && $this->f->isAccredited($this->get_absolute_class_name()."_supprimer_bypass_division") === false) {
5698    
5699              //              //
5700              return false;              return false;
# Line 2865  class instruction extends instruction_ge Line 5703  class instruction extends instruction_ge
5703          // l'événement est-il le dernier ?          // l'événement est-il le dernier ?
5704          $dernier_evenement = false;          $dernier_evenement = false;
5705          // instanciation dossier          // instanciation dossier
5706          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
5707          $dossier = new dossier($this->getVal('dossier'), $this->db, DEBUG);              "obj" => "dossier",
5708                "idx" => $this->getVal('dossier'),
5709            ));
5710          // récupération dernier événement          // récupération dernier événement
5711          $id_dernier_evenement = $dossier->get_dernier_evenement();          $id_dernier_evenement = $dossier->get_dernier_evenement();
5712          if ($id_dernier_evenement == $this->getVal($this->clePrimaire)) {          if ($id_dernier_evenement == $this->getVal($this->clePrimaire)) {
# Line 2892  class instruction extends instruction_ge Line 5732  class instruction extends instruction_ge
5732          //          //
5733          return true;          return true;
5734      }      }
5735        
5736        
5737        /**
5738         * Vérifie que l'utilisateur est instructeur et qu'il est de la division du
5739         * dossier.
5740         *
5741         * @return,  boolean true/false
5742         */
5743        function is_instructeur_from_collectivite_dossier() {
5744            if ($this->f->isUserInstructeur() === true and
5745                $this->f->om_utilisateur["om_collectivite"] == $this->get_dossier_instruction_om_collectivite()) {
5746                return true;
5747            }
5748            return false;
5749        }
5750        
5751      /**      /**
5752       * CONDITION - is_addable.       * CONDITION - is_addable.
5753       *       *
# Line 2902  class instruction extends instruction_ge Line 5757  class instruction extends instruction_ge
5757       */       */
5758      function is_addable() {      function is_addable() {
5759          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5760          $bypass = $this->f->isAccredited(get_class()."_ajouter_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_ajouter_bypass");
5761          //          //
5762          if ($bypass == true) {          if ($bypass == true) {
5763    
5764              //              //
5765              return true;              return true;
5766          }          }
5767            // Si l'utilisateur est un intructeur qui correspond à la
5768          // Si l'utilisateur est un intructeur qui ne correspond pas à la          // division du dossier ou qu'il peut changer la décision
5769          // division du dossier          if ($this->is_instructeur_from_division_dossier() === true or
5770          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) {  
   
5771              //              //
5772              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;  
5773          }          }
5774    
   
5775          //          //
5776          return true;          return false;
5777      }      }
5778    
5779      /**      /**
# Line 2940  class instruction extends instruction_ge Line 5785  class instruction extends instruction_ge
5785       */       */
5786      function is_finalizable() {      function is_finalizable() {
5787          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5788          $bypass = $this->f->isAccredited(get_class()."_finaliser_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_finaliser_bypass");
5789          //          //
5790          if ($bypass == true) {          if ($bypass == true) {
   
5791              //              //
5792              return true;              return true;
5793          }          }
5794            
         // 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;  
         }  
   
5795          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
5796          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
5797          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
5798              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
5799              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
5800              //              //
5801              return false;              return false;
5802          }          }
5803            
5804            // Si l'utilisateur est un intructeur qui correspond à la division du
5805            // dossier
5806            if ($this->is_instructeur_from_division_dossier() === true) {
5807                //
5808                return true;
5809            }
5810    
5811            // Si l'utilisateur est instructeur de la commune du dossier et que
5812            // l'instruction est créée par un instructeur de la commune
5813            if ($this->is_instructeur_from_collectivite_dossier() === true and
5814                $this->getVal('created_by_commune') === 't') {
5815                return true;
5816            }
5817    
5818          //          //
5819          return true;          return false;
5820      }      }
5821    
5822      /**      /**
# Line 3011  class instruction extends instruction_ge Line 5850  class instruction extends instruction_ge
5850       */       */
5851      function is_unfinalizable(){      function is_unfinalizable(){
5852          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
5853          $bypass = $this->f->isAccredited(get_class()."_definaliser_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_definaliser_bypass");
5854          //          //
5855          if ($bypass == true) {          if ($bypass == true) {
   
5856              //              //
5857              return true;              return true;
5858          }          }
5859            
         // 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;  
         }  
   
5860          // Si l'utilisateur est un instructeur, que le dossier est cloturé et          // Si l'utilisateur est un instructeur, que le dossier est cloturé et
5861          // que l'événement n'est pas identifié comme non verrouillable          // que l'événement n'est pas identifié comme non verrouillable
5862          if ($this->f->isUserInstructeur()          if ($this->f->isUserInstructeur()
5863              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"              && $this->getStatutAutorisationDossier($this->getParameter("idxformulaire")) == "cloture"
5864              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {              && $this->checkEvenementNonVerrouillable($this->getVal("instruction")) === false) {
   
5865              //              //
5866              return false;              return false;
5867          }          }
5868    
5869            // Si l'utilisateur est un intructeur qui correspond à la division du
5870            // dossier
5871            if ($this->is_instructeur_from_division_dossier() === true) {
5872                //
5873                return true;
5874            }
5875    
5876            // Si l'utilisateur est instructeur de la commune du dossier et que
5877            // l'instruction est créée par un instructeur de la commune
5878            if ($this->is_instructeur_from_collectivite_dossier() === true and
5879                $this->getVal('created_by_commune') === 't') {
5880                return true;
5881            }
5882    
5883          //          //
5884          return true;          return false;
5885      }      }
5886    
5887      /**      /**
# Line 3074  class instruction extends instruction_ge Line 5907  class instruction extends instruction_ge
5907    
5908    
5909      /**      /**
5910         * Permet de définir si un instructeur commune peut editer une instruction
5911         *
5912         * @return boolean true si il peut
5913         */
5914        function isInstrCanChangeDecision($idx) {
5915            
5916            if ($this->f->isAccredited(array("instruction", "instruction_changer_decision"), "OR") !== true or
5917                $this->f->isUserInstructeur() !== true) {
5918                return false;
5919            }
5920            
5921            
5922    
5923            // Sinon on vérifie l'éligibilité du dossier au changement de décision
5924            // /!\ Requête lié à celles du widget indiquant les dossiers éligible au changement
5925            // de décision :
5926            //   * dossier_instruction.class.php : view_widget_dossiers_evenement_retour_finalise()
5927            //   * dossier_instruction.inc.php : si le paramètre filtre_decision = true
5928            $sql = sprintf(
5929                'SELECT
5930                    dossier.dossier
5931                FROM
5932                    %1$sdossier
5933                    JOIN %1$setat
5934                        ON dossier.etat = etat.etat AND etat.statut = \'encours\'
5935                    JOIN %1$slien_dossier_demandeur
5936                        ON dossier.dossier = lien_dossier_demandeur.dossier AND lien_dossier_demandeur.petitionnaire_principal IS TRUE
5937                    JOIN %1$sdossier_instruction_type
5938                        ON dossier.dossier_instruction_type=dossier_instruction_type.dossier_instruction_type
5939                    JOIN %1$sinstruction
5940                        -- Recherche de la dernière instruction qui ne soit pas liée à un événement retour
5941                        ON instruction.instruction = (
5942                                SELECT instruction
5943                                FROM %1$sinstruction
5944                                JOIN %1$sevenement ON instruction.evenement=evenement.evenement
5945                                AND evenement.retour IS FALSE
5946                                WHERE instruction.dossier = dossier.dossier
5947                                ORDER BY date_evenement DESC, instruction DESC
5948                                LIMIT 1
5949                            )
5950                            -- On ne garde que les dossiers pour lesquels la dernière instruction est finalisée
5951                            -- ou alors pour laquelle l instruction a été ajouté par la commune et est
5952                            -- non signée, non notifié, etc.
5953                            AND (instruction.om_final_instruction IS TRUE
5954                                OR instruction.created_by_commune IS TRUE)
5955                            AND instruction.date_retour_signature IS NULL
5956                            AND instruction.date_envoi_rar IS NULL
5957                            AND instruction.date_retour_rar IS NULL
5958                            AND instruction.date_envoi_controle_legalite IS NULL
5959                            AND instruction.date_retour_controle_legalite IS NULL
5960                    -- On vérifie que l instruction soit un arrêté ou un changement de décision
5961                    JOIN %1$sevenement
5962                        ON instruction.evenement=evenement.evenement
5963                            AND (evenement.type = \'arrete\'
5964                                OR evenement.type = \'changement_decision\')
5965                    -- Recherche les informations du pétitionnaire principal pour l affichage
5966                    JOIN %1$sdemandeur
5967                        ON lien_dossier_demandeur.demandeur = demandeur.demandeur
5968                    -- Recherche la collectivité rattachée à l instructeur
5969                    JOIN %1$sinstructeur
5970                        ON dossier.instructeur=instructeur.instructeur
5971                    JOIN %1$sdivision
5972                        ON instructeur.division=division.division
5973                    JOIN %1$sdirection
5974                        ON division.direction=direction.direction
5975                    JOIN %1$som_collectivite
5976                        ON direction.om_collectivite=om_collectivite.om_collectivite
5977                WHERE
5978                    -- Vérification que la décision a été prise par l agglo
5979                    om_collectivite.niveau = \'2\'
5980                    AND dossier.dossier = \'%2$s\'
5981                ',
5982                DB_PREFIXE,
5983                $idx
5984            );
5985    
5986    
5987            // Si collectivité de l'utilisateur niveau mono alors filtre sur celle-ci
5988            if ($this->f->isCollectiviteMono($_SESSION['collectivite']) === true) {
5989                $sql .= sprintf(
5990                    ' AND dossier.om_collectivite=%1$s',
5991                    $_SESSION['collectivite']
5992                );
5993            }
5994            $res = $this->f->db->getone($sql);
5995            if (database::isError($res)) {
5996                die();
5997            }
5998            // Si le dossier n'est pas sujet au changement de decision
5999            if($res == null) {
6000                return false;
6001            }
6002            return true;
6003        }
6004    
6005    
6006        /**
6007       * CONDITION - can_monitoring_dates.       * CONDITION - can_monitoring_dates.
6008       *       *
6009       * Condition pour afficher le bouton de suivi des dates.       * Condition pour afficher le bouton de suivi des dates.
# Line 3091  class instruction extends instruction_ge Line 6021  class instruction extends instruction_ge
6021          }          }
6022    
6023          // Contrôle si l'utilisateur possède un bypass          // Contrôle si l'utilisateur possède un bypass
6024          $bypass = $this->f->isAccredited(get_class()."_modification_dates_bypass");          $bypass = $this->f->isAccredited($this->get_absolute_class_name()."_modification_dates_bypass");
6025          if ($bypass === true) {          if ($bypass === true) {
6026              return true;              return true;
6027          }          }
6028    
6029          // 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
6030            // un utilisateur lié à un instructeur
6031            $perm_moni_dates_d_closed = $this->f->isAccredited($this->get_absolute_class_name()."_modification_dates_cloture");
6032    
6033            // On vérifie en premier lieu que le DI n'est pas clôturé et que
6034            // l'utilisateur ne possède pas la permission de modifier le suivi des
6035            // dates sur un dossier clôturé
6036          $inst_dossier = $this->get_inst_dossier();          $inst_dossier = $this->get_inst_dossier();
6037          if ($inst_dossier->getStatut() === 'cloture') {          if ($inst_dossier->getStatut() === 'cloture'
6038                && $perm_moni_dates_d_closed === false) {
6039              //              //
6040              return false;              return false;
6041          }          }
# Line 3108  class instruction extends instruction_ge Line 6045  class instruction extends instruction_ge
6045          // et celles de son éventuel instructeur          // et celles de son éventuel instructeur
6046          $instr_di = $inst_dossier->getVal('instructeur');          $instr_di = $inst_dossier->getVal('instructeur');
6047    
6048            // Il faut disposer d'une entrée instructeur
6049            if ($this->f->isUserInstructeur() === false) {
6050                return false;
6051            }
6052    
6053          // 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
6054          $instr_di_coll_multi = false;          $instr_di_coll_multi = false;
6055          // Si un instructeur est affecté au dossier          // Si un instructeur est affecté au dossier
6056          if ($instr_di !== '' && $instr_di !== null) {          if ($instr_di !== '' && $instr_di !== null) {
             //  
             $inst_instructeur = $this->get_inst_instructeur($instr_di);  
             // Récupération de l'utilisateur lié à l'instructeur  
             $inst_om_utilisateur = $this->get_inst_om_utilisateur($inst_instructeur->getVal('om_utilisateur'));  
             $instr_di_coll = $inst_om_utilisateur->getVal('om_collectivite');  
6057              // Vérifie si l'instructeur est de la collectivité de niveau 2              // Vérifie si l'instructeur est de la collectivité de niveau 2
6058                $instr_di_coll = $this->get_instructeur_om_collectivite($instr_di);
6059              if ($this->f->isCollectiviteMono($instr_di_coll) === false) {              if ($this->f->isCollectiviteMono($instr_di_coll) === false) {
6060                  //                  //
6061                  $instr_di_coll_multi = true;                  $instr_di_coll_multi = true;
6062              }              }
6063          }          }
6064    
6065          // S'il s'agit d'un instructeur          // Il faut qu'il instruise le dossier ou soit de la même division
6066          if ($this->f->isUserInstructeur() === true) {          if ($this->f->om_utilisateur['instructeur'] === $instr_di
6067              // 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) {  
6068              //              //
6069              return true;              return true;
6070          }          }
6071    
6072          // 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
6073          if ($this->f->om_utilisateur['om_collectivite'] === $coll_di) {          // le dossier ET si l'instruction est déléguée à la communauté
6074            if ($this->f->isCollectiviteMono($this->f->om_utilisateur['om_collectivite']) === true
6075                && $this->f->om_utilisateur['om_collectivite'] === $coll_di
6076                && $instr_di_coll_multi === true) {
6077              //              //
6078              return true;              return true;
6079          }          }
6080    
6081          //          // Si l'instructeur ne rentre pas dans les deux cas précédents
6082          return false;          return false;
6083      }      }
6084    
# Line 3181  class instruction extends instruction_ge Line 6097  class instruction extends instruction_ge
6097          // 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
6098          // dites de TREATMENT.          // dites de TREATMENT.
6099          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
6100            $message = '';
6101            $ev = $this->get_inst_evenement($this->getVal('evenement'));
6102    
6103            // Controle du signataire
6104            if (! $this->controle_signataire($ev)) {
6105                $this->addToMessage(__("Le document ne peut pas être finalisé car aucun signataire n'a été sélectionné."));
6106                // Termine le traitement
6107                return $this->end_treatment(__METHOD__, false);
6108            }
6109    
6110          // Traitement de la finalisation          // Traitement de la finalisation
6111          $ret = $this->manage_finalizing("finalize", $val);          $ret = $this->manage_finalizing("finalize", $val);
# Line 3192  class instruction extends instruction_ge Line 6117  class instruction extends instruction_ge
6117              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
6118          }          }
6119    
6120            // Envoi des notifications aux demandeurs si la notification est automatique
6121            // et que la signature n'est pas requise
6122            if ($ev->getVal('notification') === 'notification_automatique') {
6123                // Récupération de la catégorie et envoie des notifications au(x) demandeur(s)
6124                $collectivite_di = $this->get_dossier_instruction_om_collectivite($this->getVal('dossier'));
6125                // Récupération de la liste des demandeurs à notifier et de la catégorie
6126                $categorie = $this->f->get_param_option_notification($collectivite_di);
6127                $isPortal = $categorie == null || $categorie == '' || $categorie == 'portal' ? true : false;
6128                $demandeursANotifie = $this->get_demandeurs_notifiable(
6129                    $this->getVal('dossier'),
6130                    $isPortal
6131                );
6132    
6133                // Création d'une notification et d'une tâche pour chaque demandeur à notifier
6134                $demandeurPrincipalNotifie = false;
6135                if (count($demandeursANotifie) > 0) {
6136                    foreach ($demandeursANotifie as $demandeur) {
6137                        // Identifie si le demandeur principal a été notifié ou pas
6138                        // et récupère ses informations
6139                        if ($demandeur['petitionnaire_principal'] == 't') {
6140                            $demandeurPrincipalNotifie = true;
6141                            // Si le demandeur principal est notifiable mais qu'il y a des erreurs dans
6142                            // son paramétrage, on effectue pas le traitement et on passe à l'itération
6143                            // suivante. On le considère également comme non notifié pour gérer l'envoie
6144                            // des messages d'erreurs
6145                            // Si la demande a été déposée via le portail alors le paramétrage n'a pas
6146                            // d'impact sur la notification
6147                            $erreursParam = $this->get_info_notification_fail();
6148                            if (! $this->dossier_depose_sur_portail() && $erreursParam != array()) {
6149                                $demandeurPrincipalNotifie = false;
6150                                continue;
6151                            }
6152                        }
6153                        // Ajout de la notif et récupération de son id
6154                        $idNotif = $this->ajouter_notification(
6155                            $this->getVal($this->clePrimaire),
6156                            $this->f->get_connected_user_login_name(),
6157                            $demandeur,
6158                            $collectivite_di,
6159                            array(),
6160                            true
6161                        );
6162                        if ($idNotif === false) {
6163                            // Termine le traitement
6164                            return $this->end_treatment(__METHOD__, false);
6165                        }
6166                        $notification_by_task = $this->notification_by_task(
6167                            $idNotif,
6168                            $this->getVal('dossier'),
6169                            $categorie
6170                        );
6171                        if ($notification_by_task === false) {
6172                            $this->addToMessage(
6173                                __("Erreur lors de la génération de la notification au(x) pétitionnaire(s).")
6174                            );
6175                            // Termine le traitement
6176                            return $this->end_treatment(__METHOD__, false);
6177                        }
6178                        $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.")));
6179                    }
6180                }
6181                // Si le demandeur principal n'est pas notifiable, on créé une nouvelle notification
6182                // en erreur avec en commentaire la raison pour laquelle le demandeur principal
6183                // n'a pas pu être notifié
6184                if (! $demandeurPrincipalNotifie) {
6185                    // Analyse pour savoir pourquoi le demandeur principal n'est pas notifiable
6186                    $erreursParam = $this->get_info_notification_fail();
6187                    $demandeurPrincipal = $this->get_info_petitionnaire_principal_dossier($this->getVal('dossier'));
6188                    // Ajout de la notif et récupération de son id
6189                    $idNotif = $this->ajouter_notification(
6190                        $this->valF[$this->clePrimaire],
6191                        $this->f->get_connected_user_login_name(),
6192                        $demandeurPrincipal,
6193                        $collectivite_di,
6194                        array(),
6195                        true,
6196                        'Echec',
6197                        implode(' ', $erreursParam)
6198                    );
6199                    if ($idNotif === false) {
6200                        $this->addToMessage(
6201                            __('Erreur : la création de la notification a échouée.').
6202                            __("Veuillez contacter votre administrateur.")
6203                        );
6204                        return false;
6205                    }
6206                    // Prépare un message d'alerte à destination de l'instructeur pour l'informer
6207                    // de l'échec de la notification
6208                    $dossier_message = $this->get_inst_dossier_message(0);
6209                    $dossier_message_val = array(
6210                        'dossier' => $this->getVal('dossier'),
6211                        'type' => _('erreur expedition'),
6212                        'emetteur' => $this->f->get_connected_user_login_name(),
6213                        'login' => $_SESSION['login'],
6214                        'date_emission' => date('Y-m-d H:i:s'),
6215                        'contenu' => _('Échec lors de la notification de l\'instruction ').
6216                            $ev->getVal('libelle').
6217                            '.<br>'.
6218                            implode("\n", $erreursParam).
6219                            '<br>'.
6220                            _('Veuillez corriger ces informations avant de renvoyer la notification.')
6221                    );
6222                    $add = $dossier_message->add_notification_message($dossier_message_val, true);
6223                    // Si une erreur se produit pendant l'ajout
6224                    if ($add !== true) {
6225                        $this->addToLog(__METHOD__."(): Le message d'alerte concernant l'echec de l'envoi de la notification n'a pas pu être envoyé.", DEBUG_MODE);
6226                        return false;
6227                    }
6228                }
6229            }
6230    
6231          // Termine le traitement          // Termine le traitement
6232          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
6233      }      }
6234    
6235      /**      /**
6236         * Récupère l'instance de dossier message.
6237         *
6238         * @param string $dossier_message Identifiant du message.
6239         *
6240         * @return object
6241         */
6242        private function get_inst_dossier_message($dossier_message = null) {
6243            //
6244            return $this->get_inst_common("dossier_message", $dossier_message);
6245        }
6246    
6247        /**
6248         * Vérifie si le signataire est obligatoire pour finaliser
6249         * le document apartir du paramétrage de l'événement.
6250         * Si c'est le cas, vérifie si il y a bien un signataire
6251         * renseigné.
6252         * Si c'est le cas renvoie true, sinon renvoie false.
6253         *
6254         * @param evenement évenement de l'instruction permettant de
6255         * récupérer le paramétrage
6256         * @return boolean
6257         */
6258        protected function controle_signataire($evenement) {
6259            // Vérifie si le signataire est obligatoire et si c'est le cas
6260            // vérifie si il y a bien un signataire pour le document
6261            if ($evenement->is_signataire_obligatoire() &&
6262                ($this->getVal('signataire_arrete') === null ||
6263                $this->getVal('signataire_arrete') === '')) {
6264                return false;
6265            }
6266            return true;
6267        }
6268    
6269        /**
6270       * TREATMENT - unfinalize.       * TREATMENT - unfinalize.
6271       *       *
6272       * Permet de définaliser un enregistrement.       * Permet de définaliser un enregistrement.
# Line 3239  class instruction extends instruction_ge Line 6309  class instruction extends instruction_ge
6309              && $this->getVal("om_final_instruction") != null) {              && $this->getVal("om_final_instruction") != null) {
6310    
6311              // Ouvre le document              // Ouvre le document
6312              $lien = '../spg/file.php?obj='.$this->table.'&'.              $lien = '../app/index.php?module=form&snippet=file&obj='.$this->table.'&'.
6313                      'champ=om_fichier_instruction&id='.$this->getVal($this->clePrimaire);                      'champ=om_fichier_instruction&id='.$this->getVal($this->clePrimaire);
6314              //              //
6315              header("Location: ".$lien);              header("Location: ".$lien);
# Line 3258  class instruction extends instruction_ge Line 6328  class instruction extends instruction_ge
6328                      "mode" => "previsualisation",                      "mode" => "previsualisation",
6329                  ),                  ),
6330              );              );
6331                // Si la rédaction libre est activée sur l'instruction
6332                if ($this->getVal("flag_edition_integrale") == 't') {
6333                    $params["specific"]["corps"] = array(
6334                        "mode" => "set",
6335                        "value" => $this->getVal("corps_om_htmletatex"),
6336                    );
6337                    $params["specific"]["titre"] = array(
6338                        "mode" => "set",
6339                        "value" => $this->getVal("titre_om_htmletat"),
6340                    );
6341                }
6342    
6343              // Génération du PDF              // Génération du PDF
6344              $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 3272  class instruction extends instruction_ge Line 6353  class instruction extends instruction_ge
6353      /**      /**
6354       * Récupère la collectivité du dossier d'instruction.       * Récupère la collectivité du dossier d'instruction.
6355       *       *
6356         * @param string $dossier_instruction_id Identifiant du DI.
6357         *
6358       * @return integer       * @return integer
6359       */       */
6360      function get_dossier_instruction_om_collectivite() {      function get_dossier_instruction_om_collectivite($dossier_instruction_id = null) {
6361    
6362            // Si l'identifiant n'est pas renseigné
6363            if ($dossier_instruction_id === null) {
6364                // Récupère la valeur
6365                if ($this->getVal('dossier') !== null && $this->getVal('dossier') !== '') {
6366                    $dossier_instruction_id = $this->getVal('dossier');
6367                } elseif ($this->getParameter('idxformulaire') !== null
6368                    && $this->getParameter('idxformulaire') !== '') {
6369                    //
6370                    $dossier_instruction_id = $this->getParameter('idxformulaire');
6371                } elseif ($this->f->get_submitted_get_value('idxformulaire') !== null
6372                    && $this->f->get_submitted_get_value('idxformulaire') !== '') {
6373                    //
6374                    $dossier_instruction_id = $this->f->get_submitted_get_value('idxformulaire');
6375                }
6376            }
6377    
6378          //          //
6379          require_once "../obj/dossier_instruction.class.php";          $dossier_instruction = $this->f->get_inst__om_dbform(array(
6380          $dossier_instruction = new dossier_instruction($this->getVal('dossier'), $this->f->db, false);              "obj" => "dossier_instruction",
6381                "idx" => $dossier_instruction_id,
6382            ));
6383    
6384          //          //
6385          return $dossier_instruction->getVal('om_collectivite');          return $dossier_instruction->getVal('om_collectivite');
# Line 3295  class instruction extends instruction_ge Line 6396  class instruction extends instruction_ge
6396          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6397          $this->checkAccessibility();          $this->checkAccessibility();
6398    
         // XXX APP  
   
         $f = $this->f;  
   
6399          /**          /**
6400           * Affichage de la structure HTML           * Affichage de la structure HTML
6401           */           */
6402          //          //
6403          if ($f->isAjaxRequest()) {          if ($this->f->isAjaxRequest()) {
6404              //              //
6405              header("Content-type: text/html; charset=".HTTPCHARSET."");              header("Content-type: text/html; charset=".HTTPCHARSET."");
6406          } else {          } else {
6407              //              //
6408              $f->setFlag("htmlonly");              $this->f->setFlag("htmlonly");
6409              $f->display();              $this->f->display();
6410          }          }
6411          //          //
6412          $f->displayStartContent();          $this->f->displayStartContent();
6413          //          //
6414          $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"));
6415          $f->displayTitle();          $this->f->displayTitle();
6416    
6417          /**          /**
6418           *           *
6419           */           */
6420          //          //
6421          ($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 = "");
6422          $evenement = intval($evenement);          $evenement = intval($evenement);
6423          //          //
6424          ($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 = "");
6425          // Récupération du code du type de DA          // Récupération du code du type de DA
6426          $code_da_type = '';          $code_da_type = '';
6427          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {
6428              $code_da_type = $matches[0];              $code_da_type = $matches[0];
6429          }          }
6430          //          //
6431          ($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");
6432    
6433          // Récupération de la collectivité du dossier          // Récupération de la collectivité du dossier
6434          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
6435          $dossier = new dossier($idx, $f->db, DEBUG);              "obj" => "dossier",
6436                "idx" => $idx,
6437            ));
6438    
6439          /**          /**
6440           *           *
# Line 3347  class instruction extends instruction_ge Line 6446  class instruction extends instruction_ge
6446              ON bible.dossier_autorisation_type=dossier_autorisation_type.dossier_autorisation_type              ON bible.dossier_autorisation_type=dossier_autorisation_type.dossier_autorisation_type
6447          LEFT JOIN ".DB_PREFIXE."om_collectivite          LEFT JOIN ".DB_PREFIXE."om_collectivite
6448              ON bible.om_collectivite = om_collectivite.om_collectivite              ON bible.om_collectivite = om_collectivite.om_collectivite
6449          WHERE evenement=".$evenement."          WHERE (evenement=".$evenement." OR evenement IS NULL)
6450              AND complement=".$complement."              AND (complement=".$complement." OR complement IS NULL)
6451              AND (bible.dossier_autorisation_type IS NULL              AND (bible.dossier_autorisation_type IS NULL
6452                  OR dossier_autorisation_type.code ='".$code_da_type."')                  OR dossier_autorisation_type.code ='".$code_da_type."')
6453              AND (om_collectivite.niveau = '2'              AND (om_collectivite.niveau = '2'
6454                  OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")                  OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")
6455          ORDER BY bible_lib ASC";          ORDER BY bible_lib ASC";
6456          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
6457          $f->addToLog(__METHOD__.": db->query(\"".$sql."\");", VERBOSE_MODE);          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\");", VERBOSE_MODE);
6458          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
6459          //          //
6460          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";          echo "<form method=\"post\" name=\"f3\" action=\"#\">\n";
6461          //          //
# Line 3388  class instruction extends instruction_ge Line 6487  class instruction extends instruction_ge
6487              echo "\t</table>\n";              echo "\t</table>\n";
6488              //              //
6489              echo "<div class=\"formControls\">\n";              echo "<div class=\"formControls\">\n";
6490              $f->layout->display_form_button(array(              $this->f->layout->display_form_button(array(
6491                  "value" => _("Valider"),                  "value" => _("Valider"),
6492                  "onclick" => "bible_return('f2', 'complement".($complement == "1" ? "" : $complement)."_om_html'); return false;",                  "onclick" => "bible_return('f2', 'complement".($complement == "1" ? "" : $complement)."_om_html'); return false;",
6493              ));              ));
6494              $f->displayLinkJsCloseWindow();              $this->f->displayLinkJsCloseWindow();
6495              echo "</div>\n";              echo "</div>\n";
6496    
6497          } else {          } else {
6498              //              //
6499              $message_class = "error";              $message_class = "error";
6500              $message = _("Aucun element dans la bible pour l'evenement")." : ".$evenement;              $message = _("Aucun element dans la bible pour l'evenement")." : ".$evenement;
6501              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
6502              //              //
6503              echo "<div class=\"formControls\">\n";              echo "<div class=\"formControls\">\n";
6504              $f->displayLinkJsCloseWindow();              $this->f->displayLinkJsCloseWindow();
6505              echo "</div>\n";              echo "</div>\n";
6506          }          }
6507          //          //
# Line 3412  class instruction extends instruction_ge Line 6511  class instruction extends instruction_ge
6511           * Affichage de la structure HTML           * Affichage de la structure HTML
6512           */           */
6513          //          //
6514          $f->displayEndContent();          $this->f->displayEndContent();
6515      }      }
6516    
6517      /**      /**
# Line 3425  class instruction extends instruction_ge Line 6524  class instruction extends instruction_ge
6524      function view_bible_auto() {      function view_bible_auto() {
6525          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6526          $this->checkAccessibility();          $this->checkAccessibility();
   
         // XXX APP  
   
         $f = $this->f;  
   
6527          //          //
6528          $f->disableLog();          $this->f->disableLog();
6529    
6530          $formatDate="AAAA-MM-JJ";          $formatDate="AAAA-MM-JJ";
6531    
6532          // Récupération des paramètres          // Récupération des paramètres
6533          $idx = $f->get_submitted_get_value('idx');          $idx = $this->f->get_submitted_get_value('idx');
6534          $evenement = $f->get_submitted_get_value('ev');          $evenement = $this->f->get_submitted_get_value('ev');
6535    
6536          // Initialisation de la variable de retour          // Initialisation de la variable de retour
6537          $retour['complement_om_html'] = '';          $retour['complement_om_html'] = '';
# Line 3445  class instruction extends instruction_ge Line 6539  class instruction extends instruction_ge
6539          $retour['complement3_om_html'] = '';          $retour['complement3_om_html'] = '';
6540          $retour['complement4_om_html'] = '';          $retour['complement4_om_html'] = '';
6541          // Vérification d'une consultation liée à l'événement          // Vérification d'une consultation liée à l'événement
6542          $consultation = $f->db->getOne(          $consultation = $this->f->db->getOne(
6543              "select consultation from ".DB_PREFIXE."evenement where evenement=".$evenement              "select consultation from ".DB_PREFIXE."evenement where evenement=".$evenement
6544          );          );
6545          $f->isDatabaseError($consultation);          $this->f->isDatabaseError($consultation);
6546          // Si consultation liée, récupération du retour d'avis          // Si consultation liée, récupération du retour d'avis
6547          if($consultation=='Oui'){          if($consultation=='Oui'){
6548              $sql="select date_retour,avis_consultation.libelle as avis_consultation,              $sql = sprintf(
6549                    service.libelle as service                  '(SELECT
6550                    from ".DB_PREFIXE."consultation inner join ".DB_PREFIXE."service                      date_retour,
6551                    on consultation.service =service.service                      avis_consultation.libelle as avis_consultation,
6552                    left join ".DB_PREFIXE."avis_consultation on                      COALESCE(service.libelle, tiers_consulte.libelle) as service
6553                      consultation.avis_consultation = avis_consultation.avis_consultation                  FROM
6554                    where dossier ='".$idx."'";                      %1$sconsultation
6555              $res = $f->db->query($sql);                      LEFT JOIN %1$stiers_consulte ON consultation.tiers_consulte = tiers_consulte.tiers_consulte
6556              $f->isDatabaseError($res);                      LEFT JOIN %1$sservice ON consultation.service = service.service
6557                        LEFT JOIN %1$savis_consultation ON consultation.avis_consultation = avis_consultation.avis_consultation
6558                    WHERE
6559                        dossier = \'%2$s\'
6560                        AND consultation.visible)',
6561                    DB_PREFIXE,
6562                    $this->f->db->escapeSimple($idx)
6563                );
6564                $res = $this->f->db->query($sql);
6565                $this->f->isDatabaseError($res);
6566              // Récupération des consultations              // Récupération des consultations
6567              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){              while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){
6568                  $correct=false;                  $correct=false;
# Line 3484  class instruction extends instruction_ge Line 6587  class instruction extends instruction_ge
6587                      $temp=$temp." du ".$date_retour_f;                      $temp=$temp." du ".$date_retour_f;
6588                  }                  }
6589                  // Concaténation des retours d'avis de consultation                  // Concaténation des retours d'avis de consultation
6590                  $retour['complement_om_html'] .= $temp;                  $retour['complement_om_html'] .= $temp . "<br/><br/>";
6591              } // while              } // while
6592                            
6593          } // consultation          } // consultation
6594          // Récupération des bibles automatiques pour le champ complement_om_html          // Récupération des bibles automatiques pour le champ complement_om_html
6595          $retour['complement_om_html'] .= $this->getBible($f, $evenement, $idx, '1');          $retour['complement_om_html'] .= $this->getBible($evenement, $idx, '1');
6596          // Récupération des bibles automatiques pour le champ complement2_om_html          // Récupération des bibles automatiques pour le champ complement2_om_html
6597          $retour['complement2_om_html'] .= $this->getBible($f, $evenement, $idx, '2');          $retour['complement2_om_html'] .= $this->getBible($evenement, $idx, '2');
6598          // Récupération des bibles automatiques pour le champ complement3_om_html          // Récupération des bibles automatiques pour le champ complement3_om_html
6599          $retour['complement3_om_html'] .= $this->getBible($f, $evenement, $idx, '3');          $retour['complement3_om_html'] .= $this->getBible($evenement, $idx, '3');
6600          // Récupération des bibles automatiques pour le champ complement4_om_html          // Récupération des bibles automatiques pour le champ complement4_om_html
6601          $retour['complement4_om_html'] .= $this->getBible($f, $evenement, $idx, '4');          $retour['complement4_om_html'] .= $this->getBible($evenement, $idx, '4');
6602    
6603    
6604    
# Line 3503  class instruction extends instruction_ge Line 6606  class instruction extends instruction_ge
6606      }      }
6607    
6608      /**      /**
6609         * VIEW - view_pdf_temp
6610         *
6611         * @return void
6612         */
6613        function view_pdf_temp() {
6614            $this->checkAccessibility();
6615            // Utilisation de $_POST pour ne pas que les textes soient altérés.
6616            $this->f->set_submitted_value();
6617            $merge_fields = array();
6618            //
6619            if (array_key_exists('c1', $_POST) === true) {
6620                $merge_fields['[complement_instruction]'] = $_POST['c1'];
6621                $merge_fields['[complement1_instruction]'] = $_POST['c1'];
6622            }
6623            if (array_key_exists('c2', $_POST) === true) {
6624                $merge_fields['[complement2_instruction]'] = $_POST['c2'];
6625            }
6626            if (array_key_exists('c3', $_POST) === true) {
6627                $merge_fields['[complement3_instruction]'] = $_POST['c3'];
6628            }
6629            if (array_key_exists('c4', $_POST) === true) {
6630                $merge_fields['[complement4_instruction]'] = $_POST['c4'];
6631            }
6632            $params = array(
6633                "watermark" => true,
6634                "specific" => array(
6635                    "merge_fields" => $merge_fields,
6636                ),
6637            );
6638            //
6639            if (array_key_exists('corps', $_POST) === true) {
6640                $params["specific"]["corps"] = array(
6641                    "mode" => "set",
6642                    "value" => $_POST['corps'],
6643                );
6644            }
6645            if (array_key_exists('titre', $_POST) === true) {
6646                $params["specific"]["titre"] = array(
6647                    "mode" => "set",
6648                    "value" => $_POST['titre'],
6649                );
6650            }
6651            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
6652            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
6653            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
6654            $retour = array(
6655                'base' => base64_encode($result['pdf_output']),
6656            );
6657            echo json_encode($retour);
6658        }
6659    
6660        /**
6661         * Dans le contexte de prévisualisation des éditions, génère le rendu du
6662         * PDF sans prise en compte de la valeur des compléments et le retourne en
6663         * base 64.
6664         *
6665         * @return string Rendu PDF converti en base 64.
6666         */
6667        function init_pdf_temp() {
6668            $params = array(
6669                "watermark" => true,
6670            );
6671            // Si la rédaction libre est activée sur l'instruction
6672            if ($this->getVal("flag_edition_integrale") == 't') {
6673                $params["specific"]["corps"] = array(
6674                    "mode" => "set",
6675                    "value" => $this->getVal("corps_om_htmletatex"),
6676                );
6677                $params["specific"]["titre"] = array(
6678                    "mode" => "set",
6679                    "value" => $this->getVal("titre_om_htmletat"),
6680                );
6681            }
6682            $dossier_instruction_om_collectivite = $this->get_dossier_instruction_om_collectivite();
6683            $collectivite = $this->f->getCollectivite($dossier_instruction_om_collectivite);
6684            $result = $this->compute_pdf_output('lettretype', $this->getVal('lettretype'), $collectivite, null, $params);
6685    
6686            return base64_encode($result['pdf_output']);
6687        }
6688    
6689        /**
6690       * Récupération des éléments de bible.       * Récupération des éléments de bible.
6691       *       *
      * @param utils   $f      handler de om_application  
6692       * @param integer $event  id de l'événement       * @param integer $event  id de l'événement
6693       * @param string  $idx    id du dossier       * @param string  $idx    id du dossier
6694       * @param integer $compnb numéro du champ complement       * @param integer $compnb numéro du champ complement
6695       *       *
6696       * @return string   Chaîne de texte à insérer dans le champ complement       * @return string   Chaîne de texte à insérer dans le champ complement
6697       */       */
6698      function getBible($f, $event, $idx, $compnb) {      function getBible($event, $idx, $compnb) {
6699          // Récupération de la collectivité du dossier          // Récupération de la collectivité du dossier
6700          require_once "../obj/dossier.class.php";          $dossier = $this->f->get_inst__om_dbform(array(
6701          $dossier = new dossier($idx, $f->db, DEBUG);              "obj" => "dossier",
6702                "idx" => $idx,
6703            ));
6704          // Récupération du code du type de DA          // Récupération du code du type de DA
6705          $code_da_type = '';          $code_da_type = '';
6706          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {          if (preg_match('/[A-Za-z]{2,3}/', $idx, $matches) !== false) {
# Line 3529  class instruction extends instruction_ge Line 6714  class instruction extends instruction_ge
6714              LEFT JOIN              LEFT JOIN
6715                      ".DB_PREFIXE."om_collectivite                      ".DB_PREFIXE."om_collectivite
6716                      ON bible.om_collectivite = om_collectivite.om_collectivite                      ON bible.om_collectivite = om_collectivite.om_collectivite
6717              WHERE evenement =".$event." and              WHERE (evenement =".$event." or evenement IS NULL) and
6718                  complement=".$compnb." and                  (complement=".$compnb." OR complement IS NULL) and
6719                  automatique='Oui' and                  automatique='Oui' and
6720                  (dossier_autorisation_type.code ='".$code_da_type."' or                  (dossier_autorisation_type.code ='".$code_da_type."' or
6721                      bible.dossier_autorisation_type IS NULL) and                      bible.dossier_autorisation_type IS NULL) and
6722                  (om_collectivite.niveau = '2' OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")";                  (om_collectivite.niveau = '2' OR bible.om_collectivite = ".$dossier->getVal("om_collectivite").")";
6723    
6724          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
6725          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
6726          $temp = "";          $temp = "";
6727          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){          while ($row=& $res->fetchRow(DB_FETCHMODE_ASSOC)){
6728              // Remplacement des retours à la ligne par des br              // Remplacement des retours à la ligne par des br
6729              $temp .= preg_replace(              $temp .= preg_replace(
6730                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']                  '#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $row['contenu']
6731              );              );
6732                // Ajout d'un saut de ligne entre chaque bible.
6733                $temp .= '<br/>';
6734          } // fin while          } // fin while
6735          return $temp;          return $temp;
6736      }      }
# Line 3561  class instruction extends instruction_ge Line 6748  class instruction extends instruction_ge
6748          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6749          $this->checkAccessibility();          $this->checkAccessibility();
6750    
         // XXX APP  
   
         $f = $this->f;  
   
6751          /**          /**
6752           * Validation du formulaire           * Validation du formulaire
6753           */           */
6754          // Si le formulaire a été validé          // Si le formulaire a été validé
6755          if ($f->get_submitted_post_value("validation") !== null) {          if ($this->f->get_submitted_post_value("validation") !== null) {
6756              // Si un bordereau à été sélectionné              // Si un bordereau à été sélectionné
6757              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") == "" ) {
6758                  // Si aucun bordereau n'a été sélectionné                  // Si aucun bordereau n'a été sélectionné
6759                  $message_class = "error";                  $message_class = "error";
6760                  $message = _("Veuillez selectionner un bordereau.");                  $message = _("Veuillez selectionner un bordereau.");
6761              }              }
6762              // Sinon si les dates ne sont pas valide              // Sinon si les dates ne sont pas valide
6763              elseif (($f->get_submitted_post_value("date_bordereau_debut") !== null              elseif (($this->f->get_submitted_post_value("date_bordereau_debut") !== null
6764                  && $f->get_submitted_post_value("date_bordereau_debut") == "")                  && $this->f->get_submitted_post_value("date_bordereau_debut") == "")
6765                  || ($f->get_submitted_post_value("date_bordereau_fin") !== null                  || ($this->f->get_submitted_post_value("date_bordereau_fin") !== null
6766                  && $f->get_submitted_post_value("date_bordereau_fin") == "")) {                  && $this->f->get_submitted_post_value("date_bordereau_fin") == "")) {
6767                  // Si aucune date n'a été saisie                  // Si aucune date n'a été saisie
6768                  $message_class = "error";                  $message_class = "error";
6769                  $message = _("Veuillez saisir une date valide.");                  $message = _("Veuillez saisir une date valide.");
6770              }              }
6771                // Sinon si les dates ne sont pas valides
6772                elseif ($this->f->get_submitted_post_value("bordereau") === "bordereau_avis_maire_prefet"
6773                    && $this->f->getParameter("id_evenement_bordereau_avis_maire_prefet") == null) {
6774                    // Si aucune date n'a été saisie
6775                    $message_class = "error";
6776                    $message = _("Erreur de parametrage. Contactez votre administrateur.");
6777                }
6778              // Affiche le message de validation              // Affiche le message de validation
6779              else {              else {
6780                  // 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
6781                  $sql = "SELECT om_etat.libelle                  $sql = "SELECT om_etat.libelle
6782                  FROM ".DB_PREFIXE."om_etat                  FROM ".DB_PREFIXE."om_etat
6783                  WHERE om_etat.id = '".$f->get_submitted_post_value("bordereau")."'";                  WHERE om_etat.id = '".$this->f->get_submitted_post_value("bordereau")."'";
6784                  $res = $f->db->getone($sql);                  $res = $this->f->db->getone($sql);
6785                  $f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);
6786                  $f->isDatabaseError($res);                  $this->f->isDatabaseError($res);
6787                  //                  //
6788                  $message_class = "valid";                  $message_class = "valid";
6789                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");                  $message = _("Cliquez sur le lien ci-dessous pour telecharger votre bordereau");
6790                  $message .= " : <br/><br/>";                  $message .= " : <br/><br/>";
6791                  $message .= "<a class='om-prev-icon pdf-16'";                  $message .= "<a class='om-prev-icon pdf-16'";
6792                  $message .= " title=\""._("Bordereau")."\"";                  $message .= " title=\""._("Bordereau")."\"";
6793                  $message .= "href='../scr/form.php?obj=instruction";                  $message .= "href='".OM_ROUTE_FORM."&obj=instruction";
6794                  $message .= "&action=220";                  $message .= "&action=220";
6795                  $message .= "&idx=0";                  $message .= "&idx=0";
6796                  $message .= "&type_bordereau=".$f->get_submitted_post_value("bordereau");                  $message .= "&type_bordereau=".$this->f->get_submitted_post_value("bordereau");
6797                  $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");
6798                  $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");
6799                  // Si l'utilisateur est MULTI alors on ajoute le paramètre collectivite                  // Si l'utilisateur est MULTI alors on ajoute le paramètre collectivite
6800                  if ($f->get_submitted_post_value("om_collectivite") !== null) {                  if ($this->f->get_submitted_post_value("om_collectivite") !== null) {
6801                      $message .= "&collectivite=".$f->get_submitted_post_value("om_collectivite");                      $message .= "&collectivite=".$this->f->get_submitted_post_value("om_collectivite");
6802                  }                  }
6803                  $message .= "'"." target='_blank'>";                  $message .= "'"." target='_blank'>";
6804                  $message .= $res." "._("du")." ".$f->get_submitted_post_value("date_bordereau_debut")                  $message .= $res." "._("du")." ".$this->f->get_submitted_post_value("date_bordereau_debut")
6805                      ." "._("au")." ".$f->get_submitted_post_value("date_bordereau_fin");                      ." "._("au")." ".$this->f->get_submitted_post_value("date_bordereau_fin");
6806                  $message .= "</a>";                  $message .= "</a>";
6807              }              }
6808          }          }
# Line 3622  class instruction extends instruction_ge Line 6812  class instruction extends instruction_ge
6812           */           */
6813          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
6814          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
6815              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
6816          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
6817          // Ouverture du formulaire          // Ouverture du formulaire
6818          printf("\t<form");          printf("\t<form");
6819          printf(" method=\"post\"");          printf(" method=\"post\"");
# Line 3634  class instruction extends instruction_ge Line 6822  class instruction extends instruction_ge
6822          printf(">\n");          printf(">\n");
6823          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
6824          $champs = array("date_bordereau_debut", "date_bordereau_fin", "bordereau");          $champs = array("date_bordereau_debut", "date_bordereau_fin", "bordereau");
6825          // 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
6826          // collectivité dans le formulaire          // collectivité dans le formulaire
6827          if($_SESSION["niveau"] == 2) {          if ($_SESSION["niveau"] == 2) {
6828              array_push($champs, "om_collectivite");              array_push($champs, "om_collectivite");
6829          }          }
6830          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
6831          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
6832                "validation" => 0,
6833                "maj" => 0,
6834                "champs" => $champs,
6835            ));
6836          // Paramétrage du champ date_bordereau_debut          // Paramétrage du champ date_bordereau_debut
6837          $form->setLib("date_bordereau_debut", _("date_bordereau_debut"));          $form->setLib("date_bordereau_debut", _("date_bordereau_debut"));
6838          $form->setType("date_bordereau_debut", "date");          $form->setType("date_bordereau_debut", "date");
# Line 3662  class instruction extends instruction_ge Line 6854  class instruction extends instruction_ge
6854          $form->setType("bordereau", "select");          $form->setType("bordereau", "select");
6855          $form->setRequired("bordereau");          $form->setRequired("bordereau");
6856          // Valeurs des champs          // Valeurs des champs
6857          if ($f->get_submitted_post_value("validation") !== null) {          if ($this->f->get_submitted_post_value("validation") !== null) {
6858              $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"));
6859              $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"));
6860              $form->setVal("bordereau", $f->get_submitted_post_value("bordereau"));              $form->setVal("bordereau", $this->f->get_submitted_post_value("bordereau"));
6861              $form->setVal("om_collectivite", $f->get_submitted_post_value("om_collectivite"));              $form->setVal("om_collectivite", $this->f->get_submitted_post_value("om_collectivite"));
6862          }          }
6863          // 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
6864          // 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 3675  class instruction extends instruction_ge Line 6867  class instruction extends instruction_ge
6867                  FROM ".DB_PREFIXE."om_etat                  FROM ".DB_PREFIXE."om_etat
6868                  WHERE om_etat.id LIKE 'bordereau_%'                  WHERE om_etat.id LIKE 'bordereau_%'
6869                  ORDER BY om_etat.id";                  ORDER BY om_etat.id";
6870          $res = $f->db->query($sql);          $res = $this->f->db->query($sql);
6871          $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);          $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
6872          $f->isDatabaseError($res);          $this->f->isDatabaseError($res);
6873          // Données du select          // Données du select
6874          $contenu = array(          $contenu = array(
6875              0 => array("", ),              0 => array("", ),
# Line 3688  class instruction extends instruction_ge Line 6880  class instruction extends instruction_ge
6880              $contenu[1][] = $row['libelle'];              $contenu[1][] = $row['libelle'];
6881          }          }
6882          $form->setSelect("bordereau", $contenu);          $form->setSelect("bordereau", $contenu);
6883      //          //
6884      if($_SESSION["niveau"] == 2) {          if ($_SESSION["niveau"] == 2) {
6885          $form->setLib("om_collectivite", _("collectivite"));              $form->setLib("om_collectivite", _("collectivite"));
6886          $form->setType("om_collectivite", "select");              $form->setType("om_collectivite", "select");
6887    
6888          // 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
6889          // de niveau 1              // de niveau 1
6890          $sql = "SELECT om_collectivite, libelle              $sql = "SELECT om_collectivite, libelle
6891                  FROM ".DB_PREFIXE."om_collectivite                      FROM ".DB_PREFIXE."om_collectivite
6892                  WHERE niveau = '1' ORDER BY libelle";                      WHERE niveau = '1' ORDER BY libelle";
6893          $res = $f->db->query($sql);              $res = $this->f->db->query($sql);
6894          $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);              $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
6895          $f->isDatabaseError($res);              $this->f->isDatabaseError($res);
6896          // La valeur par défaut du select est Toutes              // La valeur par défaut du select est Toutes
6897          $list_collectivites = array(              $list_collectivites = array(
6898              0 => array("", ),                  0 => array("", ),
6899              1 => array(_("toutes"))                  1 => array(_("toutes"))
6900          );              );
   
         $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);  
     }  
6901    
6902                $id_colls = "";
6903                // On stocke dans $id_colls l'id de toutes les collectivités de niveau 1 séparées
6904                // par des virgules, pour un traitement plus facile dans la requête de sous-état
6905                while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
6906                    if ($id_colls != "") {
6907                        $id_colls .= ",";
6908                    }
6909                    $id_colls .= $row['om_collectivite'];
6910                    $list_collectivites[0][] = $row['om_collectivite'];
6911                    $list_collectivites[1][] = $row['libelle'];
6912                }
6913                // On affecte la liste d'identifiants à l'option Toutes
6914                $list_collectivites[0][0] = $id_colls ;
6915                $form->setSelect("om_collectivite", $list_collectivites);
6916            }
6917          // Affichage du formulaire          // Affichage du formulaire
6918          $form->entete();          $form->entete();
6919          $form->afficher($champs, 0, false, false);          $form->afficher($champs, 0, false, false);
6920          $form->enpied();          $form->enpied();
6921          // Affichage du bouton          // Affichage du bouton
6922          printf("\t<div class=\"formControls\">\n");          printf("\t<div class=\"formControls\">\n");
6923          $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));          $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
6924          printf("\t</div>\n");          printf("\t</div>\n");
6925          // Fermeture du formulaire          // Fermeture du formulaire
6926          printf("\t</form>\n");          printf("\t</form>\n");
   
6927      }      }
6928    
6929    
# Line 3762  class instruction extends instruction_ge Line 6952  class instruction extends instruction_ge
6952      /**      /**
6953       * VIEW - view_suivi_envoi_lettre_rar.       * VIEW - view_suivi_envoi_lettre_rar.
6954       *       *
6955       * Vu pour imprimer les RAR.       * Vue pour imprimer les AR.
6956       *       *
6957       * @return void       * @return void
6958       */       */
# Line 3770  class instruction extends instruction_ge Line 6960  class instruction extends instruction_ge
6960          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
6961          $this->checkAccessibility();          $this->checkAccessibility();
6962    
         // XXX APP  
   
         $f = $this->f;  
   
6963          //          //
6964          if ($f->get_submitted_post_value("date") !== null) {          if ($this->f->get_submitted_post_value("date") !== null) {
6965              $date = $f->get_submitted_post_value("date");              $date = $this->f->get_submitted_post_value("date");
6966          } else {          } else {
6967              $date = "";              $date = "";
6968          }          }
6969          //          //
6970          if ($f->get_submitted_post_value("liste_code_barres_instruction") !== null) {          if ($this->f->get_submitted_post_value("liste_code_barres_instruction") !== null) {
6971              $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");
6972          } else {          } else {
6973              $liste_code_barres_instruction = "";              $liste_code_barres_instruction = "";
6974          }          }
# Line 3794  class instruction extends instruction_ge Line 6980  class instruction extends instruction_ge
6980          //          //
6981          $error = "";          $error = "";
6982    
6983            // Initialisation du tableau qui va contenir les DI pour lister les liens
6984            $dossierTab = array();
6985            // On vérifie que l'utilisateur ait les droits pour afficher des consultations
6986            $isAccredited = $this->f->isAccredited(array("dossier_instruction","dossier_instruction_consulter"), "OR");
6987            $hasHidden = true;
6988            // S'il ne peut pas les consulter il aura des dossiers caché
6989            if ($isAccredited === true) {
6990                $hasHidden = false;
6991            }
6992    
6993          /**          /**
6994           * Validation du formulaire           * Validation du formulaire
6995           */           */
6996          // Si le formulaire a été validé          // Si le formulaire a été validé
6997          if ($f->get_submitted_post_value('validation') !== null) {          if ($this->f->get_submitted_post_value('validation') !== null) {
6998              //              //
6999              if (empty($date) || empty($liste_code_barres_instruction)) {              if (empty($date) || empty($liste_code_barres_instruction)) {
7000                  //                  //
# Line 3806  class instruction extends instruction_ge Line 7002  class instruction extends instruction_ge
7002                  $message = _("Tous les champs doivent etre remplis.");                  $message = _("Tous les champs doivent etre remplis.");
7003              } else {              } else {
7004                  // Création d'un tableau d'instruction                  // Création d'un tableau d'instruction
7005                  $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"));
7006                  //                  //
7007                  foreach ($liste as $code_barres) {                  foreach ($liste as $code_barres) {
7008                      // On enlève les éventuels espaces saisis                      // On enlève les éventuels espaces saisis
# Line 3816  class instruction extends instruction_ge Line 7012  class instruction extends instruction_ge
7012                          // Si la valeur transmise est numérique                          // Si la valeur transmise est numérique
7013                          if (is_numeric($code_barres)) {                          if (is_numeric($code_barres)) {
7014                              //                              //
7015                              $sql = "SELECT count(*) FROM ".DB_PREFIXE."instruction WHERE code_barres='".$code_barres."'";                              $sql = "SELECT count(*)
7016                              $nbInstr = $f->db->getone($sql);                                      FROM ".DB_PREFIXE."instruction
7017                              $f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);                                          INNER JOIN ".DB_PREFIXE."dossier
7018                              $f->isDatabaseError($nbInstr);                                              ON dossier.dossier=instruction.dossier
7019                                            INNER JOIN ".DB_PREFIXE."dossier_instruction_type
7020                                                ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
7021                                            INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
7022                                                ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
7023                                            INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
7024                                                ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
7025                                            INNER JOIN ".DB_PREFIXE."groupe
7026                                                ON dossier_autorisation_type.groupe = groupe.groupe
7027                                            WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";
7028                                            
7029                                // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès
7030                                $group_clause = array();
7031                                foreach ($_SESSION["groupe"] as $key => $value) {
7032                                    $group_clause[$key] = "(groupe.code = '".$key."'";
7033                                    if($value["confidentiel"] !== true) {
7034                                        $group_clause[$key] .= " AND dossier_autorisation_type.confidentiel IS NOT TRUE";
7035                                    }
7036                                    $group_clause[$key] .= ")";
7037                                }
7038                                $conditions = implode(" OR ", $group_clause);
7039                                $sql .= " AND (" . $conditions . ")";
7040    
7041                                $nbInstr = $this->f->db->getone($sql);
7042                                $this->f->addToLog(__METHOD__.": db->getone(\"".$sql."\")", VERBOSE_MODE);
7043                                $this->f->isDatabaseError($nbInstr);
7044                              //                              //
7045                              if ($nbInstr == "1") {                              if ($nbInstr == "1") {
7046                                  // Récupération de la date d'envoi de l'instruction bippé                                  // Récupération de la date d'envoi de l'instruction bippé
7047                                  $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."'";
7048                                  $res = $f->db->query($sql);                                  $res = $this->f->db->query($sql);
7049                                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
7050                                  $f->isDatabaseError($res);                                  $this->f->isDatabaseError($res);
7051                                  $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);                                  $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);
7052                                  // Si pas de date ou correspond à la date du formulaire on                                  // Si pas de date ou correspond à la date du formulaire on
7053                                  // effectue le traitement                                  // effectue le traitement
7054                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {                                  if ($row["date_envoi_rar"] == "" || $row["date_envoi_rar"] == $date) {
7055                                                                            $instr = $this->f->get_inst__om_dbform(array(
7056                                      require_once '../obj/instruction.class.php';                                          "obj" => "instruction",
7057                                                                    "idx" => $row['instruction'],
7058                                      $instr = new instruction($row['instruction'], $f->db, DEBUG);                                      ));
7059                                      $valF = array();                                      $valF = array();
7060                                      foreach($instr->champs as $id => $champ) {                                      foreach($instr->champs as $id => $champ) {
7061                                          $valF[$champ] = $instr->val[$id];                                          $valF[$champ] = $instr->val[$id];
7062                                      }                                      }
7063    
7064                                        # Si on peut consulter les dossiers et que le dossier n'existe pas déjà dans la liste
7065                                        if ($isAccredited === true
7066                                            && array_key_exists($instr->getVal("dossier"), $dossierTab) === false) {
7067                                            $dossier = $this->f->get_inst__om_dbform(array(
7068                                                "obj" => "dossier",
7069                                                "idx" => $instr->getVal("dossier"),
7070                                            ));
7071                                            if ($dossier->is_user_from_allowed_collectivite()){
7072                                                $dossierTab[$instr->getVal("dossier")] = $dossier;
7073                                            } else {
7074                                                $hasHidden = true;
7075                                            }
7076                                        }
7077    
7078                                      $valF['date_evenement']=                                      $valF['date_evenement']=
7079                                          $instr->dateDBToForm($valF['date_evenement']);                                          $instr->dateDBToForm($valF['date_evenement']);
7080                                      $valF['archive_date_complet']=                                      $valF['archive_date_complet']=
# Line 3877  class instruction extends instruction_ge Line 7113  class instruction extends instruction_ge
7113                                          $instr->dateDBToForm($valF['date_envoi_controle_legalite']);                                          $instr->dateDBToForm($valF['date_envoi_controle_legalite']);
7114                                      $valF['date_retour_controle_legalite']=                                      $valF['date_retour_controle_legalite']=
7115                                          $instr->dateDBToForm($valF['date_retour_controle_legalite']);                                          $instr->dateDBToForm($valF['date_retour_controle_legalite']);
   
7116                                      $valF['date_envoi_rar'] = $date;                                      $valF['date_envoi_rar'] = $date;
7117    
7118                                      // Vérification de la finalisation du document                                      // Vérification de la finalisation du document
# Line 3886  class instruction extends instruction_ge Line 7121  class instruction extends instruction_ge
7121                                          $instr->setParameter('maj', 1);                                          $instr->setParameter('maj', 1);
7122                                          $instr->class_actions[1]["identifier"] =                                          $instr->class_actions[1]["identifier"] =
7123                                              "envoi lettre RAR (depuis le menu suivi des pièces)";                                              "envoi lettre RAR (depuis le menu suivi des pièces)";
7124                                          if ($instr->modifier($valF, $f->db, DEBUG) == true) {                                          if ($instr->modifier($valF) == true) {
7125                                              $id4Gen[] = $code_barres;                                              $id4Gen[] = $code_barres;
7126                                              $nbLettres ++;                                              $nbLettres ++;
7127                                          } else {                                          } else {
# Line 3941  class instruction extends instruction_ge Line 7176  class instruction extends instruction_ge
7176           */           */
7177          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
7178          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
7179              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
7180          }          }
7181          // Affichage du message d'erreur          // Affichage du message d'erreur
7182          if(!empty($error)) {          if(!empty($error)) {
7183              $f->displayMessage("error", $error);              $this->f->displayMessage("error", $error);
7184          }          }
7185          // Affichage du message de validation de la saisie          // Affichage du message de validation de la saisie
7186          if ($nbLettres > 0) {          if ($nbLettres > 0) {
7187              //              //
7188              $message_class = "valid";              echo "\n<div class=\"message ui-widget ui-corner-all ui-state-highlight ui-state-valid\" >";
7189              $message = _("Cliquez sur le lien ci-dessous pour telecharger votre document");              echo "\n<p>";
7190              $message .= " : <br/><br/>";              echo "\n<span class=\"ui-icon ui-icon-info\"></span>";
7191              $message .= "<a class='om-prev-icon pdf-16'";              echo "\n<span class=\"text\">";
7192              $message .= " title=\""._("imprimer les RAR")."\"";              echo _("Cliquez sur le lien ci-dessous pour telecharger votre document");
7193              $message .= " href=\"../scr/form.php?obj=instruction&action=180&idx=0&liste=".implode(",",$id4Gen)."\"";              echo " : \n<br/><br/>";
7194              $message .= " target='_blank'>";              echo "\n<a class='om-prev-icon pdf-16'";
7195              $message .= _("Telecharger le document pour")." ".$nbLettres." "._("RAR");              echo "\n title=\""._("imprimer les AR")."\"";
7196              $message .= "</a>";              echo "\n href=\"".OM_ROUTE_FORM."&obj=instruction&action=180&idx=0&liste=".implode(",",$id4Gen)."\"";
7197              $f->displayMessage($message_class, $message);              echo "\n target='_blank'>";
7198                echo _("Telecharger le document pour")." ".$nbLettres." "._("AR");
7199                echo "\n</a>";
7200                echo "\n</span>";
7201                echo "\n</p>";
7202                echo "\n<br/>\n";
7203                if ($isAccredited === true) {
7204                    echo '<fieldset id="fieldset-form-rar-lien_di" class="cadre ui-corner-all startClosed" style="background-color: inherite;">';
7205                    echo "\n<legend class=\"ui-corner-all ui-widget-content ui-state-active\" style=\"background-color: transparent; color: inherit;\">\n";
7206                    echo _('Dossiers concernés par ce traitement');
7207                    echo "\n</legend>";
7208                    echo "\n<div class=\"fieldsetContent\" style=\"display: none;background-color: inherite\">";
7209                    
7210                    if ($hasHidden === true) {
7211                        echo "\n<br/>";
7212                        echo "\n<p>";
7213                        echo "\n<span class='text'>";
7214                        echo _("Certains dossiers ont été omis de la liste ci-dessous car vous ne possédez pas les permissions nécessaires pour y accéder.");
7215                        echo "</span>";
7216                        echo "\n</p>";
7217                        echo "\n<br/>";
7218                    }
7219                    foreach ($dossierTab as $dossier) {
7220                      
7221                        $inst_da = $this->get_inst_common("dossier_autorisation", $dossier->getVal('dossier_autorisation'));
7222                        $inst_datd = $this->get_inst_common("dossier_autorisation_type_detaille", $inst_da->getVal('dossier_autorisation_type_detaille'));
7223                        $code_datd = $inst_datd->getVal('code');
7224    
7225                        $obj = "dossier_instruction";
7226                        if ($code_datd === 'REC' OR $code_datd === 'REG') {
7227                            $obj = "dossier_contentieux_tous_recours";
7228                        }
7229                        if ($code_datd === 'IN') {
7230                            $obj = "dossier_contentieux_toutes_infractions";
7231                        }
7232    
7233                        echo "\n<div class=\"bloc group\">";
7234                        echo "\n<div class=\"field field-type-text\">";
7235    
7236                        echo "\n<p>";
7237                        echo "\n<span class='text'>";
7238                        echo "\n<a class=\"om-icon om-icon-16 consult-16\" title=\"" . _('Consulter') . "\"";
7239                        echo "\n href=\"".OM_ROUTE_FORM."&obj=dossier_instruction&action=3&idx=";
7240                        echo $dossier->getVal("dossier");
7241                        echo "\">";
7242                        echo "\n</a>";
7243    
7244                        echo "\n<a title=\""._("Consulter")."\" style=\"vertical-align:middle;\"";
7245                        echo " href=\"".OM_ROUTE_FORM."&obj=";
7246                        echo $obj;
7247                        echo "&action=3&idx=";
7248                        echo $dossier->getVal("dossier");
7249                        echo "\">";
7250                        echo $dossier->getVal("dossier_libelle");
7251                        echo "\n</a>";
7252                        echo "\n</span>";
7253                        echo "\n</p>";
7254    
7255                        echo "\n</div>";
7256                        echo "\n</div>";
7257                    }
7258                    echo "\n</div>";
7259                    echo "\n</fieldset>";
7260                }
7261                echo "\n</div>";
7262                echo "\n</div>";
7263          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
7264          // Ouverture du formulaire          // Ouverture du formulaire
7265          echo "\t<form";          echo "\t<form";
7266          echo " method=\"post\"";          echo " method=\"post\"";
# Line 3972  class instruction extends instruction_ge Line 7270  class instruction extends instruction_ge
7270          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
7271          $champs = array("date", "liste_code_barres_instruction");          $champs = array("date", "liste_code_barres_instruction");
7272          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
7273          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
7274                "validation" => 0,
7275                "maj" => 0,
7276                "champs" => $champs,
7277            ));
7278          // Paramétrage du champ date du formulaire          // Paramétrage du champ date du formulaire
7279          $form->setLib("date", _("Date")."* :");          $form->setLib("date", _("Date")."* :");
7280          $form->setType("date", "date");          $form->setType("date", "date");
# Line 3992  class instruction extends instruction_ge Line 7294  class instruction extends instruction_ge
7294          $form->enpied();          $form->enpied();
7295          // Affichage du bouton          // Affichage du bouton
7296          echo "\t<div class=\"formControls\">\n";          echo "\t<div class=\"formControls\">\n";
7297          $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));          $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
7298          echo "\t</div>\n";          echo "\t</div>\n";
7299          // Fermeture du formulaire          // Fermeture du formulaire
7300          echo "\t</form>\n";          echo "\t</form>\n";
# Line 4009  class instruction extends instruction_ge Line 7311  class instruction extends instruction_ge
7311          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
7312          $this->checkAccessibility();          $this->checkAccessibility();
7313    
         // XXX APP  
   
         $f = $this->f;  
   
7314          // Récupération des valeur passées en POST ou GET          // Récupération des valeur passées en POST ou GET
7315          if($f->get_submitted_post_value("type_mise_a_jour") !== null) {          if($this->f->get_submitted_post_value("type_mise_a_jour") !== null) {
7316              $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");
7317          } elseif($f->get_submitted_get_value('type_mise_a_jour') !== null) {          } elseif($this->f->get_submitted_get_value('type_mise_a_jour') !== null) {
7318              $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');
7319          } else {          } else {
7320              $type_mise_a_jour = "";              $type_mise_a_jour = "";
7321          }          }
7322          if($f->get_submitted_post_value('date') !== null) {          if($this->f->get_submitted_post_value('date') !== null) {
7323              $date = $f->get_submitted_post_value('date');              $date = $this->f->get_submitted_post_value('date');
7324          } elseif($f->get_submitted_get_value('date') !== null) {          } elseif($this->f->get_submitted_get_value('date') !== null) {
7325              $date = $f->get_submitted_get_value('date');              $date = $this->f->get_submitted_get_value('date');
7326          } else {          } else {
7327              $date = "";              $date = "";
7328          }          }
7329          if($f->get_submitted_post_value('code_barres') !== null) {          if($this->f->get_submitted_post_value('code_barres') !== null) {
7330              $code_barres = $f->get_submitted_post_value('code_barres');              $code_barres = $this->f->get_submitted_post_value('code_barres');
7331          } elseif($f->get_submitted_get_value('code_barres') !== null) {          } elseif($this->f->get_submitted_get_value('code_barres') !== null) {
7332              $code_barres = $f->get_submitted_get_value('code_barres');              $code_barres = $this->f->get_submitted_get_value('code_barres');
7333          } else {          } else {
7334              $code_barres = "";              $code_barres = "";
7335          }          }
# Line 4043  class instruction extends instruction_ge Line 7341  class instruction extends instruction_ge
7341          $liste_champs=array();          $liste_champs=array();
7342    
7343          // Si le formulaire a été validé          // Si le formulaire a été validé
7344          if ($f->get_submitted_post_value('validation') !== null) {          if ($this->f->get_submitted_post_value('validation') !== null) {
7345              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)) {
7346    
7347                  //Vérification de l'existance de l'instruction                  // Vérification de l'existence de l'instruction
7348                  $sql = "SELECT instruction FROM ".DB_PREFIXE."instruction WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";                  $sql = "SELECT instruction
7349                  $res = $f->db->query($sql);                          FROM ".DB_PREFIXE."instruction
7350                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                              INNER JOIN ".DB_PREFIXE."dossier
7351                  $f->isDatabaseError($res);                                  ON dossier.dossier=instruction.dossier
7352                                INNER JOIN ".DB_PREFIXE."dossier_instruction_type
7353                                    ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
7354                                INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
7355                                    ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
7356                                INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
7357                                    ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
7358                                INNER JOIN ".DB_PREFIXE."groupe
7359                                    ON dossier_autorisation_type.groupe = groupe.groupe
7360                                WHERE code_barres='".$this->f->db->escapesimple($code_barres)."'";
7361    
7362                    // Ajout d'un filtre sur les groupes auxquels l'utilisateur a accès
7363                    $group_clause = array();
7364                    foreach ($_SESSION["groupe"] as $key => $value) {
7365                        $group_clause[$key] = "(groupe.code = '".$key."'";
7366                        if($value["confidentiel"] !== true) {
7367                            $group_clause[$key] .= " AND dossier_autorisation_type.confidentiel IS NOT TRUE";
7368                        }
7369                        $group_clause[$key] .= ")";
7370                    }
7371                    $conditions = implode(" OR ", $group_clause);
7372                    $sql .= " AND (" . $conditions . ")";
7373    
7374    
7375                    $res = $this->f->db->query($sql);
7376                    $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
7377                    $this->f->isDatabaseError($res);
7378    
7379                  if($res->numrows() == 1) {                  if($res->numrows() == 1) {
7380                      $liste_champs = explode(";", $type_mise_a_jour);                      $liste_champs = explode(";", $type_mise_a_jour);
7381                        $row =& $res->fetchRow(DB_FETCHMODE_ASSOC);
7382                        $instr = $this->f->get_inst__om_dbform(array(
7383                            "obj" => "instruction",
7384                            "idx" => $row['instruction'],
7385                        ));
7386                      // Mise à jour des dates après l'écran de verification                      // Mise à jour des dates après l'écran de verification
7387                      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);  
7388                          $valF = array();                          $valF = array();
7389                          foreach($instr->champs as $id => $champ) {                          foreach($instr->champs as $id => $champ) {
7390                              $valF[$champ] = $instr->val[$id];                              $valF[$champ] = $instr->val[$id];
7391                          }                          }
7392                          $valF['date_evenement']=$instr->dateDBToForm($valF['date_evenement']);                          $valF['date_evenement'] = $instr->dateDBToForm($valF['date_evenement']);
7393                          $valF['archive_date_complet']=$instr->dateDBToForm($valF['archive_date_complet']);                          $valF['archive_date_complet'] = $instr->dateDBToForm($valF['archive_date_complet']);
7394                          $valF['archive_date_rejet']=$instr->dateDBToForm($valF['archive_date_rejet']);                          $valF['archive_date_rejet'] = $instr->dateDBToForm($valF['archive_date_rejet']);
7395                          $valF['archive_date_limite']=$instr->dateDBToForm($valF['archive_date_limite']);                          $valF['archive_date_limite'] = $instr->dateDBToForm($valF['archive_date_limite']);
7396                          $valF['archive_date_notification_delai']=$instr->dateDBToForm($valF['archive_date_notification_delai']);                          $valF['archive_date_notification_delai'] = $instr->dateDBToForm($valF['archive_date_notification_delai']);
7397                          $valF['archive_date_decision']=$instr->dateDBToForm($valF['archive_date_decision']);                          $valF['archive_date_decision'] = $instr->dateDBToForm($valF['archive_date_decision']);
7398                          $valF['archive_date_validite']=$instr->dateDBToForm($valF['archive_date_validite']);                          $valF['archive_date_validite'] = $instr->dateDBToForm($valF['archive_date_validite']);
7399                          $valF['archive_date_achevement']=$instr->dateDBToForm($valF['archive_date_achevement']);                          $valF['archive_date_achevement'] = $instr->dateDBToForm($valF['archive_date_achevement']);
7400                          $valF['archive_date_chantier']=$instr->dateDBToForm($valF['archive_date_chantier']);                          $valF['archive_date_chantier'] = $instr->dateDBToForm($valF['archive_date_chantier']);
7401                          $valF['archive_date_conformite']=$instr->dateDBToForm($valF['archive_date_conformite']);                          $valF['archive_date_conformite'] = $instr->dateDBToForm($valF['archive_date_conformite']);
7402                          $valF['archive_date_dernier_depot']=$instr->dateDBToForm($valF['archive_date_dernier_depot']);                          $valF['archive_date_dernier_depot'] = $instr->dateDBToForm($valF['archive_date_dernier_depot']);
7403                          $valF['archive_date_limite_incompletude']=$instr->dateDBToForm($valF['archive_date_limite_incompletude']);                          $valF['archive_date_limite_incompletude'] = $instr->dateDBToForm($valF['archive_date_limite_incompletude']);
7404                          $valF['date_finalisation_courrier']=$instr->dateDBToForm($valF['date_finalisation_courrier']);                          $valF['date_finalisation_courrier'] = $instr->dateDBToForm($valF['date_finalisation_courrier']);
7405                          $valF['date_envoi_signature']=$instr->dateDBToForm($valF['date_envoi_signature']);                          $valF['date_envoi_signature'] = $instr->dateDBToForm($valF['date_envoi_signature']);
7406                          $valF['date_retour_signature']=$instr->dateDBToForm($valF['date_retour_signature']);                          $valF['date_retour_signature'] = $instr->dateDBToForm($valF['date_retour_signature']);
7407                          $valF['date_envoi_rar']=$instr->dateDBToForm($valF['date_envoi_rar']);                          $valF['date_envoi_rar'] = $instr->dateDBToForm($valF['date_envoi_rar']);
7408                          $valF['date_retour_rar']=$instr->dateDBToForm($valF['date_retour_rar']);                          $valF['date_retour_rar'] = $instr->dateDBToForm($valF['date_retour_rar']);
7409                          $valF['date_envoi_controle_legalite']=$instr->dateDBToForm($valF['date_envoi_controle_legalite']);                          $valF['date_envoi_controle_legalite'] = $instr->dateDBToForm($valF['date_envoi_controle_legalite']);
7410                          $valF['date_retour_controle_legalite']=$instr->dateDBToForm($valF['date_retour_controle_legalite']);                          $valF['date_retour_controle_legalite'] = $instr->dateDBToForm($valF['date_retour_controle_legalite']);
7411                            $valF['archive_date_cloture_instruction'] = $instr->dateDBToForm($valF['archive_date_cloture_instruction']);
7412                            $valF['archive_date_premiere_visite'] = $instr->dateDBToForm($valF['archive_date_premiere_visite']);
7413                            $valF['archive_date_derniere_visite'] = $instr->dateDBToForm($valF['archive_date_derniere_visite']);
7414                            $valF['archive_date_contradictoire'] = $instr->dateDBToForm($valF['archive_date_contradictoire']);
7415                            $valF['archive_date_retour_contradictoire'] = $instr->dateDBToForm($valF['archive_date_retour_contradictoire']);
7416                            $valF['archive_date_ait'] = $instr->dateDBToForm($valF['archive_date_ait']);
7417                            $valF['archive_date_transmission_parquet'] = $instr->dateDBToForm($valF['archive_date_transmission_parquet']);
7418    
7419                          foreach(explode(";", $type_mise_a_jour) as $maj_date) {                          foreach(explode(";", $type_mise_a_jour) as $maj_date) {
7420                              $valF[$maj_date]=$date;                              $valF[$maj_date]=$date;
# Line 4094  class instruction extends instruction_ge Line 7427  class instruction extends instruction_ge
7427                              $code_barres = "";                              $code_barres = "";
7428                                                            
7429                              //Désactivation de l'autocommit                              //Désactivation de l'autocommit
7430                              $f->db->autoCommit(false);                              $this->f->db->autoCommit(false);
7431                                                            
7432                              //On modifie les valeurs de l'instruction                              //On modifie les valeurs de l'instruction
7433                              $instr->setParameter('maj', 170);                              $instr->setParameter('maj', 170);
7434                              $instr->class_actions[170]["identifier"] =                              $instr->class_actions[170]["identifier"] =
7435                              "mise à jour des dates (depuis le menu suivi des pièces)";                              "mise à jour des dates (depuis le menu suivi des pièces)";
7436                              $retour = $instr->modifier($valF, $f->db, DEBUG);                              $retour = $instr->modifier($valF);
7437                                                            
7438                              //Si une erreur s'est produite, on défait les modifications                              //Si une erreur s'est produite, on défait les modifications
7439                              //qui ont été faites                              //qui ont été faites
# Line 4109  class instruction extends instruction_ge Line 7442  class instruction extends instruction_ge
7442                              }                              }
7443                              //Sinon, on valide en base de données les modifications                              //Sinon, on valide en base de données les modifications
7444                              else {                              else {
7445                                  $f->db->commit();                                  $this->f->db->commit();
7446                              }                              }
7447                                                            
7448                              // Variable correct retourné depuis la classe instruction                              // Variable correct retourné depuis la classe instruction
# Line 4150  class instruction extends instruction_ge Line 7483  class instruction extends instruction_ge
7483                                      INNER JOIN ".DB_PREFIXE."evenement ON                                      INNER JOIN ".DB_PREFIXE."evenement ON
7484                                          instruction.evenement=evenement.evenement                                          instruction.evenement=evenement.evenement
7485                                      WHERE code_barres='".$code_barres."'";                                      WHERE code_barres='".$code_barres."'";
7486                          $resInfo = $f->db->query($sqlInfo);                          $resInfo = $this->f->db->query($sqlInfo);
7487                          $f->isDatabaseError($resInfo);                          $this->f->isDatabaseError($resInfo);
7488                          $infos = $resInfo->fetchRow(DB_FETCHMODE_ASSOC);                          $infos = $resInfo->fetchRow(DB_FETCHMODE_ASSOC);
7489    
7490                          // Vérification de la non modification des dates de suivi                          // Vérification de la non modification des dates de suivi
7491                          foreach(explode(";", $type_mise_a_jour) as $champ) {                          foreach(explode(";", $type_mise_a_jour) as $champ) {
7492                                if ($champ === 'date_envoi_controle_legalite') {
7493                                    if ($instr->is_sent_to_cl() === true) {
7494                                        $error = __("Les dates de suivis ne peuvent etre modifiees");
7495                                        $date_error = true;
7496                                        break;
7497                                    }
7498                                }
7499                              if($infos[$champ] != "" AND $infos[$champ] != $date) {                              if($infos[$champ] != "" AND $infos[$champ] != $date) {
7500                                  $error = _("Les dates de suivis ne peuvent etre modifiees");                                  $error = _("Les dates de suivis ne peuvent etre modifiees");
7501                                  $date_error = true;                                  $date_error = true;
7502                                    break;
7503                              }                              }
7504                          }                          }
7505                      }                      }
# Line 4176  class instruction extends instruction_ge Line 7517  class instruction extends instruction_ge
7517           */           */
7518          // Affichage du message de validation ou d'erreur          // Affichage du message de validation ou d'erreur
7519          if (isset($message) && isset($message_class) && $message != "") {          if (isset($message) && isset($message_class) && $message != "") {
7520              $f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
7521          }          }
7522          // Affichage du message d'erreur          // Affichage du message d'erreur
7523          if(!empty($error)) {          if(!empty($error)) {
7524              $f->displayMessage("error", $error);              $this->f->displayMessage("error", $error);
7525          }          }
7526    
7527          // Affichage du message de validation de la saisie          // Affichage du message de validation de la saisie
7528          if($correct === true) {          if($correct === true) {
7529              $f->displayMessage("ok", _("Saisie enregistree"));              $this->f->displayMessage("ok", _("Saisie enregistree"));
7530          }          }
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
7531          // Ouverture du formulaire          // Ouverture du formulaire
7532          echo "\t<form";          echo "\t<form";
7533          echo " method=\"post\"";          echo " method=\"post\"";
# Line 4206  class instruction extends instruction_ge Line 7545  class instruction extends instruction_ge
7545              $champs = array("type_mise_a_jour", "date", "code_barres");              $champs = array("type_mise_a_jour", "date", "code_barres");
7546          }          }
7547          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
7548          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
7549                "validation" => 0,
7550                "maj" => 0,
7551                "champs" => $champs,
7552            ));
7553          // Paramétrage des champs du formulaire          // Paramétrage des champs du formulaire
7554          // Parametrage du champ type_mise_a_jour          // Parametrage du champ type_mise_a_jour
7555          $form->setLib("type_mise_a_jour", _("Date a mettre a jour")."* :");          $form->setLib("type_mise_a_jour", _("Date a mettre a jour")."* :");
# Line 4236  class instruction extends instruction_ge Line 7579  class instruction extends instruction_ge
7579          $contenu[1][4] = _("date de retour de controle de legalite");          $contenu[1][4] = _("date de retour de controle de legalite");
7580    
7581          $contenu[0][5] = "date_retour_rar";          $contenu[0][5] = "date_retour_rar";
7582          $contenu[1][5] = _("date de retour de l'AR");          $contenu[1][5] = __("date de notification du correspondant");
7583    
7584          $form->setSelect("type_mise_a_jour", $contenu);          $form->setSelect("type_mise_a_jour", $contenu);
7585    
# Line 4296  class instruction extends instruction_ge Line 7639  class instruction extends instruction_ge
7639              $form->setType("autorite_competente", "static");              $form->setType("autorite_competente", "static");
7640              $form->setVal("autorite_competente", $infos['autorite_competente']);              $form->setVal("autorite_competente", $infos['autorite_competente']);
7641    
7642              // Parametrage des libellés d'envoi avec RAR              // Parametrage des libellés d'envoi avec AR
7643              $form->setLib("date_envoi_rar", _("date_envoi_rar")." :");              $form->setLib("date_envoi_rar", __("date_envoi_ar")." :");
7644              $form->setLib("date_retour_rar", _("date_retour_rar")." :");              $form->setLib("date_retour_rar", __("date_notification")." :");
7645    
7646              $form->setLib("date_envoi_signature", _("date_envoi_signature")." :");              $form->setLib("date_envoi_signature", _("date_envoi_signature")." :");
7647              $form->setLib("date_retour_signature", _("date_retour_signature")." :");              $form->setLib("date_retour_signature", _("date_retour_signature")." :");
# Line 4332  class instruction extends instruction_ge Line 7675  class instruction extends instruction_ge
7675          echo "\t<div class=\"formControls\">\n";          echo "\t<div class=\"formControls\">\n";
7676          //          //
7677          if(!$date_error) {          if(!$date_error) {
7678              $f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));              $this->f->layout->display_form_button(array("value" => _("Valider"), "name" => "validation"));
7679          }          }
7680          // Si pas sur l'écran de validation          // Si pas sur l'écran de validation
7681          if(isset($infos)) {          if(isset($infos)) {
7682              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";
7683                  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;
7684              echo "\">Retour</a>";              echo "\">Retour</a>";
7685          }          }
# Line 4353  class instruction extends instruction_ge Line 7696  class instruction extends instruction_ge
7696      function view_pdf_lettre_rar() {      function view_pdf_lettre_rar() {
7697          // Vérification de l'accessibilité sur l'élément          // Vérification de l'accessibilité sur l'élément
7698          $this->checkAccessibility();          $this->checkAccessibility();
7699            //
7700            $this->f->disableLog();
7701    
7702          // XXX APP          if($this->f->get_submitted_get_value('liste') != null) {
7703                $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'));  
7704    
7705              // Classe permettant la mise en page de l'édition pdf              // Classe permettant la mise en page de l'édition pdf
7706              require_once "../obj/pdf_lettre_rar.class.php";              require_once "../obj/pdf_lettre_rar.class.php";
7707              $pdf_lettre_rar = new pdf_lettre_rar('P', 'mm', 'A4');              $pdf_lettre_rar = new pdf_lettre_rar('P', 'mm', 'A4');
7708              // Initialisation de la mise en page              // Initialisation de la mise en page
7709              $pdf_lettre_rar->init($f);              $pdf_lettre_rar->init($this->f);
7710    
7711              foreach ($listeCodeBarres as $code_barres) {              foreach ($listeCodeBarres as $code_barres) {
7712    
7713                    // On récupère le dossier
7714                    $sql = "SELECT dossier
7715                            FROM " . DB_PREFIXE . "instruction
7716                            WHERE code_barres = '" . $code_barres . "'";
7717                    $dossier = $this->f->db->getOne($sql);
7718                    $this->f->addToLog(__METHOD__."(): db->getOne(\"".$sql."\")", VERBOSE_MODE);
7719                    $this->f->isDatabaseError($dossier);
7720                    $inst_dossier = $this->f->get_inst__om_dbform(array(
7721                        "obj" => "dossier",
7722                        "idx" => $dossier,
7723                    ));
7724    
7725                    // En fonction du type de dossier, on récupère un demandeur différent dans les requêtes
7726                    $groupe = $inst_dossier->get_type_affichage_formulaire();
7727                    switch ($groupe) {
7728                        case 'CTX IN':
7729                            $sql_demandeur = "(lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='plaignant')";
7730                            break;
7731                        case 'CTX RE':
7732                            $sql_demandeur = "(lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='requerant')";
7733                            break;
7734                        case 'ADS':
7735                        case 'DPC':
7736                        case 'CONSULTATION ENTRANTE':
7737                        default:
7738                            $sql_demandeur = "((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire') OR demandeur.type_demandeur='delegataire')";
7739                            break;
7740                    }
7741    
7742                  // 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é
7743                  $sql = "SELECT                  $sql = "SELECT
7744                              dossier.dossier_libelle,                              dossier.dossier_libelle,
# Line 4396  class instruction extends instruction_ge Line 7764  class instruction extends instruction_ge
7764                          inner join ".DB_PREFIXE."demandeur on                          inner join ".DB_PREFIXE."demandeur on
7765                              demandeur.demandeur=lien_dossier_demandeur.demandeur                              demandeur.demandeur=lien_dossier_demandeur.demandeur
7766                          WHERE code_barres='".$code_barres."'                          WHERE code_barres='".$code_barres."'
7767                              AND ((lien_dossier_demandeur.petitionnaire_principal IS TRUE AND demandeur.type_demandeur='petitionnaire')                              AND " . $sql_demandeur . "
                             OR demandeur.type_demandeur='delegataire')  
7768                          GROUP BY dossier.dossier_libelle, evenement.type, phase.code, division.libelle";                          GROUP BY dossier.dossier_libelle, evenement.type, phase.code, division.libelle";
7769    
7770                  $res = $f->db->query($sql);                  $res = $this->f->db->query($sql);
7771                  $f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->query(\"".$sql."\")", VERBOSE_MODE);
7772                  $f->isDatabaseError($res);                  $this->f->isDatabaseError($res);
7773                  $testDemandeur = $res->fetchrow(DB_FETCHMODE_ASSOC);                  $testDemandeur = $res->fetchrow(DB_FETCHMODE_ASSOC);
7774                                    
7775    
# Line 4451  class instruction extends instruction_ge Line 7818  class instruction extends instruction_ge
7818                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {                  if($testDemandeur['type'] != 'arrete' AND $testDemandeur['nbdemandeur'] > 1) {
7819                      $sqlAdresse .= " AND demandeur.type_demandeur='delegataire'";                      $sqlAdresse .= " AND demandeur.type_demandeur='delegataire'";
7820                  } else {                  } else {
7821                      $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";
7822                  }                  }
7823    
7824                  $resAdresse = $f->db->query($sqlAdresse);                  $resAdresse = $this->f->db->query($sqlAdresse);
7825                  $adresse_dest = $resAdresse->fetchrow(DB_FETCHMODE_ASSOC);                  $adresse_dest = $resAdresse->fetchrow(DB_FETCHMODE_ASSOC);
7826                  $f->addToLog(__METHOD__.": db->query(\"".$sqlAdresse."\")", VERBOSE_MODE);                  $this->f->addToLog(__METHOD__.": db->query(\"".$sqlAdresse."\")", VERBOSE_MODE);
7827                  $f->isDatabaseError($resAdresse);                  $this->f->isDatabaseError($resAdresse);
7828    
7829                  // Création adresse destinataire sans ligne vide                  // Création adresse destinataire sans ligne vide
7830                  $adresse_destinataire = array();                  $adresse_destinataire = array();
# Line 4487  class instruction extends instruction_ge Line 7854  class instruction extends instruction_ge
7854                  $specifique_content[] = $testDemandeur['dossier_libelle'];                  $specifique_content[] = $testDemandeur['dossier_libelle'];
7855                  $specifique_content[] = "|||||".$adresse_dest['code_barres']."|||||";                  $specifique_content[] = "|||||".$adresse_dest['code_barres']."|||||";
7856                  unset($adresse_dest['code_barres']);                  unset($adresse_dest['code_barres']);
   
7857                  // Ajout d'une page aux pdf                  // Ajout d'une page aux pdf
7858                  $pdf_lettre_rar->addLetter($adresse_destinataire, $specifique_content, $testDemandeur['code_phase']);                  $pdf_lettre_rar->addLetter($adresse_destinataire, $specifique_content, $testDemandeur['code_phase']);
7859    
7860              }              }
7861              $pdf_output = $pdf_lettre_rar->output("lettre_rar".date("dmYHis").".pdf","S");              $pdf_output = $pdf_lettre_rar->output("lettre_rar".date("dmYHis").".pdf","S");
7862              require_once PATH_OPENMAIRIE."om_edition.class.php";              $om_edition = $this->f->get_inst__om_edition();
             $om_edition = new edition();  
7863              $om_edition->expose_pdf_output($pdf_output, "lettre_rar".date("dmYHis").".pdf");              $om_edition->expose_pdf_output($pdf_output, "lettre_rar".date("dmYHis").".pdf");
7864          }          }
7865      }      }
# Line 4557  class instruction extends instruction_ge Line 7922  class instruction extends instruction_ge
7922                              $message .= "<a class='om-prev-icon pdf-16'";                              $message .= "<a class='om-prev-icon pdf-16'";
7923                              $message .= " id=\"generer_bordereau_envoi_maire\"";                              $message .= " id=\"generer_bordereau_envoi_maire\"";
7924                              $message .= " title=\""._("Bordereau")."\"";                              $message .= " title=\""._("Bordereau")."\"";
7925                              $message .= " href='../scr/form.php?obj=instruction";                              $message .= " href='".OM_ROUTE_FORM."&obj=instruction";
7926                              $message .= "&action=200";                              $message .= "&action=200";
7927                              $message .= "&idx=".$id_instruction."'";                              $message .= "&idx=".$id_instruction."'";
7928                              $message .= " target='_blank'>";                              $message .= " target='_blank'>";
# Line 4598  class instruction extends instruction_ge Line 7963  class instruction extends instruction_ge
7963              $this->f->displayMessage($message_class, $message);              $this->f->displayMessage($message_class, $message);
7964          }          }
7965    
         // Inclusion de la classe de gestion des formulaires  
         require_once "../obj/om_formulaire.class.php";  
7966          // Ouverture du formulaire          // Ouverture du formulaire
7967          $datasubmit = $this->getDataSubmit();          $datasubmit = $this->getDataSubmit();
7968          echo "\n<!-- ########## START DBFORM ########## -->\n";          echo "\n<!-- ########## START DBFORM ########## -->\n";
# Line 4616  class instruction extends instruction_ge Line 7979  class instruction extends instruction_ge
7979          $champs = array("code_barres","date");          $champs = array("code_barres","date");
7980    
7981          // Création d'un nouvel objet de type formulaire          // Création d'un nouvel objet de type formulaire
7982          $form = new formulaire(NULL, 0, 0, $champs);          $form = $this->f->get_inst__om_formulaire(array(
7983                "validation" => 0,
7984                "maj" => 0,
7985                "champs" => $champs,
7986            ));
7987    
7988          $template_required_label = '%s *';          $template_required_label = '%s *';
7989          // Parametrage du champ code_barres          // Parametrage du champ code_barres
# Line 4675  class instruction extends instruction_ge Line 8042  class instruction extends instruction_ge
8042      }      }
8043    
8044      /**      /**
8045       * Retourne l'événement d'instruction dont on donne le code-barres       * VIEW - view_rapport_instruction.
8046         *
8047         * Ouvre le sous-formulaire en ajaxIt dans un overlay.
8048         * Cette action est bindée pour utiliser la fonction popUpIt.
8049         *
8050         * @return void
8051         */
8052        function view_overlay_notification_manuelle() {
8053    
8054            // Vérification de l'accessibilité sur l'élément
8055            $this->checkAccessibility();
8056    
8057            printf(
8058                '<script type="text/javascript" >
8059                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=411&idx=%3$s\', 1);
8060                </script>',
8061                'instruction_notification_manuelle',
8062                OM_ROUTE_SOUSFORM,
8063                $this->getVal($this->clePrimaire),
8064                $this->getVal('dossier')
8065            );
8066        }
8067    
8068        /**
8069         * VIEW - view_overlay_notification_service_consulte.
8070         *
8071         * Ouvre le sous-formulaire de notification des services consulte
8072         * en ajaxIt dans un overlay.
8073         * Cette action est bindée pour utiliser la fonction popUpIt.
8074         *
8075         * @return void
8076         */
8077        function view_overlay_notification_service_consulte() {
8078    
8079            // Vérification de l'accessibilité sur l'élément
8080            $this->checkAccessibility();
8081    
8082            printf(
8083                '<script type="text/javascript" >
8084                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=420&idx=%3$s\', 1);
8085                </script>',
8086                'instruction_notification_manuelle',
8087                OM_ROUTE_SOUSFORM,
8088                $this->getVal($this->clePrimaire),
8089                $this->getVal('dossier')
8090            );
8091        }
8092        
8093        /**
8094         * VIEW - overlay_notification_tiers_consulte.
8095         *
8096         * Ouvre le sous-formulaire de notification des tiers consulte
8097         * en ajaxIt dans un overlay.
8098         * Cette action est bindée pour utiliser la fonction popUpIt.
8099         *
8100         * @return void
8101         */
8102        function view_overlay_notification_tiers_consulte() {
8103    
8104            // Vérification de l'accessibilité sur l'élément
8105            $this->checkAccessibility();
8106    
8107            printf(
8108                '<script type="text/javascript" >
8109                    overlayIt(\'%1$s\',\'%2$s&objsf=%1$s&idxformulaire=%4$s&retourformulaire=dossier_instruction&obj=%1$s&action=430&idx=%3$s\', 1);
8110                </script>',
8111                'instruction_notification_manuelle',
8112                OM_ROUTE_SOUSFORM,
8113                $this->getVal($this->clePrimaire),
8114                $this->getVal('dossier')
8115            );
8116        }
8117        /**
8118         * Retourne l'événement d'instruction dont on donne le code-barres, avec un filtre
8119         * pour exclure les dossiers du groupe contentieux.
8120       *       *
8121       * @param   [string]  $barcode  numéro du code-barres       * @param   [string]  $barcode  numéro du code-barres
8122       * @return  [mixed]             ID de son instruction ou null si aucun code       * @return  [mixed]             ID de son instruction ou null si aucun code
# Line 4684  class instruction extends instruction_ge Line 8125  class instruction extends instruction_ge
8125          // Begin          // Begin
8126          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
8127          // Vérification de l'existence de l'événement d'instruction          // Vérification de l'existence de l'événement d'instruction
8128          // pour le code-barres donné          // pour le code-barres donné, en excluant les dossiers liés au groupe CTX
8129          $sql = "SELECT instruction          $sql = "SELECT instruction
8130              FROM ".DB_PREFIXE."instruction                  FROM ".DB_PREFIXE."instruction
8131              WHERE code_barres = '".$this->f->db->escapesimple($barcode)."'";                      INNER JOIN ".DB_PREFIXE."dossier
8132                            ON dossier.dossier=instruction.dossier
8133                        INNER JOIN ".DB_PREFIXE."dossier_instruction_type
8134                            ON dossier.dossier_instruction_type = dossier_instruction_type.dossier_instruction_type
8135                        INNER JOIN ".DB_PREFIXE."dossier_autorisation_type_detaille
8136                            ON dossier_instruction_type.dossier_autorisation_type_detaille = dossier_autorisation_type_detaille.dossier_autorisation_type_detaille
8137                        INNER JOIN ".DB_PREFIXE."dossier_autorisation_type
8138                            ON dossier_autorisation_type_detaille.dossier_autorisation_type = dossier_autorisation_type.dossier_autorisation_type
8139                        INNER JOIN ".DB_PREFIXE."groupe
8140                            ON dossier_autorisation_type.groupe = groupe.groupe
8141                                AND groupe.code != 'CTX'
8142                    WHERE code_barres = '".$this->f->db->escapesimple($barcode)."'";
8143          $res = $this->f->db->getOne($sql);          $res = $this->f->db->getOne($sql);
8144          $this->f->addToLog(__METHOD__." : db->getOne(\"".$sql."\")", VERBOSE_MODE);          $this->f->addToLog(__METHOD__." : db->getOne(\"".$sql."\")", VERBOSE_MODE);
8145          $this->f->isDatabaseError($res);          $this->f->isDatabaseError($res);
# Line 4710  class instruction extends instruction_ge Line 8162  class instruction extends instruction_ge
8162          // Begin          // Begin
8163          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
8164          // Requête          // Requête
8165          $res = $this->db->autoExecute(          $res = $this->f->db->autoExecute(
8166              DB_PREFIXE.$this->table,              DB_PREFIXE.$this->table,
8167              $valF,              $valF,
8168              DB_AUTOQUERY_UPDATE,              DB_AUTOQUERY_UPDATE,
# Line 4729  class instruction extends instruction_ge Line 8181  class instruction extends instruction_ge
8181       * validation du formulaire d'ajout.       * validation du formulaire d'ajout.
8182       * @param array $val tableau des valeurs retournées par le formulaire       * @param array $val tableau des valeurs retournées par le formulaire
8183       */       */
8184      function setValFAjout($val) {      function setValFAjout($val = array()) {
8185          // 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
8186          // par un utilisateur de commune sur un dossier instruit par la comcom          // par un utilisateur de commune sur un dossier instruit par la comcom
8187          if($this->f->isInstrCanChangeDecision($this->valF["dossier"])) {          if ($this->isInstrCanChangeDecision($this->valF["dossier"])) {
8188              $this->valF['created_by_commune'] = true;              $this->valF['created_by_commune'] = true;
8189          }          }
     }  
8190    
     /**  
      * Récupère l'instance du dossier d'instruction  
      *  
      * @param mixed Identifiant du dossier d'instruction  
      *  
      * @return object  
      */  
     function get_inst_dossier($dossier = null) {  
8191          //          //
8192          return $this->get_inst_common("dossier", $dossier);          if ($this->evenement_has_an_edition($this->valF['evenement']) === false) {
8193                if (isset($this->valF['flag_edition_integrale']) === true) {
8194                    unset($this->valF['flag_edition_integrale']);
8195                }
8196                if (isset($this->valF['signataire_arrete']) === true) {
8197                    unset($this->valF['signataire_arrete']);
8198                }
8199            }
8200      }      }
8201    
8202    
8203      /**      /**
8204       * Récupère l'instance d'un événement de workflow.       * Récupère l'instance d'un événement de workflow.
8205       *       *
# Line 4891  class instruction extends instruction_ge Line 8342  class instruction extends instruction_ge
8342          // 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
8343          // dites de TREATMENT.          // dites de TREATMENT.
8344          $this->begin_treatment(__METHOD__);          $this->begin_treatment(__METHOD__);
8345          // Définition des paramètres          $message = __('Erreur de paramétrage :');
8346          $p_objet = 'param_courriel_de_notification_commune_objet_depuis_instruction';          $erreurParametrage = false;
8347          $p_modele = 'param_courriel_de_notification_commune_modele_depuis_instruction';          // Récupération du paramétrage de la collectivité du dossier
         $p_courriel = 'param_courriel_de_notification_commune';  
         // Définition des variables de substitution  
8348          $id_di = $this->getVal('dossier');          $id_di = $this->getVal('dossier');
         $id_inst = $this->getVal($this->clePrimaire);  
         // Instanciation du DI  
8349          $di = $this->get_inst_dossier($id_di);          $di = $this->get_inst_dossier($id_di);
         // Récupération du paramétrage de la collectivité du dossier  
8350          $collectivite_di = $di->getVal('om_collectivite');          $collectivite_di = $di->getVal('om_collectivite');
8351          $params_mono = $this->f->getCollectivite($collectivite_di);          // Récupération de l'url permettant d'accèder à l'instruction et au dossier
8352          // Récupération du paramétrage de la collectivité multi          $urlAcces = $this->f->get_parametre_notification_url_acces($collectivite_di);
8353          $collectivite_multi = $this->f->get_idx_collectivite_multi();          if (empty($urlAcces) && empty(PATH_BASE_URL)) {
8354          $params_multi = $this->f->getCollectivite($collectivite_multi);              $erreurParametrage = true;
8355          // Vérification de l'objet (obligatoirement multi)              $message .= '<br>'.__("* l'url de notification n'est pas correctement paramétré");
8356          $objet = null;          }
8357          if (isset($params_multi[$p_objet]) === true  
8358              && $params_multi[$p_objet] !== '') {          // Récupération de la liste des mails
8359              $objet = $params_multi[$p_objet];          $adresses = $this->f->get_param_courriel_de_notification_commune($collectivite_di);
8360          }          if (empty($adresses)) {
8361          // Vérification du modèle mono en priorité              $erreurParametrage = true;
8362          $modele = null;              $message .= '<br>'.__("* aucun courriel valide de destinataire de la commune");
8363          if (isset($params_mono[$p_modele]) === true          }
8364              && $params_mono[$p_modele] !== '') {  
8365              $modele = $params_mono[$p_modele];          // Vérification du paramétrage des mails
8366                        $paramMail = $this->f->get_notification_commune_parametre_courriel_type($collectivite_di);
8367          }          if (empty($paramMail) || empty($paramMail['parametre_courriel_type_message'])) {
8368          // Sinon vérification du modèle multi              $erreurParametrage = true;
8369          if ($modele === null              $message .= '<br>'.__("* le modèle du courriel envoyé aux communes est vide");
8370              && isset($params_multi[$p_modele]) === true          }
8371              && $params_multi[$p_modele] !== '') {          if (empty($paramMail) || empty($paramMail['parametre_courriel_type_titre'])) {
8372              $modele = $params_multi[$p_modele];              $erreurParametrage = true;
8373          }              $message .= '<br>'.__("* l'objet du courriel envoyé aux communes est vide");
8374          // Vérification des adresses de courriel mono          }
8375          $courriels_valides = array();  
8376          $courriels_invalides = array();          // Si il y a des erreurs de paramétrage on ne déclenche pas la notification et
8377          if (isset($params_mono[$p_courriel]) === true          // un message a destination de l'utilisateur est affiché
8378              && $params_mono[$p_courriel] !== '') {          if ($erreurParametrage) {
8379              // Un mail par ligne              $message .= '<br>'.__("Veuillez contacter votre administrateur.");
8380              $adresses = explode("\n", $params_mono[$p_courriel]);              $this->addToMessage($message);
8381              // Vérification de la validité de chaque mail avec preg_match              return $this->end_treatment(__METHOD__, false);
             foreach ($adresses as $adresse) {  
                 $adresse = trim($adresse);  
                 if ($this->f->checkValidEmailAddress($adresse) === 1) {  
                     $courriels_valides[] = $adresse;  
                 } else {  
                     $courriels_invalides[] = $adresse;  
                 }  
             }  
8382          }          }
8383          // Vérification du paramétrage global :  
8384          // on stoppe le traitement si au moins un paramètre est incorrect          // Création d'un notification et de sa tâche associé pour chaque mail
8385          if ($objet === null          foreach ($adresses as $adresse) {
8386              || $modele === null              // Ajout de la notif et récupération de son id
8387              || count($courriels_valides) === 0              $destinataire = array(
8388              || count($courriels_invalides) > 0) {                  'destinataire' => $adresse,
8389              // On construit le message d'erreur adéquat                  'courriel' => $adresse
8390              $this->addToMessage(_('Erreur de paramétrage :'));              );
8391              if ($objet === null) {              $idNotif = $this->ajouter_notification(
8392                  $this->addToMessage(_("* l'objet du courriel envoyé aux communes est vide"));                  $this->getVal($this->clePrimaire),
8393              }                  $this->f->get_connected_user_login_name(),
8394              if ($modele === null) {                  $destinataire,
8395                  $this->addToMessage(_("* le modèle du courriel envoyé aux communes est vide"));                  $collectivite_di
8396                );
8397                if ($idNotif === false) {
8398                    $this->addToMessage(__("Veuillez contacter votre administrateur."));
8399                    return $this->end_treatment(__METHOD__, false);
8400              }              }
8401              if (count($courriels_valides) === 0) {              // Création de la tache en lui donnant l'id de la notification
8402                  $this->addToMessage(_("* aucun courriel valide de destinataire de la commune"));              $notification_by_task = $this->notification_by_task(
8403                    $idNotif,
8404                    $this->getVal('dossier'),
8405                    'mail',
8406                    'notification_commune'
8407                );
8408                if ($notification_by_task === false) {
8409                    $this->addToMessage(__("Erreur lors de la préparation de la notification des communes."));
8410                    $this->addToMessage(__("Veuillez contacter votre administrateur."));
8411                    return $this->end_treatment(__METHOD__, false);
8412              }              }
8413              if (count($courriels_invalides) > 0) {          }
8414                  $courriels_invalides = implode(', ', $courriels_invalides);          $this->addToMessage(__('La commune a été notifiée.'));
8415                  $this->addToMessage(_("* un ou plusieurs courriels des destinataires de la commune sont invalides : ").$courriels_invalides);          return $this->end_treatment(__METHOD__, true);
8416        }
8417    
8418        /**
8419         * Récupère l'instance de l'instructeur
8420         *
8421         * @param integer $instructeur Identifiant de l'instructeur.
8422         *
8423         * @return object
8424         */
8425        protected function get_inst_instructeur($instructeur) {
8426            //
8427            return $this->get_inst_common("instructeur", $instructeur);
8428        }
8429    
8430    
8431        /**
8432         * Récupère l'instance de l'utilisateur
8433         *
8434         * @param integer $om_utilisateur Identifiant de l'utilisateur.
8435         *
8436         * @return object
8437         */
8438        protected function get_inst_om_utilisateur($om_utilisateur) {
8439            //
8440            return $this->get_inst_common("om_utilisateur", $om_utilisateur);
8441        }
8442    
8443    
8444        /**
8445         * Récupère l'instance de la division.
8446         *
8447         * @param integer $division Identifiant de la division.
8448         *
8449         * @return object
8450         */
8451        protected function get_inst_division($division) {
8452            //
8453            return $this->get_inst_common("division", $division);
8454        }
8455    
8456    
8457         /**
8458         * Récupère l'instance de la direction.
8459         *
8460         * @param integer $direction Identifiant de la direction.
8461         *
8462         * @return object
8463         */
8464        protected function get_inst_direction($direction) {
8465            //
8466            return $this->get_inst_common("direction", $direction);
8467        }
8468    
8469    
8470        /**
8471         * Récupère la collectivité d'un instructeur en passant par sa division puis
8472         * par sa direction.
8473         *
8474         * @param integer $instructeur Identifiant de l'instructeur.
8475         *
8476         * @return integer
8477         */
8478        protected function get_instructeur_om_collectivite($instructeur) {
8479            // Chemin vers la collectivité d'un instructeur
8480            $inst_instr = $this->get_inst_instructeur($instructeur);
8481            $inst_division = $this->get_inst_division($inst_instr->getVal('division'));
8482            $inst_direction = $this->get_inst_direction($inst_division->getVal('direction'));
8483    
8484            // Collectivité
8485            $om_collectivite = $inst_direction->getVal('om_collectivite');
8486    
8487            //
8488            return $om_collectivite;
8489        }
8490    
8491        /*
8492         * CONDITION - can_user_access_dossier_contexte_ajout
8493         *
8494         * Vérifie que l'utilisateur a bien accès au dossier d'instruction passé dans le
8495         * formulaire d'ajout.
8496         * Cette méthode vérifie que l'utilisateur est lié au groupe du dossier, et si le
8497         * dossier est confidentiel qu'il a accès aux confidentiels de ce groupe.
8498         *
8499         */
8500        function can_user_access_dossier_contexte_ajout() {
8501    
8502            ($this->f->get_submitted_get_value('idxformulaire') !== null ? $id_dossier =
8503                $this->f->get_submitted_get_value('idxformulaire') : $id_dossier = "");
8504            //
8505            if ($id_dossier !== "") {
8506                $dossier = $this->f->get_inst__om_dbform(array(
8507                    "obj" => "dossier_instruction",
8508                    "idx" => $id_dossier,
8509                ));
8510                //
8511                return $dossier->can_user_access_dossier();
8512            }
8513            return false;
8514        }
8515    
8516       /*
8517         * CONDITION - can_user_access_dossier
8518         *
8519         * Vérifie que l'utilisateur a bien accès au dossier lié à l'instruction instanciée.
8520         * Cette méthode vérifie que l'utilisateur est lié au groupe du dossier, et si le
8521         * dossier est confidentiel qu'il a accès aux confidentiels de ce groupe.
8522         *
8523         */
8524        function can_user_access_dossier_contexte_modification() {
8525    
8526            $id_dossier = $this->getVal('dossier');
8527            //
8528            if ($id_dossier !== "" && $id_dossier !== null) {
8529                $dossier = $this->f->get_inst__om_dbform(array(
8530                    "obj" => "dossier_instruction",
8531                    "idx" => $id_dossier,
8532                ));
8533                //
8534                return $dossier->can_user_access_dossier();
8535            }
8536            return false;
8537        }
8538    
8539        /**
8540         * TREATMENT - envoyer_a_signature_sans_relecture
8541         *
8542         * Permet d'envoyer le document de l'instruction au parapheur pour signature sans relecture
8543         *
8544         * @return boolean true si l'envoi a été effectué avec succès false sinon
8545         */
8546        function envoyer_a_signature_sans_relecture() {
8547            return $this->envoyer_a_signature();
8548        }
8549    
8550        /**
8551         * TREATMENT - envoyer_a_signature_avec_relecture
8552         *
8553         * Permet d'envoyer le document de l'instruction au parapheur pour signature avec relecture
8554         *
8555         * @return boolean true si l'envoi a été effectué avec succès false sinon
8556         */
8557        function envoyer_a_signature_avec_relecture() {
8558            $is_forced_view_files = true;
8559            return $this->envoyer_a_signature($is_forced_view_files);
8560        }
8561    
8562        /**
8563         * TREATMENT - envoyer_a_signature
8564         *
8565         * Permet d'envoyer le document de l'instruction au parapheur pour signature
8566         *
8567         * @param  boolean  $is_forced_view_files  Indique si il y a une relecture (true) ou non (false)
8568         *
8569         * @return boolean true si l'envoi a été effectué avec succès false sinon
8570         */
8571        function envoyer_a_signature($is_forced_view_files = false) {
8572            $this->begin_treatment(__METHOD__);
8573            $this->correct = true;
8574    
8575            // Instanciation de l'objet signataire_arrete
8576            $inst_signataire_arrete = $this->f->get_inst__om_dbform(array(
8577                'obj' => 'signataire_arrete',
8578                'idx' => $this->getVal('signataire_arrete'),
8579            ));
8580    
8581            // Instanciation de l'objet dossier
8582            $inst_dossier = $this->f->get_inst__om_dbform(array(
8583                'obj' => 'dossier',
8584                'idx' => $this->getVal('dossier'),
8585            ));
8586    
8587            // Récupération du document à signer
8588            $file = $this->f->storage->get($this->getVal('om_fichier_instruction'));
8589            if ($file === OP_FAILURE) {
8590                $this->correct = false;
8591                $this->addToMessage(__("Une erreur est survenue lors de la récupération du contenu du document de l'instruction."));
8592                // Termine le traitement
8593                return $this->end_treatment(__METHOD__, false);
8594            }
8595    
8596            // Initialisation des paramètre à passer pour l'envoi en signature
8597            $data = array(
8598                "om_utilisateur_email" => $this->f->om_utilisateur['email'],
8599                "om_utilisateur_nom" => $this->f->om_utilisateur['nom'],
8600                "signataire_arrete_email" => $inst_signataire_arrete->getVal('email'),
8601                "signataire_arrete_nom" => $inst_signataire_arrete->getVal('nom'),
8602                "signataire_arrete_prenom" => $inst_signataire_arrete->getVal('prenom'),
8603                // Permet d'envoyer en signature l'instruction le jour de la date limite
8604                "date_limite_instruction" => $this->compute_date_limite(1),
8605                "dossier" => $this->getVal('dossier'),
8606                "is_forced_view_files" => $is_forced_view_files,
8607                'commentaire_signature' => $is_forced_view_files === true ? __('relecture demandee.') : null
8608            );
8609    
8610            // Initialisation des métadonnées
8611            $metadonnee_dossier = $file['metadata'];
8612            // récupération de l'extension du fichier
8613            $extension = substr($metadonnee_dossier['filename'], strrpos($metadonnee_dossier['filename'], '.'));
8614            // Modification du libellé du document transmis au parapheur
8615            // pour le mettre sous la forme : instruction_xxx_libelle_lettretype.extension
8616            $metadonnee_dossier['filename'] = $this->getDocumentLibelle().$extension;
8617            $metadonnee_dossier['titre_document'] = $this->getDocumentTitre();
8618    
8619            $metadonnee_dossier['url_di'] = sprintf(
8620                '%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',
8621                $this->f->get_param_base_path_metadata_url_di() !== null ? $this->f->get_param_base_path_metadata_url_di() : PATH_BASE_URL,
8622                $this->getVal($this->clePrimaire)
8623            );
8624    
8625            $optional_data = null;
8626            // Si il y a des paramètres supplémentaire spécifié dans le signataire alors on les récupère
8627            if ($inst_signataire_arrete->getVal('parametre_parapheur') !== null && $inst_signataire_arrete->getVal('parametre_parapheur') !== '') {
8628                $optional_data = json_decode($inst_signataire_arrete->getVal('parametre_parapheur'), true);
8629                if (json_last_error() !== JSON_ERROR_NONE) {
8630                    $this->correct = false;
8631                    $this->addToMessage(__("Les paramètres supplémentaires envoyés au parapheur ne sont pas au bon format."));
8632                    $this->addToLog(__METHOD__."(): ".
8633                        __("Erreur lors du décodage du format json des paramètres supplémentaires envoyé au parapheur.
8634                            Tableau : ").var_export($inst_signataire_arrete->getVal('parametre_parapheur'), true)
8635                    );
8636                    // Termine le traitement
8637                    return $this->end_treatment(__METHOD__, false);
8638              }              }
8639              $this->addToMessage(_("Veuillez contacter votre administrateur."));          }
8640    
8641            //Instanciation de la classe electronicsignature
8642            $inst_es = $this->get_electronicsignature_instance();
8643            if ($inst_es === false) {
8644                $this->correct = false;
8645              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
8646          }          }
8647          // Remplacement des variables de substitution  
8648          $objet = str_replace('<DOSSIER_INSTRUCTION>', $id_di, $objet);          // Appel de la méthode de l'abstracteur send_for_signature()
8649          $modele = $this->formater_modele($modele, $id_di, $id_inst);          // Cette méthode doit retourner un tableau de valeur
8650          // Exécution du traitement d'envoi du/des mail(s)          try {
8651          $fails = array();              $result = $inst_es->send_for_signature($data, $file['file_content'], $metadonnee_dossier, $optional_data);
8652          foreach ($courriels_valides as $email) {          }  catch (electronicsignature_exception $e) {
8653              if ($this->f->sendMail(              $this->handle_electronicsignature_exception($e);
                 iconv("UTF-8", "CP1252", $objet),  
                 iconv("UTF-8", "CP1252", $modele),  
                 iconv("UTF-8", "CP1252", $email)) === false) {  
                 $fails[] = $email;  
             }  
         }  
         // Si échec message d'erreur et arrêt du traitement  
         if (count($fails) > 0) {  
             $fails = implode(', ', $fails);  
             $this->addToMessage(_("Erreur lors de l'envoi du courriel aux destinataires : ").$fails);  
             $this->addToMessage(_("Veuillez contacter votre administrateur."));  
8654              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
8655          }          }
8656          // Ajout du log  
8657          $this->setValFFromVal();          // Après avoir reçu le résultat du parapheur, il faut mettre à jour les champs
8658          $val_inst = $this->valF;          $valF = array();
8659          $val_inst['mails_destinataires'] = implode(', ', $courriels_valides);  
8660          if ($this->add_log_to_dossier($id_inst, $val_inst) === false) {          // Pour appeler la fonction modifier il faut traiter tous les champs de l'objet
8661              $this->addToMessage(_("Erreur lors de la notification."));          foreach($this->champs as $identifiant => $champ) {
8662              $this->addToMessage(_("Veuillez contacter votre administrateur."));              $valF[$champ] = $this->val[$identifiant];
8663            }
8664            // On fait ensuite nos modifications spécifiques
8665            $valF['id_parapheur_signature'] = $result['id_parapheur_signature'];
8666            $valF['statut_signature'] = $result['statut'];
8667            $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
8668            $valF['date_envoi_signature'] = date("Y-m-d", strtotime($result['date_envoi_signature']));
8669            $valF['historique_signature'] = $this->get_updated_historique_signature($result);
8670    
8671            $ret = $this->modifier($valF);
8672    
8673            if ($ret === false) {
8674                $this->correct = false;
8675                $this->addToMessage(__("Une erreur est survenue lors de la mise à jour des champs."));
8676                // Termine le traitement
8677              return $this->end_treatment(__METHOD__, false);              return $this->end_treatment(__METHOD__, false);
8678          }          }
8679          // Message de validation  
8680          $this->addToMessage(_('La commune a été notifiée.'));          // Message
8681            $this->addToMessage(__("Le document a été envoyé pour signature dans le parapheur."));
8682            if (array_key_exists('signature_page_url', $result) === true) {
8683                $this->addToMessage(sprintf(
8684                    '<br> > <a href="%1$s" title="%2$s" target="_blank">%2$s</a>',
8685                    $result['signature_page_url'],
8686                    __("Signez directement le document")
8687                ));
8688            }
8689    
8690            // Tout s'est bien passé, on termine le traitement
8691          return $this->end_treatment(__METHOD__, true);          return $this->end_treatment(__METHOD__, true);
8692      }      }
8693    
8694      /**      /**
8695       * Formatte le corps du courriel notifié aux communes       * Permet de récupérer la bonne date limite en fonction de si l'instruction
8696         * est en incomplet notifié ou non.
8697         * On peut ajouter des jours à cette date grâce au paramètre "delay".
8698         * Cette fonction est utilisée dans un cas spécifique où on veut envoyer
8699         * l'instruction en signature le jour de la date limite.
8700       *       *
8701       * @param   string  $modele   template du modèle du courriel       * @param int $delay Le nombre de jour à ajouter à la date limite.
8702       * @param   string  $id_di    clé primaire du DI       *
8703       * @param   string  $id_inst  clé primaire de l'instruction       * @return string $date_limite la date limite calculé ou false
8704       * @return  string            corps du mail au format HTML       */
8705       */      private function compute_date_limite($delay) {
8706      public function formater_modele($modele, $id_di, $id_inst) {          // Instanciation de l'objet dossier
8707          // Création du lien d'accès direct à l'instruction          $inst_dossier = $this->f->get_inst__om_dbform(array(
8708          $url_inst = PATH_BASE_URL.'spg/direct_link.php?obj=dossier_instruction&action=3'.              'obj' => 'dossier',
8709              '&direct_field=dossier&direct_form=instruction&direct_action=3&direct_idx='.$id_inst;              'idx' => $this->getVal('dossier'),
8710          $url_inst = '<a href="'.$url_inst.'">'.$url_inst.'</a>';          ));
8711          // Remplacement des champs de fusion  
8712          $modele = str_replace('<DOSSIER_INSTRUCTION>', $id_di, $modele);          $date_to_compute = null;
8713          $modele = str_replace('<URL_INSTRUCTION>', $url_inst, $modele);          if ($inst_dossier->getVal('incomplet_notifie') === 't') {
8714          $modele = str_replace('<ID_INSTRUCTION>', $id_inst, $modele);            $date_to_compute = $inst_dossier->getVal('date_limite_incompletude');
8715          // Encodage HTML des sauts de ligne          } else {
8716          $modele = preg_replace("/\r\n|\r|\n/",'<br/>',$modele);            $date_to_compute = $inst_dossier->getVal('date_limite');
8717            }
8718    
8719            $date_limite = date("Y-m-d", strtotime($date_to_compute."+ $delay days"));
8720    
8721            return $date_limite;
8722        }
8723    
8724        /**
8725         * Permet de récupérer la traduction de la valeur de statut_signature
8726         *
8727         * @return string la valeur de statut_signature traduite | false
8728         */
8729        function get_trad_for_statut($value_to_trad){
8730            $statut_signature_tab = array(
8731                'waiting' => __('en préparation'),
8732                'in_progress' => __('en cours de signature'),
8733                'canceled' => __('signature annulée'),
8734                'expired' => __('délai de signature expiré'),
8735                'finished' => __('signé')
8736            );
8737            if (array_key_exists($value_to_trad, $statut_signature_tab) === true) {
8738                return $statut_signature_tab[$value_to_trad];
8739            }
8740    
8741            return false;
8742        }
8743    
8744        /**
8745         * Permet de mettre à jour le tableau json sotcké dans le champ historique_signature
8746         *
8747         * @return string (json) la valeur de historique_signature mis à jour | false
8748         */
8749        function get_updated_historique_signature($historique_signature_values) {
8750            
8751            $historique_signature_value_tab = $this->get_historique_signature_decoded();
8752    
8753            if ($historique_signature_value_tab === false) {
8754                $this->addToLog(__METHOD__."(): erreur historique signature", DEBUG_MODE);
8755                return false;
8756            }
8757    
8758            $last_val_historique_signature = array();
8759    
8760            // Si la tableau récupéré n'est pas vide alors
8761            // on récupère la dernière ligne du tableau
8762            if (empty($historique_signature_value_tab) === false) {
8763                $last_val_historique_signature = end($historique_signature_value_tab);
8764            }
8765    
8766            $format_date = '';
8767            $format_date_hour = '';
8768            $date_converted=array();
8769    
8770            $date_to_convert = array(
8771                'date_envoi_signature' => $historique_signature_values['date_envoi_signature'],
8772                'date_limite_instruction' => $this->compute_date_limite(0),
8773                'date_retour_signature' => $historique_signature_values['date_retour_signature']
8774            );
8775    
8776            // Conversion des dates en fonction de leur format
8777            foreach ($date_to_convert as $key => $value) {
8778                $date_converted[$key] = null;
8779                if ($value != null) {
8780                    $format_date = 'd/m/Y';
8781                    $format_date_hour = 'd/m/Y H:i:s';
8782                    $date_converted[$key] = empty(date_parse($value)['hour']) === false ? date($format_date_hour, strtotime($value)) : date($format_date, strtotime($value));
8783                }
8784            }
8785    
8786            // Ce tableau permet de lister les colonnes de historique_signature et de les rendre traduisibles.
8787            // Il faut en effet mettre les gettext avec l'intitulé explicite au moins
8788            // une fois afin qu'il puisse être reconnu par le logiciel de traduction.
8789            $tab_for_columns_trad = array(
8790                __('entry_date'),
8791                __('id_parapheur_signature'),
8792                __('emetteur'),
8793                __('signataire'),
8794                __('date_envoi'),
8795                __('date_limite'),
8796                __('date_retour'),
8797                __('statut_signature'),
8798                __('commentaire_signature')
8799            );
8800    
8801            array_push($historique_signature_value_tab, array(
8802                'entry_date' => date('d/m/Y H:i:s'),
8803                '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'],
8804                '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'],
8805                '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'],
8806                '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'],
8807                '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'],
8808                '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'],
8809                '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']),
8810                'commentaire_signature' => isset($historique_signature_values['commentaire_signature']) === false || $historique_signature_values['commentaire_signature'] == null ? null : $historique_signature_values['commentaire_signature'],
8811            ));
8812            
8813            return json_encode($historique_signature_value_tab, JSON_HEX_APOS);
8814        }
8815        
8816        /**
8817         * TREATMENT - annuler_envoi_en_signature
8818         *
8819         * Permet d'annuler l'envoi du document de l'instruction au parapheur pour signature
8820         *
8821         * @return boolean true si l'annulation a été effectué avec succès false sinon
8822         */
8823        function annuler_envoi_en_signature() {
8824            $this->begin_treatment(__METHOD__);
8825            $this->correct = true;
8826    
8827            //Instanciation de la classe electronicsignature
8828            $inst_es = $this->get_electronicsignature_instance();
8829            if ($inst_es === false) {
8830                $this->correct = false;
8831                return $this->end_treatment(__METHOD__, false);
8832            }
8833    
8834            $data = array();
8835            if (! empty($this->getVal('id_parapheur_signature'))) {
8836                $data['id_parapheur_signature'] = $this->getVal('id_parapheur_signature');
8837            } else {
8838                $this->correct = false;
8839                $this->addToMessage(__("Il n'y a pas d'identifiant de parapheur."));
8840                return $this->end_treatment(__METHOD__, false);
8841            }
8842    
8843            // Appel de la méthode de l'abstracteur cancel_send_for_signature()
8844            // Cette méthode doit retourner un tableau de valeur
8845            try {
8846                $result = $inst_es->cancel_send_for_signature($data);
8847            }  catch (electronicsignature_exception $e) {
8848                $this->handle_electronicsignature_exception($e);
8849                return $this->end_treatment(__METHOD__, false);
8850            }
8851    
8852            // Après avoir reçu le résultat du parapheur, il faut mettre à jour les champs
8853            $valF = array();
8854    
8855            // Pour appeler la fonction modifier il faut traiter tous les champs de l'objet
8856            foreach($this->champs as $identifiant => $champ) {
8857                $valF[$champ] = $this->val[$identifiant];
8858            }
8859            // On fait ensuite nos modifications spécifiques
8860            $valF['id_parapheur_signature'] = null;
8861            $valF['statut_signature'] = $result['statut'];
8862            $valF['commentaire_signature'] = isset($result['commentaire_signature']) == true ? $result['commentaire_signature'] : null;
8863            $valF['date_envoi_signature'] = null;
8864            $valF['historique_signature'] = $this->get_updated_historique_signature($result);
8865    
8866            $ret = $this->modifier($valF);
8867    
8868            if ($ret === false) {
8869                $this->correct = false;
8870                $this->addToMessage(__("Une erreur est survenue lors de la mise à jour des champs."));
8871                // Termine le traitement
8872                return $this->end_treatment(__METHOD__, false);
8873            }
8874    
8875            // Message
8876            $this->addToMessage(__("L'annulation a été effectuée avec succès."));
8877    
8878            // Tout s'est bien passé, on termine le traitement
8879            return $this->end_treatment(__METHOD__, true);
8880        }
8881    
8882    
8883        /**
8884         * Récupère le contenu du champ historique_signature et le converti en tableau
8885         *
8886         * @return array sinon false en cas d'erreur
8887         */
8888        protected function get_historique_signature_decoded() {
8889            $val = str_replace("'", '"', $this->getVal('historique_signature'));
8890            if ($val === '' || $val == 'false') {
8891                $val = json_encode(array());
8892            }
8893            if($this->isJson($val) === false) {
8894                return false;
8895            }
8896            return json_decode($val, true);
8897        }
8898    
8899        /**
8900         * Récupère les informations à afficher dans le tableau de suivi à l'aide
8901         * d'une requête sql. Stocke ces informations dans un tableau.
8902         * Converti le tableau au format json et renvoi le json obtenu.
8903         *
8904         * Pour identifier quel suivi est affiché (notification des demandeurs, des services ou
8905         * de tiers) ce sont les tâches liées aux notifications qui sont utilisés.
8906         * La clause where de la requête est construite à partir du tableau contenant les types
8907         * de tâches fourni en paramètre.
8908         * Il est également possible d'afficher les notifications n'étant pas lié à des tâches.
8909         *
8910         * Si le suivi concerne la notification des demandeurs via le portail citoyen,
8911         * la date de premier accès ne sera pas affichée.
8912         *
8913         * @param array liste des tâches permettant d'identifier quelles notification afficher
8914         * @param boolean permet d'afficher les notifications non liées à des tâches
8915         * @return json
8916         */
8917        protected function get_json_suivi_notification($typeTache, $nonLieTache = false) {
8918            $whereTypeTache = '';
8919            $sqlTaskNull = '';
8920    
8921            // Liste des champs à afficher. Permet également la traduction des noms de colonnes.
8922            $listeChampsTrad = array(
8923                __('emetteur'),
8924                __('date_envoi'),
8925                __('destinataire'),
8926                __('date_premier_acces'),
8927                __('instruction'),
8928                __('annexes'),
8929                __('statut'),
8930                __('commentaire')
8931            );
8932            $listeChamps = array(
8933                'emetteur',
8934                'date_envoi',
8935                'destinataire',
8936                'date_premier_acces',
8937                'instruction',
8938                'annexes',
8939                'statut',
8940                'commentaire'
8941            );
8942    
8943            // Défini si on veux que la requête récupère également les notifications qui n'ont pas
8944            // de tâches associées. C'est le cas pour les notifications de demandeurs lorsque la
8945            // notification du demandeur principal n'a pas pu être envoyée à cause d'un mauvais
8946            // paramétrage
8947            if(is_bool($nonLieTache) && $nonLieTache === true) {
8948                $sqlTaskNull = 'OR task.type is null';
8949            }
8950            // Prépare la clause where pour ne récupérer que les notifications liées à certain type de tâches
8951            // Permet de différencier les notifications des demandeurs de celle des services et de celles des
8952            // tiers consulté
8953            if (is_array($typeTache) && $typeTache != array()) {
8954                if (is_array($typeTache)) {
8955                    $whereTypeTache = sprintf(
8956                        'AND (task.type IN (%1$s) %2$s)',
8957                        "'".implode("', '", $typeTache)."'",
8958                        $sqlTaskNull
8959                    );
8960                }
8961                // La date de premier accès n'a pas besoin d'être renseigné pour
8962                // les notifications des demandeurs via le portail citoyen.
8963                // Les notifications des demandeurs sont liés à 3 types de tâches
8964                // notification_recepisse, notification_instruction, notification_decision
8965                // Si le suivi de la notification concerne un de ces types de tâches on
8966                // considère que c'est une notification de demandeurs.
8967                // Dans ce cas on vérifie si cette notification est paramétrée pour passer
8968                // via le portail. Par défaut si rien n'est paramétré on considère que la
8969                // notification est faite via le portail
8970                if ((in_array('notification_recepisse', $typeTache) ||
8971                in_array('notification_instruction', $typeTache) ||
8972                in_array('notification_decision', $typeTache))) {
8973                    $dossier = $this->getVal('dossier');
8974                    $collectivite_di = $this->get_dossier_instruction_om_collectivite($dossier);
8975                    $modeNotification = $this->f->get_param_option_notification($collectivite_di);
8976                    if (empty($modeNotification) || $modeNotification == 'portal') {
8977                        $listeChamps = array(
8978                            'emetteur',
8979                            'date_envoi',
8980                            'destinataire',
8981                            'instruction',
8982                            'annexes',
8983                            'statut',
8984                            'commentaire'
8985                        );
8986                    }
8987                }
8988                // Il n'y a pas d'annexe pour la notification des communes donc pas besoin
8989                // de les afficher dans le suivi
8990                if (in_array('notification_depot_demat', $typeTache)) {
8991                    $listeChamps = array(
8992                        'emetteur',
8993                        'date_envoi',
8994                        'destinataire',
8995                        'instruction',
8996                        'statut',
8997                        'commentaire'
8998                    );
8999                }
9000            }
9001    
9002            $valSuivi = array();
9003            // Récupération des infos nécessaires à l'affichage du tableau
9004            $sql = sprintf(
9005                'SELECT DISTINCT
9006                    instruction_notification.instruction_notification,
9007                    -- Affiche la mention automatique avec le nom de l emetteur si la notification a été envoyé automatiquement
9008                    CASE WHEN instruction_notification.automatique = TRUE
9009                        THEN TRIM(CONCAT(instruction_notification.emetteur, \' \', \'(automatique)\'))
9010                        ELSE instruction_notification.emetteur
9011                    END as emetteur,
9012                    date_envoi,
9013                    instruction_notification.destinataire,
9014                    instruction_notification.date_premier_acces,
9015                    evenement.libelle as instruction,
9016                    instruction_notification.statut,
9017                    instruction_notification.commentaire,
9018                    annexes.instruction_annexe as annexes
9019                FROM
9020                    %1$sinstruction_notification
9021                    LEFT JOIN %1$sinstruction
9022                        ON instruction.instruction = instruction_notification.instruction
9023                    LEFT JOIN %1$sevenement
9024                        ON instruction.evenement = evenement.evenement
9025                    LEFT JOIN %1$sinstruction_notification_document
9026                        ON instruction_notification.instruction_notification = instruction_notification_document.instruction_notification
9027                        AND instruction_notification_document.annexe = true
9028                    -- Récupère les tâches liées au notification pour pouvoir par la suite identifier le type de notification
9029                    LEFT JOIN %1$stask
9030                        ON instruction_notification.instruction_notification::CHARACTER VARYING = task.object_id
9031                    -- Récupération de la liste des annexes sous la forme d une liste
9032                    LEFT JOIN (
9033                        SELECT
9034                            instruction_notification,
9035                            -- Récupère la liste des annexes de la notification
9036                            -- sous la forme d un json pour récupérer toutes les informatiosn nécessaire
9037                            -- à l affichage du lien vers les annexes
9038                            CONCAT(
9039                                \'[\',
9040                                STRING_AGG(
9041                                    -- Affiche le nom du fichier selon le type de document/pièce
9042                                    CASE
9043                                        WHEN instruction_notification_document.document_type = \'instruction\'
9044                                            THEN CONCAT(
9045                                                    \'{
9046                                                        "obj" : "instruction",
9047                                                        "champs" : "om_fichier_instruction",
9048                                                        "label" : "\', evenement.libelle, \'",
9049                                                        "id" : "\', instruction.instruction,\'"
9050                                                    }\'
9051                                                )
9052                                        WHEN instruction_notification_document.document_type = \'consultation\'
9053                                            THEN CONCAT(
9054                                                    \'{
9055                                                        "obj" : "consultation",
9056                                                        "champs" : "fichier",
9057                                                        "label" : "Avis - \', service.libelle, \'",
9058                                                        "id" : "\', consultation.consultation,\'"
9059                                                    }\'
9060                                                )
9061                                    ELSE
9062                                        CONCAT(
9063                                            \'{
9064                                                "obj" : "document_numerise",
9065                                                "champs" : "uid",
9066                                                "label" : "\', document_numerise.nom_fichier, \' - \', document_numerise_type.libelle, \'",
9067                                                "id" : "\', document_numerise.document_numerise,\'"
9068                                            }\'
9069                                        )
9070                                    END,
9071                                    \', \'),
9072                                \']\'
9073                            ) AS instruction_annexe
9074                        FROM
9075                            %1$sinstruction_notification_document
9076                            LEFT JOIN %1$sinstruction
9077                                ON instruction_notification_document.instruction = instruction.instruction
9078                            LEFT JOIN %1$sevenement
9079                                ON instruction.evenement = evenement.evenement
9080                            LEFT JOIN %1$sconsultation
9081                                ON instruction_notification_document.document_id = consultation.consultation
9082                            LEFT JOIN %1$sservice
9083                                ON consultation.service = service.service
9084                            LEFT JOIN %1$sdocument_numerise
9085                                ON instruction_notification_document.document_id = document_numerise.document_numerise
9086                            LEFT JOIN %1$sdocument_numerise_type
9087                                ON document_numerise.document_numerise_type = document_numerise_type.document_numerise_type
9088                        WHERE
9089                            instruction_notification_document.annexe = \'t\'
9090                        GROUP BY
9091                            instruction_notification
9092                    ) AS annexes
9093                        ON
9094                            annexes.instruction_notification = instruction_notification.instruction_notification
9095                WHERE
9096                    instruction.instruction = %2$s
9097                    %3$s
9098                ORDER BY
9099                    date_envoi ASC, instruction_notification.destinataire ASC',
9100                DB_PREFIXE,
9101                $this->getVal('instruction'),
9102                $whereTypeTache
9103            );
9104            $res = $this->f->db->query($sql);
9105            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
9106            $this->f->isDatabaseError($res);
9107            // Préparation du lien de téléchargement des annexes
9108            $htmlList =
9109                '<style>
9110                    #content .gridjs-td a.lien_annexe {
9111                        text-decoration : underline dotted 1px;
9112                    }
9113                    #content a.lien_annexe:hover {
9114                        text-decoration : underline solid 1px;
9115                        color : #46aede;
9116                    }
9117                    ol {padding-left : 10px;}
9118                </style>
9119                <ol>%1$s</ol>';
9120            $lienTelechargement =
9121            '<a class="lien_annexe" href="../app/index.php?module=form&amp;snippet=file&amp;obj=%1$s&amp;champ=%2$s&amp;id=%3$s" target="blank" title="%4$s">
9122                Annexe
9123            </a>';
9124            // Stockage des infos de chaque notification dans un tableau
9125            while( $row =& $res->fetchrow(DB_FETCHMODE_ASSOC) ) {
9126                $valNotif = array();
9127                foreach($listeChamps as $champ) {
9128                    $valNotif[$champ] = $row[$champ];
9129                    if (($champ === 'date_envoi'
9130                        || $champ === 'date_premier_acces')
9131                        && $row[$champ] !== null
9132                        && $row[$champ] !== '') {
9133                        //
9134                        $valNotif[$champ] = date('d/m/Y H:i:s', strtotime($row[$champ]));
9135                    } else if ($champ === 'annexes') {
9136                        $listeAnnexe = '';
9137                        $infoAnnexes = json_decode($row[$champ], true);
9138                        if (! empty($infoAnnexes) && json_last_error() === JSON_ERROR_NONE) {
9139                            // A partir des infos récupérées prépare le code html du lien vers chacune
9140                            // des annexes et ajoute un élément de liste par annexe
9141                            foreach($infoAnnexes as $annexe) {
9142                                $listeAnnexe .= sprintf(
9143                                    '<li>%s</li>',
9144                                    sprintf($lienTelechargement,
9145                                        $annexe['obj'],
9146                                        $annexe['champs'],
9147                                        $annexe['id'],
9148                                        $annexe['label']
9149                                    )
9150                                );
9151                            }
9152                            // Construction de la liste des annexes
9153                            $valNotif[$champ] = sprintf(
9154                                $htmlList,
9155                                $listeAnnexe
9156                            );
9157                        }
9158                    }
9159                }
9160                array_push($valSuivi, $valNotif);
9161            }
9162    
9163            // Passage du tableau au format json
9164            return json_encode($valSuivi, JSON_HEX_APOS);
9165        }
9166    
9167        /**
9168         * Traitement des erreurs retournées par l'abstracteur electronicsignature.
9169         *
9170         * @param electronicsignature_exception $exception Exception retournée par l'abstracteur.
9171         *
9172         * @return void
9173         */
9174        public function handle_electronicsignature_exception(electronicsignature_exception $exception) {
9175            $this->f->displayMessage('error', $exception->getMessage());
9176        }
9177    
9178    
9179        /**
9180         * Retourne une instance du connecteur electronicsignature, et la créer si elle n'existe pas.
9181         *
9182         * @param  boolean $with_handle_error Flag pour afficher ou non le message d'erreur à l'utilisateur.
9183         * @return electronicsignature        Instance de l'abstracteur.
9184         */
9185        public function get_electronicsignature_instance($with_handle_error = true) {
9186            if(isset($this->electronicsignature_instance)) {
9187                return $this->electronicsignature_instance;
9188            }
9189            // Instanciation du connecteur electronicsignature
9190            try {
9191                require_once "electronicsignature.class.php";
9192                $collectivites = array("collectivite_idx" => $this->get_dossier_instruction_om_collectivite(), "collectivite_multi_idx" => $this->f->get_idx_collectivite_multi());
9193                $this->electronicsignature_instance = new electronicsignature($collectivites);
9194            } catch (electronicsignature_exception $e) {
9195                if ($with_handle_error === true) {
9196                    $this->handle_electronicsignature_exception($e);
9197                }
9198                return false;
9199            }
9200            return $this->electronicsignature_instance;
9201        }
9202    
9203        /**
9204         * TREATMENT - envoyer_au_controle_de_legalite
9205         *
9206         * Ajoute la tâche envoi_CL.
9207         * C'est le traitement de la tâche qui mettra à jour la date d'envoi au contrôle de légalité.
9208         *
9209         * @return [type] [description]
9210         */
9211        function envoyer_au_controle_de_legalite() {
9212            $this->begin_treatment(__METHOD__);
9213            $this->correct = true;
9214    
9215            //
9216            if ($this->can_be_sended_to_cl() === true) {
9217                // Création de la task 'envoi_CL'
9218                $inst_task = $this->f->get_inst__om_dbform(array(
9219                    "obj" => "task",
9220                    "idx" => 0,
9221                ));
9222                $task_val = array(
9223                    'type' => 'envoi_CL',
9224                    'object_id' => $this->getVal('instruction'),
9225                    'dossier' => $this->getVal('dossier'),
9226                );
9227                // Change l'état de la tâche de notification en fonction de l'état de
9228                // transmission du dossier d'instruction
9229                $inst_di = $this->get_inst_dossier($this->getVal('dossier'));
9230                if ($this->f->is_option_mode_service_consulte_enabled() === false
9231                    && ($inst_di->getVal('etat_transmission_platau') == 'non_transmissible'
9232                    || $inst_di->getVal('etat_transmission_platau') == 'transmis_mais_non_transmissible')) {
9233                    //
9234                    $task_val['state'] = $inst_task::STATUS_DRAFT;
9235                }
9236                $add_task = $inst_task->add_task(array('val' => $task_val));
9237                if ($add_task === false) {
9238                    $this->addToMessage(sprintf('%s %s',
9239                        __("Une erreur s'est produite lors de la création tâche."),
9240                        __("Veuillez contacter votre administrateur.")
9241                    ));
9242                    $this->correct = false;
9243                    return $this->end_treatment(__METHOD__, false);
9244                }
9245                // Mise à jour du champs 'envoye_cl_platau'
9246                $instr_val = array(
9247                    'envoye_cl_platau' => 't',
9248                );
9249                $res = $this->f->db->autoExecute(
9250                    DB_PREFIXE.$this->table,
9251                    $instr_val,
9252                    DB_AUTOQUERY_UPDATE,
9253                    $this->getCle($this->getVal($this->clePrimaire))
9254                );
9255                $this->addToLog(__METHOD__."(): db->autoexecute(\"".DB_PREFIXE.'.'.$this->table."\", ".print_r($instr_val, true).", DB_AUTOQUERY_UPDATE, \"".$this->getCle($this->clePrimaire)."\");", VERBOSE_MODE);
9256                if ($this->f->isDatabaseError($res, true) === true) {
9257                    $this->addToMessage(sprintf('%s %s',
9258                        __("Une erreur s'est produite lors de la mise à jour de l'instruction."),
9259                        __("Veuillez contacter votre administrateur.")
9260                    ));
9261                    $this->correct = false;
9262                    return $this->end_treatment(__METHOD__, false);
9263                }
9264                // Message de validation à l'utilisateur
9265                $this->addToMessage(__('Votre demande de transfert au contrôle de légalité à bien été prise en compte.'));
9266                $this->addToMessage(__("La date d'envoi au contrôle de légalité sera mise à jour ultérieurement."));
9267            }
9268          //          //
9269          return $modele;          return $this->end_treatment(__METHOD__, true);
9270      }      }
9271    
9272    
9273      /**      /**
9274       * Récupère l'instance de l'instructeur       * Retourne le lien de retour (VIEW formulaire et VIEW sousformulaire).
9275       *       *
9276       * @param integer $instructeur Identifiant de l'instructeur.       * @param string $view Appel dans le contexte de la vue 'formulaire' ou de
9277         *                     la vue 'sousformulaire'.
9278       *       *
9279       * @return object       * @return string
9280       */       */
9281      protected function get_inst_instructeur($instructeur) {      function get_back_link($view = "formulaire") {
9282          //          //
9283          return $this->get_inst_common("instructeur", $instructeur);          $href = parent::get_back_link($view);
9284            //
9285            $crud = $this->get_action_crud();
9286    
9287            // Redirection vers le formulaire de modification à la validation du
9288            // formulaire d'ajout si l'événement associé possède une lettre type
9289            if (($crud === 'create'
9290                    || ($crud === null
9291                        && $this->getParameter('maj') == 0))
9292                    && $this->correct == true
9293                    && $this->evenement_has_an_edition($this->valF['evenement']) === true) {
9294    
9295                // On instancie l'instruction
9296                $inst_instruction = $this->f->get_inst__om_dbform(array(
9297                    "obj" => "instruction",
9298                    "idx" => $this->valF[$this->clePrimaire],
9299                ));
9300    
9301                // Si l'instruction n'est pas finalisée automatiquement
9302                if ($inst_instruction->getVal('om_final_instruction') !== 't') {
9303                    $href = str_replace("&action=3", "&action=1", $href);
9304                    //
9305                    if (strpos($href, "&retour=tab") !== false) {
9306                        $href = str_replace("&retour=tab", "&retour= form", $href);
9307                    } else {
9308                        $href .= "&retour=form";
9309                    }
9310                }
9311            }
9312    
9313            //
9314            return $href;
9315      }      }
9316    
9317        public function view_json_data() {
9318            $this->checkAccessibility();
9319            $this->f->disableLog();
9320            $view = $this->get_json_data();
9321            printf(json_encode($view));
9322        }
9323    
9324        public function get_json_data() {
9325            $val = array_combine($this->champs, $this->val);
9326            foreach ($val as $key => $value) {
9327                $val[$key] = strip_tags($value);
9328            }
9329            $val['tacite'] = 'f';
9330            $inst_ad = $this->f->get_inst__om_dbform(array(
9331                "obj" => "avis_decision",
9332                "idx" => $val['avis_decision'],
9333            ));
9334            if (preg_match('/[tT]acite/', $inst_ad->getVal('libelle')) === 1) {
9335                $val['tacite'] = 't';
9336            }
9337            return $val;
9338        }
9339    
9340        public function get_related_instructions_next($next_type = 'retour_signature', $instruction = null) {
9341            if (in_array($next_type, array('retour_signature', 'retour_ar', 'suivant_tacite', )) === false) {
9342                return false;
9343            }
9344            $result = array();
9345            $evenements = array();
9346            if ($instruction === null) {
9347                $instruction = $this->getVal($this->clePrimaire);
9348                $evenement = $this->getVal('evenement');
9349                $dossier = $this->getVal('dossier');
9350            } else {
9351                $inst = $this->f->get_inst__om_dbform(array(
9352                    "obj" => "instruction",
9353                    "idx" => $instruction,
9354                ));
9355                $evenement = $inst->getVal('evenement');
9356                $dossier = $inst->getVal('dossier');
9357            }
9358            //
9359            $query = sprintf('
9360                SELECT evenement_%3$s
9361                FROM %1$sevenement
9362                WHERE evenement = %2$s
9363                ',
9364                DB_PREFIXE,
9365                $evenement,
9366                $next_type
9367            );
9368            $res = $this->f->get_one_result_from_db_query($query, true);
9369            if ($res['code'] === 'KO') {
9370                return false;
9371            }
9372            $ev_next = $res['result'];
9373            //
9374            $query = sprintf('
9375                SELECT MAX(instruction.instruction) as instruction
9376                FROM %1$sinstruction
9377                WHERE dossier = \'%3$s\'
9378                    AND evenement = %2$s
9379                ',
9380                DB_PREFIXE,
9381                $ev_next,
9382                $dossier
9383            );
9384            $res = $this->f->get_one_result_from_db_query($query, true);
9385            if ($res['code'] === 'KO') {
9386                return false;
9387            }
9388            //
9389            return $res['result'];
9390        }
9391    
9392        public function get_related_instructions($instruction = null) {
9393            $result = array();
9394            $evenements = array();
9395            if ($instruction === null) {
9396                $instruction = $this->getVal($this->clePrimaire);
9397                $evenement = $this->getVal('evenement');
9398                $dossier = $this->getVal('dossier');
9399            } else {
9400                $inst = $this->f->get_inst__om_dbform(array(
9401                    "obj" => "instruction",
9402                    "idx" => $instruction,
9403                ));
9404                $evenement = $inst->getVal('evenement');
9405                $dossier = $inst->getVal('dossier');
9406            }
9407            //
9408            $query = sprintf('
9409                SELECT evenement
9410                FROM %1$sevenement
9411                WHERE evenement_retour_ar = %2$s
9412                    OR evenement_retour_signature = %2$s
9413                ',
9414                DB_PREFIXE,
9415                $evenement
9416            );
9417            $res = $this->f->get_one_result_from_db_query($query, true);
9418            if ($res['code'] === 'KO') {
9419                return false;
9420            }
9421            $ev_parent = $res['result'];
9422            //
9423            $query = sprintf('
9424                SELECT MAX(instruction.instruction) as instruction
9425                FROM %1$sinstruction
9426                WHERE dossier = \'%3$s\'
9427                    AND evenement = %2$s
9428                ',
9429                DB_PREFIXE,
9430                $ev_parent,
9431                $dossier
9432            );
9433            $res = $this->f->get_one_result_from_db_query($query, true);
9434            if ($res['code'] === 'KO') {
9435                return false;
9436            }
9437            $result[] = $res['result'];
9438            //
9439            $query = sprintf('
9440                SELECT evenement_retour_ar
9441                FROM %1$sevenement
9442                WHERE evenement = %2$s
9443                    AND evenement_retour_ar != %3$s
9444                ',
9445                DB_PREFIXE,
9446                $ev_parent,
9447                $evenement
9448            );
9449            $res = $this->f->get_one_result_from_db_query($query, true);
9450            if ($res['code'] === 'KO') {
9451                return false;
9452            }
9453            $evenements[] = $res['result'];
9454            //
9455            $query = sprintf('
9456                SELECT evenement_retour_signature
9457                FROM %1$sevenement
9458                WHERE evenement = %2$s
9459                    AND evenement_retour_signature != %3$s
9460                ',
9461                DB_PREFIXE,
9462                $ev_parent,
9463                $evenement
9464            );
9465            $res = $this->f->get_one_result_from_db_query($query, true);
9466            if ($res['code'] === 'KO') {
9467                return false;
9468            }
9469            $evenements[] = $res['result'];
9470            foreach ($evenements as $value) {
9471                if ($value !== null) {
9472                    $query = sprintf('
9473                        SELECT MAX(instruction.instruction) as instruction
9474                        FROM %1$sinstruction
9475                        WHERE dossier = \'%3$s\'
9476                            AND evenement = %2$s
9477                        ',
9478                        DB_PREFIXE,
9479                        $value,
9480                        $dossier
9481                    );
9482                    $res = $this->f->get_one_result_from_db_query($query, true);
9483                    if ($res['code'] === 'KO') {
9484                        return false;
9485                    }
9486                    $result[] = $res['result'];
9487                }
9488            }
9489            return $result;
9490        }
9491    
9492        protected function getDocumentType($champ = null) {
9493            $evenementId = $this->getVal('evenement');
9494            if (! empty($evenementId)) {
9495                $evenement = $this->f->findObjectById('evenement', $evenementId);
9496                if (! empty($evenement)) {
9497                    return __("Instruction").':'.$evenement->getVal('libelle');
9498                }
9499            }
9500            return parent::getDocumentType();
9501        }
9502    
9503      /**      /**
9504       * Récupère l'instance de l'utilisateur       * Récupère à l'aide d'une requête sql la liste des demandeurs
9505         * pouvant être notifié. C'est à dire les demandeurs acceptant
9506         * les notifications et pour lesquels une adresse mail existe.
9507       *       *
9508       * @param integer $om_utilisateur Identifiant de l'utilisateur.       * Dans le cas, d'une notification pour le portail citoyen, seul
9509         * le pétitionnaire principal doit être notifier et uniquement si
9510         * il a une adress mail et qu'il accepte les notifications.
9511         *
9512         * @param string identifiant du dossier
9513         * @param boolean true si il faut récupérer la liste des demandeurs notifiable
9514         * pour une notification de categorie portail
9515         * @return array liste des demandeurs pouvant être notifié
9516        */
9517        protected function get_demandeurs_notifiable($idDossier = null, $portail = false) {
9518            if ($idDossier === null) {
9519                $idDossier = $this->getVal('dossier');
9520            }
9521            // Ajoute une condition sur le where pour ne récupérer que le pétitionnaire principal
9522            // pour une notification depuis le portail citoyen
9523            $sqlPetitionnairePrincipal = '';
9524            // Gestion des champs nécessaires pour la notification d'un demandeur
9525            $condition_demandeur = "AND demandeur.notification = 't'
9526                AND demandeur.courriel IS NOT NULL";
9527            if ($portail === true) {
9528                $sqlPetitionnairePrincipal = 'AND lien_dossier_demandeur.petitionnaire_principal = true';
9529                $condition_demandeur = "AND (
9530                        (notification = 't' AND courriel IS NOT NULL)
9531                        OR demande.source_depot = 'portal'
9532                    )";
9533            }
9534    
9535            $listeDemandeursNotifiable = array();
9536    
9537            // Requête de récupération des demandeurs
9538            $sql = sprintf(
9539                'SELECT
9540                    demandeur.demandeur,
9541                    CASE
9542                        WHEN demandeur.qualite=\'particulier\'
9543                        THEN TRIM(CONCAT(demandeur.particulier_nom, \' \', demandeur.particulier_prenom, \' \', demandeur.courriel))
9544                    ELSE
9545                        TRIM(CONCAT(demandeur.personne_morale_raison_sociale, \' \', demandeur.personne_morale_denomination, \' \', demandeur.courriel))
9546                    END AS destinataire,
9547                    demandeur.courriel,
9548                    petitionnaire_principal
9549                FROM
9550                    %1$sdossier
9551                    INNER JOIN %1$slien_dossier_demandeur
9552                        ON dossier.dossier = lien_dossier_demandeur.dossier
9553                    INNER JOIN %1$sdemandeur
9554                        ON lien_dossier_demandeur.demandeur = demandeur.demandeur
9555                    -- Récupération de la plus ancienne demande associée au dossier (la demande
9556                    -- de création du dossier)
9557                    INNER JOIN (
9558                        SELECT
9559                            demande,
9560                            dossier_instruction,
9561                            source_depot
9562                        FROM
9563                            %1$sdemande
9564                        WHERE
9565                            dossier_instruction = \'%2$s\'
9566                        ORDER BY
9567                            demande ASC
9568                        LIMIT 1
9569                    ) as demande
9570                        ON dossier.dossier = demande.dossier_instruction
9571                WHERE
9572                    dossier.dossier = \'%2$s\'
9573                    %3$s
9574                    %4$s',
9575                DB_PREFIXE,
9576                $idDossier,
9577                $condition_demandeur,
9578                $sqlPetitionnairePrincipal
9579            );
9580            $res = $this->f->db->query($sql);
9581            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
9582            $this->f->isDatabaseError($res);
9583            // Récupération des infos des demandeurs et stockage dans un tableau
9584            // ayant pour clé les id des demandeurs
9585            while($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
9586                $listeDemandeursNotifiable[$row['demandeur']] = $row;
9587            }
9588    
9589            return $listeDemandeursNotifiable;
9590        }
9591    
9592        /**
9593         * Renvoie la liste des notifications liées à l'instruction
9594         *
9595         * @param integer id de l'instruction dont on cherche les notifications
9596         * @return array liste des instruction_notification liés à l'instruction
9597         */
9598        public function get_instruction_notification($id_instruction, $typeNotification = null, $nonLieTache = false) {
9599            $whereTypeTache = '';
9600            $sqlTaskNull = '';
9601            // Défini si on veux que la requête récupère également les notifications qui n'ont pas
9602            // de tâches associées. C'est le cas pour les notifications de demandeurs lorsque la
9603            // notification du demandeur principal n'a pas pu être envoyée à cause d'un mauvais
9604            // paramétrage
9605            if(is_bool($nonLieTache) && $nonLieTache === true) {
9606                $sqlTaskNull = 'OR task.type is null';
9607            }
9608            if ($typeNotification != null) {
9609                if (is_array($typeNotification)) {
9610                    $whereTypeTache = sprintf(
9611                        'AND (task.type IN (%1$s) %2$s)',
9612                        "'".implode("', '", $typeNotification)."'",
9613                        $sqlTaskNull
9614                    );
9615                } else {
9616                    $whereTypeTache = sprintf(
9617                        'AND (task.type = \'%1$s\' %2$s)',
9618                        $typeNotification,
9619                        $sqlTaskNull
9620                    );
9621                }
9622            }
9623            $listeInstrNotif = array();
9624            $sql = sprintf('
9625                SELECT
9626                    instruction_notification.instruction_notification
9627                FROM
9628                    %1$sinstruction_notification
9629                    LEFT JOIN %1$stask
9630                        ON instruction_notification.instruction_notification::CHARACTER VARYING = task.object_id
9631                WHERE
9632                    instruction = %2$s
9633                    %3$s',
9634                DB_PREFIXE,
9635                $id_instruction,
9636                $whereTypeTache
9637            );
9638            $res = $this->f->db->query($sql);
9639            $this->f->addToLog(__METHOD__."(): db->query(\"".$sql."\")", VERBOSE_MODE);
9640            $this->f->isDatabaseError($res);
9641            while ($row = $res->fetchrow(DB_FETCHMODE_ASSOC)) {
9642                $listeInstrNotif[] = $row['instruction_notification'];
9643            }
9644            return $listeInstrNotif;
9645        }
9646    
9647        /**
9648         * Crée une clé d'accès unique permettant à un utilisateur
9649         * anonyme de récupérer le document.
9650       *       *
9651       * @return object       * @return string clé d'accès du document
9652       */       */
9653      protected function get_inst_om_utilisateur($om_utilisateur) {      protected function getCleAccesDocument() {
9654            // Initialisation d'un tableau
9655            $number_list = array();
9656    
9657            // Génération aléatoire d'un nombre sur 4 caractères, 4 fois
9658            for ($i = 0; $i < 4; $i++) {
9659                $number_list[] = str_pad(mt_rand(0, 9999), 4, 0, STR_PAD_LEFT);
9660            }
9661    
9662            // Transformation en chaîne tout en séparant les nombres par un "-"
9663            $result = implode('-', $number_list);
9664    
9665            // Vérifie si la clé existe déjà et si c'est le cas génére une nouvelle clé
9666            if ($this->getUidDocumentInstructionWithKey($result) != null) {
9667                return $this->getCleAccesDocument();
9668            }
9669    
9670          //          //
9671          return $this->get_inst_common("om_utilisateur", $om_utilisateur);          return $result;
9672      }      }
9673    
9674        /**
9675         * Récupère une clé et renvoie l'uid du document liée à cette
9676         * clé. Si la clé n'existe pas renvoie null.
9677         *
9678         * @param string $cleGen clé dont on cherche l'instruction
9679         * @return integer|null
9680         */
9681        protected function getUidDocumentInstructionWithKey($cleGen) {
9682            $query = sprintf(
9683                'SELECT
9684                    instruction.om_fichier_instruction
9685                FROM
9686                    %1$sinstruction_notification_document
9687                    LEFT JOIN %1$sinstruction ON instruction_notification_document.instruction = instruction.instruction
9688                WHERE
9689                    instruction_notification_document.cle = \'%2$s\'',
9690                DB_PREFIXE,
9691                $this->f->db->escapeSimple($cleGen)
9692            );
9693    
9694  }// fin classe          $res = $this->f->db->getOne($query);
9695            $this->addToLog(__METHOD__.": db->getOne(\"".$query."\");", VERBOSE_MODE);
9696            $this->f->isDatabaseError($res);
9697            return $res;
9698        }
9699    
9700  ?>      /**
9701         * Récupère une clé, fait une requête pour récupérer l'id de la notification liée a cette clé.
9702         * Récupère l'instance de instruction_notification dont l'id a été récupéré et la renvoie.
9703         *
9704         * @param string $cleGen
9705         * @return instruction_notification
9706         */
9707        protected function getInstanceNotificationWithKey($key) {
9708            $sql = sprintf(
9709                "SELECT
9710                    instruction_notification
9711                FROM
9712                    %1\$sinstruction_notification_document
9713                WHERE
9714                    cle = '%2\$s'",
9715                DB_PREFIXE,
9716                $this->f->db->escapeSimple($key)
9717            );
9718            $res = $this->f->db->getOne($sql);
9719            $this->addToLog(__METHOD__.": db->getOne(\"".$sql."\");", VERBOSE_MODE);
9720            $this->f->isDatabaseError($res);
9721    
9722            // Récupération de l'instance de notification
9723            $instNotif = $this->f->get_inst__om_dbform(array(
9724                "obj" => "instruction_notification",
9725                "idx" => $res,
9726            ));
9727            return $instNotif;
9728        }
9729    
9730    
9731        /**
9732         * Affiche la page de téléchargement du document de la notification.
9733         *
9734         * @param boolean $content_only Affiche le contenu seulement.
9735         *
9736         * @return void
9737         */
9738        public function view_telecharger_document_anonym() {
9739            // Par défaut on considère qu'on va afficher le formulaire
9740            $idx = 0;
9741            // Flag d'erreur
9742            $error = false;
9743            // Message d'erreur
9744            $message = '';
9745    
9746            // Paramètres GET : récupération de la clé d'accès
9747            $cle_acces_document = $this->f->get_submitted_get_value('key');
9748            $cle_acces_document = $this->f->db->escapeSimple($cle_acces_document);
9749            // Vérification de l'existence de la clé et récupération de l'uid du fichier
9750            $uidFichier = $this->getUidDocumentInstructionWithKey($cle_acces_document);
9751            if ($uidFichier != null) {
9752                // Récupération du document
9753                $file = $this->f->storage->get($uidFichier);
9754    
9755                // Headers
9756                header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
9757                header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
9758                header("Content-Type: ".$file['metadata']['mimetype']);
9759                header("Accept-Ranges: bytes");
9760                header("Content-Disposition: inline; filename=\"".$file['metadata']['filename']."\";" );
9761                // Affichage du document
9762                echo $file['file_content'];
9763    
9764                // Récupération de la date de premier accès et maj du suivi uniquement
9765                // si la date de 1er accès n'a pas encore été remplis
9766                $inst_notif = $this->getInstanceNotificationWithKey($cle_acces_document);
9767                if ($inst_notif->getVal('date_premier_acces') == null ||
9768                    $inst_notif->getVal('date_premier_acces') == '') {
9769                    $notif_val = array();
9770                    foreach ($inst_notif->champs as $champ) {
9771                        $notif_val[$champ] = $inst_notif->getVal($champ);
9772                    }
9773                    $notif_val['date_premier_acces'] = date("d/m/Y H:i:s");
9774                    $notif_val['statut'] = 'vu';
9775                    $notif_val['commentaire'] = 'Le document a été vu';
9776                    $suivi_notif = $inst_notif->modifier($notif_val);
9777                }
9778    
9779            } else {
9780                // Page vide 404
9781                printf('Ressource inexistante');
9782                header('HTTP/1.0 404 Not Found');
9783            }
9784        }
9785    
9786        /**
9787         * Récupère le titre du document envoyé au parapheur
9788         */
9789        protected function getDocumentTitre($champ = null) {
9790            $title = $this->getTitle();
9791            $dossier = $this->getDossier();
9792            return $dossier.' '.$title;
9793        }
9794    
9795        /**
9796         * Compose le nom du document à transmettre au parapheur.
9797         * Le nom ets composé de cette manière :
9798         * instruction_xxx_libelle_de_la_lettre_type_associee
9799         * ou xxx correspond au numéro de l'instruction
9800         */
9801        protected function getDocumentLibelle() {
9802            // Récupère le champ instruction
9803            $instruction = $this->getVal("instruction");
9804    
9805            // Requête sql servant à récupérer le titre du document
9806            // TO_CHAR() introduit un espace avant l'affichage du nombre
9807            // comme les espaces sont remplacé par des '_' dans le retour de la fonction
9808            // il n'est pas nécessaire de mettre un '_' après le mot instruction.
9809            $sql = sprintf(
9810                'SELECT
9811                    CONCAT(
9812                        \'instruction\',
9813                        TO_CHAR(instruction.instruction, \'000\'),
9814                        \'_\',
9815                        LOWER(om_lettretype.libelle)
9816                    ) as nom_fichier
9817                FROM
9818                    %1$sinstruction
9819                    LEFT JOIN %1$som_lettretype ON om_lettretype.id = instruction.lettretype
9820                WHERE
9821                    instruction = %2$s',
9822                DB_PREFIXE,
9823                $instruction
9824            );
9825            $documentLibelle = $this->f->db->getOne($sql);
9826            $this->addToLog("getDocumentTitre(): db->getOne(\"".$sql."\");", VERBOSE_MODE);
9827            if (database::isError($documentLibelle)) {
9828                die();
9829            }
9830    
9831            // Transforamtion des ' ' en '_', des accents en lettres sans accents et des
9832            // caractères spéciaux en '_'
9833            // La méthode normalize_string est utilisé pour gérer les accents
9834            $documentLibelle = $this->f->normalize_string($documentLibelle);
9835            // TODO : comparer cette liste et celle de la méthode normalize_string
9836            // pour éviter les doublons + vérifier qu'il n'y a pas de doublons dans cette
9837            // liste
9838            $invalid = array('Œ'=>'oe', 'œ'=>'oe', 'Ÿ'=>'y', 'ü'=>'u',
9839                '¢' => '_', 'ß' => '_', '¥' => '_', '£' => '_', '™' => '_', '©' => '_',
9840                '®' => '_', 'ª' => '_', '×' => '_', '÷' => '_', '±' => '_', '²' => '_',
9841                '³' => '_', '¼' => '_', '½' => '_', '¾' => '_', 'µ' => '_', '¿' => '_',
9842                '¶' => '_', '·' => '_', '¸' => '_', 'º' => '_', '°' => '_', '¯' => '_',
9843                '§' => '_', '…' => '_', '¤' => '_', '¦' => '_', '≠' => '_', '¬' => '_',
9844                'ˆ' => '_', '¨' => '_', '‰' => '_', '¤' => '_', '€' => '_', '$' => '_',
9845                '«' => '_', '»' => '_', '‹' => '_', '›' => '_', 'ƒ' => '_', '¥' => '_',
9846                '‘‘' => '_', '‚' => '_', '!' => '_', '¡' => '_', '¢' => '_', '£' => '_',
9847                '?' => '_', '[' => '_', ']' => '_', '´' => '_', '`' => '_', '^' => '_',
9848                '~' => '_', '˜' => '_', '#' => '_', '*' => '_', '.' => '_', ':' => '_',
9849                ';' => '_', '•' => '_', '¯' => '_', '‾' => '_', '–' => '_', '–' => '_',
9850                '—' => '_', '_' => '_', '|' => '_', '¦‌' => '_', '‡' => '_', '§' => '_',
9851                '¶' => '_', '©' => '_', '®' => '_', '™' => '_', '&' => '_', '@' => '_',
9852                '/' => '_', '\\' => '_', '◊' => '_', '♠' => '_', '♣' => '_', '♥' => '_',
9853                '♦' => '_', '←' => '_', '↑' => '_', '→' => '_', '↓' => '_', '↔' => '_',
9854                '°' => '_', 'µ' => '_', '<' => '_', '>' => '_', '≤' => '_', '≥' => '_',
9855                '=' => '_', '≈' => '_', '≠' => '_', '≡' => '_', '±' => '_', '−' => '_',
9856                '+' => '_', '×' => '_', '÷' => '_', '⁄' => '_', '%' => '_', '‰' => '_',
9857                '¼' => '_', '½' => '_', '¾' => '_', '¹' => '_', '²' => '_', '³' => '_',
9858                '' => '_', 'º' => '_', 'ª' => '_', 'ƒ' => '_', '′' => '_', '″' => '_',
9859                '∂' => '_', '∏' => '_', '∑' => '_', '√' => '_', '∞' => '_', '¬' => '_',
9860                '∩' => '_', '∫' => '_', 'α' => '_', 'Α' => '_', 'β' => '_', 'Β' => '_',
9861                'γ' => '_', 'Γ' => '_', 'δ' => '_', 'Δ' => '_', 'ε' => '_', 'Ε' => '_',
9862                'ζ' => '_', 'Ζ' => '_', 'η' => '_', 'Η' => '_', 'θ' => '_', 'Θ' => '_',
9863                'ι' => '_', 'Ι' => '_', 'κ' => '_', 'Κ' => '_', 'λ' => '_', 'Λ' => '_',
9864                'μ' => '_', 'Μ' => '_', 'ν' => '_', 'Ν' => '_', 'ξ' => '_', 'Ξ' => '_',
9865                'ο' => '_', 'Ο' => '_', 'π' => '_', 'Π' => '_', 'ρ' => '_', 'Ρ' => '_',
9866                'σ' => '_', 'ς' => '_', 'Σ' => '_', 'τ' => '_', 'Τ' => '_', 'υ' => '_',
9867                'Υ' => '_', 'φ' => '_', 'Φ' => '_', 'χ' => '_', 'Χ' => '_', 'ψ' => '_',
9868                'Ψ' => '_', 'ω' => '_', 'Ω' => '_', ',' => '_', ' ' => '_'
9869            );
9870    
9871            return str_replace(array_keys($invalid), array_values($invalid), $documentLibelle);
9872        }
9873    
9874        /**
9875         * Surcharge permettant de ne pas afficher le fil d'Ariane dans
9876         * l'overlay de notification des demandeurs.
9877         */
9878        function getSubFormTitle($ent) {
9879            $actionSansPath = array('411', '420', '430');
9880            if (in_array($this->getParameter('maj'), $actionSansPath)) {
9881                return '';
9882            }
9883            return parent::getSubFormTitle($ent);
9884        }
9885    }// fin classe

Legend:
Removed from v.5254  
changed lines
  Added in v.12654

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26