<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.0
 *
 * Copyright (C) 2006-2014  Sylvain FATOME
 * This program is free software; you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program
 * (in the directory docs);
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Contact : galawa@free.fr
 *
 * Web : http://smi.no-ip.org
 ****************************************************************************************/


// vérification des tentatives de hack
$pos = strpos($_SERVER['PHP_SELF'], "inc.php");
if ($pos === FALSE)
    $ok_inc = TRUE;
else
    $ok_inc = FALSE;
if ($ok_inc == FALSE) header("Location: ../index.php");


include_once("../inc/config.inc.php");
include_once("../inc/fic_age.inc.php");
include_once("../inc/fic_cli.inc.php");
include_once("../inc/fic_do.inc.php");
include_once("../inc/fic_droits.inc.php");
include_once("../inc/fic_hum.inc.php");
include_once("../inc/fic_int.inc.php");
include_once("../inc/fic_ope.inc.php");
include_once("../inc/fic_st.inc.php");
include_once("../inc/fic_tec.inc.php");
include_once("../inc/func.inc.php");
include_once("../inc/func_log.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../classes/phpmailer/class.phpmailer.php");
include_once("../classes/phpmailer/class.smtp.php");
include_once("../inc/mail.inc.php");
include_once("../classes/ezSQL/shared/ez_sql_core.php");
include_once("../classes/ezSQL/mysqli/ez_sql_mysqli.php");
include_once("../inc/func_sql.inc.php");
Archivelog(@$_SESSION["code_log"]);
// Variables Formulaire
fix_magic_quotes();

// Ce champ ne doit pas être nettoyé (codes HTML)
if (isset($_POST['txtmail']))
    $mailtxt = $_POST['txtmail'];

// Nettoyage du POST
$_GET = clean_str($_GET);
$_POST = clean_str($_POST);

$pbm_mail = FALSE;
$ci='';

if (isset($_GET['ci']))
    $ci = $_GET['ci']; // Récupération code intervention
else {
    if (isset($_POST['ci']))
        $ci = $_POST['ci']; // Récupération code intervention
    else
        $pbm_mail = TRUE;
}

if ($pbm_mail == FALSE) {
    // On vérifie si le code intervention existe
    $row = lit_enr_int($ci);
    if (is_array($row)) {
        extract($row);

        $row2 = lit_enr_cli($int_codecli, TRUE);
        if (is_array($row2)) {
            $row2 = encode_str($row2);
            extract($row2);
        } else
            $pbm_mail = TRUE;
    } else
        $pbm_mail = TRUE;
}

// Contrôle de l'expédition
$exped = FALSE;
$typeexp = "";
$messerr = "";
if ($pbm_mail == FALSE) {
    if (@$_POST["nbutton"] == "env") {
        $exped = TRUE;
        if (!ini_get('safe_mode'))
            set_time_limit(0); // On demande à PHP de ne pas interrrompre le script pendant le traitement

        // Détermination de l'expéditeur
        switch (@$_SESSION["niv_log"]) {
            case 9 :
                $typeexp = "adm";
                break;
            case 3 :
                $typeexp = "tec";
                break;
            case 5 :
                $typeexp = "cdg";
                break;
            case 4 :
                $typeexp = "age";
                break;
            case 6 :
                $typeexp = "do";
                break;
            case 10 :
                $typeexp = "st";
                break;
            default :
                break;
        }

        $mailurg = intval(@$_POST["mailurg"]);
        $maildest = @$_POST["maildest"];
        $mailcc = @$_POST["mailcc"];
        $mailbcc = @$_POST["mailbcc"];
        $mailsujet = @$_POST["mailsujet"];

        if (trim($mailtxt) <> "") // Le texte envoyé doit avoir été saisi
        {
            if ($pop_before == TRUE) {
                $pop = new POP3();
                // '0' : pas de déboggage
                // '1' : déboggage
                $pop->Authorise($pop_nom, $pop_port, $pop_timeout, $pop_login, $pop_mdp, 0);
            }

            $mail = new SMIMailer;
            $mail->init_PHPM();
            $mail->SetLanguage("fr", $root . REP . "/classes/phpmailer/language/");
            $mail->IsHTML(TRUE);
            $mail->AddAddress($maildest, '');
            if (trim($mailcc) <> "")
                $mail->AddCC($mailcc, '');
            // if ($this->Mailer <> "mail")
            if (trim($mailbcc) <> "")
                $mail->AddBCC($mailbcc, '');

            // entête de l'email
            $nom = "";
            $email = "";

            switch ($typeexp) // Analyse du type de l'expéditeur
            {
                // Administrateur
                case "adm" :
                    $nom = $admin_name;
                    $email = $admin_mail;
                    break;


                // Agence
                case "age" :
                    $row = lit_enr_age(@$_SESSION["code_log"], TRUE);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $nom = $age_nom;
                        $email = $age_email;
                    }
                    break;

                // Technicien agence
                case "tec" :
                    $row = lit_enr_tec(@$_SESSION["code_log"], TRUE);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $nom = $age_nom;
                        $email = $age_email;
                    }
                    break;

                // Centre de gestion
                case "cdg" :
                    $row = lit_enr_cdg();
                    $row = encode_str($row);
                    extract($row);
                    $nom = $cge_nom;
                    $email = $cge_email;
                    break;

                // Donneur d'ordres
                case "do" :
                    $row = lit_enr_do(@$_SESSION["code_log"]);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $nom = $do_nom;
                        $email = $do_email;
                    }
                    break;

                // Sous-traitant
                case "st" :
                    $row = lit_enr_st(@$_SESSION["code_log"]);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $nom = $st_nom;
                        $email = $st_email;
                    }
                    break;

                default :
                    break;
            }

            //Expédié par
            $mail->From = $email;
            $mail->FromName = $nom;
            $mail->Sender = $email;

            //Réponse automatique à...
            $mail->AddReplyTo($email, $nom);

            // Sujet et Corps de l'email
            $mail->Subject = $mailsujet;
            $mail->Body = $mailtxt;

            $sent = $mail->Send();

            if ($sent == FALSE)
                $messerr = _("Problème dans l'envoi du message");

            $titretra = _("Envoi mail interne");
            $desc = _("Destinataires")." :";
            $desc .= chr(13) . chr(10) . "."._("Envoi à")." -> " . $maildest;
            if (trim($mailcc) <> "")
                $desc .= chr(13) . chr(10) . "."._("Copie à")." -> " . $mailcc;
            if (trim($mailbcc) <> "")
                $desc .= chr(13) . chr(10) . "."._("Copie cachée à")." -> " . $mailbcc;

            if ($_SESSION["niv_log"] == 9)
                $code_session = _("Administrateur");
            else
                $code_session = $_SESSION["code_log"];
            $datecourante = date("Y-m-d");
            $heurecourante = date("H:i:s");

            // On se connecte a la base
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            // Ajout traçabilité
            $rech = "INSERT INTO `" . TBTRA . "`";
            $rech .= " (tra_codeutil,tra_date,tra_heure,tra_codeta,tra_titre,tra_desc,tra_typrat,tra_coderat) VALUES";
            $rech .= " ('$code_session','$datecourante','$heurecourante','EEE','" . $db->escape($titretra) . "','" . $db->escape($desc) . "','1','" . $ci . "')";
            echo "r1 : " . $rech . "<br />";
            $db->query($rech);

            // Ajout détail mail
            $last_id = $db->insert_id;
            $rech = "INSERT INTO `" . TBTRAMAIL . "`";
            $rech .= " (tramail_traid,tramail_mailexp,tramail_maildest,tramail_mailcc,tramail_mailbcc,tramail_mailurg,tramail_mailsujet,tramail_mailtxt,tramail_statut) VALUES";
            $rech .= " ('$last_id','$email','$maildest','$mailcc','$mailbcc','$mailurg','" . $db->escape($mailsujet) . "','" . $db->escape($mailtxt) . "','" . $sent . "')";
            $db->query($rech);
            $db->disconnect();
        } else
            $messerr = _("Le texte de votre email est vide");
    }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>SMI - <?PHP echo _("ESPACE PRIVE"); ?> : <?PHP echo _("Message"); ?></title>

    <?PHP include_once("../inc/header.inc.php"); ?>

    <?PHP
    if ($exped == FALSE) // Pas de formulaire si expédition demandée
    {
    ?>
    <!-- affiché uniquement si demande cohérente -->
    <script language="javascript">
        <!--
        var tab1_champ = ["nom:mailurg ; format:liste ; req:Y ; txt:<?PHP echo _("Urgence"); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad",
            "nom:maildest ; format:liste ; req:Y ; txt:<?PHP echo _("Destinataire"); ?> ; vmn:1 ; stok:frmok ; stbad:frmbad",
            "nom:mailbcc ; format:liste ; req:N ; txt:<?PHP echo _("Copie à"); ?> ; stok:frmok ; stbad:frmbad",
            "nom:mailbcc ; format:liste ; req:N ; txt:<?PHP echo _("Copie cachée à"); ?> ; stok:frmok ; stbad:frmbad",
            "nom:mailsujet ; format:txt ; req:Y ; txt:<?PHP echo _("Sujet"); ?> ; vmn:1 ; vmx:80; stok:frmok ; stbad:frmbad"];
        //-->
    </script>
    <?PHP } ?>

    <script type="text/javascript">
        <!--
        function init_all() {
            init_Body();
            <?PHP
            if ($exped == FALSE)
            {
                echo "$('#txtmail').ckeditor();";
                echo "init_valid_form('env','mailintmaj','".$_SESSION['date_fmtshort']."',tab1_champ,'','');";
            }
            else
            {
                if ($messerr == "")
                    echo "pop_txt('"._("Message envoyé")."');";
                else
                    pop_ret_auto($messerr, 'warn', 'mailint_maj.php?ci=' . $ci);
                close_fen_auto('', '');
            }
            ?>
            Focus_first();
        }

        $(document).ready(function () {
            init_all();
        });
        //-->
    </script>

</head>

<body>
<p align="center"><span class="titrepage"><?PHP echo _("ENVOI MESSAGE")?></span></p>

<p align="center"><span class="annot_petit_itgras"><?PHP echo _("Pour l'intervention"); ?> <?PHP echo $ci; ?></span></p>
<?PHP
if ($pbm_mail == FALSE) {

    if ($exped == FALSE) // Pas de formulaire si expédition demandée
    {
        ?>
        <form name="mailint_maj" id="mailint_maj" method="post" action="mailint_maj.php">
            <input name="ci" type="hidden" id="ci" value="<?PHP echo $ci; ?>">
            <input name="nbutton" type="hidden" id="nbutton" value="">
            <?PHP
            // On crée la liste des destinataires possibles
            $tab_contacts_cli = [];
            $tab_ctact = [];

            if ($cli_ste <> "") {
                // On récupère le code maître (si le client fait partie d'un regroupement)
                $tab_maitre = [];
                $tab_maitre = give_tab_maitre_cli($cli_code, TRUE);

                // création de la liste des contacts du client
                $txt_ccli = $cli_nom . " " . $cli_prenom . " (Contact principal";
                $txt_ccli .= " - " . $cli_telf;
                if ($cli_telp <> "")
                    $txt_ccli .= " / " . $cli_telp;
                $txt_ccli .= ")";
                $tab_ctact[0] = $cli_email;
                $tab_ctact[1] = $txt_ccli;
                $tab_contacts_cli[] = $tab_ctact;

                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

                // données site client
                if (intval($int_idsite) > 0) {
                    $rech = "SELECT * FROM `" . TBSCLI . "` WHERE `scli_id` = '$int_idsite'";
                    $row = $db->get_row($rech, ARRAY_A);
                    if ($row) {
                        extract($row);
                        $txt_ccli = $scli_rnom . " " . $scli_rprenom . " ("._("Contact site");
                        $txt_ccli .= " - " . $scli_telf;
                        if ($scli_telp <> "")
                            $txt_ccli .= " / " . $scli_telp;
                        $txt_ccli .= ")";
                        $tab_ctact[0] = $scli_email;
                        $tab_ctact[1] = $txt_ccli;
                        $tab_contacts_cli[] = $tab_ctact;
                    }
                }

                // Filtre sur client
                $rech = "SELECT * FROM `" . TBCCLI . "` WHERE `ccli_codecli` = '" . $cli_code . "'";
                if (count($tab_maitre) > 0) {
                    foreach ($tab_maitre as $key => $value) {
                        $rech .= " OR `ccli_codecli` = '" . $value . "'";
                    }
                }
                $rech .= " ORDER BY ccli_nom";
                $rows = $db->get_results($rech, ARRAY_A);
                if ($rows) {
                    foreach ($rows as $row) {
                        $row = encode_str($row);
                        extract($row);

                        $txt_ccli = $ccli_nom . " " . $ccli_prenom;
                        $row2 = lit_enr_fonc($ccli_codefonc, FALSE);
                        if (is_array($row2)) {
                            $row2 = encode_str($row2);
                            extract($row2);
                            $txt_fonc = $fonc_desc;
                        } else
                            $txt_fonc = $ccli_codefonc;
                        $txt_ccli .= " (";
                        if (count($tab_maitre) > 0) {
                            $nomcli = "";
                            $rech3 = "SELECT cli_ste FROM `" . TBCLI . "` WHERE `cli_code` = '$ccli_codecli'";
                            $row3 = $db->get_row($rech3, ARRAY_A);
                            if ($row3)
                                $nomcli = $row3["cli_ste"];
                            if ($nomcli <> "")
                                $txt_ccli .= $nomcli . " - ";
                        }
                        $txt_ccli .= $txt_fonc;
                        $txt_ccli .= " - " . $ccli_telf;
                        if ($ccli_telp <> "")
                            $txt_ccli .= " / " . $ccli_telp;
                        $txt_ccli .= ")";
                        $tab_ctact[0] = $ccli_email;
                        $tab_ctact[1] = $txt_ccli;
                        $tab_contacts_cli[] = $tab_ctact;
                    }
                }
                $db->disconnect();
            } else {
                $txt_ccli = "";
                $row = lit_enr_cli($cli_code, TRUE);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);
                    $txt_ccli = $cli_nom . " " . $cli_prenom . " (" . $cli_codefonc;
                    $row2 = lit_enr_fonc($cli_codefonc, TRUE);
                    if (is_array($row2)) {
                        $row2 = encode_str($row2);
                        extract($row2);
                        $txt_fonc = $fonc_desc;
                    } else
                        $txt_fonc = $ccli_codefonc;
                    $txt_ccli .= " (" . $txt_fonc;
                    $txt_ccli .= " - " . $cli_telf;
                    if ($cli_telp <> "")
                        $txt_ccli .= " / " . $cli_telp;
                    $txt_ccli .= ")";
                }
                if ($txt_ccli <> "") {
                    $tab_ctact[0] = $cli_email;
                    $tab_ctact[1] = $txt_ccli;
                    $tab_contacts_cli[] = $tab_ctact;
                }
            }

            echo '<table width="100%"  border="0">';
            echo '<tr>';
            echo '<td width="120" class="rubfrm" id="f_mailurg" align="right">'._("Urgence").'</td>';
            echo '<td align="left">';
            echo '<select name="mailurg" id="mailurg">';
            echo '<option value="">' . _("-- Faites votre choix --") . '</option>';
            foreach ($tra_urg as $key => $value) {
                echo '<option value="' . $key . '">' . $value . '</option>';
            }
            echo '</select>';
            echo '</td>';
            echo '</tr>';
            echo '<tr>';
            echo '<td width="120" class="rubfrm" id="f_maildest" align="right">'._("Destinataire").'</td>';
            echo '<td align="left">';
            echo '<select name="maildest" id="maildest">';
            echo '<option value="">' . _("-- Faites votre choix --") . '</option>';
            foreach ($tab_contacts_cli as $value) {
                echo '<option value="' . $value[0] . '">' . $value[1] . '</option>';
            }
            echo '</select>';
            echo '</td>';
            echo '</tr>';
            echo '<tr>';
            echo '<td class="rubfrm" id="f_mailcc" align="right">Copie à</td>';
            echo '<td align="left">';
            echo '<select name="mailcc" id="mailcc">';
            echo '<option value="">' . _("-- Faites votre choix --") . '</option>';
            foreach ($tab_contacts_cli as $value) {
                echo '<option value="' . $value[0] . '">' . $value[1] . '</option>';
            }
            echo '</select>';
            echo '</td>';
            echo '</tr>';
            echo '<tr>';
            echo '<td class="rubfrm" id="f_mailbcc" align="right">Copie cachée à</td>';
            echo '<td align="left">';
            echo '<select name="mailbcc" id="mailbcc">';
            echo '<option value="">' . _("-- Faites votre choix --") . '</option>';
            foreach ($tab_contacts_cli as $value) {
                echo '<option value="' . $value[0] . '">' . $value[1] . '</option>';
            }
            echo '</select>';
            echo '</td>';
            echo '</tr>';
            echo '<tr>';
            echo '<td class="rubfrm" id="f_mailsujet" align="right">Sujet</td>';
            echo '<td align="left">';
            echo '<input name="mailsujet" type="text" id="mailsujet" value="" size="80" maxlength="80">';
            echo '</td>';
            echo '</tr>';
            echo '<tr>';
            echo '<td class="rubfrm" id="f_mailtxt" align="right"><?PHP echo _("Texte"); ?></td>';
            echo '<td align="left">';
            echo '<textarea name="txtmail" id="txtmail" rows="10" cols="80">';
            echo '</textarea>';
            echo '</td>';
            echo '</tr>';
            echo '</table>';

            echo '</ br>';
            echo '<div id="butmailext" align="center" style="margin-top:10px;">';
            echo '<input name="env" type="button" class="bton_fgris_petit" id="env" value="' . _("Expédier") . '">';
            echo '</div>';
            ?>

        </form>
        <!-- Fin affiché uniquement si demande cohérente -->
    <?PHP
    } // Fin Contrôle si expédition
} else
    close_fen_auto(_("Problème de paramètres"), 'fscomp', 5000);
?>
