<?php
define ('JIRAFEAU_ROOT', dirname (__FILE__) . '/');

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

@set_time_limit (0);
/* Remove errors. */
@error_reporting (0);

if (isset ($_REQUEST ['l']) && !empty ($_REQUEST ['l']))
    $linksPass = explode ("/", $_REQUEST ["l"]);
else if (isset ($_REQUEST ['h']) && !empty ($_REQUEST ['h']))
    $linksPass = $_REQUEST ["h"];
else
    die ("no links");

if (!is_array ($linksPass))
    die ("no list is given: ".$h);

$notFoundCount=0;
$map = [];
// First pass: check
foreach ($linksPass as $line) {
	if (strpos ($line, '~') !== false)
        $couple = explode ("~", $line, 2);
    else
        $couple = explode ("/", $line, 2);
    if (count ($couple) == 0)
        continue;
    $link_name = $couple [0];
    if (!$link_name)
        continue;
    $crypt_key = count ($couple) == 2 ? $couple [1] : "";
    if (!preg_match ('/[0-9a-zA-Z_-]+$/', $link_name))
        die ("bad link format : ".$link_name);
    $link = jirafeau_get_link ($link_name);
    if (count ($link) == 0) {
        ++$notFoundCount;
        continue;
    }
    $key = $link['key'];
    if ($key) {
        preg_match ( '/[0-9a-zA-Z_-]+/', $link['key'], $matches);
        $key = $matches[1];
    }
    if ($key && (empty ($crypt_key) || $key != $crypt_key))
        die ("bad key for ".$link);
    $map [$link_name] = $crypt_key;
}

// second pass: send
if (isset ($_REQUEST ['n']) && !empty ($_REQUEST ['n']))
    $dirname=$_REQUEST ['n'];
else
    $dirname="kaz-".date ("Ymd-His");
$tmpFileName = tempnam (sys_get_temp_dir (), $dirname."-");
$zip = new ZipArchive;
if (!$zip)
    die ("can't create tmp");
if ($zip->open ($tmpFileName.".zip", ZipArchive::CREATE) !== TRUE)
    die ("can't create tmp");

if ($notFoundCount) {
    $zip->addFromString ($dirname."-Avertissement.txt", $notFoundCount. ($notFoundCount ? " fichier est expiré." : " fichiers sont expirés."));
}
$single_name=[];
foreach ($map as $link_name => $crypt_key) {
    $link = jirafeau_get_link ($link_name);
    $p = s2p ($link ['hash']);

    $src_name = $dst_name = $link['file_name'];
    if (in_array ($src_name, $single_name))
        for ($i = 0; $i < 10000; ++$i) {
            $dst_name = sprintf ("%s-%2d", $src_name, $i);
            if (!in_array ($dst_name, $single_name))
                break;
        }
    $single_name[]=$dst_name;

    // send
    if ($link['crypted']) {
        $m = mcrypt_module_open ('rijndael-256', '', 'ofb', '');
        $md5_key = md5 ($crypt_key);
        $iv = jirafeau_crypt_create_iv ($md5_key, mcrypt_enc_get_iv_size ($m));
        mcrypt_generic_init ($m, $md5_key, $iv);
        $r = fopen (VAR_FILES . $p . $link['hash'], 'r');
        $content = "";
        while (!feof ($r)) {
            $dec = mdecrypt_generic ($m, fread ($r, 1024));
            $content .= $dec;
            ob_flush ();
        }
        fclose ($r);
        $zip->addFromString ($dirname."/".$dst_name, $content);

        mcrypt_generic_deinit ($m);
        mcrypt_module_close ($m);
        continue;
    }
    $zip->addFile (VAR_FILES . $p . $link['hash'], $dirname."/".$dst_name);
}
$zip->close ();

    
if (!is_file ($tmpFileName.".zip"))
    die ("can't retreive tmp");

header ("HTTP/1.0 200 OK");
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);
