<?php

error_reporting(E_ALL | E_STRICT);

// setup includes
require_once('../../../core/includes/master.inc.php');

// check we are receiving the request from this script
if (!checkReferrer())
{
    // exit
    header('HTTP/1.0 400 Bad Request');
    exit;
}

// require login
$Auth->requireUser('login.php');

// get url
$fileName = trim($_REQUEST['fileName']);
$rowId = (int)$_REQUEST['rowId'];

// double check user is logged in if required
$Auth = Auth::getAuth();
if ((!$Auth->loggedIn()) && (SITE_CONFIG_REQUIRE_USER_ACCOUNT_UPLOAD == 'yes'))
{
    echo createUploadError(t('registration_required', 'Registration required.'), t('please_register_for_an_account', 'Please register for an account to upload.'));
    exit;
}

// check for banned ip
$bannedIP = bannedIP::getBannedType();
if (strtolower($bannedIP) == "uploading")
{
    echo createUploadError(t('unavailable', 'Unavailable.'), t('uploading_has_been_disabled', 'Uploading has been disabled.'));
    exit;
}

// check that the user has not reached their max permitted uploads
$fileRemaining = getRemainingFilesToday();
if($fileRemaining == 0)
{
    echo createUploadError(t('max_uploads_reached', 'Max uploads reached.'), t('reached_maximum_uploads', 'You have reached the maximum permitted uploads for today.'));
    exit;
}

// for cross domain uploads
$refDomain = getReffererDomainOnly();
if (!$refDomain)
{
    if ((isset($_REQUEST['p'])) && (isset($_REQUEST['r'])))
    {
        $refDomain = $_REQUEST['p'] . '://' . $_REQUEST['r'];
    }
}
else
{
    $refDomain = _CONFIG_SITE_PROTOCOL . "://" . str_replace(array("http://", "https://"), "", $refDomain);
}

header('Access-Control-Allow-Origin: ' . (($refDomain === false) ? WEB_ROOT : ($refDomain)));
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Allow-Credentials: true');
header('Content-Disposition: inline; filename="files.json"');

$pluginObj = pluginHelper::getInstance('ftpupload');
$pluginObj->handleFileTransfer($fileName, $Auth->id, $rowId);
