1

我想让网站用户在检查大型网站上的 CSP 设置方面“完成工作”,方法是让 Google Analytics Events 从浏览器调用csp-report.php但努力弄清楚如何检查代码。

它运行时没有记录错误,但没有推送任何事件。有没有人有提示,所以我可以推送控制台或服务器日志?或者可能在代码中发现了问题?

<?php
/* Thanks to
    Stu Miller – Web Consultant, WordPress developer/specialist based in Leeds, UK
    http://www.stumiller.me/implementing-google-analytics-measurement-protocol-in-php-and-wordpress/

    Amit Agarwal
    http://ctrlq.org/code/19011-google-analytics-php

    Ani Lopez
    http://dynamical.biz/blog/technical-analytics/tracking-ga-user-id-72.html

    Cardinal Path
    http://www.cardinalpath.com/ga-basics-the-structure-of-cookie-values/
*/

/* Transmitted JSON on CSP validation
{
    "csp-report": {
        "document-uri": "http://example.org/page.html",
        "referrer": "http://evil.example.com/",
        "blocked-uri": "http://evil.example.com/evil.js",
        "violated-directive": "script-src "self" https://apis.google.com",
        "original-policy": "script-src "self" https://apis.google.com; report-uri http://example.org/my_amazing_csp_report_parser"
    }
} */

// 1st Receive and store CSP message as string in temporary variable
$c = file_get_contents("php://input");

if (!$c)
    // Send GA-Event for empty JSON?
    exit;

// 2nd convert string to array
$c = json_decode($c, true);

/* 3rd get Google Analytics Client ID from "_ga" cookie
    https://developers.google.com/analytics/devguides/collection/protocol/v1/reference
    https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage#gajs
    GA#.#.[User ID].[Time Stamp]
    http://ctrlq.org/code/19011-google-analytics-php
*/
function gaParseCookie() {
    if (isset($_COOKIE["_ga"])) {
        list($version, $domainDepth, $cid1, $cid2) = split("[\.]", $_COOKIE["_ga"],4);
        $contents = array("version" => $version, "domainDepth" => $domainDepth, "cid" => $cid1.".".$cid2);
        $cid = $contents["cid"];
    } else $cid = gaGenUUID(); // Fallback
    return $cid;
}

// Generate UUID v4 function - needed to generate a CID when one isn"t available
function gaGenUUID() {
    return sprintf( "%04x%04x-%04x-%04x-%04x-%04x%04x%04x",
    // 32 bits for "time_low"
    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
    // 16 bits for "time_mid"

    mt_rand( 0, 0xffff ),
    // 16 bits for "time_hi_and_version",
    // four most significant bits holds version number 4
    mt_rand( 0, 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
    mt_rand( 0, 0x3fff ) | 0x8000,

    // 48 bits for "node"
    mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}

/* 4th match document URI with UA-String to send GA-Event to corresponding GA property */
function uaString () {
    $documentUri = $c(["csp-report"]["document-uri"]);
    switch($documentUri) {
        case (preg_match('/^(https?:\/\/)?.*mikeg.de', $documentUri) ? true : false) :
            $analyticsUA = "UA-9315806-2";
            break;
        case (preg_match('/John.*/', $documentUri) ? true : false) :
            $analyticsUA = "";
            break;
    }
    return $analyticsUA;
}

/* 5th Send GA Event via Measurement Protocol
    Google Analytics Hit Builder: https://ga-dev-tools.appspot.com/hit-builder/
    URL-Schemata: v=1&t=event&tid=UA-XXXXX-Y&cid=[Client ID form 1st party Cookie]&ec=[Event Category]&ea=[Event Action]&el=[Event Label]&ev=[Event label]
*/
function gaBuildHit( $method = null, $info = null ) {
    if ( $method && $info) {
        $data = [
            $v = 1,
            $t=event,
            $tid = $analyticsUA, // Put your own Analytics ID in here
            $cid = gaParseCookie(),
            $ec = "CSP-Error" + $c(["csp-report"]["effective-directive"]),
            $ea = $c(["csp-report"]["violated-directive"]),
            $el = $c(["csp-report"]["original-policy"]),
            $dl = $c(["csp-report"]["document-uri"])
        ];

        gaFireHit($data);
    }
}

// See https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
function gaFireHit( $data = null ) {
    if ( $data ) {
        $getString = 'https://ssl.google-analytics.com/collect';
        $getString .= '?payload_data&';
        $getString .= http_build_query($data);
        $result = wp_remote_get( $getString );
        #$sendlog = error_log($getString, 1, "ME@EMAIL.COM"); // comment this in and change your email to get an log sent to your email
        return $result;
    }
    return false;
}

/* fallback: write CSP violation to server file
    http://php.net/manual/en/function.syslog.php
*/
//file_put_contents("csp.errors", $c, FILE_APPEND);
?>

非常感谢。麦克风。

4

0 回答 0