Fix redirect to home when opening pretty URL

This commit is contained in:
Jay Trees 2022-04-11 13:06:56 +02:00
parent e9a9980fa2
commit 1f7c1bb66c
3 changed files with 76 additions and 11 deletions

View file

@ -122,6 +122,12 @@ if (isset($api)) {
/**
* Pretty URLs
*/
$url = new \wishthis\URL($_SERVER['REQUEST_URI']);
if ($url->isPretty()) {
$_SESSION['_GET'] = query_to_key_value_pair($url->getPermalink());
}
if ($_SERVER['QUERY_STRING']) {
$_SESSION['_GET'] = $_GET;
}

View file

@ -14,11 +14,53 @@ class URL
{
}
public function isPretty(): bool
{
return !preg_match('/^\/\?.+?=.+?$/', $this->url);
}
public function getPermalink(): string
{
$htaccess = preg_split('/\r\n|\r|\n/', file_get_contents(ROOT . '/.htaccess'));
$permalink = '';
foreach ($htaccess as $index => $line) {
$parts = explode(chr(32), trim($line));
if (count($parts) >= 2) {
switch ($parts[0]) {
case 'RewriteRule':
$rewriteRule = $parts[1];
$target = $parts[2];
$regex = str_replace('/', '\/', $rewriteRule);
if (preg_match('/' . $regex . '/', ltrim($this->url, '/'), $matches)) {
$permalink = $target;
preg_match_all('/\$\d+/', $target, $placeholders);
$placeholders = reset($placeholders);
foreach ($placeholders as $index => $placeholder) {
$permalink = str_replace($placeholder, $matches[$index + 1], $permalink);
}
}
break;
}
}
}
return $permalink;
}
public function getPretty(): string
{
$htaccess = preg_split('/\r\n|\r|\n/', file_get_contents(ROOT . '/.htaccess'));
$pretty_url = '';
if (!$this->url) {
return '';
}
foreach ($htaccess as $index => $line) {
$parts = explode(chr(32), trim($line));
@ -36,17 +78,7 @@ class URL
explode('&', parse_url($target, PHP_URL_QUERY))
);
$flags = explode(',', substr($parts[3], 1, -1)) ?? array();
$parameters_pairs = explode('&', parse_url($this->url, PHP_URL_PATH));
$parameters = array();
foreach ($parameters_pairs as $index => $pair) {
$parts = explode('=', $pair);
$key = reset($parts);
$value = end($parts);
$parameters[$key] = $value;
}
$parameters = query_to_key_value_pair($this->url);
preg_match_all('/\(.+?\)/', $rewriteRule, $regexes);

View file

@ -0,0 +1,27 @@
<?php
/**
* @author Jay Trees <github.jay@grandel.anonaddy.me>
*/
/**
* Query string to key value pair
*
* @return array
*/
function query_to_key_value_pair(string $query): array
{
$query = str_contains($query, '?') ? parse_url($query, PHP_URL_QUERY) : $query;
$parameters_pairs = explode('&', $query);
$parameters = array();
foreach ($parameters_pairs as $index => $pair) {
$parts = explode('=', $pair);
$key = reset($parts);
$value = end($parts);
$parameters[$key] = $value;
}
return $parameters;
}