<?php
// try to load the file object
$file = null;
if (isset($_REQUEST['u']))
{
    // only keep the initial part if there's a forward slash
    $shortUrl = current(explode("/", $_REQUEST['u']));
    $file     = file::loadByShortUrl($shortUrl);
}

/* load file details */
if (!$file)
{
    /* if no file found, redirect to home page */
    redirect(WEB_ROOT . "/index." . SITE_CONFIG_PAGE_EXTENSION);
}

// load plugin details
$pluginDetails = pluginHelper::pluginSpecificConfiguration('imageviewer');
$pluginConfig  = $pluginDetails['config'];

// for embedded videos override speed setting
if (isset($_REQUEST['idt']))
{
    // check token against db
    $downloadToken = $_REQUEST['idt'];
    $db = Database::getDatabase(true);
    $rs = $db->getValue('SELECT token FROM plugin_imageviewer_embed_token WHERE file_id=' . (int) $file->id . ' AND token="' . $db->escape($downloadToken) . '" AND ip_address = "'.getUsersIPAddress().'" LIMIT 1');
    if ($rs)
    {
        // delete any tokens older than 1 day
        $db->query('DELETE FROM plugin_imageviewer_embed_token WHERE date_added < DATE_SUB(NOW(), INTERVAL 1 DAY)');
        
        if(isset($_REQUEST['idf']))
        {
            // is download, remote token
            //$db->query('DELETE FROM plugin_imageviewer_embed_token WHERE file_id=' . (int) $file->id . ' AND token="' . $db->escape($downloadToken) . '"');
        }
        else
        {
            // is streaming
            $_SESSION['speed'] = 0;
        }
    }
    else
    {
        // show delay
        redirect($file->getFullShortUrl());
        exit();
    }
}
