Plugin GeoIP Piwik

De EjnTricks

Sur les statistiques d'accès, Piwik présente le pays d'origine de la connexion. Cependant, elle n'est pas entièrement fiable et quelques erreurs de résolution se produisent. Comme pour Awstats, il est possible d'utiliser les informations de localisation de MaxMind.

Le plugin GeoIP va permettre de consommer ces informations et fournir des rapports plus précis.

ATTENTION, ce plugin n'est plus nécessaire à partir de la vesion 1.9. Voir la procédure d'installation sur la page de mise à jour 1.8.4 → 1.9


Hand-icon.png Votre avis

Nobody voted on this yet

 You need to enable JavaScript to vote


System-Install-icon.png Installation

Command-icon.png Mise en place

Le plugin est téléchargé à l'emplacement /var/datas/piwik/extensions/GeoIP.zip avec l'outil wget depuis le site de Piwik.

#sudo wget -O /var/datas/piwik/extensions/GeoIP.zip http://dev.piwik.org/trac/attachment/ticket/45/GeoIP.zip?format=raw
--2012-03-24 00:02:34--  http://dev.piwik.org/trac/attachment/ticket/45/GeoIP.zip?format=raw
Résolution de dev.piwik.org... 91.121.92.93
Connexion vers dev.piwik.org|91.121.92.93|:80... connecté.
requête HTTP transmise, en attente de la réponse... 200 OK
Longueur: 17894 (17K) [application/zip]
Sauvegarde en : «/var/datas/piwik/extensions/GeoIP.zip»

100%[===========================================================================================>] 17 894      --.-K/s   ds 0,06s

2012-03-24 00:02:34 (298 KB/s) - «/var/datas/piwik/extensions/GeoIP.zip» sauvegardé [17894/17894]

Une fois téléchargé, il faut le décompresser, toujours dans le répertoire /var/datas/piwik/extensions.

#sudo unzip /var/datas/piwik/extensions/GeoIP.zip -d /var/datas/piwik/extensions/
Archive:  /var/datas/piwik/extensions/GeoIP.zip
   creating: /var/datas/piwik/extensions/GeoIP/
  inflating: /var/datas/piwik/extensions/GeoIP/API.php
  inflating: /var/datas/piwik/extensions/GeoIP/Controller.php
  inflating: /var/datas/piwik/extensions/GeoIP/GeoIP.php
   creating: /var/datas/piwik/extensions/GeoIP/lang/
  inflating: /var/datas/piwik/extensions/GeoIP/lang/en.php
   creating: /var/datas/piwik/extensions/GeoIP/libs/
  inflating: /var/datas/piwik/extensions/GeoIP/libs/geoip.inc
  inflating: /var/datas/piwik/extensions/GeoIP/libs/geoipcity.inc
   creating: /var/datas/piwik/extensions/GeoIP/misc/
 extracting: /var/datas/piwik/extensions/GeoIP/misc/.htaccess
  inflating: /var/datas/piwik/extensions/GeoIP/misc/geoipUpdateRows.php
 extracting: /var/datas/piwik/extensions/GeoIP/README
   creating: /var/datas/piwik/extensions/GeoIP/templates/
  inflating: /var/datas/piwik/extensions/GeoIP/templates/index.tpl
   creating: /var/datas/piwik/extensions/GeoIP/Updates/
  inflating: /var/datas/piwik/extensions/GeoIP/Updates/0.7.php
  inflating: /var/datas/piwik/extensions/GeoIP/Updates/0.9.php
#sudo rm /var/datas/piwik/extensions/GeoIP.zip

Le fichier README donne des indications sur l'installation, mais il est inutile au bon fonctionnement. Il peut donc être supprimé.

#sudo rm /var/datas/piwik/extensions/GeoIP/README

Comme pour l'installation, il est recommandé de mettre en place les sécurités sur les fichiers, pour n'autoriser que le compte d'exécution du serveur Web, soit www-data.

#sudo chown -R www-data:www-data /var/datas/piwik/extensions/GeoIP

Information de localisation

La documentation d'installation indique de placer les fichiers de localisation, GeoIP.dat et GeoLiteCity.dat, dans le répertoire libs du plugin, soit /var/datas/piwik/extensions/GeoIP/libs. Cependant, ces données étant partagés avec le plugin GeoIP sous Awstats. Les fichiers sont donc placés dans un répertoire externe, /var/datas/maxmind. Les informations de localisation sont déployées dans le répertoire /var/datas/maxmind, permettant de les partager entre ces deux plugins.

  • Création du répertoire de téléchargement /var/opt/geo.
#sudo mkdir /var/datas/maxmind
#sudo chown www-data:www-data /var/datas/maxmind
#sudo chmod 750 /var/datas/maxmind
  • Création du script pour la tâche planifiée à l'emplacement /var/opt/geo/download_geoLiteCity.sh.
#sudo mkdir /var/opt/geo
#sudo chown www-data:www-data /var/opt/geo
#sudo chmod 750 /var/opt/geo

Deux scripts sont créés pour le téléchargement des informations de location (pays / continent) et des villes.

  • Création des répertoires pour les scripts de téléchargement.
#sudo mkdir /var/opt/geo
#sudo chown www-data:www-data /var/opt/geo
#sudo chmod 750 /var/opt/geo
  • Création du script pour la tâche planifiée à l'emplacement /var/opt/geo/download_geoip.sh.
#!/bin/bash
LOCALPATH=/var/datas/maxmind/
DOWN_FILE=$LOCALPATH"GeoIp.dat.gz"

if [ -f $DOWN_FILE ]; then
        rm -f $DOWN_FILE
fi

/usr/bin/wget -q --output-document=$DOWN_FILE http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
gunzip -f $DOWN_FILE
  • Création du script pour la tâche planifiée à l'emplacement /var/opt/geo/download_geoLiteCity.sh.
#!/bin/bash
LOCALPATH=/var/datas/maxmind/
DOWN_FILE=$LOCALPATH"GeoLiteCity.dat.gz"

if [ -f $DOWN_FILE ]; then
        rm -f $DOWN_FILE
fi

/usr/bin/wget -q --output-document=$DOWN_FILE http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip -f $DOWN_FILE


  • Modification de la crontab.
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
30 5    3 * *   root    cd / && /var/opt/geo/download_geoip.sh > /dev/null
35 5    3 * *   root    cd / && /var/opt/geo/download_geoLiteCity.sh > /dev/null
#


Un lien sera donc placés dans le répertoire libs de l'extension GeoIP.

#sudo ln -s /var/datas/maxmind/GeoIP.dat /var/datas/piwik/extensions/GeoIP/libs/GeoIP.dat
#sudo ln -s /var/datas/maxmind/GeoLiteCity.dat /var/datas/piwik/extensions/GeoIP/libs/GeoLiteCity.dat
#sudo chown -h www-data:www-data /var/datas/piwik/extensions/GeoIP/libs/GeoIP.dat
#sudo chown -h www-data:www-data /var/datas/piwik/extensions/GeoIP/libs/GeoLiteCity.dat

Mise à disposition

La dernière étape de l'installation consiste à la mise à disposition du plugin dans l'instance de Piwik. Le plugin étant installé dans un répertoire externe, l'utilisation des liens permet de l'exposer.

#sudo ln -s /var/datas/piwik/extensions/GeoIP /var/opt/piwik/plugins/GeoIP
#sudo chown -h www-data:www-data /var/opt/piwik/plugins/GeoIP


Lock-icon.png Sécurité des scripts

Comme indiqué un peu plus loin dans l'article, il est possible de mettre à jour les données à partir du script geoipUpdateRows.php dans le répertoire misc. Dans ce même répertoire un fichier .htaccess est mis à disposition.

#ll /var/opt/piwik/plugins/GeoIP/misc
total 16
drwxr-xr-x 2 www-data www-data 4096 2012-03-27 01:35 ./
drwxr-xr-x 7 www-data www-data 4096 2012-03-26 01:23 ../
-rw-r--r-- 1 www-data www-data 1484 2012-03-24 01:16 geoipUpdateRows.php
-rw-r--r-- 1 www-data www-data   51 2012-03-27 01:33 .htaccess

Cependant, il permet l'accès à tous les utilisateurs, ce qui n'est pas souhaitable lors d'une exposition sur internet. Il est nécessaire de modifier le contenu de ce fichier afin d'interdire l'accès au fichier.

<Files "*">
#Allow from all
Deny from all
</Files>


Run-icon.png Activation

Une fois installé, il faut activer le plugin depuis l'interface de l'application. Cette opération s'effectue dans les paramètres et l'onglet Plugins. Le plugin est présenté mais non activé.


Attention, la description qui suit ne devrait pas se produire. La simple activation du plugin par le lien Activer permet de finaliser l'installation. Cependant, les permissions initiales du compte d'accès à la base de données était initialement faible. Cela va entraîner des erreurs inattendues, dont la résolution a été faite à la main.

Icon-database-process.png Mise à jour base de données

Erreur permission

Lors de l'activation, un message d'erreur est présenté.

SQLSTATE[42000]: Syntax error or access violation: 1142 ALTER command denied to user 'piwik'@'localhost' for table 'piwik_log_visit'
#0 /var/opt/piwik-1.7.1/libs/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#1 /var/opt/piwik-1.7.1/libs/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#2 /var/opt/piwik-1.7.1/libs/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE piw...', Array)
#3 /var/opt/piwik-1.7.1/core/Db/Adapter/Pdo/Mysql.php(211): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE piw...', Array)
#4 /var/opt/piwik-1.7.1/core/PluginsFunctions/Sql.php(45): Piwik_Db_Adapter_Pdo_Mysql->query('ALTER TABLE piw...', Array)
#5 /var/opt/piwik-1.7.1/core/PluginsFunctions/Sql.php(90): Piwik_Sql::query('ALTER TABLE piw...', Array)
#6 /var/datas/piwik/extensions/GeoIP/Updates/0.7.php(3): Piwik_Query('ALTER TABLE piw...')
#7 /var/opt/piwik-1.7.1/core/Updater.php(112): require_once('/var/datas/piwi...')
#8 /var/opt/piwik-1.7.1/plugins/CoreUpdater/Controller.php(225): Piwik_Updater->getSqlQueriesToExecute()
#9 /var/opt/piwik-1.7.1/plugins/CoreUpdater/Controller.php(211): Piwik_CoreUpdater_Controller->runUpdaterAndExit()
#10 [internal function]: Piwik_CoreUpdater_Controller->index()
#11 /var/opt/piwik-1.7.1/core/FrontController.php(138): call_user_func_array(Array, Array)
#12 /var/opt/piwik-1.7.1/index.php(53): Piwik_FrontController->dispatch()
#13 {main}

Le message indiquer un manque de permission sur le compte. Afin de s'affranchir de tout problème, des droits maximum sont accordés au compte, dans le cadre de cette installation piwik.

mysql> GRANT ALL ON piwik.* TO 'piwik'@'localhost';
Query OK, 0 rows affected (0.00 sec)
 
mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

Ces permissions seront réduites par la suite.

Erreur structure

Après la précédente tentative, un rafraîchissement de la fenêtre présente une nouvelle erreur.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'location_geoip_latitude' in 'piwik_log_visit'
#0 /var/opt/piwik-1.7.1/libs/Zend/Db/Statement.php(300): Zend_Db_Statement_Pdo->_execute(Array)
#1 /var/opt/piwik-1.7.1/libs/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement->execute(Array)
#2 /var/opt/piwik-1.7.1/libs/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('ALTER TABLE piw...', Array)
#3 /var/opt/piwik-1.7.1/core/Db/Adapter/Pdo/Mysql.php(211): Zend_Db_Adapter_Pdo_Abstract->query('ALTER TABLE piw...', Array)
#4 /var/opt/piwik-1.7.1/core/PluginsFunctions/Sql.php(45): Piwik_Db_Adapter_Pdo_Mysql->query('ALTER TABLE piw...', Array)
#5 /var/opt/piwik-1.7.1/core/PluginsFunctions/Sql.php(90): Piwik_Sql::query('ALTER TABLE piw...', Array)
#6 /var/datas/piwik/extensions/GeoIP/Updates/0.7.php(3): Piwik_Query('ALTER TABLE piw...')
#7 /var/opt/piwik-1.7.1/core/Updater.php(112): require_once('/var/datas/piwi...')
#8 /var/opt/piwik-1.7.1/plugins/CoreUpdater/Controller.php(225): Piwik_Updater->getSqlQueriesToExecute()
#9 /var/opt/piwik-1.7.1/plugins/CoreUpdater/Controller.php(211): Piwik_CoreUpdater_Controller->runUpdaterAndExit()
#10 [internal function]: Piwik_CoreUpdater_Controller->index()
#11 /var/opt/piwik-1.7.1/core/FrontController.php(138): call_user_func_array(Array, Array)
#12 /var/opt/piwik-1.7.1/index.php(53): Piwik_FrontController->dispatch()
#13 {main}

Explication des erreurs

Dans le script GeoIP.php, la fonction install est mise en place afin de modifier la table <TABLE_PREFIX>_log_visit.

        public function install()
        {
                // add column location_geoip_city, location_geoip_latitude, location_geoip_longitude in the visit table
                $query = "ALTER IGNORE TABLE `".Piwik_Common::prefixTable('log_visit')."` " .
                                "ADD `location_geoip_continent` VARCHAR( 100 ) NULL, " .
                                "ADD `location_geoip_country` VARCHAR( 100 ) NULL, " .
                                "ADD `location_geoip_city` VARCHAR( 100 ) NULL, " .
                                "ADD `location_geoip_latitude` DECIMAL(7,4) NULL, " .
                                "ADD `location_geoip_longitude` DECIMAL(7,4) NULL";

                // if the column already exist do not throw error. Could be installed twice...
                try {
                        Piwik_Exec($query);
                }
                catch(Exception $e){
                }
        }

Or dans ce cas, une erreur lors de l'exécution de la requête ne provoque pas d'interruption de l'exécution. La table n'est alors pas modifiée, entraînant ensuite les erreurs dans les scripts de mise à jour 0.7.php et 0.9.php dans le répertoire Updates.

  • Fichier 0.7.php
<?php
Piwik_Query("ALTER TABLE ". Piwik_Common::prefixTable('log_visit') . "
                                CHANGE `location_geoip_latitude` `location_geoip_latitude` DECIMAL(7,4) NULL");
Piwik_Query("ALTER TABLE ". Piwik_Common::prefixTable('log_visit') . "
                                CHANGE `location_geoip_longitude` `location_geoip_longitude` DECIMAL(7,4) NULL");
?>
  • Fichier 0.9.php
<?php
$toUpdate = array("location_geoip_continent", "location_geoip_country", "location_geoip_city");
foreach($toUpdate as $field)
{
        Piwik_Query("ALTER TABLE ". Piwik_Common::prefixTable('log_visit') . "
                                CHANGE `".$field."` `".$field."` VARCHAR( 100 ) NULL");
}
?>

Or, la structure de la table piwik_log_visit montrait l'absence des colonnes location_geoip_continent, location_geoip_country et location_geoip_city.

mysql> describe piwik_log_visit;
+---------------------------+----------------------+------+-----+---------+----------------+
| Field                     | Type                 | Null | Key | Default | Extra          |
+---------------------------+----------------------+------+-----+---------+----------------+
| idvisit                   | int(10) unsigned     | NO   | PRI | NULL    | auto_increment |
| idsite                    | int(10) unsigned     | NO   | MUL | NULL    |                |
| idvisitor                 | binary(8)            | NO   |     | NULL    |                |
| visitor_localtime         | time                 | NO   |     | NULL    |                |
| visitor_returning         | tinyint(1)           | NO   |     | NULL    |                |
| visitor_count_visits      | smallint(5) unsigned | NO   |     | NULL    |                |
| visitor_days_since_last   | smallint(5) unsigned | NO   |     | NULL    |                |
| visitor_days_since_order  | smallint(5) unsigned | NO   |     | NULL    |                |
| visitor_days_since_first  | smallint(5) unsigned | NO   |     | NULL    |                |
| visit_first_action_time   | datetime             | NO   |     | NULL    |                |
| visit_last_action_time    | datetime             | NO   |     | NULL    |                |
| visit_exit_idaction_url   | int(11) unsigned     | NO   |     | NULL    |                |
| visit_exit_idaction_name  | int(11) unsigned     | NO   |     | NULL    |                |
| visit_entry_idaction_url  | int(11) unsigned     | NO   |     | NULL    |                |
| visit_entry_idaction_name | int(11) unsigned     | NO   |     | NULL    |                |
| visit_total_actions       | smallint(5) unsigned | NO   |     | NULL    |                |
| visit_total_time          | smallint(5) unsigned | NO   |     | NULL    |                |
| visit_goal_converted      | tinyint(1)           | NO   |     | NULL    |                |
| visit_goal_buyer          | tinyint(1)           | NO   |     | NULL    |                |
| referer_type              | tinyint(1) unsigned  | YES  |     | NULL    |                |
| referer_name              | varchar(70)          | YES  |     | NULL    |                |
| referer_url               | text                 | NO   |     | NULL    |                |
| referer_keyword           | varchar(255)         | YES  |     | NULL    |                |
| config_id                 | binary(8)            | NO   |     | NULL    |                |
| config_os                 | char(3)              | NO   |     | NULL    |                |
| config_browser_name       | varchar(10)          | NO   |     | NULL    |                |
| config_browser_version    | varchar(20)          | NO   |     | NULL    |                |
| config_resolution         | varchar(9)           | NO   |     | NULL    |                |
| config_pdf                | tinyint(1)           | NO   |     | NULL    |                |
| config_flash              | tinyint(1)           | NO   |     | NULL    |                |
| config_java               | tinyint(1)           | NO   |     | NULL    |                |
| config_director           | tinyint(1)           | NO   |     | NULL    |                |
| config_quicktime          | tinyint(1)           | NO   |     | NULL    |                |
| config_realplayer         | tinyint(1)           | NO   |     | NULL    |                |
| config_windowsmedia       | tinyint(1)           | NO   |     | NULL    |                |
| config_gears              | tinyint(1)           | NO   |     | NULL    |                |
| config_silverlight        | tinyint(1)           | NO   |     | NULL    |                |
| config_cookie             | tinyint(1)           | NO   |     | NULL    |                |
| location_ip               | varbinary(16)        | NO   |     | NULL    |                |
| location_browser_lang     | varchar(20)          | NO   |     | NULL    |                |
| location_country          | char(3)              | NO   |     | NULL    |                |
| location_continent        | char(3)              | NO   |     | NULL    |                |
| custom_var_k1             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_v1             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_k2             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_v2             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_k3             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_v3             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_k4             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_v4             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_k5             | varchar(200)         | YES  |     | NULL    |                |
| custom_var_v5             | varchar(200)         | YES  |     | NULL    |                |
| location_provider         | varchar(100)         | YES  |     | NULL    |                |
+---------------------------+----------------------+------+-----+---------+----------------+
53 rows in set (0.00 sec)

Mise à jour manuelle

L'étude précédente des différents scripts permet d'identifier les modifications à apporter à la base de données. Ces requêtes ont été exécutées manuellement.

  • Requêtes suite au script 0.7.php
mysql> ALTER TABLE piwik_log_visit ADD location_geoip_latitude DECIMAL(7,4) NULL;
Query OK, 84 rows affected (0.08 sec)
Records: 84  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE piwik_log_visit ADD location_geoip_longitude DECIMAL(7,4) NULL;
Query OK, 84 rows affected (0.06 sec)
Records: 84  Duplicates: 0  Warnings: 0
  • Requêtes suite au script 0.9.php
mysql> ALTER TABLE piwik_log_visit ADD location_geoip_continent VARCHAR( 100 ) NULL;
Query OK, 84 rows affected (0.05 sec)
Records: 84  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE piwik_log_visit ADD location_geoip_country VARCHAR( 100 ) NULL;
Query OK, 84 rows affected (0.05 sec)
Records: 84  Duplicates: 0  Warnings: 0

mysql> ALTER TABLE piwik_log_visit ADD location_geoip_city VARCHAR( 100 ) NULL;
Query OK, 84 rows affected (0.05 sec)
Records: 84  Duplicates: 0  Warnings: 0

Mise à jour version du plugin

Après la mise à jour du schéma, un avertissement est présenté, indiquant la nécessité de mettre à jour le numéro de version du plugin dans la base de données.


Seule une requête doit être exécutée. Le risque étant très faible, celle-ci est confirmée et exécutée depuis l'interface. Le plugin est alors installé et activé sur l'application, comme l’atteste la fenêtre des plugins.


Update icon.png Mise à jour des données

Process-Icon.png Exécution

Une fois installé, il est possible de mettre à jour les données déjà ùéùorisées en exécutant le script geoipUpdateRows.php dans le répertoire misc. La première tentative va présenter une première erreur:

#cd /var/opt/piwik/plugins/GeoIP/misc
#php5 geoipUpdateRows.php
PHP Warning:  require_once(/var/datas/piwik/extensions/GeoIP/misc/../../../libs/upgradephp/upgrade.php): failed to open stream: 
No such file or directory in /var/datas/piwik/extensions/GeoIP/misc/geoipUpdateRows.php on line 23
PHP Fatal error:  require_once(): Failed opening required 
'/var/datas/piwik/extensions/GeoIP/misc/../../../libs/upgradephp/upgrade.php'
(include_path='.:/usr/share/php:/usr/share/pear') in /var/datas/piwik/extensions/GeoIP/misc/geoipUpdateRows.php on line 23

Cette erreur ne se produit uniquement parce que le plugin a été installé dans un répertoire externe. Si il avait été déployé dans l'instance de l'application, celle-ci ne se produirait pas. Dans le cadre de cette installation, il est donc nécessaire de le modifier légèrement, afin de référencer les emplacements.

<?php
ini_set("memory_limit", "512M");
error_reporting(E_ALL|E_NOTICE);

#define('PIWIK_DOCUMENT_ROOT', dirname(__FILE__)=='/'?'':dirname(__FILE__) .'/../../..');
define('PIWIK_DOCUMENT_ROOT', '/var/opt/piwik');
if(file_exists(PIWIK_DOCUMENT_ROOT . '/bootstrap.php'))
{
        require_once PIWIK_DOCUMENT_ROOT . '/bootstrap.php';
}
if(!defined('PIWIK_USER_PATH'))
{
        define('PIWIK_USER_PATH', PIWIK_DOCUMENT_ROOT);
}
if(!defined('PIWIK_INCLUDE_PATH'))
{
        define('PIWIK_INCLUDE_PATH', PIWIK_DOCUMENT_ROOT);
}

ignore_user_abort(true);
set_time_limit(0);
@date_default_timezone_set('UTC');

require_once PIWIK_INCLUDE_PATH . '/libs/upgradephp/upgrade.php';
require_once PIWIK_INCLUDE_PATH . '/core/testMinimumPhpVersion.php';
require_once PIWIK_INCLUDE_PATH . '/core/Loader.php';

$GLOBALS['PIWIK_TRACKER_DEBUG'] = false;
define('PIWIK_ENABLE_DISPATCH', false);

Piwik_FrontController::getInstance()->init();

if(!class_exists('Piwik_GeoIP'))
{
        echo 'ERROR: It seems the GeoIP is not enabled. Please enable the plugin in Piwik admin page.';
        exit;
}

// when script run via browser, check for Super User
if(!Piwik_Common::isPhpCliMode())
{
    try {
        Piwik::checkUserIsSuperUser();
    } catch(Exception $e) {
        echo 'ERROR: You must be logged in as Super User to run this script. Please login in Piwik and refresh this page.';
        exit;
    }
}
$geoIp = new Piwik_GeoIP();
$geoIp->updateExistingVisitsWithGeoIpData();

Enfin, la dernière étape consiste en la suppression des rapports générés et sérialisés dans la base de données. Ceux-ci se trouvent dans les tables <TABLE_PREFIX>_archive_blob_YYYY_MM et <TABLE_PREFIX>_archive_numeric_YYYY_MM, où:

  • YYYY, année du rapport.
  • MM, mois du rapport.
mysql> show tables;
+-------------------------------+
| Tables_in_piwik               |
+-------------------------------+
| piwik_access                  |
| piwik_archive_blob_2012_03    |
| piwik_archive_numeric_2012_03 |
| piwik_goal                    |
| piwik_log_action              |
| piwik_log_conversion          |
| piwik_log_conversion_item     |
| piwik_log_link_visit_action   |
| piwik_log_profiling           |
| piwik_log_visit               |
| piwik_logger_api_call         |
| piwik_logger_error            |
| piwik_logger_exception        |
| piwik_logger_message          |
| piwik_option                  |
| piwik_pdf                     |
| piwik_session                 |
| piwik_site                    |
| piwik_site_url                |
| piwik_user                    |
| piwik_user_dashboard          |
| piwik_user_language           |
+-------------------------------+
22 rows in set (0.00 sec)

mysql> drop table piwik_archive_blob_2012_03;
Query OK, 0 rows affected (0.02 sec)

mysql> drop table piwik_archive_numeric_2012_03;
Query OK, 0 rows affected (0.00 sec)

Dans cet exemple, seuls deux rapport sont purgés.

Icon-database-search.png Mise à jour manuelle des données

Comme indiqué dans le précédent paragraphe, des erreurs sont constatées au niveau du pays d'origine de la connexion. A l'aide du plugin, il est possible d'avoir des données plus fiables, permettant ensuite de mettre à jour les données "standards" de Piwik. Les précédentes études ont permis d'identifier la table <TABLE_PREFIX>_log_visit.

La requête suivante permet de lister les données invalides.

mysql> select location_country, location_continent, location_geoip_country, location_geoip_continent, location_geoip_city 
from piwik_log_visit where location_country != location_geoip_country;
+------------------+--------------------+------------------------+--------------------------+---------------------+
| location_country | location_continent | location_geoip_country | location_geoip_continent | location_geoip_city |
+------------------+--------------------+------------------------+--------------------------+---------------------+
| xx               | unk                | us                     | amn                      | Sunnyvale           |
| de               | eur                | at                     | eur                      | Bad Sankt Leonhard  |
+------------------+--------------------+------------------------+--------------------------+---------------------+
2 rows in set (0.00 sec)

Il est également possible de modifier les données, en recopiant les données depuis location_geoip_country et location_geoip_continent vers location_country et location_continent.

mysql> update piwik_log_visit set location_country = location_geoip_country, location_continent = location_geoip_continent
where location_country != location_geoip_country;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

Viewer icon.png Rendu

Une fois installé, un nouveau menu, Situation géographique et FAI est disponible sous l'onglet Visiteurs. Dans cet onglet, il est possible de visualiser le pays et continent d'origine de la connexion, mais également le fournisseur d'accès à internet.

Dans cette copie d'écran, une connexion est présentée provenant de l'Allemagne.


Cependant, cette IP provient d'Autriche. L'utilisation de GeoIP permet de fiabiliser cette information, comme l'indique les deux copies d'écran suivantes.

  • Visualisation du pays et de la ville.


  • Visualisation du continent.


Viewer icon.png Voir aussi

Documentation officielle: http://dev.piwik.org/trac/ticket/45