awaki/src/RedirectorRoutes.php

90 lines
3.1 KiB
PHP

<?php
namespace Awaki;
use Index\Data\IDbConnection;
use Index\Data\DbType;
use Index\Routing\IRouter;
final class RedirectorRoutes {
private IDbConnection $dbConn;
private array $urls;
public function __construct(IRouter $router, IDbConnection $dbConn, array $urls) {
$this->dbConn = $dbConn;
$this->urls = $urls;
$router->get('/', [$this, 'index']);
// databased
$router->get('/:id', [$this, 'redirectDatabase']);
// profile
$router->get('/u/:user', [$this, 'redirectProfile']);
$router->get('/p/:user', [$this, 'redirectProfile']);
// forum categories
$router->get('/f/:category', [$this, 'redirectForumCategory']);
$router->get('/fc/:category', [$this, 'redirectForumCategory']);
// forum topic
$router->get('/ft/:topic', [$this, 'redirectForumTopic']);
// forum post
$router->get('/fp/:post', [$this, 'redirectForumPost']);
}
public function index($response): void {
$response->accelRedirect('/index.html');
$response->setTypeHTML();
}
private function redirect($response, $request, $url) {
$params = $request->getParamString();
if(!empty($params))
$url .= (strpos($url, '?') === false ? '?' : '&') . $params;
$response->redirect($url, true);
}
public function redirectDatabase($response, $request, $id) {
$getInfo = $this->dbConn->prepare('SELECT redir_id, redir_url FROM awk_redirects WHERE redir_id = ? OR redir_vanity = ?');
$getInfo->addParameter(1, $id, DbType::INTEGER);
$getInfo->addParameter(2, $id, DbType::STRING);
$getInfo->execute();
$info = $getInfo->getResult();
if(!$info->next())
return 404;
$incClicks = $this->dbConn->prepare('UPDATE awk_redirects SET redir_clicks = redir_clicks + 1 WHERE redir_id = ?');
$incClicks->addParameter(1, $info->getInteger(0), DbType::INTEGER);
$incClicks->execute();
$this->redirect($response, $request, $info->getString(1));
}
private function redirectSimple($response, $request, string $format, string $argument) {
$scheme = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$argument = rawurlencode($argument);
$url = sprintf($format, $scheme, $argument);
$this->redirect($response, $request, $url);
}
public function redirectProfile($response, $request, string $userId) {
$this->redirectSimple($response, $request, $this->urls['user_profile'], $userId);
}
public function redirectForumCategory($response, $request, string $categoryId) {
$this->redirectSimple($response, $request, $this->urls['forum_category'], $categoryId);
}
public function redirectForumTopic($response, $request, string $topicId) {
$this->redirectSimple($response, $request, $this->urls['forum_topic'], $topicId);
}
public function redirectForumPost($response, $request, string $postId) {
$this->redirectSimple($response, $request, $this->urls['forum_post'], $postId);
}
}