<?php

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);

ob_start();

// Временное решение редиректы с IP на сканер без запуска
// https://doboard.com/1/task/26406
if (
    strpos($_SERVER['REQUEST_URI'], '/website-malware-scanner') !== false
    && isset($_GET['url'])
    && filter_var($_GET['url'], FILTER_VALIDATE_IP)
) {
    header("Location: /website-malware-scanner", true, 301);
    exit;
}

require_once __DIR__ . '/vendor/autoload.php';

require_once 'includes/configuration_main.php';
require_once 'includes/local_configuration.php';
require_once ( __DIR__ . '/includes/helpers/apc_compatibility.php' );
require_once __DIR__ . '/includes/service/Database/store_connection_credentials.php';

use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Cleantalk\App\Services\LinkManager;
use Cleantalk\Service\Helpers\StringHelper;

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

extract(require_once __DIR__ . '/includes/App/index.php');

$noc_headers = 'From: ' . cfg::noc_email . "\r\n" . 'Reply-To: ' . cfg::noc_email . "\r\n" . 'Content-type: text/html; charset=UTF-8' . "\r\n";

$default_src = require_once __DIR__ . '/includes/App/config/src/default.php';
$style_src   = require_once __DIR__ . '/includes/App/config/src/style.php';
$script_src  = require_once __DIR__ . '/includes/App/config/src/script.php';
$frame_src   = require_once __DIR__ . '/includes/App/config/src/frame.php';
$font_src    = require_once __DIR__ . '/includes/App/config/src/font.php';
$img_src     = require_once __DIR__ . '/includes/App/config/src/img.php';
$connect_src = require_once __DIR__ . '/includes/App/config/src/connect.php';

if ( in_array($_SERVER["HTTP_HOST"], array('cleantalk.loc','polygon.cleantalk.org'))) {
    $connect_src[] = 'api.loc';
    $connect_src[] = 'api-next.cleantalk.org';
}

header("Content-Security-Policy: default-src " . implode(' ', $default_src) . "; style-src " . implode(' ', $style_src) . "; script-src " . implode(' ', $script_src) . "; frame-src " . implode(' ', $frame_src) . "; font-src 'self' data: " . implode(' ', $font_src) . "; img-src 'self' data: " . implode(' ', $img_src) . "; connect-src 'self' " . implode(' ', $connect_src) . "; base-uri 'self';");
header("Cache-Control: max-age=2592000");

if (cfg::enable_profiling) {
    $profile_start = null;
    $page_request_id = md5(rand());
    profile_code();
}

require "anti-ddos-lite/anti-ddos-lite.php";

if ($request->is('api/*') && $requestMatchesRoute($router, $request)) {
    try {
        $response = $router->dispatch($request);
    } catch (NotFoundHttpException $e) {
        $response = new JsonResponse([
            'ok' => false,
            'message' => 'API route not found.',
        ], 404);
    } catch (MethodNotAllowedHttpException $e) {
        $response = new JsonResponse([
            'ok' => false,
            'message' => 'HTTP method is not allowed for this API route.',
        ], 405);
    }

    $response->send();

    die();
}

require "includes/ccs.php";
$ccs = new CCS();
$linkManager = new LinkManager();
$ccs->get_ct_lang();
$uri_prefix = $ccs->page_info['url_lang_prefix'];
$path = parse_url($_SERVER['REQUEST_URI']);
$uri = ($path && isset($path['path'])) ? $path['path'] : '/';
$correctURI = strtolower($uri);
if ($uri != '/') {
    $correctURI = preg_replace('/\/+/', '/', $correctURI);
    if (!isset($path['query'])) {
        $correctURI = preg_replace('/\/*$/', '', $correctURI);
    }
}
if ($uri != $correctURI && $correctURI != '/ru' && $correctURI != 'ru') {
    header("HTTP/1.1 301 Moved Permanently");
    $location = "location: https://".$_SERVER['HTTP_HOST'].$correctURI;
    if (isset($path['query'])) {
        $location .= '?' . $path['query'];
    }
    header("location: https://".$_SERVER['HTTP_HOST'].$correctURI);
    exit();
}

$matches = explode('/', $uri);
$routeLangPrefix = null;
if ($matches && isset($matches[1]) && array_key_exists($matches[1], $ccs->ct_langs)) {
    if ($matches[1] == 'en') {
        $redir = parse_url($_SERVER['REQUEST_URI']);
        $redir['path'] = explode('/', $redir['path']);
        unset($redir['path'][1]);
        $redir['path'] = implode('/', $redir['path']);
        header('Location: ' . $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $redir['path'] . ((isset($redir['query']) && !empty($redir['query'])) ? ('?' . $redir['query']) : ''));
        exit();
    }
    $routeLangPrefix = strtolower($matches[1]);
    unset($matches[1]);
    $uri = implode('/', $matches);
}

$matches = null;
if (preg_match("/^\/([a-z0-9_\/\.\-\(\)]+)/i", $uri, $matches)) {
    if (isset($matches[1]) && preg_match("/^(blacklists|update|email-checker|whois|uptime-monitoring|my-ip|ipinfo)/", $matches[1]))
        $matches = null;
}
if ($matches === null || (isset($matches[1]) && !preg_match("/^[a-z0-9\-\/\_]+$/i", $matches[1])))
    preg_match("#^/([^/]+)#i", $uri, $matches);

if ($matches === null || (isset($matches[1]) && !preg_match("/^[a-z0-9\-\/\_]+$/i", $matches[1])))
    preg_match("#^/([^?]+)#i", $uri, $matches);

if (isset($matches[1])){
    $page_url = addslashes($matches[1]);

    if (stripos($page_url, 'antispam-security-apps-releases/') === 0) {
        $page_url = 'antispam-security-apps-releases';
    }

    if ($page_url == 'api') {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: ".$uri_prefix."/help/api-cleantalk-all");
        exit();
    }

    $original_page_url = $page_url;

    if (substr_count($page_url, 'help/') == 1 && strlen($page_url) > 5 && substr_count($page_url, 'help/help') != 1)
        $page_url = str_replace('help/', '', $page_url);

    if ($page_url == 'blog') {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: https://blog.cleantalk.org/");
        exit();
    }

    if ($page_url == 'forum') {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: https://community.cleantalk.org/ ");
        exit();
    }

    if ($page_url == 'blacklists' && isset($_GET['record']) && !empty($_GET['record']) && empty($_GET['action'])) {
        header("HTTP/1.1 301 Moved Permanently");
        header('Location: /blacklists/'.$_GET['record']);
    }

    if ($uri == '/blacklists/') {
        header("HTTP/1.1 301 Moved Permanently");
        header('Location: /blacklists');
    }

    $ccs->page_url = $page_url;

    if (StringHelper::isValidLinkPath($page_url)) {
        $link = $linkManager->findByTemplate($page_url);
    }

    // Ищем страницу по SEO_URL
    if (isset($link['id'])) {
        // Если есть SEO URL, то делаем перенаправление на него, т.к. так лучше с точки зрения поисковой оптимизации
        if (isset($link['seo_url']) && $link['seo_url'] != $page_url) {
            header("Location:/" . $link['seo_url'], true, 301);
            exit();
        }
    } else {
        if (StringHelper::isValidLinkPath($page_url)) {
            $link = $linkManager->findBySeoUrl($page_url);
        }
    }

    /** Логика для статей на тех языках, которых пока нет в списке локалей */
    $newLangArticle = preg_match("#^([a-z]{2})/(.+)$#i", $original_page_url, $articlePathMatches);
    if (empty($link) && $newLangArticle) {
        $articleRequestedLang = strtolower($articlePathMatches[1]);
        $articlePageUrl = $articlePathMatches[2];
        if (
            substr_count($articlePageUrl, 'help/') == 1
            && strlen($articlePageUrl) > 5
            && substr_count($articlePageUrl, 'help/help') != 1
        ) {
            $articlePageUrl = str_replace('help/', '', $articlePageUrl);
        }

        if (StringHelper::isValidLinkPath($articlePageUrl)) {
            $articleLink = $linkManager->findByTemplateOrSeoUrl($articlePageUrl);

            if (is_article_link($articleLink)) {
                $link = $articleLink;
                $page_url = $articlePageUrl;
                $ccs->page_url = $page_url;
                $ccs->article_requested_lang = $articleRequestedLang;
            }
        }
    }

    if (
        $ccs->article_requested_lang === null
        && $routeLangPrefix !== null
        && is_article_link($link)
    ) {
        $ccs->article_requested_lang = $routeLangPrefix;
    }

    if (isset($link['class']) && $link['class'] === 'LandingPage') {
        if (strpos($original_page_url, 'help/') === 0) {
            $correct_url = str_replace('help/', '', $original_page_url);
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: /" . $correct_url);
            exit();
        }
    }

    if ($link) {
        $page_id = $link['id'];
    }
} else {
    $page_id = $_GET['page'] ?? null;
    if (!preg_match("/^(\d+)$/", $page_id)) {
        $page_id = 1;
    }

    $link = $linkManager->findById((int)$page_id);
}
if ($link === false || !$link){
    $link = [
        'id' => null,
        'url' => null,
        'class' => null,
        'name' => null,
        'template' => cfg::pagenotfound_tpl,
    ];
}

if (strlen((string)($link['url'] ?? '')) > 0 ){
	header("Location:" . $link['url']);
    exit;
}

if ($link['class'] ?? null) {
    $class_filename = cfg::includes_dir . strtolower($link['class']) . ".php";
    include $class_filename;
}

$ajax = isset($_GET['ajax']) ? true : false;

if (class_exists($link['class'] ?? '')){
    $class = new $link['class'];
    $class->noc_headers = $noc_headers;
    $class->link = (object)$link;
    $class->page_url = $ccs->page_url;
    $class->article_requested_lang = $ccs->article_requested_lang;
    $class->show_page(true, $ajax);
} else {
    include cfg::includes_dir . 'simplepage.php';
    $class = new SimplePage;
    $class->noc_headers = $noc_headers;
    $class->link = (object)$link;
    $class->page_url = $ccs->page_url;
    $class->article_requested_lang = $ccs->article_requested_lang;
    $class->show_page(true, $ajax);
}
profile_code();
exit();

function is_article_link($link): bool
{
    if (empty($link)) {
        return false;
    }

    $template = is_array($link) ? ($link['template'] ?? '') : ($link->template ?? '');
    $class = is_array($link) ? ($link['class'] ?? '') : ($link->class ?? '');
    $id = (int)(is_array($link) ? ($link['id'] ?? 0) : ($link->id ?? 0));

    return $template === 'article.html'
        || $class === 'LandingPage'
        || ($class === 'SimplePage' && in_array($id, [20, 91, 92], true));
}

/**
* Функция измеряет скорость загрузки страницы
*/
function profile_code() {
    global $profile_start, $page_request_id;

    if (!cfg::enable_profiling) {
        return cfg::enable_profiling;
    }

    if ($profile_start) {
        error_log(sprintf("Request: %s, page %s load time %.3f seconds.", $page_request_id, $_SERVER['SCRIPT_NAME'], microtime() - $profile_start));
    }

    $profile_start = microtime();

    return null;
}
