<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.2
 *
 * Copyright (C) 2006-2015  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");

if ((stristr($_SERVER['PHP_SELF'], "/admin/")) OR (stristr($_SERVER['PHP_SELF'], "/age/")) OR (stristr($_SERVER['PHP_SELF'], "/cli/")) OR (stristr($_SERVER['PHP_SELF'], "/do/")) OR (stristr($_SERVER['PHP_SELF'], "/ope/")) OR (stristr($_SERVER['PHP_SELF'], "/st/"))) {
    include_once("../inc/phpm_ext.inc.php");
    include_once("../classes/phpmailer/class.pop3.php");
} else {
    include_once("inc/phpm_ext.inc.php");
    include_once("classes/phpmailer/class.pop3.php");
}

/********************************/
/* Fonctions d'envoi des emails */
/********************************/

// Création des destinataires

/**
 * Création des destinataires centre de gestion
 *
 * @param $tab
 * @param $dir
 * @param $tec
 * @return mixed
 */
function cre_dest_cdg($tab, $dir, $tec)
{
    $tab_dest = $tab;

    $row = lit_enr_cdg();
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($dir == TRUE)
            $tab_dest[$cge_emaild] = _("Centre de gestion (Service direction)");
        if ($tec == TRUE) {
            if (array_key_exists($cge_emailt, $tab_dest) == false)
                $tab_dest[$cge_emailt] = _("Centre de gestion (Service technique)");
        }
    }
    return $tab_dest;
}

/**
 * Création des destinataires agence
 *
 * @param $code
 * @param $tab
 * @param $dir
 * @param $tec
 * @param bool $open
 * @return mixed
 */
function cre_dest_age($code, $tab, $dir, $tec, $open = TRUE)
{
    $tab_dest = $tab;

    $row = lit_enr_age($code, TRUE, $open);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($dir == TRUE) {
            if (array_key_exists($age_emaild, $tab_dest) == false)
                $tab_dest[$age_emaild] = _("Agence").' ' . $age_nom . ' ('._("Service direction").')';
        }
        if ($tec == TRUE) {
            if (array_key_exists($age_emailt, $tab_dest) == false)
                $tab_dest[$age_emailt] = _("Agence").' ' . $age_nom . ' ('._("Service technique").')';
        }
    }
    return $tab_dest;
}

/**
 * Création des destinataires contacts client
 *
 * @param $code
 * @param $tab
 * @param bool $open
 * @return mixed
 */
function cre_dest_ccli($code, $tab, $open = TRUE)
{
    $tab_dest = $tab;
    $row = lit_enr_ccli($code, $open);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($ccli_email <> "") // Coordonnées du contact
            $tab_dest[$ccli_email] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
    }
    return $tab_dest;
}

/**
 * Création des destinataires client
 *
 * @param $code
 * @param $tab
 * @param $dir
 * @param $tec
 * @param bool $open
 * @return mixed
 */
function cre_dest_cli($code, $tab, $dir, $tec, $open = TRUE)
{
    global
    $db;
    $tab_dest = $tab;

    $row = lit_enr_cli($code, TRUE);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($cli_email <> "") // Contact Principal
            $tab_dest[$cli_email] = $cli_civilite . " " . $cli_prenom . " " . $cli_nom;

        $rexist = "SELECT DISTINCT * FROM `" . TBCCLI . "` WHERE `ccli_codecli` = '$cli_code' AND `ccli_email`<>''";
        if (($dir == TRUE) OR ($tec == TRUE)) {
            $rexist .= " AND (";
            if ($dir == TRUE)
                $rexist .= " `ccli_maild` = '1'";
            if ($tec == TRUE) {
                if ($dir == TRUE)
                    $rexist .= " OR `ccli_mailt` = '1'";
                else
                    $rexist .= " `ccli_mailt` = '1'";
            }
            $rexist .= ")";
        } else {
            $rexist .= " AND (";
            $rexist .= " `ccli_maild` <> '0'";
            $rexist .= " OR `ccli_mailt` <> '0'";
            $rexist .= ")";
        }
        $rexist .= " AND `ccli_email` <> '" . $cli_email . "'";
        if ($open == TRUE)
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

        $rows = $db->get_results($rexist, $ARRAY_A);
        if ($rows) {
            foreach ($rows as $row) {
                extract($row);
                if (array_key_exists($ccli_email, $tab_dest) == false)
                    $tab_dest[$ccli_email] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
            }
        }
        if ($open == TRUE)
            $db->disconnect();
    }
    return $tab_dest;
}

/**
 * Création des destinataires donneurs d'ordres
 *
 * @param $code
 * @param $tab
 * @param $dir
 * @param $tec
 * @param bool $open
 * @return mixed
 */
function cre_dest_do($code, $tab, $dir, $tec, $open = TRUE)
{
    $tab_dest = $tab;

    $row = lit_enr_do($code, $open);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($dir == TRUE)
            $tab_dest[$do_emaild] = $do_nom . ' ('._("Service direction").')';
        if ($tec == TRUE) {
            if (array_key_exists($do_emailt, $tab_dest) == false)
                $tab_dest[$do_emailt] = $do_nom . ' ('._("Service technique").')';
        }
    }
    return $tab_dest;
}

/**
 * Création des destinataires sous-traitants
 *
 * @param $code
 * @param $tab
 * @param $dir
 * @param $tec
 * @param bool $open
 * @return mixed
 */
function cre_dest_st($code, $tab, $dir, $tec, $open = TRUE)
{
    $tab_dest = $tab;

    $row = lit_enr_st($code,$open);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if ($dir == TRUE)
            $tab_dest[$st_emaild] = $st_nom . ' ('._("Service direction").')';
        if ($tec == TRUE) {
            if (array_key_exists($st_emailt, $tab_dest) == false)
                $tab_dest[$st_emailt] = $st_nom . ' ('._("Service technique").')';
        }
    }
    return $tab_dest;
}

// Récupération des codes

/**
 * @param $code
 * @param bool $open
 * @return string
 */
function give_codeage($code, $open = TRUE)
{
    $codeage = "";
    $row = lit_enr_age($code, $open);
    if (is_array($row)) {
        extract($row);
        $codeage = $age_code;
    }
    return $codeage;
}

/**
 * @param $code
 * @param bool $open
 * @return string
 */
function give_codedo($code, $open = TRUE)
{
    $codedo = "";
    $row = lit_enr_do($code, $open);
    if (is_array($row)) {
        extract($row);
        $codedo = $do_code;
    }
    return $codedo;
}

/**
 * @param $code
 * @param bool $open
 * @return string
 */
function give_codest($code, $open = TRUE)
{
    $codest = "";
    $row = lit_enr_st($code,$open);
    if (is_array($row)) {
        extract($row);
        $codest = $st_code;
    }
    return $codest;
}

// Construction des logos

/**
 * "Moulinage" des logos
 *
 * @param $codedest
 * @param $typedest
 * @param $txt
 * @param bool $open
 * @return mixed
 */
function parse_logos($codedest, $typedest, $txt, $open = TRUE)
{
    global
    $url_logos,
    $cheminr_logos;

    $txtcorps = $txt;

    // Il y a au moins un champ logo dans le texte ?
    if (stristr($txtcorps, "%logo_cge%") OR stristr($txtcorps, "%logo_age%") OR stristr($txtcorps, "%logo_do%")  OR stristr($txtcorps, "%logo_st%")) {
        // Il y a un logo centre de gestion
        if (stristr($txtcorps, "%logo_cge%")) {
            $chem_logo = $cheminr_logos . "/logcge.png";
            $infos_img = @getimagesize($chem_logo);
            $url_logo = $url_logos . "/logcge.png";
            $src_img = '<img src="' . $url_logo . '" alt="'._("logo_siege").'"' . $infos_img[3] . ' border="0">';
            $txtcorps = str_replace("%logo_cge%", $src_img, $txtcorps);
        }

        // Il y a un logo agence
        if (stristr($txtcorps, "%logo_age%")) {
            $codedestage = "";
            // Balayage des types
            switch ($typedest) {
                // Agence
                case "age" :
                    $codedestage = give_codeage($codedest,$open);
                    break;

                // Client
                case "cli" :
                    $row = lit_enr_cli($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($cli_prop <> "")
                            $codedestage = give_codeage($cli_prop,$open);
                        else
                            $codedestage = "cge";
                    }
                    break;

                // Contrat
                case "con" :
                    $row = lit_enr_cocl($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($cocl_codeage <> "")
                            $codedestage = give_codeage($cocl_codeage,$open);
                    }
                    break;

                // Intervention
                case "int" :
                    $row = lit_enr_int($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($int_codeage <> "")
                            $codedestage = give_codeage($int_codeage,$open);
                    }
                    break;

                // Intervention : détail horaire
                case "inth" :
                    $row = lit_enr_inth(intval($codedest),$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $row2 = lit_enr_int($inth_codeint,$open);
                        if (is_array($row2)) {
                            $row2 = encode_str($row2);
                            extract($row2);
                            if ($int_codeage <> "")
                                $codedestage = give_codeage($int_codeage,$open);
                        }
                    }
                    break;

                // Ordre Sous-traitance
                case "ot" :
                    $row = lit_enr_ot($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $row2 = lit_enr_int($ot_codeint,$open);
                        if (is_array($row2)) {
                            $row2 = encode_str($row2);
                            extract($row2);
                            if ($int_codeage <> "")
                                $codedestage = give_codeage($int_codeage,$open);
                        }
                    }
                    break;

                // Relevé (Dossier)
                case "rel" :
                    $row = lit_enr_rel($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($rel_codeage <> "")
                            $codedestage = give_codeage($rel_codeage,$open);
                    }
                    break;

                // Produit à retourner
                case "retp" :
                    // Traitement du retour
                case "retr" :
                    $row = lit_enr_retp($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($retp_codeage <> "")
                            $codedestage = give_codeage($retp_codeage,$open);
                    }
                    break;

                // Relevé (Licence)
                case "rlic" :
                    $row = lit_enr_rlic($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($rlic_codeage <> "")
                            $codedestage = give_codeage($rlic_codeage,$open);
                    }
                    break;

                // Relevé (Matériel)
                case "rpdt" :
                    $row = lit_enr_rpdt($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($rpdt_codeage <> "")
                            $codedestage = give_codeage($rpdt_codeage,$open);
                    }
                    break;

                // Déclaration de problème
                case "rpbm" :
                    $row = lit_enr_rpbm($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        switch ($rpbm_typrel) {
                            case 1 :
                                $row2 = lit_enr_rlic($rpbm_coderlp,$open);
                                if (is_array($row2)) {
                                    $row2 = encode_str($row2);
                                    extract($row2);
                                    if ($rlic_codeage <> "")
                                        $codedestage = give_codeage($rlic_codeage,$open);
                                }
                                break;
                            case 2 :
                                $row2 = lit_enr_rpdt($rpbm_coderlp,$open);
                                if (is_array($row2)) {
                                    $row2 = encode_str($row2);
                                    extract($row2);
                                    if ($rpdt_codeage <> "")
                                        $codedestage = give_codeage($rpdt_codeage,$open);
                                }
                                break;
                            default :
                                break;
                        }
                    }
                    break;

                // Technicien
                case "tec" :
                    $row = lit_enr_tec($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($tec_codeage <> "")
                            $codedestage = give_codeage($tec_codeage,$open);
                    }
                    break;

                default :
                    break;
            }

            if ($codedestage <> "") {
                $txt_alt = _("logo_agence");
                $row = lit_enr_age($codedestage, $open);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);
                    $txt_alt = "logo_" . str_upload($age_nom);
                }
                $chem_logo = $cheminr_logos . "/log" . strtolower($codedestage) . ".png";
                $infos_img = @getimagesize($chem_logo);
                $url_logo = $url_logos . "/log" . strtolower($codedestage) . ".png";
                $src_img = '<img src="' . $url_logo . '" alt="' . $txt_alt . '" ' . $infos_img[3] . ' border="0">';
                $txtcorps = str_replace("%logo_age%", $src_img, $txtcorps);
            }
        }

        // Il y a un logo donneur d'ordres
        if (stristr($txtcorps, "%logo_do%")) {
            $codedestdo = "";
            // Balayage des types
            switch ($typedest) {
                // Client
                case "cli" :
                    $row = lit_enr_cli($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($cli_codedo <> "")
                            $codedestdo = give_codedo($cli_codedo,$open);
                    }
                    break;

                // Intervention
                case "int" :
                    $row = lit_enr_int($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($int_codedo <> "")
                            $codedestdo = give_codedo($int_codedo,$open);
                    }
                    break;

                // Technicien
                case "tec" :
                    $row = lit_enr_tec($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($tec_codedo <> "")
                            $codedestdo = give_codedo($tec_codedo,$open);
                    }
                    break;

                default :
                    break;
            }

            if ($codedestdo <> "") {
                $txt_alt = "logo_do";
                $row = lit_enr_do($codedestdo,$open);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);
                    $txt_alt = "logo_" . str_upload($do_nom);
                }
                $chem_logo = $cheminr_logos . "/log" . strtolower($codedestdo) . ".png";
                $infos_img = @getimagesize($chem_logo);
                $url_logo = $url_logos . "/log" . strtolower($codedestdo) . ".png";
                $src_img = '<img src="' . $url_logo . '" alt="' . $txt_alt . '" ' . $infos_img[3] . ' border="0">';
                $txtcorps = str_replace("%logo_do%", $src_img, $txtcorps);
            }
        }

        // Il y a un logo sous-traitant
        if (stristr($txtcorps, "%logo_st%")) {
            $codedestst = "";
            // Balayage des types
            switch ($typedest) {
                // Intervention
                case "int" :
                    $row = lit_enr_int($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($int_codest <> "")
                            $codedestst = give_codest($int_codest,$open);
                    }
                    break;

                // Ordre de sous-traitance
                case "ot" :
                    $row = lit_enr_ot($codedest,$open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($ot_codest <> "")
                            $codedestst = give_codest($ot_codest,$open);
                    }
                    break;

                // Technicien
                case "tec" :
                    $row = lit_enr_tec($codedest, $open);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($tec_codest <> "")
                            $codedestst = give_codest($tec_codest,$open);
                    }
                    break;

                default :
                    break;
            }

            if ($codedestst <> "") {
                $txt_alt = "logo_st";
                $row = lit_enr_st($codedestst);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);
                    $txt_alt = "logo_" . str_upload($st_nom);
                }
                $chem_logo = $cheminr_logos . "/log" . strtolower($codedestst) . ".png";
                $infos_img = @getimagesize($chem_logo);
                $url_logo = $url_logos . "/log" . strtolower($codedestst) . ".png";
                $src_img = '<img src="' . $url_logo . '" alt="' . $txt_alt . '" ' . $infos_img[3] . ' border="0">';
                $txtcorps = str_replace("%logo_st%", $src_img, $txtcorps);
            }
        }
    }

    return $txtcorps;
}

// Envois des emails

/**
 * Envoi des emails "classiques"
 *
 * @param $nomfic
 * @param $sujet
 * @param $type
 * @param $mode
 * @param $orig
 * @param $dest
 * @param $code
 * @param $pass
 * @param $total
 * @param $copieadmin
 * @param string $attach
 * @param bool $open
 */
function envoi_mail($nomfic, $sujet, $type, $mode, $orig, $dest, $code, $pass, $total, $copieadmin, $attach = "", $open = TRUE)
{
    global
    $db,
    $admin_name,
    $admin_mail,
    $code_util,
    $niv_util,
    $root,
    $_SESSION,
    $pop_before,
    $pop_nom,
    $pop_port,
    $pop_timeout,
    $pop_login,
    $pop_mdp;

    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);

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

    //Copie administrateur ?
    $mail->copieadmin = $copieadmin;

    // Destinataires
    $tab_dest = [];

    if ($dest == "wm") // Le destinataire est le webmaster
        $tab_dest[$admin_mail] = $admin_name;
    else // Ce n'est pas uniquement le Webmaster
    {
        // Création des destinataires
        switch ($type) // Analyse du type d'opération
        {
            // Agence
            case "age" :
                switch ($dest) {
                    case "age" :
                        $tab_dest = cre_dest_age($code, $tab_dest, TRUE, TRUE);
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Centre de Gestion
            case "cdg" :
                $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                break;

            // Contact Client
            case "ccli" :
                switch ($dest) {
                    case "ccli" :
                        // Si on crée un compte contact client, ou si on modifie le MDP, direction uniquement
                        if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MDP"))
                            $tab_dest = cre_dest_ccli($code, $tab_dest);
                        else
                            $tab_dest = cre_dest_ccli($code, $tab_dest);
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Client
            case "cli" :
                switch ($dest) {
                    case "cli" :
                        // Si on crée un compte client, ou si on modifie le MDP, ou si déménagement copie à direction uniquement
                        if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MDP") OR (str_majuscules($mode) == "DEM"))
                            $tab_dest = cre_dest_cli($code, $tab_dest, TRUE, FALSE);
                        else
                            $tab_dest = cre_dest_cli($code, $tab_dest, FALSE, FALSE);
                        break;
                    case "do" :
                        $row = lit_enr_cli($code, TRUE);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_do($cli_codedo, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Contrat location
            case "col" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_coloc($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, on le modifie, ou on en accuse réception, copies à direction et technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD"))
                                $tab_dest = cre_dest_cli($coloc_codecli, $tab_dest, TRUE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($coloc_codecli, $tab_dest, FALSE, FALSE);
                        }
                        break;
                    case "age" :
                        $row = lit_enr_coloc($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($coloc_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Contrat
            case "con" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_cocl($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, on le modifie, ou on en accuse réception, copies à direction et technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD") OR (str_majuscules($mode) == "ENV") OR (str_majuscules($mode) == "AR"))
                                $tab_dest = cre_dest_cli($cocl_codecli, $tab_dest, TRUE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($cocl_codecli, $tab_dest, FALSE, FALSE);
                        }
                        break;
                    case "age" :
                        $row = lit_enr_cocl($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($cocl_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Si demande
            case "dde" :
                if (str_majuscules($mode) == "CRE") // On est en mode demande
                {
                    $row = lit_enr_dde($code);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        if ($dde_codedded <> "VA") {
                            $row2 = lit_enr_dded($dde_codedded);
                            if (is_array($row2)) {
                                $row2 = encode_str($row2);
                                extract($row2);
                                $tab_dest[$dded_email] = $dded_desc;
                            }
                        } else // Le destinataire est "Votre agence"
                        {
                            if ($niv_util == 1) // On vérifie que c'est un client qui demande
                            {
                                $row2 = lit_enr_cli($code_util, TRUE);
                                if (is_array($row2)) {
                                    $row2 = encode_str($row2);
                                    extract($row2);
                                    if (($cli_prop <> NULL) AND ($cli_prop <> "")) // Le client est géré par une agence
                                    {
                                        $row3 = lit_enr_age($cli_prop, TRUE);
                                        if (is_array($row3)) {
                                            $row3 = encode_str($row3);
                                            extract($row3);
                                            $tab_dest[$age_email] = _("Agence").' ' . $age_nom;
                                        }
                                    } else // Le client n'est pas géré par une agence, on envoie à toutes les agences de sa zone
                                    {
                                        if ($open == TRUE)
                                            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
                                        $rech = "SELECT * FROM `" . TBAGE . "`";
                                        $rech .= "  WHERE `age_ouvert` = 1 AND `age_codepays`='" . str_majuscules($cli_codepays) . "'";
                                        $rows = $db->get_results($rech, ARRAY_A);
                                        if ($rows) {
                                            foreach ($rows as $row) {
                                                $row = encode_str($row);
                                                extract($row);
                                                $tab_depzc = tab_zcc_age_open($age_code, FALSE);
                                                if (count($tab_depzc) > 0) {
                                                    foreach ($tab_depzc as $key => $value) {
                                                        if (trim($key) <> "") {
                                                            if (array_key_exists($age_email, $tab_dest) == false)
                                                                $tab_dest[$age_email] = _("Agence").' ' . $age_nom;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if ($open == TRUE)
                                            $db->disconnect();
                                    }
                                }
                            }
                        }
                    }
                }
                if (str_majuscules($mode) == "AR") // On est en mode accusé de réception
                {
                    $row = lit_enr_dde($code);
                    if (is_array($row)) {
                        $row = encode_str($row);
                        extract($row);
                        $tab_dest[$dde_email] = $dde_civilite . " " . $dde_prenom . " " . $dde_nom;
                    }
                }
                break;

            // Donneur d'ordres
            case "do" :
                switch ($dest) {
                    case "do" :
                        $tab_dest = cre_dest_do($code, $tab_dest, TRUE, TRUE);
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Dossiers de suivi
            case "dos" :
                switch ($dest) {
                    case "age" :
                        $row = lit_enr_dos($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($dos_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Fichiers internes
            case "fic" :
                switch ($dest) {
                    case "age" :
                        $tab_dest = cre_dest_age($code, $tab_dest, TRUE, TRUE);
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Intervention
            case "int" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_int($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée une intervention, ou si on la termine, copie à technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "FAIT"))
                                $tab_dest = cre_dest_cli($int_codecli, $tab_dest, FALSE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($int_codecli, $tab_dest, FALSE, FALSE);

                            // On prévient également le contact demandeur
                            // Si ce contact n'est pas le contact du site principal (qui est de toutes façons prévenu)
                            if ((trim($int_ddeur) <> "") AND (trim($int_ddeur) <> "-1")) {
                                // C'est le contact principal du site
                                if (trim($int_ddeur) == "0") {
                                    $row = lit_enr_scli_id($int_idsite, TRUE);
                                    if (is_array($row)) {
                                        $row = encode_str($row);
                                        extract($row);
                                        if (trim($scli_remail) <> "") {
                                            if (array_key_exists($scli_remail, $tab_dest) == false)
                                                $tab_dest[$scli_email] = $scli_rcivil . " " . $scli_rprenom . " " . $scli_rnom;
                                        }
                                    }
                                } else // C'est un autre contact
                                {
                                    if ($open == TRUE)
                                        $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

                                    $rexist = "SELECT * FROM `" . TBCCLI . "` WHERE `ccli_id` = '" . trim($int_ddeur) . "' AND `ccli_email`<>''";
                                    $row = $db->get_row($rexist, ARRAY_A);
                                    if ($row) {
                                        $row = encode_str($row);
                                        extract($row);
                                        if (array_key_exists($ccli_email, $tab_dest) == false)
                                            $tab_dest[$ccli_email] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
                                    }
                                    if ($open == TRUE)
                                        $db->disconnect();
                                }
                            }
                        }
                        break;
                    case "age" :
                        $row = lit_enr_int($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            switch ($_SESSION["niv_log"]) {
                                case 3 :
                                case 4 :
                                    // On contrôle si le code connecté est différent du code agence responsable de l'intervention
                                    // (Si c'est le cas, on envoie un email, sinon, non)
                                    if ($_SESSION["code_age"] <> $int_codeage)
                                        $tab_dest = cre_dest_age($int_codeage, $tab_dest, TRUE, TRUE);
                                    // On contrôle si le code connecté est différent du code agence responsable du site de l'intervention
                                    // (Si c'est le cas, on envoie un email, sinon, non)
                                    if (($_SESSION["code_age"] <> $codeages) AND ($int_idsite > 0))
                                        $tab_dest = cre_dest_age($int_codeages, $tab_dest, TRUE, TRUE);
                                    break;
                                default :
                                    $tab_dest = cre_dest_age($int_codeage, $tab_dest, TRUE, TRUE);
                                    $tab_dest = cre_dest_age($int_codeages, $tab_dest, TRUE, TRUE);
                                    break;
                            }
                        }
                        break;
                    case "do" :
                        $row = lit_enr_int($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_do($int_codedo, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "st" :
                        $row = lit_enr_int($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_st($int_codest, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "tec" :
                        $row = lit_enr_int($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $row = lit_enr_tec($int_codetec, TRUE);
                            if (is_array($row)) {
                                $row = encode_str($row);
                                extract($row);
                                $tab_dest[$tec_email] = $tec_civilite . " " . $tec_prenom . " " . $tec_nom;
                            }
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Intervention : détail horaire
            case "inth" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_inth(intval($code));
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            $row2 = lit_enr_int($inth_codeint);

                            if (is_array($row2)) {
                                $row2 = encode_str($row2);
                                extract($row2);

                                $tab_dest = cre_dest_cli($int_codecli, $tab_dest, FALSE, TRUE);

                                // On prévient également le contact demandeur
                                // Si ce contact n'est pas le contact du site principal (qui est de toutes façons prévenu)
                                if ((trim($int_ddeur) <> "") AND (trim($int_ddeur) <> "-1")) {
                                    // C'est le contact principal du site
                                    if (trim($int_ddeur) == "0") {
                                        $row = lit_enr_scli_id($int_idsite, TRUE);
                                        if (is_array($row)) {
                                            $row = encode_str($row);
                                            extract($row);
                                            if (trim($scli_remail) <> "") {
                                                if (array_key_exists($scli_remail, $tab_dest) == false)
                                                    $tab_dest[$scli_email] = $scli_rcivil . " " . $scli_rprenom . " " . $scli_rnom;
                                            }
                                        }
                                    } else // C'est un autre contact
                                    {
                                        if ($open == TRUE)
                                            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

                                        $rexist = "SELECT * FROM `" . TBCCLI . "` WHERE `ccli_id` = '" . trim($int_ddeur) . "' AND `ccli_email`<>''";
                                        $row = $db->get_row($rexist, ARRAY_A);
                                        if ($row) {
                                            $row = encode_str($row);
                                            extract($row);
                                            if (array_key_exists($ccli_email, $tab_dest) == false)
                                                $tab_dest[$ccli_email] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
                                        }
                                        if ($open == TRUE)
                                            $db->disconnect();
                                    }
                                }
                            }
                        }
                        break;
                    case "age" :
                        break;
                    case "do" :
                        break;
                    case "st" :
                        break;
                    case "tec" :
                        break;
                    case "cdg" :
                        break;
                }
                break;

            // Opérateur
            case "ope" :
                switch ($dest) {
                    case "ope" :
                        $row = lit_enr_ope($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest[$ope_email] = $ope_civilite . " " . $ope_prenom . " " . $ope_nom;
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Ordre sous-traitance
            case "ot" :
                switch ($dest) {
                    case "age" :
                        $row = lit_enr_ot($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            if ($ot_codeint <> "--AR--") {
                                $row = lit_enr_int($ot_codeint);
                                if (is_array($row)) {
                                    $row = encode_str($row);
                                    extract($row);
                                    $tab_dest = cre_dest_age($int_codeage, $tab_dest, TRUE, TRUE);
                                }
                            } else {
                                $row = lit_enr_cli($ot_codecli, TRUE);
                                if (is_array($row)) {
                                    $row = encode_str($row);
                                    extract($row);
                                    $tab_dest = cre_dest_age($cli_prop, $tab_dest, TRUE, TRUE);
                                }
                            }
                        }
                        break;
                    case "st" :
                        $row = lit_enr_ot($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_st($ot_codest, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Technicien
            case "tec" :
                switch ($dest) {
                    case "age" :
                        $row = lit_enr_tec($code, TRUE);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($tec_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "tec" :
                        $row = lit_enr_tec($code, TRUE);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest[$tec_email] = $tec_civilite . " " . $tec_prenom . " " . $tec_nom;
                        }
                        break;
                    case "do ":
                        $row = lit_enr_tec($code, TRUE);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_do($tec_codedo, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "st" :
                        $row = lit_enr_tec($code, TRUE);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_st($tec_codest, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Relevé de parc
            case "rel" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_rel($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, ou si on le modifie, copies à technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD"))
                                $tab_dest = cre_dest_cli($rel_codecli, $tab_dest, FALSE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($rel_codecli, $tab_dest, FALSE, FALSE);
                        }
                        break;
                    case "age" :
                        $row = lit_enr_rel($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($rel_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Relevé Licence
            case "rlic" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_rlic($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, ou si on le modifie, copies à technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD"))
                                $tab_dest = cre_dest_cli($rlic_codecli, $tab_dest, FALSE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($rlic_codecli, $tab_dest, FALSE, FALSE);

                            // On envoie une copie au contact principal du site
                            if ($rlic_idsite > 0) {
                                $row = lit_enr_scli_id($rlic_idsite, TRUE);
                                if (is_array($row)) {
                                    $row = encode_str($row);
                                    extract($row);
                                    if (array_key_exists($scli_remail, $tab_dest) == false)
                                        $tab_dest[$scli_remail] = $scli_rcivil . " " . $scli_rprenom . " " . $scli_rnom;
                                }
                            }
                        }
                        break;
                    case "age" :
                        $row = lit_enr_rlic($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($rlic_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Relevé Produit
            case "rpdt" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_rpdt($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, ou si on le modifie, copies à technique uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD"))
                                $tab_dest = cre_dest_cli($rpdt_codecli, $tab_dest, FALSE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($rpdt_codecli, $tab_dest, FALSE, FALSE);

                            // On envoie une copie au contact principal du site
                            if ($rpdt_idsite > 0) {
                                $row = lit_enr_scli_id($rpdt_idsite, TRUE);
                                if (is_array($row)) {
                                    $row = encode_str($row);
                                    extract($row);
                                    if (array_key_exists($scli_remail, $tab_dest) == false)
                                        $tab_dest[$scli_remail] = $scli_rcivil . " " . $scli_rprenom . " " . $scli_rnom;
                                }
                            }
                        }
                        break;
                    case "age" :
                        $row = lit_enr_rpdt($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);
                            $tab_dest = cre_dest_age($rpdt_codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Déclaration de problème
            case "rpbm" :
                switch ($dest) {
                    case "cli" :
                        $row = lit_enr_rpbm($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            // Si on crée un contrat, ou si on le modifie, copies à technique et contact du site (si existe) uniquement
                            if ((str_majuscules($mode) == "CRE") OR (str_majuscules($mode) == "MOD"))
                                $tab_dest = cre_dest_cli($rpbm_codecli, $tab_dest, FALSE, TRUE);
                            else
                                $tab_dest = cre_dest_cli($rlic_codecli, $tab_dest, FALSE, FALSE);

                            // On envoie une copie au contact principal du site
                            if ($rpbm_idsite > 0) {
                                $row = lit_enr_scli_id($rpbm_idsite, TRUE);
                                if (is_array($row)) {
                                    $row = encode_str($row);
                                    extract($row);
                                    if (array_key_exists($scli_remail, $tab_dest) == false)
                                        $tab_dest[$scli_remail] = $scli_rcivil . " " . $scli_rprenom . " " . $scli_rnom;
                                }
                            }
                        }
                        break;
                    case "age" :
                        $row = lit_enr_rpbm($code);
                        if (is_array($row)) {
                            $row = encode_str($row);
                            extract($row);

                            switch ($rpbm_typrel) {
                                case 1 :
                                    $row = lit_enr_rlic($rpbm_coderlp);
                                    $row = encode_str($row);
                                    extract($row);
                                    $codeage = $rlic_codeage;
                                    break;
                                case 2 :
                                    $row = lit_enr_rpdt($rpbm_coderlp);
                                    $row = encode_str($row);
                                    extract($row);
                                    $codeage = $rpdt_codeage;
                                    break;
                            }
                            $tab_dest = cre_dest_age($codeage, $tab_dest, TRUE, TRUE);
                        }
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Sous-traitant
            case "st" :
                switch ($dest) {
                    case "st" :
                        $tab_dest = cre_dest_st($code, $tab_dest, TRUE, TRUE);
                        break;
                    case "cdg" :
                        $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                        break;
                }
                break;

            // Produit à retourner
            case "retp" :
                // Traitement du retour
            case "retr" :
                $row = lit_enr_retp($code, TRUE);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);

                    switch ($dest) {
                        case "age" :
                            $tab_dest = cre_dest_age($retp_codeage, $tab_dest, TRUE, FALSE);
                            break;
                        case "cdg" :
                            $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                            break;
                    }
                }
                break;

            // Tâches
            case "tac" :
                $row = lit_enr_tac($code, TRUE);
                if (is_array($row)) {
                    $row = encode_str($row);
                    extract($row);

                    switch ($dest) {
                        case "tec" :
                            $row = lit_enr_tec($tac_codedest, TRUE);
                            if (is_array($row)) {
                                $row = encode_str($row);
                                extract($row);
                                $tab_dest[$tec_email] = $tec_civilite . " " . $tec_prenom . " " . $tec_nom;
                            }
                            break;
                        case "age" :
                            $tab_dest = cre_dest_age($tac_codedest, $tab_dest, TRUE, FALSE);
                            break;
                        case "st" :
                            $tab_dest = cre_dest_st($tac_codedest, $tab_dest, TRUE, TRUE);
                            break;
                        case "cdg" :
                            $tab_dest = cre_dest_cdg($tab_dest, TRUE, TRUE);
                            break;
                    }
                }
                break;

            default :
                break;
        }
    }


    // Corps de l'email
    $txtcorps = cre_corps_txtm($nomfic, $type, $mode, $orig, $dest, $code, $pass, $total, $attach);

    if ((count($tab_dest) > 0) && (trim($txtcorps) <> "") && (trim($sujet) <> "")) {
        $txtcorps = parse_logos($code, $type, $txtcorps);

        $mail->Subject = $sujet;
        $mail->MsgHTML($txtcorps);

        $mail->attach = $attach;
        $mail->attach_PHPM();

        $mail->tab_dest = $tab_dest;
        $mail->send_PHPM();
        $sent = $mail->result_mail;
    } else
        $sent = false;
    $mail->SmtpClose();
    $mail->ClearAllRecipients();
    unset($mail);
}

/**
 * Envoi des emails aux administrateurs seulement
 *
 * @param $nomfic
 * @param $sujet
 * @param $type
 * @param $mode
 * @param $orig
 * @param $dest
 * @param $code
 * @param $pass
 * @param $total
 * @param bool $open
 * @throws Exception
 * @throws phpmailerException
 */
function envoi_mailwm($nomfic, $sujet, $type, $mode, $orig, $dest, $code, $pass, $total, $open = TRUE)
{
    global
    $admin_name,
    $admin_mail,
    $root,
    $pop_before,
    $pop_nom,
    $pop_port,
    $pop_timeout,
    $pop_login,
    $pop_mdp;

    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);

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

    // Le destinataire est le webmaster
    $mail->AddAddress($admin_mail, $admin_name);

    // Corps de l'email
    $txtcorps = cre_corps_txtm($nomfic, $type, $mode, $orig, $dest, $code, $pass, $total, $open);
    if ((trim($txtcorps) <> "") && (trim($sujet) <> "")) {
        $txtcorps = parse_logos($code, $type, $txtcorps, $open);

        $mail->Subject = $sujet;
        $mail->Body = $txtcorps;

        $sent = $mail->Send();

    } else
        $sent = false;

    $mail->SmtpClose();
    $mail->ClearAllRecipients();
    unset($mail);
}

// $typdest : cli, tec, age, ope
// $codedest : code du destinataire
// $typeexp : type de l'expéditeur (administrateur, cdg, agence)
// $codeexp : code de l'expéditeur (administrateur, cdg, agence)
// $txt : code du texte type utilisé
// $sujet : titre du message
/**
 * Envoi des emailings
 *
 * @param $typedest
 * @param $typemail
 * @param $codedest
 * @param $typeexp
 * @param $codeexp
 * @param $txt
 * @param $sujet
 * @param bool $open
 * @return bool
 * @throws Exception
 * @throws phpmailerException
 */
function envoi_emailing($typedest, $typemail, $codedest, $typeexp, $codeexp, $txt, $sujet, $open = TRUE)
{
    global
    $db,
    $admin_name,
    $admin_mail,
    $root,
    $pop_before,
    $pop_nom,
    $pop_port,
    $pop_timeout,
    $pop_login,
    $pop_mdp;

    $tab_dest = [];

    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);

    // Destinataires
    switch ($typedest) // Analyse du type de destinataire
    {
        // Agence
        case "age" :
            $row = lit_enr_age($codedest, TRUE);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);
                for ($i = 0; $i < 4; $i++) {
                    if ($typemail[$i] == 1) {
                        switch ($i) {
                            case 0 :
                                $tab_dest[$age_email] = _("Agence").' ' . $age_nom;
                                break;
                            case 1 :
                                if (array_key_exists($age_emaild, $tab_dest) == false)
                                    $tab_dest[$age_emaild] = _("Agence").' ' . $age_nom . ' ('._("Service direction").')';
                                break;
                            case 2 :
                                if (array_key_exists($age_emailc, $tab_dest) == false)
                                    $tab_dest[$age_emailc] = _("Agence").' ' . $age_nom . ' ('._("Service comptabilité").')';
                                break;
                            case 3 :
                                if (array_key_exists($age_emailt, $tab_dest) == false)
                                    $tab_dest[$age_emailt] = _("Agence").' ' . $age_nom . ' ('._("Service technique").')';
                                break;
                            default :
                                break;
                        }
                    }
                }
            }
            break;

        // Client
        case "cli" :
            $row = lit_enr_cli($codedest, TRUE);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);

                if ($typemail[0] == 1)
                    $tab_dest[$cli_email] = $cli_civilite . " " . $cli_prenom . " " . $cli_nom;

                // Récupération des contacts
                if ($open == TRUE)
                    $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

                $rexist = "SELECT DISTINCT ccli_email FROM `" . TBCCLI . "` WHERE `ccli_codecli` = '" . $db->escape($cli_code) . "'";
                $rows = $db->get_results($rexist, ARRAY_A);
                if (($rows) AND (count($rows) > 0)) {
                    foreach ($rows as $row) {
                        $row = encode_str($row);
                        extract($row);

                        for ($i = 1; $i < 4; $i++) {
                            if ($typemail[$i] == 1) {
                                switch ($i) {
                                    case 1 :
                                        if ($ccli_emaild == 1) {
                                            if (array_key_exists($ccli_email, $tab_dest) == false)
                                                $tab_dest[$ccli_email] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
                                        }
                                        break;
                                    case 2 :
                                        if ($ccli_emailc == 1) {
                                            if (array_key_exists($ccli_emailc, $tab_dest) == false)
                                                $tab_dest[$ccli_emailc] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
                                        }
                                        break;
                                    case 3 :
                                        if ($ccli_emailt == 1) {
                                            if (array_key_exists($ccli_emailt, $tab_dest) == false)
                                                $tab_dest[$ccli_emailt] = $ccli_civilite . " " . $ccli_prenom . " " . $ccli_nom;
                                        }
                                        break;
                                    default :
                                        break;
                                }
                            }
                        }
                    }
                }
                if ($open == TRUE)
                    $db->disconnect();
            }
            break;

        // Donneur d'ordres
        case "do" :
            $row = lit_enr_do($codedest);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);
                for ($i = 0; $i < 4; $i++) {
                    if ($typemail[$i] == 1) {
                        switch ($i) {
                            case 0 :
                                $tab_dest[$do_email] = $age_nom;
                                break;
                            case 1 :
                                if (array_key_exists($do_emaild, $tab_dest) == false)
                                    $tab_dest[$do_emaild] = $do_nom . ' ('._("Service direction").')';
                                break;
                            case 2 :
                                if (array_key_exists($do_emailc, $tab_dest) == false)
                                    $tab_dest[$do_emailc] = $do_nom . ' ('._("Service comptabilité").')';
                                break;
                            case 3 :
                                if (array_key_exists($do_emailt, $tab_dest) == false)
                                    $tab_dest[$do_emailt] = $do_nom . ' ('._("Service technique").')';
                                break;
                            default :
                                break;
                        }
                    }
                }
            }
            break;

        // Opérateur
        case "ope" :
            $row = lit_enr_ope($codedest);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);
                $tab_dest[$ope_email] = $ope_civilite . " " . $ope_prenom . " " . $ope_nom;
            }
            break;

        // Sous-traitant
        case "st" :
            $row = lit_enr_st($codedest);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);
                for ($i = 0; $i < 4; $i++) {
                    if ($typemail[$i] == 1) {
                        switch ($i) {
                            case 0 :
                                $tab_dest[$st_email] = $st_nom;
                                break;
                            case 1 :
                                if (array_key_exists($st_emaild, $tab_dest) == false)
                                    $tab_dest[$st_emaild] = $st_nom . ' ('._("Service direction").')';
                                break;
                            case 2 :
                                if (array_key_exists($st_emailc, $tab_dest) == false)
                                    $tab_dest[$st_emailc] = $st_nom . ' ('._("Service comptabilité").')';
                                break;
                            case 3 :
                                if (array_key_exists($st_emailt, $tab_dest) == false)
                                    $tab_dest[$st_emailt] = $st_nom . ' ('._("Service technique").')';
                                break;
                            default :
                                break;
                        }
                    }
                }
            }
            break;

        // Technicien
        case "tec" :
        case "tecd" :
        case "tecs" :
            $row = lit_enr_tec($codedest, TRUE);
            if (is_array($row)) {
                $row = encode_str($row);
                extract($row);
                $tab_dest[$tec_email] = $tec_civilite . " " . $tec_prenom . " " . $tec_nom;
            }
            break;

        default :
            break;
    }

    $i = 0;
    foreach ($tab_dest as $key => $value) {
        if ($i == 0)
            $mail->AddAddress($key, $value);
        else
            $mail->AddCC($key, $value);
        $i++;
    }

    // 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($codeexp, TRUE);
            $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($codeexp);
            $row = encode_str($row);
            extract($row);
            $nom = $do_nom;
            $email = $do_email;
            break;

        // Sous-traitant
        case "st" :
            $row = lit_enr_st($codeexp);
            $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);

    // Corps de l'email
    $txtcorps = cre_corps_txtem($typedest, $codedest, $typeexp, $codeexp, $txt);

    if (($tab_dest && count($tab_dest) > 0) && (trim($txtcorps) <> "") && (trim($sujet) <> "")) {
        $txtcorps = parse_logos($codedest, $typedest, $txtcorps);

        $mail->Subject = $sujet;
        $mail->Body = $txtcorps;

        $sent = $mail->Send();
    } else
        $sent = false;

    return $sent;
}
