Test Failed
Push — master ( fcbbf0...aa6767 )
by Alexey
04:58
created

Geography   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 106
rs 10
wmc 27
lcom 1
cbo 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
D init() 0 32 13
C updateDb() 0 67 14
1
<?php
2
3
/**
4
 * Geography module
5
 *
6
 * @author Alexey Krupskiy <[email protected]>
7
 * @link http://inji.ru/
8
 * @copyright 2016 Alexey Krupskiy
9
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
10
 */
11
class Geography extends Module {
12
13
    public $geographyDbDir = '/tmp/Geography';
14
15
    public function init() {
16
        if (!empty(App::$primary->config['site']['domain'])) {
17
            $domain = App::$primary->config['site']['domain'];
18
        } else {
19
            $domain = implode('.', array_slice(explode('.', idn_to_utf8(INJI_DOMAIN_NAME)), -2));
20
        }
21
        $alias = str_replace($domain, '', idn_to_utf8(INJI_DOMAIN_NAME));
22
        $city = null;
23
        if ($alias) {
24
            $alias = str_replace('.', '', $alias);
25
            $city = Geography\City::get($alias, 'alias');
26
        }
27
        if (!$city) {
28
            if (!file_exists(App::$primary->path . $this->geographyDbDir . '/SxGeoCity.dat')) {
29
                $this->updateDb();
30
            }
31
            if (file_exists(App::$primary->path . $this->geographyDbDir . '/SxGeoCity.dat')) {
32
                $SxGeo = new Geography\SxGeo(App::$primary->path . $this->geographyDbDir . '/SxGeoCity.dat');
33
                $cityIp = $SxGeo->getCity($_SERVER['REMOTE_ADDR']);
34
                if (!empty($cityIp['city']['name_ru'])) {
35
                    $city = Geography\City::get($cityIp['city']['name_ru'], 'name');
36
                }
37
            }
38
        }
39
        if (!$city) {
40
            $city = Geography\City::get(1, 'default');
41
        }
42
        if (!empty($this->config['aliasRedirect']) && $city && $city->alias && !$alias && Module::$cur->moduleName !== 'Exchange1c') {
43
            Tools::redirect('//' . $city->alias . '.' . $domain . $_SERVER['REQUEST_URI']);
44
        }
45
        Geography\City::$cur = $city;
0 ignored issues
show
Documentation Bug introduced by
It seems like $city of type boolean or object<Model> is incompatible with the declared type object<Geography\City> of property $cur.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
46
    }
47
48
    public function updateDb() {
49
        // Обновление файла базы данных Sypex Geo
50
        // Настройки
51
        $url = 'https://sypexgeo.net/files/SxGeoCity_utf8.zip';  // Путь к скачиваемому файлу
52
        $dat_file_dir = App::$primary->path . $this->geographyDbDir; // Каталог в который сохранять dat-файл
53
        $last_updated_file = $dat_file_dir . '/SxGeo.upd'; // Файл в котором хранится дата последнего обновления
54
        $info = false; // Вывод сообщений о работе, true заменить на false после установки в cron
55
56
// Конец настроек
57
58
        set_time_limit(600);
59
//error_reporting(E_ALL);
60
        //header('Content-type: text/plain; charset=utf8');
61
62
        $t = microtime(1);
0 ignored issues
show
Unused Code introduced by
$t is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
63
        Tools::createDir($dat_file_dir);
64
        $types = array(
65
            'Country' => 'SxGeo.dat',
66
            'City' => 'SxGeoCity.dat',
67
            'Max' => 'SxGeoMax.dat',
68
        );
69
// Скачиваем архив
70
        preg_match("/(Country|City|Max)/", pathinfo($url, PATHINFO_BASENAME), $m);
71
        $type = $m[1];
72
        $dat_file = $types[$type];
73
        if ($info) echo "Скачиваем архив с сервера\n";
74
75
        $fp = fopen($dat_file_dir . '/SxGeoTmp.zip', 'wb');
76
        $ch = curl_init($url);
77
        curl_setopt_array($ch, array(
78
            CURLOPT_FILE => $fp,
79
            CURLOPT_HTTPHEADER => file_exists($last_updated_file) ? array("If-Modified-Since: " . file_get_contents($last_updated_file)) : array(),
80
        ));
81
        if (!curl_exec($ch)) {
82
            if ($info) echo 'Ошибка при скачивании архива';
83
            return;
84
        }
85
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
86
        curl_close($ch);
87
        fclose($fp);
88
        if ($code == 304) {
89
            @unlink($dat_file_dir . '/SxGeoTmp.zip');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
90
            if ($info) echo "Архив не обновился, с момента предыдущего скачивания\n";
91
            return;
92
        }
93
94
        if ($info) echo "Архив с сервера скачан\n";
95
// Распаковываем архив
96
        $fp = fopen('zip://' . $dat_file_dir . '/SxGeoTmp.zip#' . $dat_file, 'rb');
97
        $fw = fopen($dat_file_dir . '/' . $dat_file, 'wb');
98
        if (!$fp) {
99
            if ($info)
100
                echo "Не получается открыть\n";
101
            return;
102
        }
103
        if ($info) echo "Распаковываем архив\n";
104
        stream_copy_to_stream($fp, $fw);
105
        fclose($fp);
106
        fclose($fw);
107
        if (filesize($dat_file) == 0) {
108
            if ($info) echo 'Ошибка при распаковке архива';
109
        }
110
        @unlink($dat_file_dir . '/SxGeoTmp.zip');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
111
        file_put_contents($last_updated_file, gmdate('D, d M Y H:i:s') . ' GMT');
112
        if ($info) echo "Перемещен файл в {$dat_file_dir}/{$dat_file}\n";
113
114
    }
115
116
}
117