Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge updates for version 11 #34

Merged
merged 12 commits into from
Apr 26, 2022
27 changes: 16 additions & 11 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ on:
jobs:
integration:
name: Integration tests
runs-on: ubuntu-18.04
runs-on: ubuntu-20.04
strategy:
matrix:
php-version: [7.2, 7.3, 7.4]
php-version: [7.4, 8.0]
steps:
- name: Checkout
uses: actions/checkout@v2
Expand All @@ -27,24 +27,29 @@ jobs:
phpunit:
needs: integration
name: PHP ${{ matrix.php-version }} - T3 ${{ matrix.typo3-version }}
runs-on: ubuntu-18.04
runs-on: ubuntu-20.04
continue-on-error: ${{ matrix.experimental }}
strategy:
matrix:
experimental: [false]
php-version: [7.2, 7.3, 7.4]
typo3-version: [^10.4]
include:
- php-version: 7.4
typo3-version: 10.4.x-dev
experimental: true
typo3-version: ^10.4
experimental: false

- php-version: 7.4
typo3-version: ^11.0
typo3-version: ^11.5
experimental: false

- php-version: 7.4
typo3-version: dev-master
- php-version: 8.0
typo3-version: ^11.5
experimental: false

- php-version: 8.0
typo3-version: 11.5.x-dev
experimental: true

- php-version: 8.1
typo3-version: dev-main
experimental: true
env:
PHP_VERSION: ${{ matrix.php-version }}
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
.phpunit.result.cache
/composer.lock
/var
.idea
.idea
5 changes: 4 additions & 1 deletion Classes/Command/UpdateIpDatabaseCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ private function validateArguments(): bool
private function truncateTable(): void
{
$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($this->table);
$connection->executeUpdate($connection->getDatabasePlatform()->getTruncateTableSQL($this->table, true));
$databasePlatform = $connection->getDatabasePlatform();
if ($databasePlatform) {
$connection->executeStatement($databasePlatform->getTruncateTableSQL($this->table, true));
}
}

/**
Expand Down
4 changes: 2 additions & 2 deletions Classes/Domain/Repository/RegionRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function getCountriesForPage(int $id): array
->join('rmm', 'static_countries', 'c', 'c.uid = rmm.uid_foreign')
->where($qb->expr()->eq('pmm.uid_local', $qb->createNamedParameter($id, \PDO::PARAM_INT)))
->execute()
->fetchAll();
->fetchAllAssociative();

foreach ($results as $result) {
$iso2Codes[$result['cn_iso_2']] = true;
Expand All @@ -52,7 +52,7 @@ public function shouldApplyWhenNoIpMatches(int $id): bool
->where($qb->expr()->eq('uid_local', $qb->createNamedParameter($id, \PDO::PARAM_INT)))
->andWhere($qb->expr()->eq('uid_foreign', $qb->createNamedParameter(self::APPLY_WHEN_NO_IP_MATCHES, \PDO::PARAM_INT)))
->execute()
->fetchAll();
->fetchAllAssociative();

return !empty($results);
}
Expand Down
4 changes: 3 additions & 1 deletion Classes/FactProvider/AbstractFactProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ abstract class AbstractFactProvider

/**
* @param string $basename The basename for the factsArray. This name comes from configuration.
* @param array $configuration TypoScript configuration array for this fact provider
*/
public function __construct(string $basename = '')
public function __construct(string $basename = '', array $configuration = [])
{
$this->basename = $basename;
$this->configuration = $configuration;
}

public function isMultiple(): bool
Expand Down
4 changes: 3 additions & 1 deletion Classes/FactProvider/IP2Country.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ public function getBasename(): string
*/
public function process(): self
{
$iso2 = GeneralUtility::makeInstance(LocateUtility::class)->getCountryIso2FromIP();
$simulateIp = $this->configuration['settings']['simulateIp'] ? : null;

$iso2 = GeneralUtility::makeInstance(LocateUtility::class)->getCountryIso2FromIP($simulateIp) ?? '';
LocateUtility::mainstreamValue($iso2);
$this->facts[$this->getBasename()] = $iso2;

Expand Down
2 changes: 1 addition & 1 deletion Classes/Hook/OverrideIconOverlayHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,6 @@ private function countRegions(string $table, array $row): int
->from($table)
->where($qb->expr()->eq('uid', $row['uid']))
->execute()
->fetchColumn(0);
->fetchOne();
}
}
2 changes: 1 addition & 1 deletion Classes/Judge/Condition.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function adjudicate(AbstractFactProvider $factProvider, int $priority = A
{
$prosecution = $this->configuration['prosecution'] ?? $this->configuration['prosecution.'] ?? null;

if ($prosecution !== null && $factProvider->isGuilty($prosecution) && isset($this->configuration['verdict'])) {
if ($prosecution !== null && isset($this->configuration['verdict']) && $factProvider->isGuilty($prosecution)) {
$this->decision = (new Decision())->withVerdictName($this->configuration['verdict']);
$this->decision->setPriority($priority);

Expand Down
1 change: 1 addition & 0 deletions Classes/Middleware/LanguageRedirectMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
'overrideSessionValue' => (bool)($locateSetup['overrideSessionValue'] ?? 0),
'sessionHandling' => (bool)($locateSetup['sessionHandling'] ?? 0),
'excludeBots' => (bool)($locateSetup['excludeBots'] ?? 1),
'simulateIp' => $locateSetup['simulateIp'] ? : null,
],
];

Expand Down
5 changes: 2 additions & 3 deletions Classes/Processor/Court.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ protected function processFacts(): void
}

/* @var $factProvider AbstractFactProvider */
$factProvider = GeneralUtility::makeInstance($className);
$factProvider = GeneralUtility::makeInstance($className, $key, $this->configuration);

if (!$factProvider instanceof AbstractFactProvider) {
throw new IllegalFactProviderException(
Expand Down Expand Up @@ -141,8 +141,7 @@ protected function callJudges(): ?Decision
$configuration = $this->configuration['judges'][$key . '.'] ?? [];

if (empty($configuration)) {
$this->logger->warning('');
// TODO: Do something?
$this->logger->warning('No judges are configured.');
}

$this->logger->info(sprintf('Judge with key "%s" will be called.', $key));
Expand Down
11 changes: 6 additions & 5 deletions Classes/Utility/LocateUtility.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class LocateUtility
public function getCountryIso2FromIP(?string $ip = null)
{
$ip = $this->getNumericIp($ip);
$tableName = self::getTableNameForIp($ip);
$tableName = $this->getTableNameForIp($ip);
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($tableName);

return $queryBuilder
Expand All @@ -36,12 +36,12 @@ public function getCountryIso2FromIP(?string $ip = null)
->where($queryBuilder->expr()->lte('ip_from', $queryBuilder->createNamedParameter($ip)))
->andWhere($queryBuilder->expr()->gte('ip_to', $queryBuilder->createNamedParameter($ip)))
->execute()
->fetchColumn(0);
->fetchOne();
}

public function getNumericIp(?string $ip = null): string
{
$ip = $ip ?? GeneralUtility::getIndpEnv('REMOTE_ADDR');
$ip = $ip ?? (string)GeneralUtility::getIndpEnv('REMOTE_ADDR');

return strpos($ip, '.') !== false ? (string)ip2long($ip) : $this->convertIpv6($ip);
}
Expand All @@ -63,7 +63,8 @@ private function convertIpv6(string $ip): string
break;

case function_exists('bcadd'):
for ($i = 0; $i < strlen($bin); $i++) {
$max = strlen($bin);
for ($i = 0; $i < $max; $i++) {
$decimalIp = bcmul($decimalIp, '2');
$decimalIp = bcadd($decimalIp, $bin[$i]);
}
Expand All @@ -80,7 +81,7 @@ private function convertIpv6(string $ip): string
return $decimalIp;
}

public static function mainstreamValue(string &$value)
public static function mainstreamValue(string &$value): void
{
$value = mb_strtolower(str_replace('-', '_', $value));
}
Expand Down
78 changes: 39 additions & 39 deletions Classes/Verdict/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Redirect extends AbstractVerdict
const SESSION_KEY = 'language';
const OVERRIDE_PARAMETER = 'setLang';

private $cookieMode = false;
private $sessionMode = false;

private $redirectLanguageUid = 0;

Expand All @@ -43,9 +43,9 @@ public function execute(): ?ResponseInterface
$this->redirectLanguageUid = (int)$this->configuration['sys_language'];
$this->requestedLanguageUid = GeneralUtility::makeInstance(Context::class)->getAspect('language')->getId();

// Initialize Cookie mode if necessary and prepare everything for possible redirects
$this->initializeCookieMode();
$this->handleCookieStuff();
// Initialize Session mode if necessary and prepare everything for possible redirects
$this->initializeSessionMode();
$this->handleSessionStuff();

// Skip if no redirect is necessary
if (!$this->shouldRedirect()) {
Expand All @@ -66,60 +66,60 @@ public function execute(): ?ResponseInterface
}

/**
* Set CookeMode Param to true if sessionHandling is enables
* Set sessionMode Param to true if sessionHandling is enables
*/
private function initializeCookieMode(): void
private function initializeSessionMode(): void
{
if ((bool)($this->configuration['sessionHandling'] ?? false) === true) {
$this->logger->info('Cookie Handling is set.');
$this->cookieMode = true;
$this->logger->info('Session Handling is set.');
$this->sessionMode = true;
}
}

private function handleCookieStuff()
private function handleSessionStuff()
{
$currentLanguageUid = $this->requestedLanguageUid;

if ($this->isCookieSet()) {
// Cookie is not in current language
$this->logger->info('Cookie is set.');
if ($this->isSessionValueSet()) {
// Session is not in current language
$this->logger->info('Session value is set.');

if ($this->isCookieInCurrentLanguage() === false && $this->shouldOverrideSessionValue() === true) {
// Override cookie
$this->logger->info('Cookie is not in current language, so we override it.');
if ($this->isSessionInCurrentLanguage() === false && $this->shouldOverrideSessionValue() === true) {
// Override session
$this->logger->info('Session is not in current language, so we override it.');
$this->redirectLanguageUid = $currentLanguageUid;
$this->setCookie($currentLanguageUid);
} elseif ($this->isCookieInCurrentLanguage()) {
// Cookie is in current language
$this->logger->info('Cookie is in current language.');
$this->setSessionValue($currentLanguageUid);
} elseif ($this->isSessionInCurrentLanguage()) {
// Session is in current language
$this->logger->info('Session is in current language.');
$this->redirectLanguageUid = $currentLanguageUid;
} else {
// Override config array by cookie value
$this->logger->info('Cookie is not in current language and overriding is not allowed.');
$this->redirectLanguageUid = $this->getCookieValue();
$this->configuration['sys_language'] = $this->getCookieValue();
// Override config array by session value
$this->logger->info('Session is not in current language and overriding is not allowed.');
$this->redirectLanguageUid = $this->getSessionValue();
$this->configuration['sys_language'] = $this->getSessionValue();
}
} elseif ($this->cookieMode === true) {
$this->logger->info('Cookie is not set, but we are in cookie mode.');
} elseif ($this->sessionMode === true) {
$this->logger->info('Session is not set, but we are in session mode.');

if ($currentLanguageUid !== $this->redirectLanguageUid) {
// Set cookie value to target language
$this->setCookie($this->redirectLanguageUid);
// Set session value to target language
$this->setSessionValue($this->redirectLanguageUid);
} else {
// Set cookie value to current language
$this->setCookie($currentLanguageUid);
// Set session value to current language
$this->setSessionValue($currentLanguageUid);
}
}
}

private function isCookieSet(): bool
private function isSessionValueSet(): bool
{
return $this->getCookieValue() !== null;
return $this->getSessionValue() !== null;
}

private function isCookieInCurrentLanguage(): bool
private function isSessionInCurrentLanguage(): bool
{
return $this->requestedLanguageUid === $this->getCookieValue();
return $this->requestedLanguageUid === $this->getSessionValue();
}

private function shouldOverrideSessionValue(): bool
Expand All @@ -131,7 +131,7 @@ private function shouldOverrideSessionValue(): bool
return false;
}

private function setCookie(?int $value)
private function setSessionValue(?int $value)
{
if ($value === null) {
$value = (int)$this->configuration['sys_language'];
Expand All @@ -140,15 +140,15 @@ private function setCookie(?int $value)
$this->session->set(self::SESSION_KEY, $value);
}

private function getCookieValue(): ?int
private function getSessionValue(): ?int
{
return $this->session->get(self::SESSION_KEY);
}

private function shouldRedirect(): bool
{
// Always redirect when we are not in cookie mode
if ($this->cookieMode === false) {
// Always redirect when we are not in session mode
if ($this->sessionMode === false) {
return true;
}

Expand All @@ -162,8 +162,8 @@ private function shouldRedirect(): bool
}
}

// Do not redirect, when cookie is set and cookie value matches given language id
if ($this->isCookieInCurrentLanguage()) {
// Do not redirect, when session is set and session value matches given language id
if ($this->isSessionInCurrentLanguage()) {
return false;
}

Expand Down
2 changes: 1 addition & 1 deletion Configuration/Services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ services:
tags:
- name: console.command
command: locate:update
schedulable: flase
schedulable: false
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ config.tx_locate {
# URL Parameter which has to be true when overrideCookie is allowed within action and cookieHandling is enabled
overrideQueryParameter = setLang

# Simulate your IP address for countryByIP fact provider (for test purposes only), 109.10.163.98 is a french IP address
simulateIp = 109.10.163.98

verdicts {
redirectToMainlandChina = Leuchtfeuer\Locate\Verdict\Redirect
redirectToMainlandChina.url = https://www.example.cn
Expand Down
7 changes: 5 additions & 2 deletions Configuration/TypoScript/setup.typoscript
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@ config.tx_locate {
# URL Parameter which has to be true when overrideCookie is allowed within action and cookieHandling is enabled
overrideQueryParameter = setLang

# Simulate your IP address for countryByIP fact provider (for test purposes only)
simulateIp =

# See example file for configuration
verdicts {
}

facts {
browserAcceptLanguage = Leuchtfeuer\Locate\FactProvider\BrowserAcceptedLanguage
countryByIP = Leuchtfeuer\Locate\FactProvider\IP2Country
#browserAcceptLanguage = Leuchtfeuer\Locate\FactProvider\BrowserAcceptedLanguage
#countryByIP = Leuchtfeuer\Locate\FactProvider\IP2Country
}

# See example file for configuration
Expand Down
Loading