Daniel_79

core-encoded-php56.php

Jun 9th, 2021
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 22.63 KB | None | 0 0
  1. <?php
  2. namespace progroman\CityManager;
  3.  
  4. /**
  5.  * Class Core
  6.  * @package progroman\CityManager
  7.  * @author Roman Shipilov (ProgRoman) <mr.progroman@yandex.ru>
  8.  */
  9. abstract class Core
  10. {
  11.     private static $instance = NULL;
  12.     /** @var \Registry; */
  13.     protected $registry = NULL;
  14.     /** @var \Session */
  15.     protected $session = NULL;
  16.     /** @var \Request */
  17.     protected $request = NULL;
  18.     protected $fias_country_id = NULL;
  19.     protected $fias_zone_id = NULL;
  20.     protected $fias_district_id = NULL;
  21.     protected $fias_id = NULL;
  22.     protected $country_id = NULL;
  23.     protected $zone_id = NULL;
  24.     protected $country_name = NULL;
  25.     protected $zone_name = NULL;
  26.     protected $district_name = NULL;
  27.     protected $postcode = NULL;
  28.     protected $city_name = NULL;
  29.     protected $popup_city_name = NULL;
  30.     /** @var string Тип населенного пункта (д., г. и т.д.) */
  31.     protected $prefix_city_name = NULL;
  32.     protected $prefix_district_name = NULL;
  33.     protected $prefix_zone_name = NULL;
  34.     protected $session_key = "prmn.city_manager";
  35.     protected $cookie_prefix = "prmn_";
  36.     protected $is_first_visit = NULL;
  37.     protected $main_domain = NULL;
  38.     protected $dev_mode = NULL;
  39.     protected $settings = NULL;
  40.     protected $messages = NULL;
  41.     protected $redirects = NULL;
  42.     private static $drivers = array();
  43.     const NOMINATIVE = "nc";
  44.     protected function __construct()
  45.     {
  46.         $this->registry = \progroman\Common\Registry::instance()->getRegistry();
  47.         $this->session = $this->registry->get("session");
  48.         $this->request = $this->registry->get("request");
  49.         $this->settings = $this->registry->get("config")->get("module_progroman_citymanager_setting");
  50.         $this->main_domain = !empty($this->settings["main_domain"]) ? $this->settings["main_domain"] : parse_url(HTTPS_SERVER ? HTTPS_SERVER : HTTP_SERVER, PHP_URL_HOST);
  51.         if ($this->dev_mode) {
  52.             $this->logger = new \Log("citymanager");
  53.         }
  54.         $this->is_first_visit = !isset($this->session->data[$this->getSessionKey()]) && empty($this->request->cookie[$this->getCookieKey("fias")]);
  55.     }
  56.     /**
  57.      * @param $registry
  58.      * @return $this|CityManager
  59.      */
  60.     public static function instance()
  61.     {
  62.         if (!static::$instance) {
  63.             static::$instance = new static();
  64.         }
  65.         return static::$instance;
  66.     }
  67.     public function setFias($fias_id)
  68.     {
  69.         if ($fias_id != $this->fias_id && self::checkLicense($this->setting("secret_key"))) {
  70.             $data = $this->getAllFields(array("fias_id" => $fias_id));
  71.             if ($data) {
  72.                 $this->log("setFias(" . $fias_id . ")" . print_r($data, true));
  73.                 $this->setFields($data);
  74.                 $this->setValueInSession("redirected", 0);
  75.                 $this->setValueInSession("force_redirect", 1);
  76.                 $this->setCurrency(true);
  77.                 $this->log("fias_id in SESSION \"" . $this->getValueFromSession("fias_id") . "\"");
  78.                 return true;
  79.             }
  80.         }
  81.         return false;
  82.     }
  83.     /**
  84.      * По имеющимся полям вычисляет недостающие
  85.      * @param $fields
  86.      * @return array|bool
  87.      */
  88.     private function getAllFields($fields)
  89.     {
  90.         $model_fias = $this->loadModel("fias");
  91.         if (isset($fields["fias_id"])) {
  92.             $fields["fias_id"] = (int) $fields["fias_id"];
  93.         }
  94.         $fias = false;
  95.         if (!empty($fields["fias_id"])) {
  96.             $fias = $model_fias->getFiasById($fields["fias_id"]);
  97.         } else {
  98.             if (!empty($fields["country_name"])) {
  99.                 if (!empty($fields["zone_name"])) {
  100.                     $fields["zone_name"] = $this->prepareZoneNameForFias($fields["zone_name"]);
  101.                 }
  102.                 $fias = $model_fias->getFias($fields);
  103.             }
  104.         }
  105.         if (isset($fields["iso_code_2"])) {
  106.             $country = $model_fias->getCountryByIsoCode($fields["iso_code_2"]);
  107.             if ($country) {
  108.                 $fields["country_id"] = $country["country_id"];
  109.                 $fields["country_name"] = $country["name"];
  110.             }
  111.         }
  112.         if ($fias) {
  113.             $fields["fias_id"] = $fias["f1_fias_id"];
  114.             if ($fias["f1_level"] == \ModelExtensionModuleProgromanFias::LEVEL_COUNTRY) {
  115.                 $this->fillFiasNames("country", $fields, $fias, 1);
  116.             } else {
  117.                 $fields["postcode"] = $fias["f1_postalcode"] ? $fias["f1_postalcode"] : "";
  118.                 if ($fias["f1_level"] == \ModelExtensionModuleProgromanFias::LEVEL_REGION) {
  119.                     $this->fillFiasNames("zone", $fields, $fias, 1);
  120.                     $this->fillFiasNames("country", $fields, $fias, 2);
  121.                     if ($fias["f1_shortname"] == "г.") {
  122.                         $this->fillFiasNames("city", $fields, $fias, 1);
  123.                     }
  124.                 } else {
  125.                     if ($fias["f2_level"] == \ModelExtensionModuleProgromanFias::LEVEL_REGION) {
  126.                         $this->fillFiasNames("city", $fields, $fias, 1);
  127.                         $this->fillFiasNames("zone", $fields, $fias, 2);
  128.                         $this->fillFiasNames("country", $fields, $fias, 3);
  129.                     } else {
  130.                         if ($fias["f3_level"] == \ModelExtensionModuleProgromanFias::LEVEL_REGION) {
  131.                             $this->fillFiasNames("city", $fields, $fias, 1);
  132.                             $this->fillFiasNames("district", $fields, $fias, 2);
  133.                             $this->fillFiasNames("zone", $fields, $fias, 3);
  134.                             $this->fillFiasNames("country", $fields, $fias, 4);
  135.                         } else {
  136.                             if ($fias["f4_level"] == \ModelExtensionModuleProgromanFias::LEVEL_REGION) {
  137.                                 $this->fillFiasNames("city", $fields, $fias, 1);
  138.                                 $this->fillFiasNames("district", $fields, $fias, 3);
  139.                                 $this->fillFiasNames("zone", $fields, $fias, 4);
  140.                                 $country_fias = $model_fias->getFiasById($fias["f4_parent_id"]);
  141.                                 $this->fillFiasNames("country", $fields, $country_fias, 1);
  142.                             } else {
  143.                                 return $fields;
  144.                             }
  145.                         }
  146.                     }
  147.                 }
  148.                 $fias_to_zone = $model_fias->getFiasToZone();
  149.                 if (isset($fias_to_zone[$fields["fias_zone_id"]])) {
  150.                     $fields["zone_id"] = $fias_to_zone[$fields["fias_zone_id"]]["zone_id"];
  151.                 }
  152.             }
  153.             if (empty($fields["country_id"])) {
  154.                 $fias_to_country = $model_fias->getFiasToCountry();
  155.                 if (isset($fias_to_country[$fields["fias_country_id"]])) {
  156.                     $fields["country_id"] = $fias_to_country[$fields["fias_country_id"]]["country_id"];
  157.                 }
  158.             }
  159.         }
  160.         return $fields;
  161.     }
  162.     /**
  163.      * Заполняет однообразые поля zone_name, fias_zone_id, country_name, fias_country_id и т.д.
  164.      * @param string $type Одно из значений: country, zone, district, city
  165.      * @param $fields
  166.      * @param $fias
  167.      * @param $depth
  168.      */
  169.     private function fillFiasNames($type, &$fields, $fias, $depth)
  170.     {
  171.         $fields["fias_" . $type . "_id"] = $fias["f" . $depth . "_fias_id"];
  172.         $fields[$type . "_name"] = $fias["f" . $depth . "_name"];
  173.         if ($type != "country") {
  174.             $fields["prefix_" . $type . "_name"] = $fias["f" . $depth . "_shortname"];
  175.         }
  176.     }
  177.     /**
  178.      * Обрабатывает название региона для поиска его в fias
  179.      * @param $zone_name
  180.      * @return string
  181.      */
  182.     protected function prepareZoneNameForFias($zone_name)
  183.     {
  184.         return trim(str_replace("область", "", $zone_name));
  185.     }
  186.     /**
  187.      * Инициализация полей.
  188.      * @param array $data Значения для инициализации.
  189.      */
  190.     private function setFields($data = array())
  191.     {
  192.         if (!$data) {
  193.             return NULL;
  194.         }
  195.         $fields = array("country_id", "country_name", "zone_id", "zone_name", "prefix_zone_name", "district_name", "prefix_district_name", "city_name", "prefix_city_name", "fias_country_id", "fias_zone_id", "fias_district_id", "fias_id", "postcode");
  196.         if (empty($data["fias_id"])) {
  197.             if (!empty($data["fias_zone_id"])) {
  198.                 $data["fias_id"] = $data["fias_zone_id"];
  199.             } else {
  200.                 if (!empty($data["fias_country_id"])) {
  201.                     $data["fias_id"] = $data["fias_country_id"];
  202.                 }
  203.             }
  204.         }
  205.         foreach ($fields as $field) {
  206.             $this->{$field} = !empty($data[$field]) ? trim($data[$field]) : null;
  207.             $this->setValueInSession($field, $this->{$field});
  208.         }
  209.         $this->setValueInSession("short_city_name", $this->setting("use_fullname_city") ? $this->getFullCityName() : $this->getCityName());
  210.         if ($this->fias_id) {
  211.             $this->setCookie($this->getCookieKey("fias"), $this->fias_id);
  212.         }
  213.     }
  214.     public function defineLocation()
  215.     {
  216.         $sources = array("Session", "Cookie", "Drivers", "Config");
  217.         foreach ($sources as $source) {
  218.             if ($data = call_user_func(array($this, "getFrom" . $source))) {
  219.                 $this->log(print_r($data, true) . " from " . $source);
  220.                 if ($source == "Drivers") {
  221.                     if (!$this->checkDefaultCity($data)) {
  222.                         break;
  223.                     }
  224.                 } else {
  225.                     break;
  226.                 }
  227.             }
  228.         }
  229.         $this->setFields($data);
  230.         $this->checkRedirect();
  231.     }
  232.     private function getFromSession()
  233.     {
  234.         return !empty($this->session->data[$this->getSessionKey()]) ? $this->session->data[$this->getSessionKey()] : false;
  235.     }
  236.     private function getFromCookie()
  237.     {
  238.         if (!empty($this->request->cookie[$this->getCookieKey("fias")])) {
  239.             $data = $this->getAllFields(array("fias_id" => $this->request->cookie[$this->getCookieKey("fias")]));
  240.             if ($data) {
  241.                 return $data;
  242.             }
  243.         }
  244.         return false;
  245.     }
  246.     private function getFromDrivers()
  247.     {
  248.         if (self::checkLicense($this->setting("secret_key"))) {
  249.             foreach (self::$drivers as $driver) {
  250.                 $data = $driver->getGeoFilter();
  251.                 if ($data) {
  252.                     return $this->getAllFields($data);
  253.                 }
  254.             }
  255.         }
  256.         return false;
  257.     }
  258.     private function getFromConfig()
  259.     {
  260.         return $this->setting("default_city") ? $this->getAllFields(array("fias_id" => $this->setting("default_city"))) : false;
  261.     }
  262.     /**
  263.      * Проверка нужно ли устанавливать город по умолчанию
  264.      * @return bool
  265.      */
  266.     private function checkDefaultCity($data)
  267.     {
  268.         if ($this->setting("default_city")) {
  269.             switch ($this->setting("use_default_city")) {
  270.                 case "any_country":
  271.                     return empty($data["city_name"]);
  272.                 case "one_country":
  273.                     if (empty($data["city_name"]) && !empty($data["country_id"])) {
  274.                         $default_fias = $this->loadModel("fias")->getFiasById($this->setting("default_city"));
  275.                         $default_fias_country_id = 0;
  276.                         for ($i = 1; $i <= 4; $i++) {
  277.                             if ($default_fias["f" . $i . "_level"] == \ModelExtensionModuleProgromanFias::LEVEL_COUNTRY) {
  278.                                 $default_fias_country_id = $default_fias["f" . $i . "_fias_id"];
  279.                                 break;
  280.                             }
  281.                         }
  282.                         $fias_to_country = $this->loadModel("fias")->getFiasToCountry();
  283.                         if (isset($fias_to_country[$default_fias_country_id])) {
  284.                             return $fias_to_country[$default_fias_country_id]["country_id"] == $data["country_id"];
  285.                         }
  286.                     }
  287.                     break;
  288.                 default:
  289.                     return empty($data);
  290.             }
  291.         }
  292.         return false;
  293.     }
  294.     public function setCurrency($force = false)
  295.     {
  296.         if ($this->setting("enable_switch_currency")) {
  297.             $key = $this->getCookieKey("currency");
  298.             if ($force || !isset($this->request->cookie[$key])) {
  299.                 $code = $this->loadModel("citymanager")->getCurrencyForCountry($this->country_id);
  300.                 $current_code = isset($this->session->data["currency"]) ? $this->session->data["currency"] : null;
  301.                 if ($code && $current_code != $code) {
  302.                     if (version_compare(VERSION, "2.0", "<")) {
  303.                         $this->registry->get("currency")->set($code);
  304.                     } else {
  305.                         $this->session->data["currency"] = $code;
  306.                         $this->setCookie("currency", $code);
  307.                     }
  308.                     $this->setCookie($key, $code);
  309.                 }
  310.             }
  311.         }
  312.     }
  313.     protected function setMessages()
  314.     {
  315.         if ($this->setting("enable_switch_messages")) {
  316.             $messages = $this->loadModel("citymanager")->getMessages($this->getFiasIds());
  317.             if (is_array($messages)) {
  318.                 $group_messages = array();
  319.                 foreach ($messages as $message) {
  320.                     $message["value"] = htmlspecialchars_decode($message["value"]);
  321.                     $group_messages[$message["key"]][] = $message;
  322.                 }
  323.                 foreach ($group_messages as $key => $group) {
  324.                     foreach ($group as $message) {
  325.                         if ($message["fias_id"] == $this->fias_id) {
  326.                             $this->messages[$key] = $message["value"];
  327.                             break;
  328.                         }
  329.                         if ($message["fias_id"] == $this->fias_zone_id) {
  330.                             $this->messages[$key] = $message["value"];
  331.                         } else {
  332.                             if ($message["fias_id"] == $this->fias_country_id && !isset($this->messages[$key])) {
  333.                                 $this->messages[$key] = $message["value"];
  334.                             }
  335.                         }
  336.                     }
  337.                 }
  338.             }
  339.         }
  340.     }
  341.     public function getFiasIds()
  342.     {
  343.         $ids = array();
  344.         if ($this->fias_id) {
  345.             $ids[] = $this->fias_id;
  346.         }
  347.         if ($this->fias_zone_id) {
  348.             $ids[] = $this->fias_zone_id;
  349.         }
  350.         if ($this->fias_country_id) {
  351.             $ids[] = $this->fias_country_id;
  352.         }
  353.         return $ids;
  354.     }
  355.     public function getMessages()
  356.     {
  357.         if (is_null($this->messages)) {
  358.             $this->setMessages();
  359.         }
  360.         return $this->messages;
  361.     }
  362.     public function getMessage($key, $default = "")
  363.     {
  364.         $this->getMessages();
  365.         return isset($this->messages[$key]) ? $this->messages[$key] : $default;
  366.     }
  367.     protected function checkRedirect()
  368.     {
  369.         if (!$this->needRedirect()) {
  370.             return NULL;
  371.         }
  372.         if ($redirect_url = $this->getRedirectUrl()) {
  373.             $this->setValueInSession("redirected", 1);
  374.             $location = str_replace(array("&amp;", "\n", "\r"), array("&", "", ""), $redirect_url);
  375.             $this->log("Location: " . $location);
  376.             header("Location: " . $location, true, 302);
  377.             exit;
  378.         }
  379.     }
  380.     protected function getRedirectUrl($request_uri = false)
  381.     {
  382.         if (!$this->setting("enable_switch_redirects")) {
  383.             return false;
  384.         }
  385.         $redirect_url = false;
  386.         foreach ($this->getRedirects() as $redirect) {
  387.             if ($redirect["fias_id"] == $this->fias_id) {
  388.                 $redirect_url = $redirect["url"];
  389.                 break;
  390.             }
  391.             if ($redirect["fias_id"] == $this->fias_zone_id) {
  392.                 $redirect_url = $redirect["url"];
  393.             } else {
  394.                 if (!$redirect_url && $redirect["fias_id"] == $this->fias_country_id) {
  395.                     $redirect_url = $redirect["url"];
  396.                 }
  397.             }
  398.         }
  399.         if (!$redirect_url) {
  400.             $redirect_url = "http" . (\progroman\Util::isSSL() ? "s" : "") . "://" . $this->main_domain . "/";
  401.         }
  402.         if (!$request_uri) {
  403.             $request_uri = $this->request->server["REQUEST_URI"];
  404.         }
  405.         $request_uri = ltrim($request_uri, "/");
  406.         $new_request_uri = $request_uri;
  407.         $paths = $this->getRedirectPaths();
  408.         if ($request_uri && $paths) {
  409.             $new_request_uri = preg_replace("#^(" . implode("|", $paths) . ")(?:/|\$)#iu", "", $request_uri);
  410.         }
  411.         $current_url = preg_replace("#^(www\\.)?#", "", $this->request->server["HTTP_HOST"]) . "/" . $request_uri;
  412.         if (preg_replace("#^http(s)?://(www\\.)?#", "", $redirect_url) . $new_request_uri != $current_url) {
  413.             return $redirect_url . $new_request_uri;
  414.         }
  415.         return false;
  416.     }
  417.     public function getRedirects()
  418.     {
  419.         if (!$this->redirects) {
  420.             $this->redirects = $this->loadModel("citymanager")->getRedirects($this->getFiasIds());
  421.         }
  422.         return $this->redirects;
  423.     }
  424.     /**
  425.      * @return array Список подкаталогов для редиректа, если есть.
  426.      * site.com/spb/, site.com/msc/ => ['spb', 'msc']
  427.      */
  428.     protected function getRedirectPaths()
  429.     {
  430.         $paths = array();
  431.         $regex = "#" . preg_quote($this->main_domain) . "/(.+)/\$#";
  432.         foreach ($this->getRedirects() as $redirect) {
  433.             if (preg_match($regex, $redirect["url"], $matches)) {
  434.                 $paths[] = $matches[1];
  435.             }
  436.         }
  437.         return $paths;
  438.     }
  439.     /**
  440.      * Проверка - нужно ли делать редирект
  441.      * @return bool
  442.      */
  443.     protected function needRedirect()
  444.     {
  445.         if ($this->is_first_visit && $this->setting("disable_autoredirect") && !$this->getValueFromSession("force_redirect")) {
  446.             return false;
  447.         }
  448.         if (\progroman\Util::isAjax() || self::isBot()) {
  449.             return false;
  450.         }
  451.         return true;
  452.     }
  453.     /**
  454.      * Проверка ботов ПС
  455.      * @return bool
  456.      */
  457.     protected function isBot()
  458.     {
  459.         if (isset($_SERVER["HTTP_USER_AGENT"])) {
  460.             foreach ($this->getBots() as $bot) {
  461.                 if (stripos($_SERVER["HTTP_USER_AGENT"], $bot) !== false) {
  462.                     return true;
  463.                 }
  464.             }
  465.         }
  466.         return false;
  467.     }
  468.     protected function getBots()
  469.     {
  470.         return array();
  471.     }
  472.     public static function validLicense($license)
  473.     {
  474.         return self::checkLicense($license);
  475.     }
  476.     private static function checkLicense($license)
  477.     {
  478.         if ($license) {
  479.             $settings = \progroman\Common\Registry::instance()->get("config")->get("module_progroman_citymanager_setting");
  480.             $host = !empty($settings["main_domain"]) ? "//" . $settings["main_domain"] : (HTTPS_SERVER ? HTTPS_SERVER : HTTP_SERVER);
  481.             $host = parse_url($host, PHP_URL_HOST);
  482.             foreach (explode("|", $license) as $key) {
  483.                 $host_parts = explode(".", $host);
  484.                 while (self::verifySecrectKey(implode(".", $host_parts), $key)) {
  485.                     return true;
  486.                 }
  487.                 array_shift($host_parts);
  488.                 if (1 < count($host_parts)) {
  489.                 }
  490.             }
  491.         }
  492.         return false;
  493.     }
  494.     private static function verifySecrectKey($host, $key)
  495.     {
  496.         $publickey = openssl_get_publickey("file://" . PROGROMAN_CITYMANAGER_DIR . "/public.key");
  497.         return $publickey && openssl_verify($host, base64_decode($key), $publickey, OPENSSL_ALGO_SHA256);
  498.     }
  499.     public function setting($key, $value = NULL)
  500.     {
  501.         if (!is_null($value)) {
  502.             $this->settings[$key] = $value;
  503.         }
  504.         return isset($this->settings[$key]) ? $this->settings[$key] : null;
  505.     }
  506.     /**
  507.      * Загрузка модели
  508.      * @param $model
  509.      * @return ModelCityManager|ModelFias
  510.      */
  511.     protected function loadModel($model)
  512.     {
  513.         if (!isset($this->{"model_" . $model})) {
  514.             $this->registry->get("load")->model("extension/module/progroman/" . $model);
  515.             $this->{"model_" . $model} = $this->registry->get("model_extension_module_progroman_" . $model);
  516.         }
  517.         return $this->{"model_" . $model};
  518.     }
  519.     public function getSessionKey()
  520.     {
  521.         return $this->session_key;
  522.     }
  523.     protected function getValueFromSession($key)
  524.     {
  525.         return isset($this->session->data[$this->getSessionKey()][$key]) ? $this->session->data[$this->getSessionKey()][$key] : null;
  526.     }
  527.     protected function setValueInSession($key, $value)
  528.     {
  529.         if (in_array($key, array("force_redirect", "fias_id"))) {
  530.             $this->session->data[$this->getSessionKey() . "." . $key] = $value;
  531.         }
  532.         $this->session->data[$this->getSessionKey()][$key] = $value;
  533.     }
  534.     public function setCookie($key, $value, $time = 2592000)
  535.     {
  536.         setcookie($key, $value, $time ? time() + $time : null, "/", $this->getCookieDomain());
  537.     }
  538.     public function getCookieKey($key)
  539.     {
  540.         return $this->cookie_prefix . $key;
  541.     }
  542.     protected function getCookieDomain()
  543.     {
  544.         $session_cookie_domain = ini_get("session.cookie_domain");
  545.         $http_host = $this->request->server["HTTP_HOST"];
  546.         if ($session_cookie_domain && strpos($http_host, ltrim($session_cookie_domain, ".")) !== false) {
  547.             return $session_cookie_domain;
  548.         }
  549.         $main_domain = preg_replace("#^(www\\.)?#", "", $this->main_domain, 1);
  550.         if (strpos($http_host, $main_domain) !== false) {
  551.             return "." . $main_domain;
  552.         }
  553.         return "." . preg_replace("#^(www\\.)?#", "", $http_host, 1);
  554.     }
  555.     public static function addDriver($driver)
  556.     {
  557.         self::$drivers[] = $driver;
  558.     }
  559.     protected function log($message)
  560.     {
  561.         if ($this->dev_mode) {
  562.             $this->logger->write($message);
  563.         }
  564.     }
  565. }
  566.  
  567. ?>
Add Comment
Please, Sign In to add comment