File size: 6,415 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<?php

namespace Mautic\CoreBundle\IpLookup;

use GuzzleHttp\RequestOptions;
use Mautic\CoreBundle\Form\Type\IpLookupDownloadDataStoreButtonType;

abstract class AbstractLocalDataLookup extends AbstractLookup implements IpLookupFormInterface
{
    /**
     * @const TAR_CACHE_FOLDER
     */
    public const TAR_CACHE_FOLDER = 'unpack';

    /**
     * @const TAR_TEMP_FILE
     */
    public const TAR_TEMP_FILE = 'temp.tar.gz';

    /**
     * Path to the local data store.
     *
     * @return string
     */
    abstract public function getLocalDataStoreFilepath();

    /**
     * Return the URL to manually download.
     *
     * @return string
     */
    abstract public function getRemoteDateStoreDownloadUrl();

    /**
     * @return string
     */
    public function getConfigFormService()
    {
        return IpLookupDownloadDataStoreButtonType::class;
    }

    /**
     * @return array
     */
    public function getConfigFormThemes()
    {
        return [];
    }

    /**
     * Download remote data store.
     *
     * Used by the mautic:iplookup:update_data command and form fetch button (if applicable) to update local IP data stores
     *
     * @return bool
     */
    public function downloadRemoteDataStore()
    {
        $package   = $this->getRemoteDateStoreDownloadUrl();

        if (empty($package)) {
            $this->logger->error('Failed to fetch remote IP data: Invalid or inactive MaxMind license key');

            return false;
        }
        try {
            $data = $this->client->get($package, [
                RequestOptions::ALLOW_REDIRECTS => true,
            ]);
        } catch (\Exception $exception) {
            $this->logger->error('Failed to fetch remote IP data: '.$exception->getMessage());
        }

        $tempTarget        = $this->cacheDir.'/'.basename($package);
        $tempExt           = strtolower(pathinfo($package, PATHINFO_EXTENSION));
        $localTarget       = $this->getLocalDataStoreFilepath();
        $localTargetExt    = strtolower(pathinfo($localTarget, PATHINFO_EXTENSION));

        try {
            $success = false;

            switch (true) {
                case $localTargetExt === $tempExt:
                    $success = (bool) file_put_contents($localTarget, $data->getBody());

                    break;

                case $this->endsWith($package, 'tar.gz'):
                    /**
                     * If tar.gz it loops whole folder structure and copy the file which has the same basename as
                     * desired localTarget.
                     */
                    $tempTargetFolder = $this->cacheDir.'/'.self::TAR_CACHE_FOLDER;
                    $temporaryPhar    = $tempTargetFolder.'/'.self::TAR_TEMP_FILE;
                    if (!is_dir($tempTargetFolder)) {
                        // dir doesn't exist, make it
                        mkdir($tempTargetFolder);
                    }
                    file_put_contents($temporaryPhar, $data->getBody());
                    $pharData = new \PharData($temporaryPhar);
                    foreach (new \RecursiveIteratorIterator($pharData) as $file) {
                        /** @var \PharFileInfo $file */
                        if ($file->getBasename() === basename($localTarget)) {
                            $success = copy($file->getPathname(), $localTarget);
                        }
                    }
                    @unlink($temporaryPhar);

                    break;

                case 'gz' == $tempExt:
                    $memLimit = $this->sizeInByte(ini_get('memory_limit'));
                    $freeMem  = $memLimit - memory_get_peak_usage();
                    // check whether there is enough memory to handle large iplookp DB
                    // or will throw iplookup exception
                    if (function_exists('gzdecode') && strlen($data->getBody()) < ($freeMem / 3)) {
                        $success = (bool) file_put_contents($localTarget, gzdecode($data->getBody()));
                    } elseif (function_exists('gzopen')) {
                        if (file_put_contents($tempTarget, $data->getBody())) {
                            $bufferSize = 4096; // read 4kb at a time
                            $file       = gzopen($tempTarget, 'rb');
                            $outFile    = fopen($localTarget, 'wb');
                            while (!gzeof($file)) {
                                fwrite($outFile, gzread($file, $bufferSize));
                            }
                            fclose($outFile);
                            gzclose($file);
                            @unlink($tempTarget);
                            $success = true;
                        }
                    }

                    break;

                case 'zip' == $tempExt:
                    file_put_contents($tempTarget, $data->getBody());

                    $zipper = new \ZipArchive();

                    $zipper->open($tempTarget);
                    $success = $zipper->extractTo($localTarget);
                    $zipper->close();
                    @unlink($tempTarget);
                    break;
            }
        } catch (\Exception $exception) {
            error_log($exception);

            $success = false;
        }

        return $success;
    }

    /**
     * Get the common directory for data.
     *
     * @return string|null
     */
    protected function getDataDir()
    {
        if (null !== $this->cacheDir) {
            if (!file_exists($this->cacheDir)) {
                mkdir($this->cacheDir);
            }

            $dataDir = $this->cacheDir.'/../ip_data';

            if (!file_exists($dataDir)) {
                mkdir($dataDir);
            }

            return $dataDir;
        }

        return null;
    }

    protected function sizeInByte($size)
    {
        $data = (int) substr($size, 0, -1);
        switch (strtoupper(substr($size, -1))) {
            case 'K':
                return $data * 1024;
            case 'M':
                return $data * 1024 * 1024;
            case 'G':
                return $data * 1024 * 1024 * 1024;
        }
    }

    /**
     * Get if the string ends with.
     *
     * @param string $haystack
     * @param string $needle
     */
    private function endsWith($haystack, $needle): bool
    {
        return str_ends_with($haystack, $needle);
    }
}