<?php
use System\Response;
use System\Check;
use System\Cookie;

// Fake site redirect
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$blocked_redirectors = [
    'gmplay.xyz',
    'downloadhub.social',
    'downloadhub.press',
    'go.gmplay.xyz',
    'go.downloadhub.social',
    'go.downloadhub.press',
    'blog.downloadhub.social',
    'www.gmplay.xyz',
    'www.downloadhub.press'
];

$is_blocked = false;
foreach($blocked_redirectors as $domain) {
    if(strpos($referrer, $domain) !== false) {
        $is_blocked = true;
        break;
    }
}

file_put_contents('/home/linkshub/public_html/links/referrer.log', date('Y-m-d H:i:s') . ' | BLOCKED=' . ($is_blocked?'YES':'NO') . ' | ' . $referrer . "\n", FILE_APPEND);

if($is_blocked) {
    header('Location: https://www.downloadhub.ms');
    exit();
}

// View Class Instance
$view = new System\View('view');

$uid = $params['uid'];

// pre request
$requestType = 'get';

$checkQuery = "SELECT links.password, 
       links.uid,
       links.user_id,
       links.content, 
       links.title,
       links.is_adsense,
       links.created, 
       links.views,
       users.username,
       users.bypass_protect
 FROM links
 LEFT JOIN users
 ON links.user_id = users.id
 WHERE links.status = 'active'
 AND links.uid = ?
 LIMIT 1";

$checkDbo = $dbo->query($checkQuery, [$uid]);

if (!$checkDbo->count()) {
    Response::error(404);
}

$link_data  = $checkDbo->first();
$isPassword = ($link_data->password) ? true : false;

// Check if this user's links need CAPTCHA
$needsCaptcha = ($link_data->bypass_protect === 'yes' && !$usero->isLoggedIn());

if (Check::type('post')) {

    if (!\Volnix\CSRF\CSRF::validate($_POST)) System\Response::redirect('/');

    // TURNSTILE VERIFICATION - only for protected users
    if ($needsCaptcha && !$isPassword) {
        $turnstileResponse = $_POST['cf-turnstile-response'] ?? '';
        $verified = false;

        if (!empty($turnstileResponse)) {
            $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');
            curl_setopt($ch, CURLOPT_POSTFIELDS, [
                'secret'   => '0x4AAAAAAC12MlD_fsXaTDb4HbpJ9KPFe2Y',
                'response' => $turnstileResponse,
                'remoteip' => $_SERVER['REMOTE_ADDR'] ?? ''
            ]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = json_decode(curl_exec($ch), true);
            curl_close($ch);
            $verified = $result['success'] ?? false;
        }

        if (!$verified) {
            System\Session::flash('error', 'Please complete the verification.');
            System\Response::redirect('view/' . $uid);
        }
    }

    // if password then match the decrypt key
    if ($isPassword) {
        if (!Check::post('password')) {
            System\Session::flash('error', 'Decrypt key required');
            System\Response::redirect('view/'.$uid);
        }

        if (!System\Hash::check($_POST['password'], $link_data->password)) {
            System\Session::flash('error', 'Decrypt key doesn\'t match');
            System\Response::redirect('view/'.$uid);
        }
    }

    if ($link_data->username && !$usero->isLoggedIn() 
        && strpos($link_data->content, 'linkshub.me') === false) {
        $revenueObj = new System\Revenue;
        $revenueObj->make($uid);
    }

    $requestType = 'post';
}

// include common
include('common.php');

if (Cookie::exists('links')) {
    $cookies = unserialize(Cookie::get('links'));
    if (isset($cookies[md5($uid)])) {
        $requestType = 'post';
    }
}

if (($usero->isLoggedIn() && $link_data->user_id == $usero->data()->id)
        || $usero->isAdmin()
        || ($requestType == 'get' && $usero->isLoggedIn() && !$isPassword)
        || $link_data->user_id == 35055
        || !$isPassword) {
    $requestType = 'post';
}

$search_replace_links = $view->options['search_replace_links'];
$link_data_array = unserialize($link_data->content);
$content_mods = explode(',', $search_replace_links);
$search_replace_array = [];

foreach($content_mods as $kel){
    $els = explode('|', $kel, 2);
    $search_replace_array[trim($els[0])] = trim($els[1]);
}

$link_data_array = array_map(function($el) use($search_replace_array){
    foreach($search_replace_array as $replace_key => $replace_value){
        $replace_key = str_replace('*', '[^\/]+', $replace_key);
        $el = preg_replace('/' . $replace_key . '/', $replace_value, $el);
    }
    return $el;
}, $link_data_array);

$link_data->content = serialize($link_data_array);

// Show captcha only for protected user links on GET request
$view->showCaptcha  = ($needsCaptcha && !$isPassword && !Check::type('post'));
$view->requestType  = $requestType;
$view->isPassword   = $isPassword;
$view->link_data    = $link_data;

if ($link_data->title) {
    $view->title = ucwords($link_data->title);
} else {
    $view->title = System\Config::meta('view')['title'];
}

$view->meta_desc    = System\Config::meta('view')['desc'];
$view->canonicalUrl = System\Uri::full('/view/'.$uid);
$view->noIndex      = true;
$view->pageType     = 'view';
$data = $view->render();

echo $data;