Welcome to mirror list, hosted at ThFree Co, Russian Federation.

VisitorGeolocator.php « UserCountry « plugins - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 35a95e8a2a2329639790afeb453f4bf41576dbf7 (plain)
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\UserCountry;

use Matomo\Cache\Cache;
use Matomo\Cache\Transient;
use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\DataAccess\RawLogDao;
use Matomo\Network\IPUtils;
use Piwik\Plugins\UserCountry\LocationProvider\DisabledProvider;
use Piwik\Tracker\Visit;
use Psr\Log\LoggerInterface;

require_once PIWIK_INCLUDE_PATH . "/plugins/UserCountry/LocationProvider.php";

/**
 * Service that determines a visitor's location using visitor information.
 *
 * Individual locations are provided by a LocationProvider instance. By default,
 * the configured LocationProvider (as determined by
 * `Common::getCurrentLocationProviderId()` is used.
 *
 * If the configured location provider cannot provide a location for the visitor,
 * the default location provider (`DefaultProvider`) is used.
 *
 * A cache is used internally to speed up location retrieval. By default, an
 * in-memory cache is used, but another type of cache can be supplied during
 * construction.
 *
 * This service can be used from within the tracker.
 */
class VisitorGeolocator
{
    const LAT_LONG_COMPARE_EPSILON = 0.0001;

    /**
     * @var string[]
     */
    public static $logVisitFieldsToUpdate = array(
        'location_country'   => LocationProvider::COUNTRY_CODE_KEY,
        'location_region'    => LocationProvider::REGION_CODE_KEY,
        'location_city'      => LocationProvider::CITY_NAME_KEY,
        'location_latitude'  => LocationProvider::LATITUDE_KEY,
        'location_longitude' => LocationProvider::LONGITUDE_KEY
    );

    /**
     * @var Cache
     */
    protected static $defaultLocationCache = null;

    /**
     * @var LocationProvider
     */
    private $provider;

    /**
     * @var LocationProvider
     */
    private $backupProvider;

    /**
     * @var Cache
     */
    private $locationCache;

    /**
     * @var RawLogDao
     */
    protected $dao;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function __construct(LocationProvider $provider = null, LocationProvider $backupProvider = null, Cache $locationCache = null,
                                RawLogDao $dao = null, LoggerInterface $logger = null)
    {
        if ($provider === null) {
            // note: Common::getCurrentLocationProviderId() uses the tracker cache, which is why it's used here instead
            // of accessing the option table
            $provider = LocationProvider::getProviderById(Common::getCurrentLocationProviderId());

            if (empty($provider)) {
                Common::printDebug("GEO: no current location provider sent, falling back to '" . LocationProvider::getDefaultProviderId() . "' one.");

                $provider = $this->getDefaultProvider();
            }
        }
        $this->provider = $provider;

        $this->backupProvider = $backupProvider ?: $this->getDefaultProvider();
        $this->locationCache = $locationCache ?: self::getDefaultLocationCache();
        $this->dao = $dao ?: new RawLogDao();
        $this->logger = $logger ?: StaticContainer::get('Psr\Log\LoggerInterface');
    }

    public function getLocation($userInfo, $useClassCache = true)
    {
        $userInfoKey = md5(implode(',', $userInfo));
        if ($useClassCache
            && $this->locationCache->contains($userInfoKey)
        ) {
            return $this->locationCache->fetch($userInfoKey);
        }

        $location = $this->getLocationObject($this->provider, $userInfo);

        if (empty($location)) {
            $providerId = $this->provider->getId();
            Common::printDebug("GEO: couldn't find a location with Geo Module '$providerId'");

            // Only use the default provider as fallback if the configured one isn't "disabled"
            if ($providerId != DisabledProvider::ID && $providerId != $this->backupProvider->getId()) {
                Common::printDebug("Using default provider as fallback...");

                $location = $this->getLocationObject($this->backupProvider, $userInfo);
            }
        }

        $location = $location ?: array();
        if (empty($location['country_code'])) {
            $location['country_code'] = Visit::UNKNOWN_CODE;
        }

        $this->locationCache->save($userInfoKey, $location);

        return $location;
    }

    /**
     * @param LocationProvider $provider
     * @param array $userInfo
     * @return array|false
     */
    private function getLocationObject(LocationProvider $provider, $userInfo)
    {
        $location   = $provider->getLocation($userInfo);
        $providerId = $provider->getId();
        $ipAddress  = $userInfo['ip'];

        if ($location === false) {
            return false;
        }

        Common::printDebug("GEO: Found IP $ipAddress location (provider '" . $providerId . "'): " . var_export($location, true));

        return $location;
    }

    /**
     * Geolcates an existing visit and then updates it if it's current attributes are different than
     * what was geolocated. Also updates all conversions of a visit.
     *
     * **This method should NOT be used from within the tracker.**
     *
     * @param array $visit The visit information. Must contain an `"idvisit"` element and `"location_ip"` element.
     * @param bool $useClassCache
     * @return array|null The visit properties that were updated in the DB mapped to the updated values. If null,
     *                    required information was missing from `$visit`.
     */
    public function attributeExistingVisit($visit, $useClassCache = true)
    {
        if (empty($visit['idvisit'])) {
            $this->logger->debug('Empty idvisit field. Skipping re-attribution..');
            return null;
        }

        $idVisit = $visit['idvisit'];

        if (empty($visit['location_ip'])) {
            $this->logger->debug('Empty location_ip field for idvisit = %s. Skipping re-attribution.', array('idvisit' => $idVisit));
            return null;
        }

        $ip = IPUtils::binaryToStringIP($visit['location_ip']);
        $location = $this->getLocation(array('ip' => $ip), $useClassCache);

        $valuesToUpdate = $this->getVisitFieldsToUpdate($visit, $location);

        if (!empty($valuesToUpdate)) {
            $this->logger->debug('Updating visit with idvisit = {idVisit} (IP = {ip}). Changes: {changes}', array(
                'idVisit' => $idVisit,
                'ip' => $ip,
                'changes' => json_encode($valuesToUpdate)
            ));

            $this->dao->updateVisits($valuesToUpdate, $idVisit);
            $this->dao->updateConversions($valuesToUpdate, $idVisit);
        } else {
            $this->logger->debug('Nothing to update for idvisit = %s (IP = {ip}). Existing location info is same as geolocated.', array(
                'idVisit' => $idVisit,
                'ip' => $ip
            ));
        }

        return $valuesToUpdate;
    }

    /**
     * Returns location log values that are different than the values currently in a log row.
     *
     * @param array $row The visit row.
     * @param array $location The location information.
     * @return array The location properties to update.
     */
    private function getVisitFieldsToUpdate(array $row, $location)
    {
        if (isset($location[LocationProvider::COUNTRY_CODE_KEY])) {
            $location[LocationProvider::COUNTRY_CODE_KEY] = strtolower($location[LocationProvider::COUNTRY_CODE_KEY]);
        }

        $valuesToUpdate = array();
        foreach (self::$logVisitFieldsToUpdate as $column => $locationKey) {
            if (empty($location[$locationKey])) {
                continue;
            }

            $locationPropertyValue = $location[$locationKey];
            $existingPropertyValue = $row[$column];

            if (!$this->areLocationPropertiesEqual($locationKey, $locationPropertyValue, $existingPropertyValue)) {
                $valuesToUpdate[$column] = $locationPropertyValue;
            }
        }
        return $valuesToUpdate;
    }

    /**
     * Re-geolocate visits within a date range for a specified site (if any).
     *
     * @param string $from A datetime string to treat as the lower bound. Visits newer than this date are processed.
     * @param string $to A datetime string to treat as the upper bound. Visits older than this date are processed.
     * @param int|null $idSite If supplied, only visits for this site are re-attributed.
     * @param int $iterationStep The number of visits to re-attribute at the same time.
     * @param callable|null $onLogProcessed If supplied, this callback is called after every row is processed.
     *                                      The processed visit and the updated values are passed to the callback.
     */
    public function reattributeVisitLogs($from, $to, $idSite = null, $iterationStep = 1000, $onLogProcessed = null)
    {
        $visitFieldsToSelect = array_merge(array('idvisit', 'location_ip'), array_keys(VisitorGeolocator::$logVisitFieldsToUpdate));

        $conditions = array(
            array('visit_last_action_time', '>=', $from),
            array('visit_last_action_time', '<', $to)
        );

        if (!empty($idSite)) {
            $conditions[] = array('idsite', '=', $idSite);
        }

        $self = $this;
        $this->dao->forAllLogs('log_visit', $visitFieldsToSelect, $conditions, $iterationStep, function ($logs) use ($self, $onLogProcessed) {
            foreach ($logs as $row) {
                $updatedValues = $self->attributeExistingVisit($row);

                if (!empty($onLogProcessed)) {
                    $onLogProcessed($row, $updatedValues);
                }
            }
        }, $willDelete = false);
    }

    /**
     * @return LocationProvider
     */
    public function getProvider()
    {
        return $this->provider;
    }

    /**
     * @return LocationProvider
     */
    public function getBackupProvider()
    {
        return $this->backupProvider;
    }

    private function areLocationPropertiesEqual($locationKey, $locationPropertyValue, $existingPropertyValue)
    {
        if (($locationKey == LocationProvider::LATITUDE_KEY
             || $locationKey == LocationProvider::LONGITUDE_KEY)
            && $existingPropertyValue != 0
        ) {
            // floating point comparison
            return abs(($locationPropertyValue - $existingPropertyValue) / $existingPropertyValue) < self::LAT_LONG_COMPARE_EPSILON;
        } else {
            return $locationPropertyValue == $existingPropertyValue;
        }
    }

    private function getDefaultProvider()
    {
        return LocationProvider::getProviderById(LocationProvider::getDefaultProviderId());
    }

    public static function getDefaultLocationCache()
    {
        if (self::$defaultLocationCache === null) {
            if (class_exists('\Piwik\Cache\Transient')) {
                // during the oneclickupdate from 3.x => greater, this class will be loaded, so we have to use it instead of the Matomo namespaced one
                self::$defaultLocationCache = new \Piwik\Cache\Transient();
            } else {
                self::$defaultLocationCache = new Transient();
            }
        }
        return self::$defaultLocationCache;
    }
}