Google Measurement Protocol : vitesse à zéro ?

WRInaute accro
Bonjour

J'ai mis en place récemment sur mon site, la mesure "pageview", avec le code suivant :

Code:
<?php
// GDPR_Analytics.php

// Cette fonction traduit
// l'utf8 en iso-8859-15.
function decode_vers_iso($var)
{
    if(utf8_encode(utf8_decode($var)) == $var)
    {
        /**
        * UTF_8.
        * On remplace
        * et decode
        * vers ISO.
        */
        $send = preg_replace("{\xC2\xA0}u",  " ", $var);
        $var = utf8_decode($send);
    }
    return $var;
}
function hash_nom($nom)
{
    return(hash('crc32', $nom) . hash('crc32b', $nom));
}
function is_valid_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
    {
        return false;
    }
 
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
    {
        return false;
    }
    return(true);
}
function format_ip6($remote_addr)
{
    $array_ip6    = array();
    $array_ip6_fin    = array();
    if(!empty($remote_addr))
    {
        $array_ip6 = preg_split("{:}", $remote_addr);
        $tmp_count = 8;
        for($i = 0; $i < count($array_ip6); $i++)
        {
            if($array_ip6[$i] !== "")
            {
                $tmp_count--;
            }
        }
        $j = -1;
        $k_count = 0;
        for($i = count($array_ip6) - 1; $i >= 0; $i--)
        {
            if($array_ip6[$i] !== "")
            {
                unset($tmp);
                $tmp = substr("000". $array_ip6[$i], -4);
                $j++;
                $array_ip6_fin[$j] = $tmp;
            }
            else
            {
                unset($tmp);
                $tmp = "0000";
                while($k_count < $tmp_count)
                {
                    $j++;
                    $array_ip6_fin[$j] = $tmp;
                    $k_count++;
                }
            }
        }
        $addr_remote = "";
        for($i = count($array_ip6_fin) - 1; $i >= 0; $i--)
        {
            unset($tmp);
            $tmp = $array_ip6_fin[$i];
            if($i == (count($array_ip6_fin) - 1))
            {
                $addr_remote = $tmp;
            }
            else
            {
                $addr_remote .= ":" . $tmp;
            }
        }
        $addr_remote = strtolower($addr_remote);
        return((empty($addr_remote)) ? false : $addr_remote);
    }
    else
    {
        return(false);
    }
}
function sanitize($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false)
    {
        return(format_ip6($ip));
    }
    elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false)
    {
        return(long2ip(ip2long($ip)));
    }
    return false;
}
function ip_address()
{
//    $array_type_ip = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR');
    $array_type_ip = array('REMOTE_ADDR', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED');
    foreach($array_type_ip as $key)
    {
        if(!isset($_SERVER[$key]))
        {
            continue;
        }
        unset($ip);
        $ip = $_SERVER[$key];
        if(!empty($ip))
        {
            $ip = trim($ip);
            if(strpos($ip, ",") !== false)
            {
                $array_ip = explode($ip);
                foreach($array_ip as $value2)
                {
                    unset($tmp_ip);
                    $tmp_ip = sanitize($value2);
                    if(is_valid_ip($tmp_ip))
                    {
                        return($tmp_ip);
                    }
                }
            }
            else
            {
                $tmp_ip = trim(sanitize($ip));
                if(is_valid_ip($tmp_ip))
                {
                    return($tmp_ip);
                }
            }
        }
    }
    return(false);
}
function http_post($url, $data)
{
    foreach($data as $key => $value)
    {
        if($key != 'ua')
        {
            $data[$key] = utf8_encode($value);
        }
    }
    $request = http_build_query($data);
    $user_agent = $data['ua'];
    //    Utilisation de la librairie Curl
    //    pour envoi de paramètres POST.
    $ch = @curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = @curl_exec($ch);
    if(@curl_errno($ch) != 0)
    {
        echo @curl_error($ch) . "<br>\n";
        @curl_close($ch);
        exit;
    }
    else
    {
        @curl_close($ch);
    }
    $response = array();
    $response = preg_split("/\n/", $content);
    return($response);
}
/**
 * Plugin Name: GDPR Analytics
 * Plugin URI: https://www.legiscope.com
 * Description: Google Analyics compatible with GDPR (completely anonymizing data)
 * Version: 1.0
 * Author: Legiscope
 * Author URI: https://www.lesgiscope.com
 *
 * Note : this a proof of concept of 100% compliant Google Analytics integration
 *       no personal data is sent back to GA, therefore GDPE will no apply ( art. 2 and art. 4)
 *       Check our legal study : https://www;donneespersonnelles.fr
 *
 *       Google API implementation : https://ga-dev-tools.appspot.com/hit-builder
 *                      https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
 *                      https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
 */
function getHost($Address)
{
    $parseUrl = parse_url(trim($Address));
    foreach(array('host', 'path') as $key)
    {
        $parseUrl[$key] = (isset($parseUrl[$key])) && (!empty($parseUrl[$key])) ? $parseUrl[$key] : '';
    }
    if(($pos = strpos($parseUrl['path'], '/')) !== false)
    {
        $pseudo_host = substr($parseUrl['path'], 0, $pos);
    }
    else
    {
        $pseudo_host = '';
    }
    return trim(!empty($parseUrl['host']) ? $parseUrl['host'] : $pseudo_host);
}
function parseUrl($url, $field = null)
{
    $tmp_array = parse_url($url);
    if(($pos = strpos($tmp_array['path'], "/")) !== false)
    {
        if(($host = substr($tmp_array['path'], 0, $pos)) != '')
        {
            if($host == getHost($url))
            {
                $tmp_array['host'] = $host;
                $tmp_array['path'] = substr($tmp_array['path'], $pos);
            }
        }
    }
    else
    {
        $tmp_array['path'] = '/' . $tmp_array['path'];
    }
    $matches_array = array('scheme',
        'host',
        'user',
        'pass',
        'user',
        'pass',
        'port',
        'path',
        'query',
        'fragment');
    foreach($matches_array as $key)
    {
        $tmp_array[$key] = array_key_exists($key, $tmp_array) && (isset($tmp_array[$key])) && (!empty($tmp_array[$key])) ? $tmp_array[$key] : '';
    }
    //    return $tmp_array;
    $url = (!empty($tmp_array['scheme'])) ? $tmp_array['scheme'] . '://' : '';
    $url .= (!empty($tmp_array['host'])) ? ':' . $tmp_array['host'] : '';
    $url .= (!empty($tmp_array['user']))&&(!empty($tmp_array['pass'])) ? $tmp_array['user'] . '@' . $tmp_array['pass'] : '';
    $url .= (!empty($tmp_array['port'])) ? ':' . $tmp_array['port'] : '';
    $url .= (!empty($tmp_array['path'])) ? $tmp_array['path'] : '';
    $url .= (!empty($tmp_array['query'])) ? '?' . $tmp_array['query'] : '';
    $url .= (!empty($tmp_array['fragment'])) ? '#' . $tmp_array['fragment'] : '';
    if($field !== null)
    {
        if((array_key_exists($field, $tmp_array))&&(isset($tmp_array[$field])))
        {
            return $tmp_array[$field];
        }
        else
        {
            return null;
        }
    }
    return $url;
}
function UUID($anon_id)
{
        // Binary Value
        $nstr = '';
        // Convert Namespace UUID to bits
        for($i = 0; $i < strlen($anon_id); $i+=2) {
            $nstr .= chr(hexdec(substr($anon_id, $i, 1)).hexdec(substr($anon_id,$i + 1, 1)));
        }
        // Calculate hash value
        $hash = sha1($nstr . $anon_id);
        return sprintf('%08s-%04s-%04x-%04x-%12s',
            // 32 bits for "time_low"
            substr($hash, 0, 8),
            // 16 bits for "time_mid"
            substr($hash, 8, 4),
            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 3
            (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x4000,
            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
            // 48 bits for "node"
            substr($hash, 20, 12)
        );
}
function Client_UUID($anon_id)
{
    $hashed = hash_nom($anon_id);
    if(preg_match("{^(0)+}", $hashed, $output) === 1)
    {
        $prefix = (string)$output[0];
        $tmp_len = strlen($prefix);
        $tmp_prefix = '';
        for($i = 0; $i < $tmp_len; $i++)
        {
            unset($nbre);
            $nbre = 1 + ($i * 2) % 10;
            $tmp_prefix .= (string)$nbre;
        }
        $tmp_prefix .= preg_replace("{^(0)+}", "", $hashed);
        $hashed = $tmp_prefix;
    }
    return $hashed;
}
/**
 * This function will send a request to GA servers with anonymous users's ID and details about the visit
 */
function gdpr_analytics() {
    $ip_address = ip_address();
    if($ip_address === false)
    {
        return(null);
    }
    $ga_url = "https://www.google-analytics.com/collect";
//    $ga_url = "https://www.google-analytics.com/debug/collect";
    $data = array();
    // Protocol Version
    $data["v"] = "1";
    // Tracking ID / Web Property ID
    $data['tid'] = "UA-2860929-2";
    // Data Source
    $data['ds'] = "web";
    // Create an anonymous ID - we double hash with salt, GA won't who's who
    $salt = sha1($_SERVER['SERVER_NAME'] . $_SERVER['SERVER_ADDR']);
    $hash_const = sha1($ip_address . $salt);
    $hash_const2 = sha1($ip_address);
    // Client ID
    $data['cid'] = UUID($hash_const);
    // User ID
    $data['uid'] = Client_UUID($hash_const2);
    // IP Override
    $data['uip'] = $ip_address;
    // User Agent  Override
    $data['ua'] = str_replace(";", " ", $_SERVER['HTTP_USER_AGENT']);
    // Document Referrer
    // Entier ou Host ?
    if(isset($_SERVER['HTTP_REFERER']))
    {
        $data['dr'] = decode_vers_iso($_SERVER['HTTP_REFERER']);
    }
    // User Language
    $langue = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    if((($pos1 = strpos($langue, ";")) !== false)&&
        (($pos2 = strpos($langue, ",")) !== false))
    {
        $natio = substr($langue, min($pos1, $pos2) + 1, max($pos1, $pos2) - min($pos1, $pos2) - 1);
    }
    elseif(($pos1 = strpos($langue, ";")) !== false)
    {
        $natio = substr($langue, 0, $pos1);
    }
    elseif(($pos2 = strpos($langue, ",")) !== false)
    {
        $natio = substr($langue, 0, $pos2);
    }
    if(isset($natio))
    {
        $data['ul'] = decode_vers_iso($natio);
    }
    // Hit type
    $data['t'] = 'pageview';
    // Document Host Name
    $data['dh'] = decode_vers_iso($_SERVER['HTTP_HOST']);
    // Document Path
    $data['dp'] = decode_vers_iso(parseUrl($_SERVER['REQUEST_URI'], 'path'));
    // Send the request
    $response = http_post($ga_url, $data);
    return($response);
}
/*
print_r(gdpr_analytics());
*/
?>


Le bug, c'est que les mesures de vitesse sont toutes nulles.

Que faire ?

Merci.
 
Dernière édition:
WRInaute accro
En fait...

Je dois résoudre le problème des vitesses nulles avant de faire ma première analyse RM Tech.

Je vais faire d'abord un audit avec Chrome.

Mes mesures GA ont par ailleurs augmenté avec GMP.

Merci beaucoup de vos réponses.

Amicalement.
 
WRInaute accro
Rebond ;)

Voici les paramètres de timing :

J'aurais besoin de savoir la signification de quelques paramètres ( Sens ? ), et comment les calculer ( tous ) ( en PHP théoriquement ) :

Code:
User timing category
********************
Required for timing hit type.
-----------------------------
Specifies the user timing category.  ( Sens ? )
utc    text    None    150 Bytes    timing
Example value: category


User timing variable name
*************************
Required for timing hit type.
-----------------------------
Specifies the user timing variable. ( Sens ? )
utv    text    None    500 Bytes    timing
Example value: lookup


User timing time
****************
Required for timing hit type.
-----------------------------
Specifies the user timing value. The value is in milliseconds. ( Sens ? )
utt    integer    None    None    timing
Example value: 123


User timing label
*****************
Optional.
---------
Specifies the user timing label.  ( Sens ? ) 
utl    text    None    500 Bytes    timing
Example value: label


Page Load Time
**************
Optional.
---------
Specifies the time it took for a page to load. The value is in milliseconds.
plt    integer    None    None    timing
Example value: 3554


DNS Time
********
Optional.
---------
Specifies the time it took to do a DNS lookup.The value is in milliseconds.
Example value: 43


Page Download Time
******************
Optional.
---------
Specifies the time it took for the page to be downloaded. The value is in milliseconds.
pdt    integer    None    None    timing
Example value: 500


Redirect Response Time
**********************
Optional.
---------
Specifies the time it took for any redirects to happen. The value is in milliseconds.
rrt    integer    None    None    timing
Example value: 500


TCP Connect Time
****************
Optional.
---------
Specifies the time it took for a TCP connection to be made. The value is in milliseconds.
tcp    integer    None    None    timing
Example value: 500


Server Response Time
********************
Optional.
---------
Specifies the time it took for the server to respond after the connect time. The value is in milliseconds.
srt    integer    None    None    timing
Example value: 500


DOM Interactive Time
********************
Optional.
---------
Specifies the time it took for Document.readyState to be 'interactive'. The value is in milliseconds.
dit    integer    None    None    timing
Example value: 500


Content Load Time
*****************
Optional.
---------
Specifies the time it took for the DOMContentLoaded Event to fire. The value is in milliseconds.
clt    integer    None    None    timing
Example value: 500


Merci beaucoup de votre aide.

J'espère que les réponses aideront aussi d'autres Wrinautes.

Respectueusement.
 
WRInaute accro
Rebonjour

Seulement pour les trois variables ci-dessous( required ), j'aurais besoin de savoir leur signification, et la manière de les calculer.

Pour l'instant, mon implémentation est en PHP, mais bon si Javascript est obligatoire pour les calculs je serai bien obligé de m'y mettre.

Merci à vous pour vos réponses.

Respectueusement.


Code:
User timing category
********************
Required for timing hit type.
-----------------------------
Specifies the user timing category.
utc    text    None    150 Bytes    timing
Example value: category


User timing variable name
*************************
Required for timing hit type.
-----------------------------
Specifies the user timing variable.
utv    text    None    500 Bytes    timing
Example value: lookup


User timing time
****************
Required for timing hit type.
-----------------------------
Specifies the user timing value. The value is in milliseconds.
utt    integer    None    None    timing
Example value: 123
 
WRInaute accro
Je vous demande pardon. ;(

Toutes les infos se trouvent dans la NavigationTiming API.

Si vous voulez, je fais mon implémentation ( très réduite ), et je vous la donne asap.

Respectueusement.
 
WRInaute accro
Bonjour

Merci de corriger :

JavaScript:
var t = window.performance.timing;                      // Instance de Performance.Timing.
var utc = 'all_timing';                                 // Category.
var utv = 'lookup';                                     // Var Name.
var utt = t.domContentLoadedEventStart - t.fetchStart;  // User Timing Time.
var utl = 'label';                                      // Label.
var plt = t.domContentLoadedEventStart - t.domLoading;  // Page Load Time.
var dns = t.domainLookupEnd - t.domainLookupStart;      // DNS Time.
var pdt = t.loadEventEnd - t.loadEventStart;            // Page Download Time.
var rrt = t.redirectEnd - t.redirectStart;              // Redirect Response Time.
var tcp = t.connectEnd - t.connectStart;                // TCP Connect Time.
var srt = t.responseStart - t.requestStart;             // Server Response Time.
var dit = t.domInteractive - t.domLoading;              // DOM Interactive Time.
var clt = t.domContentLoadedEventEnd - t.domContentLoadedEventStart;    // Content Load Time.
 
WRInaute accro
Rebonjour

Pour le reste çà va à peu près.

Le code suivant est-il correct ?

Code:
var t = window.performance.timing;
var utt = t.domContentLoadedEventStart - t.fetchStart;  // User Timing Time.


Merci.
 
WRInaute accro
Bonjour

Voici le test sur localhost :


Code:
       var t = window.performance.timing;                      // Instance de Performance.Timing.\n";
       var utc = 'all_timing';                                 // Category.\n";
       var utv = 'load';                                       // Var Name.\n";
       var utt = t.domInteractive - t.navigationStart; // User Timing Time.\n";
       var utl = 'label';                                      // Label.\n";
       var plt = t.domContentLoadedEventStart - t.domLoading;  // Page Load Time.\n";
       var dns = t.domainLookupEnd - t.domainLookupStart;      // DNS Time.\n";
       var pdt = t.loadEventEnd - t.loadEventStart;            // Page Download Time.\n";
       var rrt = t.redirectEnd - t.redirectStart;              // Redirect Response Time.\n";
       var tcp = t.connectEnd - t.connectStart;                // TCP Connect Time.\n";
       var srt = t.responseStart - t.requestStart;             // Server Response Time.\n";
       var dit = t.domInteractive - t.domLoading;              // DOM Interactive Time.\n";
      var clt = t.domContentLoadedEventEnd - t.domContentLoadedEventStart;    // Content Load Time.\n";

Je loggue le request :

utc=all_timing&utv=load&utt=1750&utl=label&plt=164&dns=0&pdt=-1528368997421&rrt=0&tcp=0&srt=1551&dit=164&clt=0

N'y a-t-il pas des erreurs ?

Merci beaucoup de votre aide.

Amicalement.
 
Discussions similaires
Haut