<?php

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

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

// for page footer link
if(!defined('REPORT_URL'))
{
    define('REPORT_URL', $file->getFullShortUrl());
}

// load plugin details
$pluginDetails  = pluginHelper::pluginSpecificConfiguration('imageviewer');
$pluginConfig   = $pluginDetails['config'];
$pluginSettings = json_decode($pluginDetails['data']['plugin_settings'], true);

// Initialize current user
$Auth = Auth::getAuth();

// make sure we should be showing the image for this user type
$showPage = false;
if ((int) $pluginSettings['non_show_viewer'] == 1)
{
    $showPage = true;
}

// logged in free users
if (($Auth->level == 'free user') && ($Auth->loggedIn == true))
{
    $showPage = false;
    if ((int) $pluginSettings['free_show_viewer'] == 1)
    {
        $showPage = true;
    }
}

// paid users
if (($Auth->level == 'paid user') || ($Auth->level == 'admin'))
{
    $showPage = false;
    if ((int) $pluginSettings['paid_show_viewer'] == 1)
    {
        $showPage = true;
    }
}

// if this is a download request
if ((!isset($_REQUEST['idt'])) && ($file->isImage()) && ($showPage == true))
{
	define('_INT_FILE_ID', (int)$file->id);
	include_once(SITE_TEMPLATES_PATH.'/account_home.html');
	exit;
}
elseif ((isset($_REQUEST['idt'])) && ($file->isImage()))
{
    $directDownloadUrl = $file->generateDirectDownloadUrl();
    coreFunctions::redirect($directDownloadUrl);
}
