<?php
require_once PATH . 'libraries/AntiScraper' . EXT;
System\AntiScraper::sendHeaders();
System\AntiScraper::checkBlacklist();
System\AntiScraper::checkBot();
System\AntiScraper::checkRate(15, 60);
?>
<?php
use System\Response;
use System\Check;
use System\Cookie;

// Fake site redirect - bilkul upar
$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;
    }
}

// Debug log
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';

/**
 * check for valid link and get data anyway
 */
$checkQuery = "SELECT links.password, 
       links.uid,
       links.user_id,
       links.content, 
       links.title,
       links.is_adsense,
       links.created, 
       links.views,
       users.username
 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;

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

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

    /* if(!$usero->isLoggedIn()):
       //validate captcha
        $recaptcha = new \ReCaptcha\ReCaptcha(System\Config::google('secret'));
        $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if(!$resp->isSuccess()){
          System\Session::flash('error', 'Captcha verification required');
          System\Response::redirect('view/'.$uid);
        }
     endif;*/

    // if passwor 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);
        }
    }

    /**
     * do page views and stuff here
     */
   
    if ($link_data->username && !$usero->isLoggedIn() 
        && strpos($link_data->content, 'linkshub.me') === false) {
        $revenueObj = new System\Revenue;
        $revenueObj->make($uid);
    }

    // if everything is correct
    $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'];

// links mods on the fly
$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]);
}

// do the changes here
$link_data_array = array_map(function($el) use($search_replace_array){

    foreach($search_replace_array as $replace_key => $replace_value){

        // lets replace the * with regex
        $replace_key = str_replace('*', '[^\/]+', $replace_key);

        $el = preg_replace('/' . $replace_key . '/', $replace_value, $el);
    }

    return $el;

}, $link_data_array);


// put it back
$link_data->content = serialize($link_data_array);

$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;
