<?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_fici.inc.php");
include_once("../inc/fic_hum.inc.php");
include_once("../inc/fic_txt.inc.php");
include_once("../inc/func.inc.php");
include_once("../inc/func_date.inc.php");
include_once("../inc/func_log.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_mail.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/func_txtcm.inc.php");
include_once("../classes/phpmailer/class.phpmailer.php");
include_once("../classes/phpmailer/class.smtp.php");
include_once("mail.inc.php");
include_once("../classes/ephpu/upload_class.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();
$_POST = clean_str($_POST);

// Téléchargement réservé à l'admin, le centre de gestion, les agences, et les techniciens
if ((@$_SESSION["niv_log"] == 9) OR (@$_SESSION["niv_log"] == 5) OR (@$_SESSION["niv_log"] == 4) OR (@$_SESSION["niv_log"] == 3)) {
    $rep_actif = $_SESSION["rb"];

    switch ($_SESSION["niv_log"]) {
        case 9 :
            $max_size = $taille_maxi_admin; // Taille maximum autorisée pour téléchargement
            break;
        case 5 :
            $max_size = $taille_maxi_cge; // Taille maximum autorisée pour téléchargement
            break;
        case 4 :
            $max_size = $taille_maxi_age; // Taille maximum autorisée pour téléchargement
            break;
        case 3 :
            $max_size = $taille_maxi_tec; // Taille maximum autorisée pour téléchargement
            break;
        default :
            break;
    }

    $my_upload = new file_upload;

    // Définition du chemin de stockage
    $my_upload->upload_dir = $rep_actif."/";
    /*
    if ($rep_actif <> "")
        $my_upload->upload_dir = $url_gfc . "/" . $rep_actif . "/";
    else
        $my_upload->upload_dir = $url_gfc . "/";
    */
    $my_upload->extensions = $extensions_ok; // specify the allowed extensions here
    $my_upload->language = $_SESSION["lng"]; // use this to switch the messages into an other language (translate first!!!)
    $my_upload->max_length_filename = 100; // change this value to fit your field length in your database (standard 100)
    $my_upload->rename_file = true;

    if (@$_POST['nbutton'] == "val_upl") {
        $codeuser = @$_SESSION["code_log"];

        $my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
        $my_upload->the_file = $_FILES['upload']['name'];
        $my_upload->http_error = $_FILES['upload']['error'];
        $my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
        $my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename
        $new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
        $new_name = str_upload($new_name);
        if ($my_upload->upload($new_name)) { // new name is an additional filename information, use this to rename the uploaded file
            $full_path = $my_upload->upload_dir . $my_upload->file_copy;
            $info = $my_upload->get_uploaded_file_info($full_path);
            // ... or do something like insert the filename to the database

            $nouveau_nom = $my_upload->upload_dir . $new_name . strtolower(strrchr($_FILES['upload']['name'], "."));
            $desc = $_POST['desc'];
            $detail = $_POST['detail'];
            $prive = 0;
            if ($_POST['prive'] == "y") $prive = 1;
            $lier = 0;
            if ($_POST['lier'] == "y") $lier = 1;
            $tx = "";
            $tx = @$_POST['tx'];
            $min_level = $_SESSION["niv_log"];
            $min_level = intval($_POST['minlevel']);

            $last_id = 0;

            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
            $rech = "SELECT fic_id FROM `" . TBFIC . "` WHERE fic_nom = '" . $db->escape($nouveau_nom) . "'";
            $row = $db->get_row($rech, ARRAY_A);
            if ($row) {
                extract($row);
                $last_id = $fic_id;

                $rech = "UPDATE `" . TBFIC;
                $rech .= "` SET `fic_desc`='" . $db->escape($desc) . "', `fic_detail`='" . $db->escape($detail) . "', `fic_prive`='" . $prive . "',";
                $rech .= " `fic_minlevel`='" . $min_level . "', `fic_datecrea`='" . $datea . "', `fic_codecrea`='" . $codeuser . "'";
                $rech .= " WHERE `fic_nom` = '" . $db->escape($nouveau_nom) . "'";
            } else // On a pas trouvé, on ajoute l'enregistrement
            {
                $rech = "INSERT INTO `" . TBFIC . "`";
                $rech .= " (fic_nom,fic_desc,fic_detail,fic_prive,fic_minlevel,fic_datecrea,fic_codecrea,fic_nbtel) VALUES";
                $rech .= " ('" . $db->escape($nouveau_nom) . "','" . $db->escape($desc) . "','" . $db->escape($detail) . "','$prive','$min_level','$datea','$codeuser','')";
            }
            $db->query($rech);

            if ($last_id == 0)
                $last_id = $db->insert_id;

            $rech = "";
            switch ($tx) {
                // On charge depuis une intervention
                case "int" :
                    // On vérifie s'il faut lier à l'intervention
                    if ($lier == 1) {
                        // Pas encore lié (et liaisons demandée) => On va le lier
                        if (est_PJ_code($nouveau_nom, @$_POST['ci'], FALSE) == FALSE) {
                            $rech = "INSERT INTO `" . TBFICPJ . "`";
                            $rech .= " (ficpj_typrat,ficpj_coderat,ficpj_idfic)";
                            $rech .= " VALUES ('1','" . @$_POST['ci'] . "','" . $last_id . "')";
                        }
                    } else // Liaison pas demandée : on supprimer la liaison existante
                    {
                        $rech = "DELETE FROM `" . TBFICPJ . "` WHERE `ficpj_coderat` = '$coderat'";
                        $rech .= " AND `ficpj_idfic` = '$last_id'";
                    }
                    break;
                default :
                    break;
            }
            if ($rech <> "")
                $db->query($rech);

            $db->disconnect();

            // Envoi d'email vers l'administrateur
            envoi_mailwm($nouveau_nom, _("Téléchargement de fichier"), "fic", "cre", "xxx", "wm", $nouveau_nom, "", "");


            // Envoi d'email vers l'agence
            if ((@$_SESSION["niv_log"] == 9) OR (@$_SESSION["niv_log"] == 5)) {
                // On vérifie si on est dans le répertoire d'une agence pour lui envoyer un email
                $pos = strpos($rep_actif, "agences");
                if ($pos === FALSE) {
                    // On est pas le répertoire agences, pas besoin d'envoyer d'email
                } else {
                    // On y est..si on est dans un sous répertoire de "agences" (donc dans un répertoire privé), on peut envoyer un email
                    if ($rep_actif <> "agences") {
                        $tab_url = explode("/", $rep_actif);
                        $code_agence = $tab_url[1];
                        $rep_aff = str_replace("agences/" . $tab_url[1], "", $rep_actif);
                        if (trim($rep_aff) <> "")
                            envoi_mail($nouveau_nom, _("Téléchargement de fichier"), "fic", "cre2", "xxx", "age", $code_agence, "", "", FALSE);
                        else
                            envoi_mail($nouveau_nom, _("Téléchargement de fichier"), "fic", "cre1", "xxx", "age", $code_agence, "", "", FALSE);
                    }
                }
            }


            // Envoi d'email vers le client

            // On vérifie si on est dans le répertoire d'un client pour lui envoyer un email
            $pos = strpos($rep_actif, "clients");
            if ($pos === FALSE) {
                // On est pas le répertoire clients, pas besoin d'envoyer d'email
            } else {
                // On y est..si on est dans un sous répertoire de "clients" (donc dans un répertoire privé), on peut envoyer un email
                if ($rep_actif <> "clients") {
                    $tab_url = explode("/", $rep_actif);
                    $code_client = $tab_url[1];
                    $rep_aff = str_replace("clients/" . $tab_url[1], "", $rep_actif);
                    if (trim($rep_aff) <> "")
                        envoi_mail($nouveau_nom, _("Téléchargement de fichier"), "fic", "cre2", "xxx", "cli", $code_client, "", "", FALSE);
                    else
                        envoi_mail($nouveau_nom, _("Téléchargement de fichier"), "fic", "cre1", "xxx", "cli", $code_client, "", "", FALSE);

                    // Copie vers l'agence "propriétaire" du client si ce n'est pas elle qui a téléchargé
                    if ((@$_SESSION["niv_log"] == 9) OR (@$_SESSION["niv_log"] == 5)) {
                        if ($cli_prop <> NULL) {
                            $row = lit_enr_age($cli_prop, TRUE);
                            if (is_array($row)) {
                                extract($row);

                                $code_agence = $age_code;

                                if (trim($rep_aff) <> "")
                                    envoi_mail("", _("Téléchargement de fichier"), "fic", "cre4", "xxx", "age", $nouveau_nom, "", "", FALSE);
                                else
                                    envoi_mail("", _("Téléchargement de fichier"), "fic", "cre3", "xxx", "age", $nouveau_nom, "", "", FALSE);
                            }
                        }
                    }
                }
            }

            $msg = _("Téléchargement réussi");
            $retourliste = TRUE;
        } else {
            $retourliste = FALSE;
            $msg = $my_upload->show_error_string();
        }
    }
} else {
    $retourliste = FALSE;
    $msg = _("Vous n'avez pas le droit de télécharger des fichiers");
}
?>
<!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 _("Téléchargement de fichier"); ?></title>

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

    <script type="text/javascript">
        <!--
        function init_all() {
            init_Body();
            Focus_first();
        }

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

</head>
<body>

<?php
switch (@$_POST['tx']) {
    case "cli" :
    case "int" :
        break;
    default :
        include_once("entete.inc.php");
        break;
}
?>
<p align="center"><span class="titrepage"><?PHP echo _("TELECHARGEMENT DE FICHIER"); ?></span></p>

<p align="center">&nbsp;</p>

<?PHP
$lnk_rep ='';
if ($url_gfc <> $rep_actif)
    $lnk_rep = str_replace($url_gfc.'/','',$rep_actif);
switch (@$_POST['tx']) {
    case "cli" :
        $chemin_retour = "fic_pj.php?dir=" . $lnk_rep . "&cc=" . @$_POST['cc'] . "&tx=" . @$_POST['tx'];
        break;
    case "int" :
        $chemin_retour = "fic_pj.php?dir=" . $lnk_rep . "&cc=" . @$_POST['cc'] . "&ci=" . @$_POST['ci'] . "&tx=" . @$_POST['tx'];
        break;
    default :
        $chemin_retour = "fic_down.php?dir=" . $lnk_rep . "&ope=" . @$_POST['ope'] . "&date=" . @$_POST['date'] . "&search=" . $_POST['search'];
        break;
}

if ($retourliste == FALSE)
{
    exec_func_js("warn_txt('" . str_escape($msg) . "')");
    aff_ret_idx_man($td, $chemin_retour, _("Retour à la liste"), TRUE);
}
else
{
    exec_func_js("pop_txt('" . str_escape($msg) . "')");
    pop_ret_auto('', '', $chemin_retour);
}

switch (@$_POST['tx']) {
    case "cli" :
    case "int" :
        break;
    default :
        include_once("pied.php");
        break;
}
?>
