Skip to content

Commit

Permalink
Add new redirection text type
Browse files Browse the repository at this point in the history
Fix
  • Loading branch information
zawaze committed Apr 25, 2024
1 parent 071bcfc commit 428a440
Show file tree
Hide file tree
Showing 10 changed files with 104 additions and 50 deletions.
2 changes: 1 addition & 1 deletion Config/module.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<descriptive locale="fr_FR">
<title>Gérer la réécriture d'url</title>
</descriptive>
<version>2.1.6</version>
<version>2.1.8</version>
<author>
<name>Vincent Lopes, Gilles Bourgeat, Tom Pradat</name>
<email>[email protected], [email protected], [email protected]</email>
Expand Down
49 changes: 27 additions & 22 deletions Controller/Admin/ModuleConfigController.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,15 +47,14 @@ public function viewConfigAction()

public function getDatatableRules(Request $request)
{
$requestSearchValue = $request->get('search') ? '%'.$request->get('search')['value'].'%' : '';
$requestSearchValue = $request->get('search') ? '%' . $request->get('search')['value'] . '%' : '';
$recordsTotal = RewriteurlRuleQuery::create()->count();
$search = RewriteurlRuleQuery::create();
if ('' !== $requestSearchValue) {
$search
->filterByValue($requestSearchValue, Criteria::LIKE)
->_or()
->filterByRedirectUrl($requestSearchValue)
;
->filterByRedirectUrl($requestSearchValue);
}

$recordsFiltered = $search->count();
Expand Down Expand Up @@ -85,8 +84,7 @@ public function getDatatableRules(Request $request)

$search
->offset($request->get('start'))
->limit($request->get('length'))
;
->limit($request->get('length'));
$searchArray = $search->find()->toArray();

$resultsArray = [];
Expand All @@ -95,14 +93,16 @@ public function getDatatableRules(Request $request)
$isRegexSelected = $row['RuleType'] === RewriteurlRule::TYPE_REGEX ? 'selected' : '';
$isParamsSelected = $row['RuleType'] === RewriteurlRule::TYPE_GET_PARAMS ? 'selected' : '';
$isRegexParamsSelected = $row['RuleType'] === RewriteurlRule::TYPE_REGEX_GET_PARAMS ? 'selected' : '';
$isTextParamsSelected = $row['RuleType'] === RewriteurlRule::TYPE_TEXT ? 'selected' : '';
$isOnly404Checked = $row['Only404'] ? 'checked' : '';
$rewriteUrlRuleParams = RewriteurlRuleQuery::create()->findPk($row['Id'])->getRewriteUrlParamCollection();
$resultsArray[] = [
'Id' => $row['Id'],
'RuleType' => '<select class="js_rule_type form-control" data-idrule="'.$id.'" required>
<option value="'.RewriteurlRule::TYPE_REGEX.'" '.$isRegexSelected.'>'.Translator::getInstance()->trans('Regex', [], RewriteUrl::MODULE_DOMAIN).'</option>
<option value="'.RewriteurlRule::TYPE_GET_PARAMS.'" '.$isParamsSelected.'>'.Translator::getInstance()->trans('Get Params', [], RewriteUrl::MODULE_DOMAIN).'</option>
<option value="'.RewriteurlRule::TYPE_REGEX_GET_PARAMS.'" '.$isRegexParamsSelected.'>'.Translator::getInstance()->trans('Regex and Get Params', [], RewriteUrl::MODULE_DOMAIN).'</option>
'RuleType' => '<select class="js_rule_type form-control" data-idrule="' . $id . '" required>
<option value="' . RewriteurlRule::TYPE_REGEX . '" ' . $isRegexSelected . '>' . Translator::getInstance()->trans('Regex', [], RewriteUrl::MODULE_DOMAIN) . '</option>
<option value="' . RewriteurlRule::TYPE_GET_PARAMS . '" ' . $isParamsSelected . '>' . Translator::getInstance()->trans('Get Params', [], RewriteUrl::MODULE_DOMAIN) . '</option>
<option value="' . RewriteurlRule::TYPE_REGEX_GET_PARAMS . '" ' . $isRegexParamsSelected . '>' . Translator::getInstance()->trans('Regex and Get Params', [], RewriteUrl::MODULE_DOMAIN) . '</option>
<option value="' . RewriteurlRule::TYPE_TEXT . '" ' . $isTextParamsSelected . '>' . Translator::getInstance()->trans('Text', [], RewriteUrl::MODULE_DOMAIN) . '</option>
</select>',
'Value' => $this->renderRaw(
'RewriteUrl/tab-value-render',
Expand All @@ -112,15 +112,15 @@ public function getDatatableRules(Request $request)
'VALUE' => $row['Value'],
]
),
'Only404' => '<input class="js_only404 form-control" type="checkbox" style="width: 100%!important;" '.$isOnly404Checked.'/>',
'Only404' => '<input class="js_only404 form-control" type="checkbox" style="width: 100%!important;" ' . $isOnly404Checked . '/>',
'RedirectUrl' => '<div class="col-md-12 input-group">
<input class="js_url_to_redirect form-control" type="text" placeholder="/path/mypage.html" value="'.$row['RedirectUrl'].'"/>
<input class="js_url_to_redirect form-control" type="text" placeholder="/path/mypage.html" value="' . $row['RedirectUrl'] . '"/>
</div>',
'Position' => '<a href="#" class="u-position-up js_move_rule_position_up" data-idrule="'.$id.'"><i class="glyphicon glyphicon-arrow-up"></i></a>
<span class="js_editable_rule_position editable editable-click" data-idrule="'.$id.'">'.$row['Position'].'</span>
<a href="#" class="u-position-down js_move_rule_position_down" data-idrule="'.$id.'"><i class="glyphicon glyphicon-arrow-down"></i></a>',
'Actions' => '<a href="#" class="js_btn_update_rule btn btn-success" data-idrule="'.$id.'"><span class="glyphicon glyphicon-check"></span></a>
<a href="#" class="js_btn_remove_rule btn btn-danger" data-idrule="'.$id.'"><span class="glyphicon glyphicon-remove"></span></a>
'Position' => '<a href="#" class="u-position-up js_move_rule_position_up" data-idrule="' . $id . '"><i class="glyphicon glyphicon-arrow-up"></i></a>
<span class="js_editable_rule_position editable editable-click" data-idrule="' . $id . '">' . $row['Position'] . '</span>
<a href="#" class="u-position-down js_move_rule_position_down" data-idrule="' . $id . '"><i class="glyphicon glyphicon-arrow-down"></i></a>',
'Actions' => '<a href="#" class="js_btn_update_rule btn btn-success" data-idrule="' . $id . '"><span class="glyphicon glyphicon-check"></span></a>
<a href="#" class="js_btn_remove_rule btn btn-danger" data-idrule="' . $id . '"><span class="glyphicon glyphicon-remove"></span></a>
',
];
}
Expand Down Expand Up @@ -246,11 +246,16 @@ protected function fillRuleObjectFields(RewriteurlRule $rule, Request $request):

$isParamRule = $ruleType === RewriteurlRule::TYPE_GET_PARAMS || $ruleType === RewriteurlRule::TYPE_REGEX_GET_PARAMS;
$isRegexRule = $ruleType === RewriteurlRule::TYPE_REGEX || $ruleType === RewriteurlRule::TYPE_REGEX_GET_PARAMS;
$isTextRule = $ruleType === RewriteurlRule::TYPE_TEXT;

if (!($isParamRule || $isRegexRule)) {
if (!($isParamRule || $isRegexRule || $isTextRule)) {
throw new TheliaProcessException(Translator::getInstance()->trans('Unknown rule type.', [], RewriteUrl::MODULE_DOMAIN));
}

if ($isTextRule && !$textValue = $request->get('textValue', null)) {
throw new TheliaProcessException(Translator::getInstance()->trans('Text value cannot be empty.', [], RewriteUrl::MODULE_DOMAIN));
}

$regexValue = $request->get('value', null);

if ($isRegexRule && empty($regexValue)) {
Expand All @@ -263,6 +268,8 @@ protected function fillRuleObjectFields(RewriteurlRule $rule, Request $request):
throw new TheliaProcessException(Translator::getInstance()->trans('Redirect url cannot be empty.', [], RewriteUrl::MODULE_DOMAIN));
}

$value = $isTextRule ? $textValue : $regexValue;

$paramRuleArray = [];

if ($isParamRule) {
Expand All @@ -272,12 +279,10 @@ protected function fillRuleObjectFields(RewriteurlRule $rule, Request $request):
}
}

$rule
->setRuleType($ruleType)
->setValue($regexValue)
$rule->setRuleType($ruleType)
->setValue($value)
->setOnly404($request->get('only404', 1))
->setRedirectUrl($redirectUrl)
;
->setRedirectUrl($redirectUrl);

if (empty($rule->getPosition())) {
$rule->setPosition($rule->getNextPosition());
Expand Down
18 changes: 15 additions & 3 deletions EventListeners/KernelExceptionListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,26 @@ public function onKernelHttpNotFoundException(ExceptionEvent $event)
if ($event->getThrowable() instanceof NotFoundHttpException) {
$urlTool = URL::getInstance();

$request = $this->requestStack->getCurrentRequest();
$pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();

// Check RewriteUrl text rules
$textRule = RewriteurlRuleQuery::create()
->filterByOnly404(0)
->filterByValue(ltrim($pathInfo, '/'))
->filterByRuleType('text')
->orderByPosition()
->findOne();

if ($textRule) {
$event->setThrowable(new RedirectException($urlTool->absoluteUrl($textRule->getRedirectUrl()), 301));
}

$ruleCollection = RewriteurlRuleQuery::create()
->filterByOnly404(1)
->orderByPosition()
->find();

$request = $this->requestStack->getCurrentRequest();
$pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();

/** @var RewriteurlRule $rule */
foreach ($ruleCollection as $rule) {
if ($rule->isMatching($pathInfo, $request->query->all())) {
Expand Down
11 changes: 7 additions & 4 deletions Model/RewriteurlRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ class RewriteurlRule extends BaseRewriteurlRule
/** @var string */
public const TYPE_REGEX_GET_PARAMS = 'regex-params';

/** @var string */
public const TYPE_TEXT = 'text';

protected $rewriteUrlParamCollection = null;

/**
Expand All @@ -47,15 +50,15 @@ protected function isMatchingPath(string $url): bool
{
if (!empty($this->getValue())) {
try {
$match = @preg_match('/'.$this->getValue().'/', $url);
$match = @preg_match('/' . $this->getValue() . '/', $url);

if (false === $match) {
Tlog::getInstance()->error('Invalid pattern: '.$this->getValue());
Tlog::getInstance()->error('Invalid pattern: ' . $this->getValue());
}

return (bool) $match;
return (bool)$match;
} catch (\Exception $ex) {
Tlog::getInstance()->error('Failed to match rule : '.$ex->getMessage());
Tlog::getInstance()->error('Failed to match rule : ' . $ex->getMessage());
}
}

Expand Down
13 changes: 7 additions & 6 deletions RewriteUrl.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
namespace RewriteUrl;

use Propel\Runtime\Connection\ConnectionInterface;
use RewriteUrl\Model\RewriteurlRuleQuery;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator;
use Symfony\Component\Finder\Finder;
use Thelia\Model\ConfigQuery;
Expand All @@ -30,10 +32,10 @@
*/
class RewriteUrl extends BaseModule
{
/** @var string */
/** @var string */
const MODULE_DOMAIN = "rewriteurl";

/** @var string */
/** @var string */
const MODULE_NAME = "rewriteurl";

/* @var string */
Expand All @@ -43,7 +45,6 @@ class RewriteUrl extends BaseModule
static protected $unknownSources;



public function preActivation(ConnectionInterface $con = null)
{
if (!$this->getConfigValue('is_initialized', false)) {
Expand All @@ -65,7 +66,7 @@ public function preActivation(ConnectionInterface $con = null)
* @throws \Propel\Runtime\Exception\PropelException
* @since 1.2.3
*/
public function update($currentVersion, $newVersion, ConnectionInterface $con = null):void
public function update($currentVersion, $newVersion, ConnectionInterface $con = null): void
{
$finder = (new Finder())->files()->name('#.*?\.sql#')->sortByName()->in(self::UPDATE_PATH);

Expand Down Expand Up @@ -121,8 +122,8 @@ public static function getUnknownSources()
*/
public static function configureServices(ServicesConfigurator $servicesConfigurator): void
{
$servicesConfigurator->load(self::getModuleCode().'\\', __DIR__)
->exclude([THELIA_MODULE_DIR.ucfirst(self::getModuleCode()).'/I18n/*'])
$servicesConfigurator->load(self::getModuleCode() . '\\', __DIR__)
->exclude([THELIA_MODULE_DIR . ucfirst(self::getModuleCode()) . '/I18n/*'])
->autowire(true)
->autoconfigure(true);
}
Expand Down
20 changes: 13 additions & 7 deletions Service/RewritingRouterFirst.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,26 @@ class RewritingRouterFirst extends RewritingRouter
/**
* @inheritdoc
*/
public function matchRequest(Request $request) : array
public function matchRequest(Request $request): array
{
if (ConfigQuery::isRewritingEnable()) {
$urlTool = URL::getInstance();

$pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();

// Check RewriteUrl text rules
$textRule = RewriteurlRuleQuery::create()
->filterByOnly404(0)
->filterByValue(ltrim($pathInfo, '/'))
->filterByRuleType('text')
->orderByPosition()
->findOne();

if ($textRule) {
$this->redirect($urlTool->absoluteUrl($textRule->getRedirectUrl()), 301);
}

// Check RewriteUrl rules

$ruleCollection = RewriteurlRuleQuery::create()
->filterByOnly404(0)
->orderByPosition()
Expand All @@ -48,8 +57,6 @@ public function matchRequest(Request $request) : array
}
}



try {
$rewrittenUrlData = $urlTool->resolve($pathInfo);
} catch (UrlRewritingException $e) {
Expand All @@ -64,7 +71,7 @@ public function matchRequest(Request $request) : array

// If we have a "lang" parameter, whe have to check if the found URL has the proper locale
// If it's not the case, find the rewritten URL with the requested locale, and redirect to it.
if (null ==! $requestedLocale = $request->get('lang')) {
if (null == !$requestedLocale = $request->get('lang')) {
if (null !== $requestedLang = LangQuery::create()->findOneByLocale($requestedLocale)) {
if ($requestedLang->getLocale() != $rewrittenUrlData->locale) {
$localizedUrl = $urlTool->retrieve(
Expand All @@ -85,8 +92,7 @@ public function matchRequest(Request $request) : array
->filterByViewId($rewrittenUrlData->viewId)
->filterByViewLocale($rewrittenUrlData->locale)
->filterByRedirected(null, Criteria::ISNULL)
->findOne()
;
->findOne();

// Differences with the base class for handling 301 or 302 redirection
$redirectType = $this->fetchRewritingRedirectTypeFromUrl($rewrittenUrlData->rewrittenUrl);
Expand Down
16 changes: 13 additions & 3 deletions Service/RewritingRouterLast.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,24 @@ public function matchRequest(Request $request) : array
{
if (ConfigQuery::isRewritingEnable()) {
$urlTool = URL::getInstance();
$pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();

$ruleCollection = RewriteurlRuleQuery::create()
// Check RewriteUrl text rules
$textRule = RewriteurlRuleQuery::create()
->filterByOnly404(1)
->filterByValue(ltrim($pathInfo, '/'))
->filterByRuleType('text')
->orderByPosition()
->find();
->findOne();

$pathInfo = $request instanceof TheliaRequest ? $request->getRealPathInfo() : $request->getPathInfo();
if ($textRule) {
$this->redirect($urlTool->absoluteUrl($textRule->getRedirectUrl()), 301);
}

$ruleCollection = RewriteurlRuleQuery::create()
->filterByOnly404(1)
->orderByPosition()
->find();

/** @var RewriteurlRule $rule */
foreach ($ruleCollection as $rule) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,21 @@
$container.find(".js_regex_group").css('margin-bottom', '0px');

if (selectedRuleType === "regex"){
$container.find(".js_regex_group").show();
$container.find(".js_text_group").hide();
$container.find(".js_param_rule_group").hide();
$container.find(".js_regex_group").show();
} else if (selectedRuleType === "params"){
$container.find(".js_text_group").hide();
$container.find(".js_regex_group").hide();
$container.find(".js_param_rule_group").show();
} else if (selectedRuleType === "regex-params"){
$container.find(".js_text_group").hide();
$container.find(".js_regex_group").css('margin-bottom', '5px').show();
$container.find(".js_param_rule_group").show();
} else if (selectedRuleType === "text") {
$container.find(".js_regex_group").hide();
$container.find(".js_param_rule_group").hide();
$container.find(".js_text_group").show();
}
});

Expand Down Expand Up @@ -104,8 +111,6 @@
moveRulePosition(id_rule, "down");
});



function onChangeParamCondition(element){
var selectedParamCondition = $(element).val();

Expand Down Expand Up @@ -235,6 +240,7 @@
data.id = ruleid;
data.ruleType = $tr.find(".js_rule_type").val();
data.value = $tr.find(".js_regex").val();
data.textValue = $tr.find(".js_text").val();
data.only404 = $tr.find(".js_only404").prop("checked") ? 1 : 0;
data.redirectUrl = $tr.find(".js_url_to_redirect").val();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ <h3 class="panel-title">
<option value="regex">{intl d=$d l="Regex"}</option>
<option value="params">{intl d=$d l="GET params"}</option>
<option value="regex-params">{intl d=$d l="Regex and GET params"}</option>
<option value="text">{intl d=$d l="Text"}</option>
</select>
</td>
<td>
Expand All @@ -60,7 +61,11 @@ <h3 class="panel-title">
<input class="js_regex form-control" type="text" placeholder="{literal}^[a-z0-9_-]{3,16}${/literal}"/>
<span class="input-group-addon">/</span>
</div>

<div class="js_text_group input-group">
<span class="input-group-addon">/</span>
<input class="js_text form-control" type="text" placeholder=""/>
<span class="input-group-addon"></span>
</div>
<div class="js_param_rule_group"></div>
</td>
<td class="text-center">
Expand Down
Loading

0 comments on commit 428a440

Please sign in to comment.