<?php
/*
 *  Kaz addon (see https://git.kaz.bzh/KAZ/depollueur for information)
 *  create un archive for a set of file or update file deadline

 a.php?r=email => track
 a.php?p=email => period
 a.php?u=month&h=HHHHHHHH => update deadline
 a.php?g=l~k => zip
 a.php?time=month&key=password + POST file => upload
 a.php?s=mel@domain.org => form
 a.php?s=mel@domain.org&t=password + [action] => manage account
 action: a=login a=logout a=r[on|off] a=p[minute|hour|day|week|month|quarter]
*/

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

define ('JIRAFEAU_ROOT', dirname (__FILE__) . '/');

require (JIRAFEAU_ROOT . 'lib/settings.php');
require (JIRAFEAU_ROOT . 'lib/functions.php');
require (JIRAFEAU_ROOT . 'lib/lang.php');

define ('VAR_TOKENS', $cfg ['var_root'].'tokens/');
define ('VAR_MODE', $cfg ['var_root'].'mode/');
define ('VAR_TRACKS', $cfg ['var_root'].'tracks/');
define ('VAR_PERIOD', $cfg ['var_root'].'period/');
define ('VAR_LANG', $cfg ['var_root'].'lang/');
define ('VAR_FAKE', $cfg ['var_root'].'fake/');
define ('VAR_ADMIN', $cfg ['var_root'].'admin/');

$domain="kaz.local";
if (preg_match ("%^.*//([^/]*)/?.*$%", $cfg ['web_root'], $matches))
    $domain = $matches [1];

define ('MAX_VALID_UPLOAD_TIME', 60);
define ('TOKEN_USE_LIMIT', "-2 hours");
define ('TOKEN_LOGIN_LIMIT', "-15 minutes");
define ('TOKEN_LOGOUT_LIMIT', "-8 hours");
define ('DEFAULT_MODE', "footer");
define ('DEFAULT_PERIOD', "month");
define ('DEFAULT_LANG', "fr");

define ('E_BAD_ARCHIVE_NAME', 'Bad archive name format');
define ('E_CREATE_ZIP', "Impossible de cr&eacute;er l'archive.");
define ('E_OPEN_ZIP', "Impossible d'ouvrir l'archive.");
define ('M_BAD_KEY', "Mauvaise clef pour ");
define ('M_BAD_SENDER_NAME', 'Votre m&eacute;l est incorrect');
define ('M_BAD_TOKEN', "Vous n'utilisez pas le bon jeton (consultez votre messagerie).");
define ('M_TOO_LONG_BEFORE_LOGGED', "Jeton de connexion trop ancien.");
define ('M_TOO_LONG_LOGGED', "Temps de connexion d&eacute;pass&eacute;.");
define ('M_EMAIL_CONTENT', "Bonjour,<br/><br/>Ceci est un message automatique, car vous venez de cliquer sur une demande de consultation de vos pi&egrave;ces jointes.<br/><br/>!!! Si vous n'&ecirc;tes pas &agrave; l'origine de cette demande, ne cliquez sur aucun lien de ce message. !!!<br/><br/>Le lien de connexion suivant est valable 15 minutes.<br/><a href=\"___LINK___\">___LINK___</a><br/><br/>Vous pouvez signaler des abus aupr&egrave;s de Kaz en faisant suivre ce message qui contient les traces de son &eacute;metteur (___IP___, ___DATE___).<br/><br/>Bonne navigation.<br/>.");
define ('M_DOWNLOAD', "T&eacute;l&eacute;charger");
define ('M_UPDATE', "Prolonger");
define ('M_EMAIL_SUBJECT', "Lien de consultation des envois sur ".$domain.".");
define ('M_FILE', " fichier.");
define ('M_FILES', " fichiers.");
define ('M_FILES_NOT_FOUND', " fichiers sont expirés.");
define ('M_FILES_RENAMED', " fichiers renommés.");
define ('M_FILE_NOT_FOUND', " fichier est expiré.");
define ('M_FILE_RENAMED', " fichier renommé.");
define ('M_INTRO_FORM', "Quelles sont les informations me concernant ?");
define ('M_MEL', "votre m&eacute;l");
define ('M_NO_FILENAME', 'SansNom');
define ('M_NO_SENDER', 'kaz-');
define ('M_NEW_ATTACHEMENT_DIRNAME', "nouveau");
define ('M_OLD_ATTACHEMENT_DIRNAME', "ancien");
define ('M_SEND', "Connexion");
define ('M_LOGOUT', 'Deconnecter');
define ('M_REFRESH', 'Actualiser');
define ('M_LOGOUT_TOKEN', "Vous n'&ecirc;tes plus connect&eacute;.");
define ('M_SEND_TOKEN', "<br/><p>Vous allez recevoir un <b>lien d'acc&egrave;s temporaire</b> &agrave; vos donn&eacute;es.</p>");
define ('M_WELCOME', "<p>Informations concernant le compte : <b>___SENDER___</b>___ADMIN___<br/>(page actualis&eacute;e &agrave; ___DATE___)</p>");
define ('M_INCONSISTENT_DATES',
        " (dates incoh&eacute;antes avec ___FILENAME___ : ___DIRTIME___ != ___FILETIME___)");

define ('A_ACTION', 'a');			// action : T_LOGIN, T_LOGOUT, A_MODE(footer|attachment|both), A_RECORD+(on|off), A_PERIOD(minute|hour|day|week|month|quarter), A_LANG(fr|en|br)
define ('A_GET', 'g');				// get archive
define ('A_HASH', 'h');				// file to update or delete
define ('A_OPEN_TOKEN', 'o');		// ask token
define ('A_SENDER', 's');			// session sender
define ('A_TOKEN', 't');			// session token
define ('A_UPDATE', 'u');			// update perriod for file or archive
define ('A_MODE', 'm');				// get mode status
define ('A_RECORD', 'r');			// get track status
define ('A_PERIOD', 'p');			// get period status
define ('A_LANG', 'l');				// get lang status
define ('A_DELETE', 'd');			// delete file ou archive + (sender+token)
define ('T_BAD_PASW', 'bad_psw');
define ('T_CREATE', "create");
define ('T_CRYPTED', 'crypted');
define ('T_CRYPT_KEY', 'crypt_key');
define ('T_ENTRIES', 'entries');
define ('T_FILENAME', 'file_name');
define ('T_HASH', 'hash');
define ('T_LOGGED', "logged");
define ('T_NEW', 'new');
define ('T_SIGN', 'sign');
define ('T_NOT_FOUND', 'not_found');
define ('T_OLD', 'old');
define ('T_RENAME', 'rename');
define ('T_LOGIN', 'login');
define ('T_LOGOUT', 'logout');
define ('T_SENDER', 'sender');
define ('T_TIME', 'time');
define ('T_ID', 'id');
define ('T_TOKEN', "token");
define ('T_WARNING_FILENAME', "-Avertissement.txt");
define ('T_ZIP_EXT', ".zip");
define ('T_ARCHIVE_TITLE', "archive_content");
define ('T_ARCHIVE_MIME', "text/kaz_email_archive");


$modeText = ['footer' => "pied de page", 'attachment' => "pi&egrave;ce jointe", 'both' => "les deux"];
$trackText = ['on' => "oui", 'off' => "non"];
$periodText = ['minute' => "minute", 'hour' => "heure", 'day' => "jour", 'week' => "semaine", 'month' => "mois"];
// XXX , 'quarter' => "trimestre"];
$periodButton = ['hour' => ["&#128341;", ">1 heure"],
                 'day' => ["&#128348;", ">1 jour"],
                 'week' => ["&#128349;", "> 1 semaine"],
                 'month' => ["&#128350;", "> 1 mois"]];
// XXX 'quarter' => ["&#128351;", "> 1 trimestre"]];
$langText = ['fr' => "Francais", 'br' => "Breton", 'en' => "english"];
$doLogout = '';
$message = '';

/* Operations may take a long time.
 * Be sure PHP's safe mode is off.
 */
@set_time_limit (0);
/* Remove errors. */
@error_reporting (0);

// ========================================
if (isset ($_REQUEST [A_MODE]) && !empty ($_REQUEST [A_MODE])) {
    if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_MODE]))
        $content = DEFAULT_MODE.NL;
    else
        $content = getSenderMode ($_REQUEST [A_MODE]).NL;
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;
}

// ========================================
if (isset ($_REQUEST [A_RECORD]) && !empty ($_REQUEST [A_RECORD])) {
    if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_RECORD]))
        $content = false.NL;
    else
        $content = isSenderTrack ($_REQUEST [A_RECORD]).NL;
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;
}

// ========================================
if (isset ($_REQUEST [A_PERIOD]) && !empty ($_REQUEST [A_PERIOD])) {
    if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_PERIOD]))
        $content = DEFAULT_PERIOD.NL;
    else
        $content = getSenderPeriod ($_REQUEST [A_PERIOD]).NL;
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;
}

// ========================================
if (isset ($_REQUEST [A_LANG]) && !empty ($_REQUEST [A_LANG])) {
    if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_LANG]))
        $content = DEFAULT_LANG.NL;
    else
        $content = getSenderLang ($_REQUEST [A_LANG]).NL;
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;
}

// ========================================
$doUpdate = false;
if (isset ($_REQUEST [A_UPDATE]) && !empty ($_REQUEST [A_UPDATE])) {
    $doUpdate = true;
}

$doDownload = false;
if (isset ($_REQUEST [A_GET]) && !empty ($_REQUEST [A_GET])) {
    $doDownload = true;
}

$doUpload = false;
if (isset ($_FILES ['file'])) {
    $doUpload = true;
}

// ========================================
function returnError ($msg) {
    require (JIRAFEAU_ROOT.'lib/template/header.php');
    echo '<div class="error"><p>' . $msg . '</p></div>';
    require (JIRAFEAU_ROOT.'lib/template/footer.php');
    exit;
}

// ========================================
function setSenderMode ($sender, $mode) {
    if (!$sender)
        return;
    if (!file_exists (VAR_MODE))
        mkdir (VAR_MODE, 0755);
    if (empty ($mode) || DEFAULT_MODE == $mode) {
        rmSenderMode ($sender);
    } else
        file_put_contents (VAR_MODE.$sender, $mode.NL);
}
function rmSenderMode ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_MODE.$sender))
        unlink (VAR_MODE.$sender);
}
function getSenderMode ($sender) {
    if ($sender && file_exists (VAR_MODE.$sender))
        return trim (file (VAR_MODE.$sender)[0]);
    return DEFAULT_MODE;
}

// ========================================
function setSenderTrack ($sender) {
    if (!$sender)
        return;
    if (!file_exists (VAR_TRACKS))
        mkdir (VAR_TRACKS, 0755);
    touch (VAR_TRACKS.$sender);
}
function rmSenderTrack ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_TRACKS.$sender))
        unlink (VAR_TRACKS.$sender);
}
function isSenderTrack ($sender) {
    return $sender && file_exists (VAR_TRACKS.$sender);
}

// ========================================
function setSenderPeriod ($sender, $period) {
    if (!$sender)
        return;
    if (!file_exists (VAR_PERIOD))
        mkdir (VAR_PERIOD, 0755);
    if (empty ($period) || DEFAULT_PERIOD == $period) {
        rmSenderPeriod ($sender);
    } else
        file_put_contents (VAR_PERIOD.$sender, $period.NL);
}
function rmSenderPeriod ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_PERIOD.$sender))
        unlink (VAR_PERIOD.$sender);
}
function getSenderPeriod ($sender) {
    if ($sender && file_exists (VAR_PERIOD.$sender))
        return trim (file (VAR_PERIOD.$sender)[0]);
    return DEFAULT_PERIOD;
}
function period2seconds ($periodName) {
    if (!$periodName)
        return JIRAFEAU_MONTH;
    switch ($periodName) {
    case 'minute':
        return JIRAFEAU_MINUTE;
        break;
    case 'hour':
        return JIRAFEAU_HOUR;
        break;
    case 'day':
        return JIRAFEAU_DAY;
        break;
    case 'week':
        return JIRAFEAU_WEEK;
        break;
    case 'month':
        return JIRAFEAU_MONTH;
        break;
    case 'quarter':
        return JIRAFEAU_QUARTER;
        break;
    case 'year':
        return JIRAFEAU_YEAR;
        break;
    default:
        returnError (t ('ERR_OCC') . ' (periodName)');
    }
}

// ========================================
function setSenderLang ($sender, $lang) {
    if (!$sender)
        return;
    if (!file_exists (VAR_LANG))
        mkdir (VAR_LANG, 0755);
    if (empty ($lang) || DEFAULT_LANG == $lang) {
        rmSenderLang ($sender);
    } else
        file_put_contents (VAR_LANG.$sender, $lang.NL);
}
function rmSenderLang ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_LANG.$sender))
        unlink (VAR_LANG.$sender);
}
function getSenderLang ($sender) {
    if ($sender && file_exists (VAR_LANG.$sender))
        return trim (file (VAR_LANG.$sender)[0]);
    return DEFAULT_LANG;
}

// ========================================
function setSenderFake ($error, $sender, $owner, $dirLink, $fileLink) {
    global $doLogout;

    if (!file_exists (VAR_FAKE))
        mkdir (VAR_FAKE, 0755);
    $dirTime = $fileTime = $fileName = $fileType = $ip = '';
    if (count ($dirLink) != 0) {
        $dirTime = $dirLink ['upload_date'].date (" Y-m-d H:i:s", $dirLink ['upload_date']);
        $ip = $dirLink ['ip'];
    }
    if (!$sender)
        return;
    if (count ($fileLink) != 0) {
        $fileTime = $fileLink ['upload_date'].date (" Y-m-d H:i:s", $fileLink ['upload_date']);
        $fileName = $link ['file_name'];
        $fileType = $link ['mime_type'];
    }
    $content =
             "time    : ".time ().NL.
             "date    : ".date ("Y-m-d H:i:s").NL.
             "error   : ".$error.NL.
             "sender  : <".$sender.">".NL.
             "owner   : <".$owner.">".NL.
             "dirLink : <".$dirLink.">".NL.
             "dirTime : ".$dirTime.NL.
             "dirIp   : ".$ip.NL.
             "fileTime: ".$fileTime.NL.
             "fileType: <".$fileType.">".NL.
             "fileName: <".$fileName.">".NL;
    
    $log = $ip.$sender;
    if ($log)
        file_put_contents (VAR_FAKE.$log, $content);

    // $doLogout = true;
    // rmToken ($sender);
}
function getSenderFake ($sender) {
    return false;
    // return $sender && file_exists (VAR_FAKE.$sender);
}

// ========================================
function isKazArchive ($link) {
    return
        @preg_match ("/".T_ARCHIVE_TITLE."/", jirafeau_escape ($link ['file_name'])) &&
        jirafeau_escape ($link ['mime_type']) == T_ARCHIVE_MIME;
}

// ========================================
function readArchiveFromLink ($link) {
    $p = s2p ($link ['hash']);
    $lines = file (VAR_FILES . $p . $link ['hash']);
    $archive = readArchiveFromLines ($lines);
    return $archive;
}
function readArchiveFromLines ($lines) {
    $archive = [];
    $error = false;
    foreach ($lines as $line) {
        switch (true) {
        case preg_match ("/^\s*id:\s*(\d++)\s*$/", $line, $matches):
            $archive [T_ID] = $matches [1];
            break;
        case preg_match ("/^\s*time:\s*(\d{4}([:-]\d{2}){5})\s*$/i", $line, $matches):
            $archive [T_TIME] = $matches [1];
            break;
            // XXX
            //case preg_match ("/^\s*sender:\s*(([a-z0-9_+-]+)(\.[a-z0-9_+-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6})\s*$/i", $line, $matches):
            case preg_match ("/^\s*sender:\s*(([a-z0-9_=+-]+)(\.[a-z0-9_=+-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6})\s*$/i", $line, $matches):
            $archive [T_SENDER] = $matches [1];
            break;
            // XXX issue ")"
        case preg_match ("/^\s*new:\s*([0-9a-zA-Z_-]+)\s+([0-9a-zA-Z_-]+)\)?\s*$/", $line, $matches):
            $archive [T_NEW][] = [$matches [1], $matches [2]];
            break;
        case preg_match ("/^\s*old:\s*([0-9a-zA-Z_-]+)\s+([0-9a-zA-Z_-]+)\)?\s*$/", $line, $matches):
            $archive [T_OLD][] = [$matches [1], $matches [2]];
            break;
        case preg_match ("/^\s*sign:\s*([0-9a-zA-Z_-]+)\s*$/", $line, $matches):
            $archive [T_SIGN] = $matches [1];
            break;
        default:
            $error = true;
            break;
        }
    }
    global $message, $admin;
    if ($error && $admin)
        $message .= "readArchiveFromLines <pre>".print_r ($lines, true)."</pre>";
    return $error ? [] : $archive;
}

// ========================================
function getFileName ($hash) {
    $p = s2p ($hash);
    return VAR_FILES.$p.$hash;
}
function getTimeFile ($hash) {
    $f = getFileName ($hash);
    return file_exists ($f) ? filemtime ($f) : 0;
}
function valideTime ($t1, $t2) {
    global $message;
    return abs ($t1 - $t2) < MAX_VALID_UPLOAD_TIME;
}

// ========================================
/** Update link 
 * @param $link the link's name (hash)
 * @param $update_period the period (i.e in : "month")
 */
function updateLink ($link_name, $link, $maxLimit) {
    $time_max = $link ['time'];
    if ($time_max < 0 || $maxLimit < $time_max)
        return $time_max;
    $time_more = $maxLimit + JIRAFEAU_MINUTE;
    $link ['time'] = $time_more;
    $link_tmp_name =  VAR_LINKS . $link ['hash'] . rand (0, 10000) . '.tmp';
    $handle = fopen ($link_tmp_name, 'w');
    fwrite ($handle,
            $link ['file_name'] .NL. $link ['mime_type'] .NL. $link ['file_size'] .NL. $link ['key'] .NL. $link ['time'] .NL.
            $link ['hash'] .NL. $link ['onetime'] .' '.JIRAFEAU_MONTH . ' '. JIRAFEAU_DAY .NL. $link ['upload_date'] .NL.
            $link ['ip'] .NL. $link ['link_code'] .NL. $link ['crypted']);
    fclose ($handle);
    $link_file = VAR_LINKS . s2p ("$link_name") . $link_name;
    rename ($link_tmp_name, $link_file);
    return $time_more;
}

// ========================================
function sendEMail ($receiver, $receiver_name,  $subject, $body_string){
    try {
        // SERVER SETTINGS
        $mail = new PHPMailer (true);
        $mail->isSMTP ();
        $mail->Host        = 'smtp';
        $mail->SMTPAuth    = false;
        $mail->SMTPAutoTLS = false;
        $mail->SMTPSecure  = "none";
        $mail->Port        = 25;
        $mail->charSet     = "UTF-8";
        $mail->ContentType = 'text/html';

        global $domain;
        //Recipients (change this for every project)
        $mail->setFrom ('no-reply@'.$domain, '');
        $mail->addAddress ($receiver, $receiver_name);

        //Content
        $mail->isHTML (true);
        $mail->Subject = $subject;
        $mail->Body    = $body_string;

        //send the message, check for errors
        if (!$mail->send ()) {
            //echo 'Mailer Error: ' . $mail->ErrorInfo;
            return 0;
        } else {
            //echo 'Message sent!';
            return 1;
        }
    } catch (Exception $e) {
        return 0;
    }
}

// ========================================
function cleanToken () {
    if (!file_exists (VAR_TOKENS))
        mkdir (VAR_TOKENS, 0755);
    $d = dir (VAR_TOKENS);
    $oldest = strtotime (TOKEN_USE_LIMIT);
    foreach (glob (VAR_TOKENS."*") as $file) {
        if (filemtime ($file) <= $oldest)
            unlink ($file);
    }
}
function rmToken ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_TOKENS.$sender))
        unlink (VAR_TOKENS.$sender);
}
function setToken ($sender) {
    if (!$sender)
        return;
    $token = md5 (rand ());
    if (file_put_contents (VAR_TOKENS.$sender, T_CREATE.": ".time ().NL.T_TOKEN.": ".$token.NL))
        return $token;
    return false;
}
function setLoggedToken ($sender, $token) {
    if (!$sender || !$token)
        return;
    file_put_contents (VAR_TOKENS.$sender, T_CREATE.": ".time ().NL.T_TOKEN.": ".$token.NL.T_LOGGED.": ok".NL);
}
function getTokenVar ($sender, $varName) {
    if (!$sender)
        return;
    if (!file_exists (VAR_TOKENS.$sender))
        return false;
    $content = file_get_contents (VAR_TOKENS.$sender);
    if (preg_match ("/\b".$varName.":\s*([^\s]+)\n/", $content, $matches))
        return $matches [1];
    return false;
}
function getToken ($sender) {
    return getTokenVar ($sender, T_TOKEN,);
}
function getCreateToken ($sender) {
    return getTokenVar ($sender, T_CREATE);
}
function getLoggedToken ($sender) {
    return getTokenVar ($sender, T_LOGGED);
}
function getTimeToken ($sender) {
    if (!$sender || !file_exists (VAR_TOKENS.$sender))
        return false;
    return filemtime (VAR_TOKENS.$sender);
}

// ========================================
function setAdmin ($sender) {
    if (!$sender)
        return;
    if (!file_exists (VAR_ADMIN))
        mkdir (VAR_ADMIN, 0755);
    touch (VAR_ADMIN.$sender);
}
function rmAdmin ($sender) {
    if (!$sender)
        return;
    if (file_exists (VAR_ADMIN.$sender))
        unlink (VAR_ADMIN.$sender);
}
function isAdmin ($sender) {
    return $sender && file_exists (VAR_ADMIN.$sender);
}

// ========================================
function deleteAction ($linkName) {
    global $sender, $token, $message, $doLogout;

    $link = jirafeau_get_link ($linkName);
    //$message .= "ln: ".$linkName." l: "."<pre>".print_r ($link, 1)."</pre> mt: ".getTimeFile ($link ['hash'])."</br>";
    if (!count ($link))
        return;
    if (isKazArchive ($link)) {
        $dirName = $linkName;
        $dirLink = $link;
        $dirTime = $dirLink ['upload_date'];
        $archiveInfo = readArchiveFromLink ($dirLink);
        if (! count ($archiveInfo))
            return;
        if ($sender != $archiveInfo [T_SENDER]) {
            setSenderFake ("rmdir: not owner", $sender, $archiveInfo [T_SENDER], $dirLink, null);
            $message .= "Tentative de supprimer un envoi dont vous n'&ecirc;tes pas le propri&eacute;taire";
            return;
        }
        $fileToDelete = false;
        if ($archiveInfo [T_NEW])
            foreach ($archiveInfo [T_NEW] as [$fileName, $cryptKey]) {
                $fileLink = jirafeau_get_link ($fileName);
                if (! count ($fileLink))
                    continue;
                $fileTime = $fileLink ['upload_date'];
                if (! valideTime ($dirTime, $fileTime)) {
                    setSenderFake ("rmdir: newfile not same time", $sender, null, $dirLink, $fileLink);
                    $message .= "Cet envoi a &eacute;t&eacute; forg&eacute;e".
                             str_replace (["___FILENAME___", "___DIRTIME___", "___FILETIME___"],
                                          [$fileLink ['file_name'], $dirTime , $fileTime], M_INCONSISTENT_DATES);
                    return;
                }
                $fileToDelete = true;
            }
        $message .= "l'envoi ".$archiveInfo [T_TIME]." est supprim&eacute;";
        if ($fileToDelete)
            $message .= " avec<ul>";
        if ($archiveInfo [T_NEW])
            foreach ($archiveInfo [T_NEW] as [$fileName, $cryptKey]) {
                $fileLink = jirafeau_get_link ($fileName);
                if (! count ($fileLink))
                    continue;
                $message .= "<li>".jirafeau_escape ($fileLink ['file_name'])."</li>";
                jirafeau_delete_link ($fileName);
            }
        jirafeau_delete_link ($dirName);
        $message .= $fileToDelete ? "</ul>" : ".";
        return;
    }
    $fileName = $linkName;
    $fileLink = $link;
    $fileTime = $fileLink ['upload_date'];
    $stack = array (VAR_LINKS);
    while (($d = array_shift ($stack)) && $d != null) {
        if (!file_exists ($d))
            continue;
        $dir = scandir ($d);
        foreach ($dir as $dirName) {
            if (strcmp ($dirName, '.') == 0 || strcmp ($dirName, '..') == 0 ||
                preg_match ('/\.tmp/i', "$dirName")) {
                continue;
            }
            if (is_dir ($d . $dirName)) {
                $stack [] = $d . $dirName . '/';
                continue;
            }
            $dirLink = jirafeau_get_link ($dirName);
            //$dirTime = getTimeFile ($dirLink ['hash']);
            $dirTime = $dirLink ['upload_date'];
            if (!count ($dirLink))
                continue;
            if (!isKazArchive ($dirLink))
                continue;
            $archiveInfo = readArchiveFromLink ($dirLink);
            if (! count ($archiveInfo))
                return;
            if ($archiveInfo [T_NEW])
                foreach ($archiveInfo [T_NEW] as [$newName, $cryptKey]) {
                    if ($fileName != $newName)
                        continue;
                    if ($sender == $archiveInfo [T_SENDER]) {
                        if (valideTime ($dirTime, $fileTime)) {
                            jirafeau_delete_link ($fileName);
                            $message .= jirafeau_escape ($fileLink ['file_name'])." est supprim&eacute;";
                            // check empty dir
                            $empty = true;
                            foreach ([T_OLD, T_NEW] as $cat)
                                if ($empty && isset ($archiveInfo [$cat]))
                                    foreach ($archiveInfo [$cat] as [$l, $c])
                                        if (count (jirafeau_get_link ($l))) {
                                            $empty = false;
                                            break;
                                        }
                            if ($empty) {
                                $message .= " ainsi que l'envoie ".$archiveInfo [T_TIME]." qui est vide.";
                                jirafeau_delete_link ($dirName);
                            } else
                                $message .= ".";
                            break;
                        }
                        setSenderFake ("rm: dir not same time", $sender, null, $dirLink, $fileLink);
                        $message .= "Cet envoi a &eacute;t&eacute; forg&eacute;e. ".
                                 str_replace (["___FILENAME___", "___DIRTIME___", "___FILETIME___"],
                                              [$fileLink ['file_name'], $dirTime , $fileTime], M_INCONSISTENT_DATES);
                        break;
                    }
                    if (valideTime ($dirTime, $fileTime)) {
                        setSenderFake ("rm: not owner", $sender, $archiveInfo [T_SENDER], $dirLink, $fileLink);
                        $message .= "Tentative de supprimer un envoi dont vous n'&ecirc;tes pas le propri&eacute;taire.".
                                 str_replace (["___FILENAME___", "___DIRTIME___", "___FILETIME___"],
                                              [$fileLink ['file_name'], $dirTime , $fileTime], M_INCONSISTENT_DATES);
                        break;
                    }
                    setSenderFake ("rm: find not owner", $archiveInfo [T_SENDER], $sender, $dirLink, $fileLink);
                    $message .= "Quelqu'un av&eacute;tait revandiqu&eacute; cet envoi. (".$sender." != ".$archiveInfo [T_SENDER].")";
                    break;
                }
        }
    }
}

// ========================================
if ($doUpload) {
    $maxtime = time ()+period2seconds ($_REQUEST ['time']);
    $key = isset ($_REQUEST ['key']) ? $_REQUEST ['key'] : '';
    $ip = $_SERVER ['HTTP_X_REAL_IP']; // XXX
    $res = jirafeau_upload (
        $_FILES['file'],
        isset ($_POST ['one_time_download']),
        $key,
        $maxtime,
        $ip,
        $cfg['enable_crypt'],
        $cfg['link_name_length'],
        $cfg['file_hash']
    );
    if (! count ($res ['error']) || $res['error']['has_error'])
        $content = 'Error 6 ' . $res['error']['why'];
    else
        $content = $res ['link'].NL.$res ['delete_link'].NL;
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;    
}

// ========================================
if ($doUpdate) {
    $maxTime = time ()+period2seconds ($_REQUEST [A_UPDATE]);
    // XXX issue ")"
    if (!preg_match ('/([0-9a-zA-Z_-]+)\)?$/', $_REQUEST [A_HASH], $matches))
        returnError (t ('FILE_404'));
    $linkName = $matches [1];
    $link = jirafeau_get_link ($linkName);
    if (count ($link) == 0)
        returnError (t ('FILE_404'));
    $time = updateLink ($linkName, $link, $maxTime);
    $content = '' . $time . NL;

    if (isKazArchive ($link)) {
        $archiveInfo = readArchiveFromLink ($l);
        if (count ($archiveInfo)) {
            foreach ([T_OLD, T_NEW] as $cat)
                if (isset ($archiveInfo [$cat]))
                    foreach ($archiveInfo [$cat] as [$linkName, $cryptKey])
                        updateLink ($linkName, jirafeau_get_link ($linkName), $maxTime);
        }
    }
    header ('HTTP/1.0 200 OK');
    header ('Content-Length: ' . strlen ($content));
    header ('Content-Type: text/plain');
    echo $content;
    exit;
}

$sender = '';
$senderError = false;
if (isset ($_REQUEST [A_SENDER]) && !empty ($_REQUEST [A_SENDER])) {
    // XXX
    //if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_SENDER]))
    if (!preg_match ("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i", $_REQUEST [A_SENDER]))
        $senderError = true;
    else {
        cleanToken ();
        $sender = $_REQUEST [A_SENDER];
    }
}

// ========================================
if ($doDownload) {
    // check archive exist
    $couple = explode ("~", $_REQUEST [A_GET], 2);
    if (count ($couple) == 0)
        returnError (E_BAD_ARCHIVE_NAME);
    $linkName = $couple [0];
    if (!$linkName || !preg_match ('/[0-9a-zA-Z_-]+$/', $linkName))
        returnError (E_BAD_ARCHIVE_NAME);
    $cryptKey = count ($couple) == 2 ? $couple [1] : "";
    $link = jirafeau_get_link ($linkName);
    if (count ($link) == 0)
        returnError (t ('FILE_404'));
    $key = $link ['key'];
    if ($key && (empty ($cryptKey) || $key != $cryptKey))
        returnError (t ('BAD_PSW'));

    $archiveInfo = readArchiveFromLink ($link);

    // check entries
    $archiveContent = [];
    $modif = false;
    $singleName = [];
    foreach ([T_OLD, T_NEW] as $cat)
        if (isset ($archiveInfo [$cat]))
            foreach ($archiveInfo [$cat] as [$linkName, $cryptKey]) {
                $link = jirafeau_get_link ($linkName);
                if (count ($link) == 0) {
                    if (isset ($archiveContent [T_NOT_FOUND]))
                        ++$archiveContent [T_NOT_FOUND];
                    else
                        $archiveContent [T_NOT_FOUND] = 1;
                    $modif = true;
                    continue;
                }
                $key = $link ['key'];
                if ($key && (empty ($cryptKey) || $key != $cryptKey)) {
                    if (isset ($archiveContent [T_BAD_PASW]))
                        ++$archiveContent [T_BAD_PASW];
                    else
                        $archiveContent [T_BAD_PASW] = 1;
                    $modif = true;
                    continue;
                }
                $dstName = ($link ['file_name'] ? $link ['file_name'] : M_NO_FILENAME);
                if (in_array ($dstName, $singleName)) {
                    $dstFilename = $dstName;
                    $dstExtension = "";
                    $dstExtensionPos = strrpos ($dstName, '.');
                    if ($dstExtensionPos) {
                        $dstFilename = substr ($dstName, 0, $dstExtensionPos);
                        $dstExtension = substr ($dstName, $dstExtensionPos);
                    }
                    for ($i = 1; $i < 10000; ++$i) {
                        $dstName = sprintf ("%s-%02d%s", $dstFilename, $i, $dstExtension);
                        if (!in_array ($dstName, $singleName)) {
                            if (isset ($archiveContent [T_RENAME]))
                                ++$archiveContent [T_RENAME];
                            else
                                $archiveContent [T_RENAME] = 1;    
                            $modif = true;
                            break;
                        }
                    }
                }
                $singleName [] = $dstName;
                $archiveContent [$cat][T_ENTRIES][] = [T_HASH => $link ['hash'], T_FILENAME => $dstName, T_CRYPT_KEY => $cryptKey, T_CRYPTED => $link ['crypted']];
            }

    // build zip
    $dirname = M_NO_SENDER.(isset ($archiveInfo [T_TIME]) && !empty ($archiveInfo [T_TIME])) ?
             $archiveInfo [T_TIME] : date ("Y-m-d-H:i:s");
    $dirname = str_replace (":", "_", $dirname);
    $tmpFileName = tempnam (sys_get_temp_dir (), $dirname."-");
    $zip = new ZipArchive;
    if (!$zip)
        returnError (E_CREATE_ZIP);
    if ($zip->open ($tmpFileName.T_ZIP_EXT, ZipArchive::CREATE) !== TRUE)
        returnError (E_OPEN_ZIP);

    // create info
    if ($modif) {
        $info = '';
        if (isset ($archiveContent [T_NOT_FOUND]))
            $info .= $archiveContent [T_NOT_FOUND]. ($archiveContent [T_NOT_FOUND] ? M_FILE_NOT_FOUND : M_FILES_NOT_FOUND).NL;
        if (isset ($archiveContent [T_BAD_PASW]))
            $info .= M_BAD_KEY. $archiveContent [T_BAD_PASW]. ($archiveContent [T_BAD_PASW] ? M_FILE : M_FILES).NL;
        if (isset ($archiveContent [T_RENAME]))
            $info .= $archiveContent [T_RENAME]. ($archiveContent [T_RENAME] ? M_FILE_RENAMED : M_FILES_RENAMED).NL;
        $zip->addFromString ($dirname.T_WARNING_FILENAME, $info);
    }
    foreach ([T_OLD, T_NEW] as $cat)
        if (isset ($archiveContent [$cat])) {
            $subdir = $dirname . "-".($cat == T_NEW ? M_NEW_ATTACHEMENT_DIRNAME : M_OLD_ATTACHEMENT_DIRNAME);
            foreach ($archiveContent [$cat][T_ENTRIES] as $entry) {
                $p = s2p ($entry [T_HASH]);
                if ($entry [T_CRYPTED]) {
                    $m = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
                    $md5_key = md5 ($entry [T_CRYPT_KEY]);
                    $iv = jirafeau_crypt_create_iv ($md5Key, mcrypt_enc_get_iv_size ($m));
                    mcrypt_generic_init ($m, $md5Key, $iv);
                    $r = fopen (VAR_FILES . $p . $entry [T_HASH], 'r');
                    $content = "";
                    while (!feof ($r)) {
                        $dec = mdecrypt_generic ($m, fread ($r, 1024));
                        $content .= $dec;
                        ob_flush ();
                    }
                    fclose ($r);
                    $zip->addFromString ($subdir."/".$entry [T_FILENAME], $content);
                    mcrypt_generic_deinit ($m);
                    mcrypt_module_close ($m);
                    continue;
                }
                $zip->addFile (VAR_FILES.$p.$entry [T_HASH], $subdir."/".$entry [T_FILENAME]);
            }
        }
    $zip->close ();

    
    if (false) {
        // log
        $message .= print_r ($archiveInfo, 1);
        $message .= print_r ($archiveContent, 1);

        header ('HTTP/1.0 200 OK');
        header ('Content-Length: ' . strlen ($message));
        header ('Content-Type: text/plain');
        echo $message;
        exit;
    }

    if (!is_file ($tmpFileName.T_ZIP_EXT,))
        returnError (E_OPEN_ZIP);

    header ("Content-Type: application/zip");
    header ('Content-Disposition: filename="'.$dirname.'.zip"');
    $r = fopen ($tmpFileName.".zip", 'r');
    while (!feof ($r)) {
        print fread ($r, 1024);
        ob_flush ();
    }
    fclose ($r);

    unlink ($tmpFileName.".zip");
    unlink ($tmpFileName);
    exit;    
}

// ========================================
// form
$token = '';
if (isset ($_REQUEST [A_TOKEN]) && !empty ($_REQUEST [A_TOKEN])) {
    if (!preg_match ("/^([0-9a-zA-Z_-]+)$/", $_REQUEST [A_TOKEN]))
        return false;
    $token = $_REQUEST [A_TOKEN];
}

$refToken = getToken ($sender);
$urlBase = $_SERVER ['HTTP_X_FORWARDED_PROTO']."://".$_SERVER ['HTTP_HOST'];
if (isset ($_REQUEST [A_ACTION]) && $_REQUEST [A_ACTION] == T_LOGIN && $sender) {
    require (JIRAFEAU_ROOT . 'lib/template/header.php');
    if (getSenderFake ($sender))
        echo "Ce compte ne peut plus se connecter. Veuillez contacter les administrateurs.";
    else {
        $token = setToken ($sender);
        // XXX test token
        $url = $urlBase.$_SERVER ['SCRIPT_NAME']."?".A_SENDER."=".$sender."&".A_TOKEN."=".$token;
        $result = sendEMail ($sender, "",  M_EMAIL_SUBJECT,
                            str_replace (["___LINK___", "___IP___", "___DATE___"],
                                        [$url, $_SERVER ['HTTP_X_REAL_IP'] , date ("Y-m-d H:i:s")], M_EMAIL_CONTENT));
        if ($result)
            echo M_SEND_TOKEN;
        else
            echo
                "Erreur dans l'envoi. V&eacute;ritiez votre m&eacute;l.";
    }
    echo "<br/><br/><br/>";
    require (JIRAFEAU_ROOT.'lib/template/footer.php');
    exit;
}

if (! ($sender && $token && $token == $refToken &&
       (getLoggedToken ($sender) || (getTimeToken ($sender) >= strtotime (TOKEN_LOGIN_LIMIT))) &&
       (getCreateToken ($sender) >= strtotime (TOKEN_LOGOUT_LIMIT)))) {
    // XXX temps de connexion
    require (JIRAFEAU_ROOT . 'lib/template/header.php');
    echo M_INTRO_FORM;
    if ($senderError)
        echo "<p>".M_BAD_SENDER_NAME."</p>";
    else if (($token && !$refToken) || !getLoggedToken ($sender))
        echo "<p>".M_TOO_LONG_BEFORE_LOGGED."</p>";
    else if ($token && $token != $refToken)
        echo "<p>".M_BAD_TOKEN."</p>";
    else if (getCreateToken ($sender) < strtotime (TOKEN_LOGOUT_LIMIT))
        echo "<p>".M_TOO_LONG_LOGGED."</p>";

    ?>
    <Form method="post" class="form login">
                <fieldset>
    <table>
    <tr>
    <td class="label"><label for="enter_password"><?php echo M_MEL . ' :'; ?></label>
    </td>
    </tr>
    <tr>
    <td class="field"><input type="text" name="<?php echo A_SENDER; ?>" size="40" value="<?php echo jirafeau_escape ($_REQUEST [A_SENDER]);?>"/>
    </td>
    </tr>
    <tr class="nav">
    <td class="nav next">
    <input type="hidden" name="<?php echo A_ACTION; ?>" value="<?php echo T_LOGIN; ?>" />
    <input type="submit" value="<?php echo M_SEND; ?>" />
    </td>
    </tr>
    </table>
    </fieldset>
    </form>
<?php
    require (JIRAFEAU_ROOT.'lib/template/footer.php');
    exit;
}

if (!getLoggedToken ($sender))
    setLoggedToken ($sender, $token);
else
    touch (VAR_TOKENS.$sender);

// ========================================
// sender OK, token OK
// ========================================

$admin = isAdmin ($sender);

// delete
if (isset ($_REQUEST [A_DELETE])) {
    if (!preg_match ('/[0-9a-zA-Z_-]+$/', $_REQUEST [A_DELETE]))
        returnError (t ('FILE_404'));
    deleteAction ($_REQUEST [A_DELETE]);
}

// logout
if ($doLogout || (isset ($_REQUEST [A_ACTION]) && $_REQUEST [A_ACTION] == T_LOGOUT)) {
    rmToken ($sender);
    require (JIRAFEAU_ROOT . 'lib/template/header.php');
    echo str_replace (["___SENDER___", "___ADMIN___", "___DATE___"],
                      [$sender, ($admin ? " (admin)" : ""), jirafeau_get_datetimefield (time ())],
                      M_WELCOME);
    if ($message)
        echo "<p>Info : ".$message."</p>";
    echo M_LOGOUT;
    require (JIRAFEAU_ROOT.'lib/template/footer.php');
    exit;
}

if (isset ($_REQUEST [A_ACTION])) {
    // change track
    switch (true) {
    case preg_match ("/^".A_MODE."(".implode ("|", array_keys ($modeText)).")$/i", $_REQUEST [A_ACTION], $matches):
        setSenderMode ($sender, $matches [1]);
        $message .= "Votre mode &agrave; &eacute;t&eacute; mise &agrave; jour.";
        break;
    case preg_match ("/^".A_RECORD."(on|off)$/i", $_REQUEST [A_ACTION], $matches):
        if ($matches [1] == "on")
            setSenderTrack ($sender);
        else
            rmSenderTrack ($sender);
        $message .= "Votre suivi &agrave; &eacute;t&eacute; mise &agrave; jour.";
        break;
    case preg_match ("/^".A_PERIOD."(".implode ("|", array_keys ($periodText)).")$/i", $_REQUEST [A_ACTION], $matches):
        setSenderPeriod ($sender, $matches [1]);
        $message .= "Votre p&eacute;riode &agrave; &eacute;t&eacute; mise &agrave; jour.";
        break;
    case preg_match ("/^".A_LANG."(".implode ("|", array_keys ($langText)).")$/i", $_REQUEST [A_ACTION], $matches):
        setSenderLang ($sender, $matches [1]);
        $message .= "Votre lang &agrave; &eacute;t&eacute; mise &agrave; jour.";
        break;
    }
}

// list
$archives = [];
$stack = array (VAR_LINKS);
while ( ($d = array_shift ($stack)) && $d != null) {
    $dir = scandir ($d);
    foreach ($dir as $dirName) {
        if (strcmp ($dirName, '.') == 0 || strcmp ($dirName, '..') == 0 ||
            preg_match ('/\.tmp/i', "$dirName")) {
            continue;
        }
        if (is_dir ($d . $dirName)) {
            /* Push new found directory. */
            $stack [] = $d . $dirName . '/';
            continue;
        }
        /* Read link informations. */
        $l = jirafeau_get_link ($dirName);
        if (!count ($l))
            continue;
        if (!isKazArchive ($l))
            continue;
        $archiveInfo = readArchiveFromLink ($l);
        if ($sender != $archiveInfo [T_SENDER])
            continue;
        $archiveInfo ['link'] = $dirName;
        $archiveInfo ['key'] = $l ['key'];
        $archiveInfo ['maxtime'] = $l ['time'];
        $archiveInfo ['hash'] = $l ['hash'];
        $archives [] = $archiveInfo;
    }
}
require (JIRAFEAU_ROOT . 'lib/template/header.php');
echo str_replace (["___SENDER___", "___ADMIN___", "___DATE___"],
                  [$sender, ($admin ? " (admin)" : ""), jirafeau_get_datetimefield (time ())],
                  M_WELCOME);
if ($message)
    echo "<p>Info : ".$message."</p>";
echo '<script type="text/javascript">';
?>
function getURI (uri, params) {
    var form = document.createElement ('form');
    form.setAttribute ('method', 'post');
    form.setAttribute ('action', "<?php echo $urlBase; ?>"+uri);
    var hiddenField = document.createElement ('input');
    for (var key in params) {
        if (params.hasOwnProperty (key)) {
            var hiddenField = document.createElement ('input');
            hiddenField.setAttribute ('type', 'hidden');
            hiddenField.setAttribute ('name', key);
            hiddenField.setAttribute ('value', params [key]);
            form.appendChild (hiddenField);
        }
        document.body.appendChild (form);
        form.submit ();
    }
}
function getKazArchive (l, k) {
    getURI ("<?php echo $_SERVER ['SCRIPT_NAME']; ?>", {<?php echo A_GET; ?>:l+'~'+k});
}
function getKazFile (l, k) {
    window.location.href = "<?php echo $urlBase; ?>/f.php?h="+l+"&k="+k;
}
function showLink (l, k) {
    alert ("<?php echo $urlBase;?>/f.php?h="+l+"&k="+k);
}
function ajaxUpdate (period, hash) {
    var xhr = new XMLHttpRequest ();
    xhr.open ("POST", "<?php echo $_SERVER ['SCRIPT_NAME']; ?>", true);
    xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            getURI ("<?php echo $_SERVER ['SCRIPT_NAME']; ?>", {<?php echo A_SENDER.": '".$sender."', ".A_TOKEN.": '".$token."'"; ?>});
        }
    }
       xhr.send ("<?php echo A_UPDATE; ?>="+period+"&<?php echo A_HASH; ?>="+hash);
}
function rmFile (f) {
    if (!confirm ("Les suppressions sont definitives. Voulez-vous continuer ?"))
        return;
    getURI ("<?php echo $_SERVER ['SCRIPT_NAME']; ?>", {<?php echo A_DELETE; ?>: f, <?php echo A_SENDER.": '".$sender."', ".A_TOKEN.": '".$token."'"; ?>});
}
</script>

<style type="text/css"><!-- a {text-decoration: none;}
div.frame {border: 1px; border-style: solid; padding: 1em; margin: 1em;}
[data-tooltip]:before {position : absolute; content : attr(data-tooltip); opacity : 0; background: yellow; padding: 10px; marging: 1em; transform: translate(10px, 10px);}
[data-tooltip]:hover:before {opacity : 1;}
[data-tooltip]:not([data-tooltip-persistent]):before {pointer-events: none;}
--></style>
<?php
$defaultChecked = [];
$defaultChecked [getSenderMode ($sender)] = ' selected="selected"';
$defaultChecked [isSenderTrack ($sender) ? "on" : "off"] = ' checked="checked"';
$defaultChecked [getSenderPeriod ($sender)] = ' selected="selected"';
$defaultChecked [getSenderLang ($sender)] = ' selected="selected"';
echo
    '<form method="post">'.
    'Je veux que mes futurs envois soient d&eacute;pollu&eacute; en pla&ccedil;ant les liens de t&eacute;l&eacute;chargements '.
    '<select name="'.A_ACTION.'" style="width: auto !important;">';
foreach ($modeText as $item => $text)
    echo '  <option value="'.A_MODE.$item.'"'.$defaultChecked [$item].'>'.$text.'</option>';
echo
    '</select> '.
    '<button type="submit">'."valider".'</button>'.
    '</form>'.
    '<form method="post">'.
    'Je veux que Kaz suive tous mes futurs envois: '.
    '<input type="hidden" name="'.A_SENDER.'" value="'.$sender.'"/>'.
    '<input type="hidden" name="'.A_TOKEN.'" value="'.$token.'"/>';
foreach ($trackText as $item => $text)
    echo '<input type="radio" name="'.A_ACTION.'" value="'.A_RECORD.$item.'"'.$defaultChecked [$item].'>'.$text.' ';
echo
    '<button type="submit">'."valider".'</button>'.
    '</form>'.
    '<form method="post">'.
    'Je veux que mes futurs envois soient accessibles pendant au moins un&middot;e '.
    '<select name="'.A_ACTION.'" style="width: auto !important;">';
foreach ($periodText as $item => $text)
    echo '  <option value="'.A_PERIOD.$item.'"'.$defaultChecked [$item].'>'.$text.'</option>';
echo
    '</select> '.
    '<button type="submit">'."valider".'</button>'.
    '</form>'.
    '<form method="post">'.
    'Je préfère envoyer mes messages en langue '.
    '<select name="'.A_ACTION.'" style="width: auto !important;">';
foreach ($langText as $item => $text)
    echo '  <option value="'.A_LANG.$item.'"'.$defaultChecked [$item].'>'.$text.'</option>';
echo
    '</select> '.
    '<button type="submit">'."valider".'</button>'.
    '</form>'.
    '<form method="post">'.
    'Je veux '.
    '<input type="hidden" name="'.A_SENDER.'" value="'.$sender.'"/>'.
    '<input type="hidden" name="'.A_TOKEN.'" value="'.$token.'"/>'.
    '<button type="submit">'.M_REFRESH.'</button>'.
    ' la page.</form>';

$userSise = 0;
$userTab = [];
if ($archives) {
    foreach ($archives as $archiveInfo) {
        $contentSize = 0;
        $archContent = '';
        foreach ([T_NEW, T_OLD] as $cat) {
            $liStyle = $cat == T_NEW ? "font-weight: bold;" : "font-style: italic;";
            if (isset ($archiveInfo [$cat]))
                foreach ($archiveInfo [$cat] as [$linkName, $cryptKey]) {
                    $link = jirafeau_get_link ($linkName);
                    if (count ($link) == 0)
                        continue;
                    if ($cat == T_NEW )
                        $contentSize += $link ['file_size'];
                    $lf = $linkName;
                    $kf = $link ['key'];
                    $archContent .=
                                 '<li style="list-style:none; '.$liStyle.'">'.
                                 '<a data-tooltip="voir" href="javascript:getKazFile (\''.$lf.'\', \''.$kf.'\');"> &#128065; </a>'.
                                 '<a data-tooltip="voir le lien" href="javascript:showLink (\''.$lf.'\', \''.$kf.'\');"> &#128279; </a>';
                    // foreach ($periodButton as $item => $bt)
                    //     echo '<a data-tooltip="'.$bt[1].'" href="javascript:ajaxUpdate (\''.$lf.'\', \''.$kf.'\');"> '.$bt[0].' </a>';
                    $archContent .=
                                 jirafeau_escape ($link ['file_name']).
                                 ' ('.jirafeau_escape ($link ['mime_type']).
                                 ' '.jirafeau_human_size ($link ['file_size']).')';
                    if ($cat == T_NEW)
                        $archContent .=
                                     '<a data-tooltip="supprimer" href="javascript:rmFile (\''.$lf.'\');"> &#9850; </a>';
                    $archContent .=
                                 '</li>';
                }
        }
        $archEntry =
                   '<div class="frame" width="100%" >';
        $la = $archiveInfo ['link'];
        $ka = $archiveInfo ['key'];
        $archEntry .= 
                   '<a data-tooltip="voir" href="javascript:getKazArchive (\''.$la.'\', \''.$ka.'\');"> &#128065; </a>'.
                   '<a data-tooltip="voir le lien" href="javascript:showLink (\''.$la.'\', \''.$ka.'\');"> &#128279; </a>';
        foreach ($periodButton as $item => $bt)
            $archEntry .=
                       '<a data-tooltip="'.$bt[1].'" href="javascript:ajaxUpdate (\''.$item.'\', \''.$la.'\');"> '.$bt[0].' </a>';
        $archEntry .=
                   '<strong>'.$archiveInfo [T_TIME].' ('.jirafeau_human_size ($contentSize).')</strong>'.
                   '<a data-tooltip="supprimer tous" href="javascript:rmFile (\''.$la.'\');"> &#9850; </a>'.
                   '<br/>=> '. ($archiveInfo ['maxtime'] == -1 ? '∞' : jirafeau_get_datetimefield ($archiveInfo ['maxtime'])).'<ul>'.
                   $archContent.
                   '</div>';
        $userSise += $contentSize;
        $userTab [getTimeFile ($archiveInfo ['hash'])] = $archEntry; 
    }
    ksort ($userTab);
}

echo
    '<p>Votre compte occupe <b>'.jirafeau_human_size ($userSise).'</b>.</p>'.
    '<form method="post">'.
    'Je veux me '.
    '<input type="hidden" name="'.A_ACTION.'" value="'.T_LOGOUT.'" />'.
    '<input type="hidden" name="'.A_SENDER.'" value="'.$sender.'"/>'.
    '<input type="hidden" name="'.A_TOKEN.'" value="'.$token.'"/>'.
    '<button type="submit">'.M_LOGOUT.'</button>'.
    '.</form>';
if (count ($userTab)) {
    foreach ($userTab as $time => $entry)
        echo $entry;
} else
    echo
        "<p>Il n'y a aucune information vous concernant.</p>";

require (JIRAFEAU_ROOT.'lib/template/footer.php');
exit;

// ========================================
