Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Lustery\Service;
- use App\Common\Helper\Config;
- use App\Common\Service\Logger\Log;
- use Doctrine\Common\Collections\ArrayCollection;
- use Doctrine\ORM\EntityManagerInterface;
- use GeoIp2\Database\Reader;
- use GeoIp2\Exception\AddressNotFoundException;
- use Exception;
- use Lustery\Model\Base\Country;
- use Lustery\Model\Members\User;
- use Lustery\Repository\Base\CountryRepository;
- class GeoIpUtils
- {
- private static $readers;
- private $entityManager;
- public function __construct(EntityManagerInterface $entityManager)
- {
- $this->entityManager = $entityManager;
- }
- /**
- * @param User|null $user
- * @return ArrayCollection<Country>
- */
- public function detectCountry(?User $user): ArrayCollection
- {
- $countryCode = !empty($_COOKIE['country_name']) ? $_COOKIE['country_name'] : '';
- $isInternal = $_SERVER['REMOTE_ADDR'] !== '127.0.0.1';
- $isGoogleBot = strstr(strtolower(@$_SERVER['HTTP_USER_AGENT']), "googlebot");
- $isCdn = strstr(strtolower(@$_SERVER['HTTP_HOST']), "cdn");
- if (!$countryCode && $isInternal && !$isGoogleBot && !$isCdn) {
- $countryCode = strtolower(self::countryCodeByIp($_SERVER['REMOTE_ADDR']));
- if ($countryCode) {
- setcookie('country_name', $countryCode, time()+(365*24*3600), "/", COOKIE_DOMAIN);
- } else {
- Log::geoIpFail($_SERVER['REMOTE_ADDR']);
- }
- }
- /** @var CountryRepository $countryRepository */
- $countryRepository = $this->entityManager->getRepository(Country::class);
- $country = $countryCode ? $countryRepository->findOneBy(['iso2' => $countryCode]) : null;
- $countries = new ArrayCollection();
- if ($country) {
- $countries->add($country);
- }
- if ($user && $user->getCountry()) {
- $countries->add($user->getCountry());
- }
- return $countries;
- }
- /**
- * @param User|null $user
- * @param ArrayCollection<Country> $countries
- * @return bool
- */
- public function isUserFromOceania(?User $user, ArrayCollection $countries): bool
- {
- $country = $user && $user->getCountry() ? $user->getCountry() : $countries->first();
- return $country && in_array($country->getIso2(), Country::OCEANIA);
- }
- private static function getReader($database_filename)
- {
- if (!isset(self::$readers[$database_filename])) {
- self::$readers[$database_filename] = new Reader($database_filename);
- }
- return self::$readers[$database_filename];
- }
- public static function countryCodeByIp($ip): string
- {
- $countryCode = '';
- if (!$ip) {
- return $countryCode;
- }
- $config = Config::get("geoip");
- try {
- $filename = $config['db_path']['country'];
- $reader = self::getReader($filename);
- $record = $reader->country($ip);
- $countryCode = strtolower($record->country->isoCode);
- } catch (AddressNotFoundException $e) {
- } catch (Exception $e) {
- trigger_error($e->getMessage());
- }
- return $countryCode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement