<?php

/*
 * This file is part of Chevereto.
 *
 * (c) Rodolfo Berrios <rodolfo@chevereto.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Chevereto\Legacy\G\Handler;
use function Chevereto\Legacy\decryptString;
use function Chevereto\Legacy\G\is_url_web;
use function Chevereto\Legacy\G\redirect;
use function Chevereto\Vars\get;

/**
 * This is an internal redirection try to avoid spammers trying to get some
 * SEO juice by putting links all over your Chevereto website.
 *
 * It also avoids spammers to use this redirection to hang spam and whatnot in
 * third-party websites (auth_token stuff).
 *
 * The redirection is only issued if the URL was generated by crypt().
 */
return function (Handler $handler) {
    $encrypted = get()['to'] ?? null;
    if ($encrypted === null) {
        $handler->issueError(404);

        return;
    }
    $url = decryptString($encrypted);
    $validations = [
        is_url_web($url),
        $handler::checkAuthToken(get()['auth_token'] ?? ''),
    ];
    if (in_array(false, $validations)) {
        $handler->issueError(404);

        return;
    }
    redirect($url, 302);
};
