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
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugins\PrivacyManager\Dao;
use Piwik\Common;
use Piwik\Db;
use Piwik\DbHelper;
use Matomo\Network\IP;
use Piwik\Plugins\PrivacyManager\Config;
use Piwik\Plugins\PrivacyManager\IPAnonymizer;
use Piwik\Plugins\PrivacyManager\Tracker\RequestProcessor;
use Piwik\Plugins\UserCountry\LocationProvider;
use Piwik\Plugins\UserCountry\VisitorGeolocator;
use Piwik\Tracker\Model;
use Exception;
class LogDataAnonymizer
{
public const NUM_ROWS_UPDATE_AT_ONCE = 10000;
protected $COLUMNS_BLACKLISTED = array('idvisit', 'idvisitor', 'idsite', 'visit_last_action_time', 'config_id', 'location_ip', 'idlink_va', 'server_time', 'idgoal', 'buster', 'idorder');
/**
* @var string
*/
private $logVisitTable;
public function __construct()
{
$this->logVisitTable = Common::prefixTable('log_visit');
}
public function anonymizeVisitInformation($idSites, $startDate, $endDate, $anonymizeIp, $anonimizeLocation, $anonymizeUserId)
{
if (!$anonymizeIp && !$anonimizeLocation && !$anonymizeUserId) {
return 0; // nothing to do
}
if (empty($idSites)) {
$idSites = $this->getAllIdSitesString($this->logVisitTable);
} else {
$idSites = array_map('intval', $idSites);
}
if (empty($idSites)) {
return 0; // no visit tracked yet, the idsite in() would otherwise fail
}
$idSitesArray = $idSites;
$idSites = implode(', ', $idSites);
$numVisitsToUpdate = $this->getNumVisitsInTimeRange($idSites, $startDate, $endDate);
if (empty($numVisitsToUpdate)) {
return 0;
}
$privacyConfig = new Config();
$minimumIpAddressMaskLength = 2;
$ipMaskPerSite = [];
foreach ($idSitesArray as $idSite) {
$privacyConfig->setIdSite($idSite);
$ipMaskPerSite[$idSite] = max($minimumIpAddressMaskLength, $privacyConfig->ipAddressMaskLength);
}
$numRecordsUpdated = 0;
$trackerModel = new Model();
$geolocator = new VisitorGeolocator();
for ($i = 0; $i < $numVisitsToUpdate; $i = $i + self::NUM_ROWS_UPDATE_AT_ONCE) {
$offset = $i;
$limit = self::NUM_ROWS_UPDATE_AT_ONCE;
if (($offset + $limit) > $numVisitsToUpdate) {
$limit = $numVisitsToUpdate % $limit;
}
$sql = sprintf('SELECT idsite, idvisit, location_ip, user_id, location_longitude, location_latitude, location_city, location_region, location_country FROM `%s` WHERE idsite in (%s) and visit_last_action_time >= ? and visit_last_action_time <= ? ORDER BY idsite, visit_last_action_time, idvisit LIMIT %d OFFSET %d', $this->logVisitTable, $idSites, $limit, $offset);
$rows = Db::query($sql, array($startDate, $endDate))->fetchAll();
foreach ($rows as $row) {
$ipObject = IP::fromBinaryIP($row['location_ip']);
$ipString = $ipObject->toString();
$ipAnonymized = IPAnonymizer::applyIPMask($ipObject, $ipMaskPerSite[$row['idsite']]);
$update = array();
if ($anonymizeIp) {
if ($ipString !== $ipAnonymized->toString()) {
// needs updating
$update['location_ip'] = $ipAnonymized->toBinary();
}
}
if ($anonymizeUserId && isset($row['user_id']) && $row['user_id'] !== false && $row['user_id'] !== '') {
$update['user_id'] = RequestProcessor::anonymizeUserId($row['user_id']);
}
if ($anonimizeLocation) {
$location = $geolocator->getLocation(array('ip' => $ipAnonymized->toString()));
$keys = array(
'location_longitude' => LocationProvider::LONGITUDE_KEY,
'location_latitude' => LocationProvider::LATITUDE_KEY,
'location_city' => LocationProvider::CITY_NAME_KEY,
'location_region' => LocationProvider::REGION_CODE_KEY,
'location_country' => LocationProvider::COUNTRY_CODE_KEY,
);
foreach ($keys as $name => $val) {
$newLocationData = null;
if (isset($location[$val]) && $location[$val] !== false) {
$newLocationData = $location[$val];
}
if ($newLocationData !== $row[$name]) {
$update[$name] = $newLocationData;
}
}
}
if (!empty($update)) {
$trackerModel->updateVisit($row['idsite'], $row['idvisit'], $update);
$numRecordsUpdated++;
}
}
unset($rows);
}
return $numRecordsUpdated;
}
public function unsetLogVisitTableColumns($idSites, $startDate, $endDate, $columns)
{
return $this->unsetLogTableColumns('log_visit', 'visit_last_action_time', $idSites, $startDate, $endDate, $columns);
}
public function unsetLogConversionTableColumns($idSites, $startDate, $endDate, $visitColumns)
{
$columnsToUnset = array();
$table = 'log_conversion';
$logTableFields = $this->getAvailableColumnsWithDefaultValue(Common::prefixTable($table));
foreach ($visitColumns as $column) {
// we do not fail if a specified column does not exist here as this is applied to visit columns
// and some visit columns may not exist in log_conversion. We do not want to fail in this case
if (array_key_exists($column, $logTableFields)) {
$columnsToUnset[] = $column;
}
}
return $this->unsetLogTableColumns($table, 'server_time', $idSites, $startDate, $endDate, $columnsToUnset);
}
public function unsetLogLinkVisitActionColumns($idSites, $startDate, $endDate, $columns)
{
return $this->unsetLogTableColumns('log_link_visit_action', 'server_time', $idSites, $startDate, $endDate, $columns);
}
public function checkAllVisitColumns($visitColumns)
{
$this->areAllColumnsValid('log_visit', $visitColumns);
return null;
}
public function checkAllLinkVisitActionColumns($linkVisitActionColumns)
{
$this->areAllColumnsValid('log_link_visit_action', $linkVisitActionColumns);
return null;
}
public function getAvailableVisitColumnsToAnonymize()
{
return $this->getAvailableColumnsWithDefaultValue(Common::prefixTable('log_visit'));
}
public function getAvailableLinkVisitActionColumnsToAnonymize()
{
return $this->getAvailableColumnsWithDefaultValue(Common::prefixTable('log_link_visit_action'));
}
private function areAllColumnsValid($table, $columns)
{
if (empty($columns)) {
return;
}
$table = Common::prefixTable($table);
$logTableFields = $this->getAvailableColumnsWithDefaultValue($table);
foreach ($columns as $column) {
if (!array_key_exists($column, $logTableFields)) {
throw new Exception(sprintf('The column "%s" seems to not exist in %s or cannot be unset. Use one of %s', $column, $table, implode(', ', array_keys($logTableFields))));
}
}
}
private function unsetLogTableColumns($table, $dateColumn, $idSites, $startDate, $endDate, $columns)
{
if (empty($columns)) {
return 0;
}
$table = Common::prefixTable($table);
if (empty($idSites)) {
$idSites = $this->getAllIdSitesString($table);
} else {
$idSites = array_map('intval', $idSites);
}
if (empty($idSites)) {
return 0; // no visit tracked yet, the idsite in() would otherwise fail
}
$idSites = implode(', ', $idSites);
$logTableFields = $this->getAvailableColumnsWithDefaultValue($table);
$col = [];
$bind = [];
foreach ($columns as $column) {
if (!array_key_exists($column, $logTableFields)) {
throw new Exception(sprintf('The column "%s" cannot be unset because it has no default value or it does not exist in "%s". Use one of %s', $column, $table, implode(', ', array_keys($logTableFields))));
}
$col[] = $column . ' = ?';
$bind[] = $logTableFields[$column];
}
$col = implode(',', $col);
$bind[] = $startDate;
$bind[] = $endDate;
$sql = sprintf('UPDATE `%s` SET %s WHERE idsite in (%s) and %s >= ? and %s <= ?', $table, $col, $idSites, $dateColumn, $dateColumn);
return Db::query($sql, $bind)->rowCount();
}
private function getNumVisitsInTimeRange($idSites, $startDate, $endDate)
{
$sql = sprintf('SELECT count(*) FROM `%s` WHERE idsite in (%s) and visit_last_action_time >= ? and visit_last_action_time <= ?', $this->logVisitTable, $idSites);
$numVisits = Db::query($sql, array($startDate, $endDate))->fetchColumn();
return $numVisits;
}
private function getAvailableColumnsWithDefaultValue($table)
{
$columns = DbHelper::getTableColumns($table);
$values = array();
foreach ($columns as $column => $config) {
$hasDefaultKey = array_key_exists('Default', $config);
if (in_array($column, $this->COLUMNS_BLACKLISTED, true)) {
continue;
} elseif (strtoupper($config['Null']) === 'NO' && $hasDefaultKey && $config['Default'] === null) {
// we cannot unset this column as it may result in an error or random data
continue;
} elseif ($hasDefaultKey) {
$values[$column] = $config['Default'];
} elseif (strtoupper($config['Null']) === 'YES') {
$values[$column] = null;
}
}
return $values;
}
private function getAllIdSitesString($table)
{
// we need the idSites in order to use the index
$sites = Db::query(sprintf('SELECT DISTINCT idsite FROM `%s`', $table))->fetchAll();
$idSites = array();
foreach ($sites as $site) {
$idSites[] = (int) $site['idsite'];
}
return $idSites;
}
}
|