<?php
/**
 * CAI CP v.1
 *
 * @module     : Download application
 * @author     : Alexander I. Chebykin <alex.chebykin@gmail.com>
 * @copyright  : Copyright (c) 2016-2017 Alexander I. Chebykin
 * @version    : 1.0
 * @build date : 2017-07-17
 * @license    : MIT
 * @link       : https://github.com/CAI79/CAI-CP
 ******************************************************************/

header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');

require_once('../../../settings.php');

/* Places to store files by type */
$ParentDir = array('.gif' => 'images/_animations/',   
                   '.jpg' => 'images/',   '.jpeg' => 'images/',   '.png' => 'images/',
                   '.tif' => 'images/',   '.tiff' => 'images/',
                   '.avi' => 'video/',    '.flv'  => 'video/',    '.mkv' => 'video/',
                   '.mp4' => 'video/',    '.mpeg' => 'video/',    '.mpg' => 'video/',
                   '.exe' => 'soft/',     '.msi'  => 'soft/',
                   '.7z'  => 'archives/', '.iso'  => 'archives/', '.rar' => 'archives/', 
                   '.tar' => 'archives/', '.zip'  => 'archives/');
/* Filter parameters */
$Dir = str_replace(array('.', '/', '~', '\\', ' ', '%'), 
                   '_', 
                   filter_input(INPUT_POST, 'dir', FILTER_SANITIZE_STRING)
                  );
$Overwrite = (int)filter_input(INPUT_POST, 'overwrite', FILTER_SANITIZE_NUMBER_INT);

$URI = filter_input(INPUT_POST, 'uri', FILTER_SANITIZE_URL);

$SubstrPos = 0;
$PDir = '';
foreach ($ParentDir as $Key => $Val) {
    if (mb_stripos($URI, $Key) !== false){
        $SPos = mb_stripos($URI, $Key);
        if ($SubstrPos == 0) {
            $SubstrPos = $SPos;
            $PDir = $Val;
        } else {
            if ($SubstrPos < $Pos && $Pos > 0) {
                $SubstrPos = $Pos;
                $PDir = $Val;
            }
        }
    }
}

if ($Overwrite !== 1 && file_exists(str_replace('\ ', ' ', FILE_DOWNLOAD_DIR) . $PDir . $Dir . '/')) {
    $i = 1;
    while (file_exists(str_replace('\ ', ' ', FILE_DOWNLOAD_DIR) . $PDir . $Dir . '/' . $i)) {
        $i++;
    }
    $Dir .= '/' . $i;
}

echo exec(sprintf('bash -c "%s > /dev/null 2>&1 &"',
                  sprintf("./scripts/app.sh %s %s", 
                          FILE_DOWNLOAD_DIR . $PDir . $Dir, 
                          $URI)
                )
        );
echo '[langDownloadStarted]';
