├── .gitignore ├── .editorconfig ├── ganalytics.yaml ├── LICENSE ├── languages ├── es.yaml ├── en.yaml └── de.yaml ├── CHANGELOG.md ├── blueprints.yaml ├── README.md └── ganalytics.php /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # top-most EditorConfig file 2 | root = true 3 | 4 | # All files 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | indent_style = space 11 | indent_size = 2 12 | 13 | # 4 space indentation for PHP 14 | [{*.php,*.inc}] 15 | indent_style = space 16 | indent_size = 4 17 | -------------------------------------------------------------------------------- /ganalytics.yaml: -------------------------------------------------------------------------------- 1 | enabled: true # Global enable/disable the entire plugin 2 | trackingId: "" # GA Tracking ID `REQUIRED` 3 | 4 | position: "head" # Code Position in the HTML document 5 | objectName: "gtag" # Name for the global (gtag) object 6 | dnt: true # Respect Do Not Track header 7 | blockedIps: [] # Array of blocked IP addresses 8 | blockedIpRanges: ["private", "loopback", "link-local"] # Array of blocked IP address ranges 9 | blockingCookie: "blockGA" # Name of a cookie blocking GA tracking 10 | 11 | cookieConfig: false # Use custom cookie configuration 12 | cookiePrefix: "" # Cookie name prefix 13 | cookieDomain: "" # Cookie domain 14 | cookieExpires: 63072000 # Expiration time in seconds (Default: 2 years) 15 | 16 | optOutEnabled: false # enable opt out function 17 | optOutMessage: "" # confirmation message on opt out 18 | 19 | debugMode: false # Enable/disable Debugging 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 John Linhart (admin@escope.cz), Christian Worreschk (cw@marsec.de) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /languages/es.yaml: -------------------------------------------------------------------------------- 1 | PLUGIN_GANALYTICS: 2 | _YES: "Sí" #BUG: Only "YES" or "NO" will not work! 3 | _NO: "No" #BUG: Only "YES" or "NO" will not work! 4 | ENABLED: "Activo" 5 | DISABLED: "Inactivo" 6 | PLUGIN_STATUS: "Estado del Complemento" 7 | SECONDS: "segundos" 8 | SECTION_CONFIGURATION: "Configuración" 9 | SECTION_ADVANCED: "Avanzada" 10 | SECTION_COOKIE: "Cookie" 11 | SECTION_OPTOUT: "Optar por no" 12 | SECTION_DEBUG: "Depuración" 13 | TRACKING_ID: "ID Seguimiento" 14 | TRACKING_ID_HELP: "ID Seguimiento estadísticas Google" 15 | POSITION: "Posición del Código" 16 | POSITION_HELP: "Posición del código en el documento HTML (cabecera o cuerpo)" 17 | POSITION_HEAD: "Cabecera" 18 | POSITION_BODY: "Final del cuerpo" 19 | OBJECT_NAME: "Objeto (gtag) global" 20 | OBJECT_NAME_HELP: "Renombrar el objeto (gtag) global de las estadísticas Google" 21 | DNT: "Compatibilidad con el encabezado \"Do Not Track\"" 22 | DNT_HELP: "Cuando está habilitado, el código de Google Analytics no se incrustará si un cliente envía el encabezado \"Do Not Track\"" 23 | BLOCKED_IPS: "Direcciones IP bloquedas" 24 | BLOCKED_IPS_HELP: "Para estas direcciones IP no se cargará el seguimiento de las estadísticas Google" 25 | COOKIE_CONFIG: "Configuración Personalizada" 26 | COOKIE_CONFIG_HELP: "Utilizar un cookie personalizado en vez del por defecto" 27 | COOKIE_PREFIX: "Prefijo del nombre" 28 | COOKIE_PREFIX_HELP: "Se añadirá un prefijo al nombre de la cookie de Google Analytics" 29 | COOKIE_DOMAIN: "Dominio" 30 | COOKIE_DOMAIN_HELP: "El dominio del cookie. Por defecto se utilizará el hostname de la URL actual" 31 | COOKIE_EXPIRES: "Caduca" 32 | COOKIE_EXPIRES_HELP: "El tiempo de caducidad del cookie para las estadísticas Google. Por defecto es dos años" 33 | DEBUG_MODE: "Modo depuración" 34 | DEBUG_MODE_HELP: "Habilite para enviar eventos a DebugView en la consola de Google Analytics" 35 | OPTOUT_STATUS: "Optar por no" 36 | OPTOUT_STATUS_HELP: "Los visitantes pueden desactivar el seguimiento de Google Analytics" 37 | OPTOUT_MESSAGE: "Confirmación en optar por no" 38 | OPTOUT_MESSAGE_HELP: "Confirmación mostrada cuando el seguimiento está desactivado" 39 | OPTOUT_HINT: "Para que sus visitantes puedan desactivar el seguimiento de Google Analytics, active "opt out" aquí e inserte el siguiente enlace en algún lugar de sus páginas:" 40 | OPTOUT_LINK: "Enlace de exclusión voluntaria" 41 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # v2.1.0 2 | ## 06/19/2023 3 | 4 | 1. [](#new) 5 | * Added "Do Not Track" header support which is enabled by default 6 | 2. [](#bugfix) 7 | * Fixed opt-out dialog output when confirmation message contains quotes 8 | * Fixed opt-out section title translation 9 | * Fixed an issue which prevented being able to install this plugin via `bin/gpm direct-install` command 10 | 11 | # v2.0.0 12 | ## 06/09/2023 13 | 14 | 1. [](#new) 15 | * BREAKING CHANGE! The plugin now uses Google Analytics 4 API, which is not compatible with an old Universal Analytics functionality. You must migrate your existing Universal Analytics properties to Google Analytics 4 data streams before performing the upgrade. Please, read upgrade section in the [README](https://github.com/escopecz/grav-ganalytics/blob/master/README.md#upgrading-from-1x) file for the detailed steps. 16 | 17 | # v1.5.2 18 | ## 03/10/2023 19 | 20 | 1. [](#bugfix) 21 | * Fixed changelog formating 22 | 23 | # v1.5.1 24 | ## 03/10/2023 25 | 26 | 1. [](#bugfix) 27 | * Fix previously broken 1.5.0 release 28 | 29 | # v1.5.0 30 | ## 09/22/2019 31 | 32 | 1. [](#new) 33 | * Added support for environment variables 34 | * Add capabilities to block address ranges and use a blocking cookie 35 | * Opt out code added 36 | 2. [](#improved) 37 | * Changes for General Data Protection Regulation (GDPR) 38 | 39 | # v1.4.0 40 | ## 01/04/2017 41 | 42 | 1. [](#new) 43 | * Preload the Google Analytics script asynchronously 44 | * Choose the code position in the HTML document (head or body) 45 | * Custom Cookie Configuration. Name, domain and expiration time are configurable. 46 | * Force SSL - Send all data using SSL, even from insecure (HTTP) pages 47 | 2. [](#improved) 48 | * Improve plugin configuration with tab views. 49 | * Better use and configuration of the global object name. Please use `objectName` instead of `renameGa`. 50 | 51 | # v1.3.0 52 | ## 12/21/2016 53 | 54 | 1. [](#new) 55 | * Block IP addresses (_Google Analytics code will not be embedded_) 56 | 2. [](#improved) 57 | * Added german translation 58 | 3. [](#bugfix) 59 | * Fixed the date format in the changelog 60 | 61 | # v1.2.0 62 | ## 08/11/2016 63 | 64 | 1. [](#new) 65 | * Rename the global (ga) variable of the Google Analytics object 66 | * Enable the debug version of the analytics.js library + Trace Debugging 67 | 68 | # v1.1.0 69 | ## 08/02/2016 70 | 71 | 1. [](#new) 72 | * Anonymize the IP address sent to Google Analytics 73 | 74 | # v1.0.0 75 | ## 11/08/2015 76 | 77 | 1. [](#new) 78 | * GA Plugin started 79 | -------------------------------------------------------------------------------- /languages/en.yaml: -------------------------------------------------------------------------------- 1 | PLUGIN_GANALYTICS: 2 | _YES: "Yes" #BUG: Only "YES" or "NO" will not work! 3 | _NO: "No" #BUG: Only "YES" or "NO" will not work! 4 | ENABLED: "Enabled" 5 | DISABLED: "Disabled" 6 | PLUGIN_STATUS: "Plugin status" 7 | SECONDS: "seconds" 8 | SECTION_CONFIGURATION: "Configuration" 9 | SECTION_ADVANCED: "Advanced" 10 | SECTION_COOKIE: "Cookie" 11 | SECTION_OPTOUT: "Opt-Out" 12 | SECTION_DEBUG: "Debug" 13 | TRACKING_ID: "Tracking ID" 14 | TRACKING_ID_HELP: "Google Analytics Tracking ID" 15 | POSITION: "Code Position" 16 | POSITION_HELP: "Code Position in the HTML document (head or body)" 17 | POSITION_HEAD: "Head" 18 | POSITION_BODY: "End of Body" 19 | OBJECT_NAME: "Global (gtag) Object" 20 | OBJECT_NAME_HELP: "Rename the global (gtag) variable of the Google Analytics object" 21 | DNT: "\"Do Not Track\" header support" 22 | DNT_HELP: "When enabled, Google Analytics code will not be embedded if a client sends \"Do Not Track\" header" 23 | BLOCKED_IPS: "Blocked IP addresses" 24 | BLOCKED_IPS_HELP: "For the given IP addresses the Google Analytics code will not be embedded" 25 | BLOCKED_IP_RANGES: "Blocked IP address ranges" 26 | BLOCKED_IP_RANGES_HELP: "For the given IPv4 or IPv6 address ranges the Google Analytics code will not be embedded" 27 | BLOCKED_IP_RANGES_VALUE: "IP range (e.g. '10.4.3.1-10.4.3.20')" 28 | BLOCKING_COOKIE: "Blocking cookie" 29 | BLOCKING_COOKIE_HELP: "Name of a blocking cookie, which, when set, prevents Google Analytics code being embedded" 30 | COOKIE_CONFIG: "Custom Configuration" 31 | COOKIE_CONFIG_HELP: "Use a custom cookie configuration instead of the default one" 32 | COOKIE_PREFIX: "Name prefix" 33 | COOKIE_PREFIX_HELP: "Prefix will be added to the name of the Google Analytics cookie" 34 | COOKIE_DOMAIN: "Domain" 35 | COOKIE_DOMAIN_HELP: "The Cookie domain. Default is the hostname of the current URL" 36 | COOKIE_EXPIRES: "Expires" 37 | COOKIE_EXPIRES_HELP: "The expiration time of the Google Analytics cookie. Default is two years" 38 | DEBUG_MODE: "Debug Mode" 39 | DEBUG_MODE_HELP: "Enable to send events to DebugView in the Google Analytics console" 40 | OPTOUT_STATUS: "Tracking opt-out" 41 | OPTOUT_STATUS_HELP: "Visitor can disable tracking by Google Analytics" 42 | OPTOUT_MESSAGE: "Confirmation on opt-out" 43 | OPTOUT_MESSAGE_HELP: "Confirmation message shown to the visitor when she/he disables tracking" 44 | OPTOUT_HINT: "To give your users the possibility to disable Google Analytics tracking you have to enable "opt-out" here and put the following link somewhere in your pages:" 45 | OPTOUT_LINK: "Opt-out link" 46 | -------------------------------------------------------------------------------- /languages/de.yaml: -------------------------------------------------------------------------------- 1 | PLUGIN_GANALYTICS: 2 | _YES: "Ja" #BUG: Only "YES" or "NO" will not work! 3 | _NO: "Nein" #BUG: Only "YES" or "NO" will not work! 4 | ENABLED: "Aktiviert" 5 | DISABLED: "Deaktiviert" 6 | PLUGIN_STATUS: "Plugin Status" 7 | SECONDS: "Sekunden" 8 | SECTION_CONFIGURATION: "Einstellungen" 9 | SECTION_ADVANCED: "Erweitert" 10 | SECTION_COOKIE: "Cookie" 11 | SECTION_OPTOUT: "Ablehnen" 12 | SECTION_DEBUG: "Debugging" 13 | TRACKING_ID: "Tracking-ID" 14 | TRACKING_ID_HELP: "Google Analytics Tracking-ID" 15 | POSITION: "Code-Position" 16 | POSITION_HELP: "Position des Codes im HTML-Dokument (Head oder Body)" 17 | POSITION_HEAD: "Kopf" 18 | POSITION_BODY: "Inhaltsende" 19 | OBJECT_NAME: "Globales (gtag) Objekt" 20 | OBJECT_NAME_HELP: "Variablenname des globalen Google Analytics Objekts (gtag)" 21 | DNT: "Unterstützung für \"Do Not Track\"-Header" 22 | DNT_HELP: "Wenn diese Option aktiviert ist, wird der Google Analytics-Code nicht eingebettet, wenn ein Kunde den \"Do Not Track\"-Header sendet" 23 | BLOCKED_IPS: "Gesperrte IP-Adressen" 24 | BLOCKED_IPS_HELP: "Für die angegebenen IP-Adressen wird der Google Analytics Code nicht eingebunden" 25 | BLOCKED_IP_RANGES: "Gesperrte IP-Adressbereiche" 26 | BLOCKED_IP_RANGES_HELP: "Für die angegebenen IPv4- oder IPv6-Adressbereiche wird der Google Analytics Code nicht eingebunden" 27 | BLOCKED_IP_RANGES_VALUE: "Bereich (z.B. '10.4.3.1-10.4.3.20')" 28 | BLOCKING_COOKIE: "Sperr-Cookie" 29 | BLOCKING_COOKIE_HELP: "Name eines Sperr-Cookies, der - wenn gesetzt - die Einbindung von Google Analytics Code verhindert" 30 | COOKIE_CONFIG: "Eigene Konfiguration" 31 | COOKIE_CONFIG_HELP: "Soll eine eigene Cookie-Konfiguration oder die von Google Analytics genutzt werden" 32 | COOKIE_PREFIX: "Namenspräfix" 33 | COOKIE_PREFIX_HELP: "Dem Namen des Google Analytics Cookie wird ein Präfix hinzugefügt" 34 | COOKIE_DOMAIN: "Domain" 35 | COOKIE_DOMAIN_HELP: "Cookie Domain. Standardmäßig wird der Host-Name der aktuellen URL benutzt" 36 | COOKIE_EXPIRES: "Läuft ab" 37 | COOKIE_EXPIRES_HELP: "Die Ablaufzeit des Google Analytics Cookie. Standard sind zwei Jahre" 38 | DEBUG_MODE: "Debug-Modus" 39 | DEBUG_MODE_HELP: "Aktivieren Sie diese Option, um Ereignisse an DebugView in der Google Analytics-Konsole zu senden" 40 | OPTOUT_STATUS: "Tracking Opt-Out" 41 | OPTOUT_STATUS_HELP: "Besucher können das Tracking durch Google Analytics abschalten" 42 | OPTOUT_MESSAGE: "Bestätigung beim Opt-Out" 43 | OPTOUT_MESSAGE_HELP: "Angezeigte Bestätigung, wenn Tracking abgeschaltet wird" 44 | OPTOUT_HINT: "Damit Ihre Besucher Google Analytics Tracking abschalten können müssen Sie "opt out" hier aktivieren und den folgenden Link irgendwo auf Ihren Seiten einfügen:" 45 | OPTOUT_LINK: "Opt-Out-Link" 46 | -------------------------------------------------------------------------------- /blueprints.yaml: -------------------------------------------------------------------------------- 1 | name: Google Analytics 2 | type: plugin 3 | slug: ganalytics 4 | version: 2.1.0 5 | description: "Easily integrate and configure Google Analytics without the need to touch any code within your Grav site." 6 | icon: google 7 | author: 8 | name: John Linhart 9 | email: admin@escope.cz 10 | url: http://johnlinhart.com 11 | homepage: https://github.com/escopecz/grav-ganalytics 12 | keywords: google, plugin, tracking, analytics, grav 13 | bugs: https://github.com/escopecz/grav-ganalytics/issues 14 | docs: https://github.com/escopecz/grav-ganalytics/blob/master/README.md 15 | license: MIT 16 | 17 | form: 18 | validation: strict 19 | fields: 20 | 21 | tabs: 22 | type: tabs 23 | active: 1 24 | class: subtle 25 | 26 | fields: 27 | 28 | configuration: 29 | type: tab 30 | title: PLUGIN_GANALYTICS.SECTION_CONFIGURATION 31 | fields: 32 | 33 | enabled: 34 | type: toggle 35 | label: PLUGIN_GANALYTICS.PLUGIN_STATUS 36 | hightlight: 1 37 | default: 0 38 | options: 39 | 1: PLUGIN_GANALYTICS.ENABLED 40 | 0: PLUGIN_GANALYTICS.DISABLED 41 | validate: 42 | type: bool 43 | 44 | trackingId: 45 | type: text 46 | size: medium 47 | label: PLUGIN_GANALYTICS.TRACKING_ID 48 | help: PLUGIN_GANALYTICS.TRACKING_ID_HELP 49 | placeholder: "G-XXXXXXXXXX" 50 | validate: 51 | required: true 52 | 53 | advanced: 54 | type: section 55 | title: PLUGIN_GANALYTICS.SECTION_ADVANCED 56 | underline: true 57 | fields: 58 | 59 | position: 60 | type: toggle 61 | label: PLUGIN_GANALYTICS.POSITION 62 | help: PLUGIN_GANALYTICS.POSITION_HELP 63 | hightlight: 1 64 | default: head 65 | options: 66 | head: PLUGIN_GANALYTICS.POSITION_HEAD 67 | body: PLUGIN_GANALYTICS.POSITION_BODY 68 | validate: 69 | type: string 70 | 71 | objectName: 72 | type: text 73 | label: PLUGIN_GANALYTICS.OBJECT_NAME 74 | help: PLUGIN_GANALYTICS.OBJECT_NAME_HELP 75 | size: small 76 | default: "gtag" 77 | 78 | dnt: 79 | type: toggle 80 | label: PLUGIN_GANALYTICS.DNT 81 | help: PLUGIN_GANALYTICS.DNT_HELP 82 | hightlight: 1 83 | default: 1 84 | options: 85 | 1: PLUGIN_GANALYTICS.ENABLED 86 | 0: PLUGIN_GANALYTICS.DISABLED 87 | validate: 88 | type: bool 89 | 90 | blockedIps: 91 | type: array 92 | size: large 93 | label: PLUGIN_GANALYTICS.BLOCKED_IPS 94 | help: PLUGIN_GANALYTICS.BLOCKED_IPS_HELP 95 | value_only: true 96 | 97 | blockedIpRanges: 98 | type: array 99 | size: large 100 | label: PLUGIN_GANALYTICS.BLOCKED_IP_RANGES 101 | help: PLUGIN_GANALYTICS.BLOCKED_IP_RANGES_HELP 102 | placeholder_value: PLUGIN_GANALYTICS.BLOCKED_IP_RANGES_VALUE 103 | value_only: true 104 | 105 | blockingCookie: 106 | type: text 107 | label: PLUGIN_GANALYTICS.BLOCKING_COOKIE 108 | help: PLUGIN_GANALYTICS.BLOCKING_COOKIE_HELP 109 | size: small 110 | default: "blockGA" 111 | 112 | cookie: 113 | type: tab 114 | title: PLUGIN_GANALYTICS.SECTION_COOKIE 115 | fields: 116 | cookieConfig: 117 | type: toggle 118 | label: PLUGIN_GANALYTICS.COOKIE_CONFIG 119 | help: PLUGIN_GANALYTICS.COOKIE_CONFIG_HELP 120 | hightlight: 1 121 | default: 0 122 | options: 123 | 1: PLUGIN_GANALYTICS._YES 124 | 0: PLUGIN_GANALYTICS._NO 125 | validate: 126 | type: bool 127 | 128 | cookiePrefix: 129 | type: text 130 | label: PLUGIN_GANALYTICS.COOKIE_PREFIX 131 | help: PLUGIN_GANALYTICS.COOKIE_PREFIX_HELP 132 | size: small 133 | default: "" 134 | 135 | cookieDomain: 136 | type: text 137 | label: PLUGIN_GANALYTICS.COOKIE_DOMAIN 138 | help: PLUGIN_GANALYTICS.COOKIE_DOMAIN_HELP 139 | size: medium 140 | 141 | cookieExpires: 142 | type: text 143 | size: small 144 | label: PLUGIN_GANALYTICS.COOKIE_EXPIRES 145 | help: PLUGIN_GANALYTICS.COOKIE_EXPIRES_HELP 146 | append: PLUGIN_GANALYTICS.SECONDS 147 | default: 63072000 148 | validate: 149 | type: number 150 | min: 0 151 | 152 | optout: 153 | type: tab 154 | title: PLUGIN_GANALYTICS.SECTION_OPTOUT 155 | fields: 156 | hint: 157 | type: spacer 158 | text: PLUGIN_GANALYTICS.OPTOUT_HINT 159 | underline: false 160 | 161 | linkhint: 162 | type: display 163 | size: large 164 | label: PLUGIN_GANALYTICS.OPTOUT_LINK 165 | markdown: true 166 | content: "`Disable Google Analytics ...`" 167 | 168 | optOutEnabled: 169 | type: toggle 170 | label: PLUGIN_GANALYTICS.OPTOUT_STATUS 171 | help: PLUGIN_GANALYTICS.OPTOUT_STATUS_HELP 172 | hightlight: 0 173 | default: 0 174 | options: 175 | 1: PLUGIN_GANALYTICS.ENABLED 176 | 0: PLUGIN_GANALYTICS.DISABLED 177 | validate: 178 | type: bool 179 | 180 | optOutMessage: 181 | type: text 182 | label: PLUGIN_GANALYTICS.OPTOUT_MESSAGE 183 | help: PLUGIN_GANALYTICS.OPTOUT_MESSAGE_HELP 184 | size: medium 185 | default: "Google tracking is now disabled." 186 | 187 | debug: 188 | type: tab 189 | title: PLUGIN_GANALYTICS.SECTION_DEBUG 190 | fields: 191 | debugMode: 192 | type: toggle 193 | label: PLUGIN_GANALYTICS.DEBUG_MODE 194 | help: PLUGIN_GANALYTICS.DEBUG_MODE_HELP 195 | hightlight: 1 196 | default: 0 197 | options: 198 | 1: PLUGIN_GANALYTICS.ENABLED 199 | 0: PLUGIN_GANALYTICS.DISABLED 200 | validate: 201 | type: bool 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Grav Google Analytics Plugin 2 | 3 | The **Google Analytics** Plugin for [Grav CMS](http://github.com/getgrav/grav) allows you to integrate and configure [Google Analytics](https://www.google.com/analytics) without the need to touch any code within your Grav site. 4 | 5 | ### Features 6 | * Choose the Google Analytics code position in the HTML document (head or body). 7 | * Renaming of the Global (gtag) Object 8 | * Debug Mode 9 | * Custom Cookie Configuration. Name prefix, domain and expiration time are configurable. 10 | * DNT header support 11 | * Blocking IP Addresses 12 | * Opt Out (disable tracking by the user) 13 | * Multi-Language Support for the [Grav Administration Panel](https://github.com/getgrav/grav-plugin-admin) 14 | 15 | ## Installation 16 | 17 | Installing the Google Analytics plugin can be done in one of two ways. The GPM (Grav Package Manager) installation method enables you to quickly and easily install the plugin with a simple terminal command, while the manual method enables you to do so via a zip file. 18 | 19 | ### GPM Installation (Preferred) 20 | 21 | The simplest way to install this plugin is via the [Grav Package Manager (GPM)](https://learn.getgrav.org/advanced/grav-gpm) through your system's terminal (also called the command line). From the root of your Grav install type: 22 | 23 | bin/gpm install ganalytics 24 | 25 | This will install the Google Analytics plugin into your `/user/plugins` directory within Grav. Its files can be found under `/your/site/grav/user/plugins/ganalytics`. 26 | 27 | ### Manual Installation 28 | 29 | To install this plugin, just download the zip version of this repository and unzip it under `/your/site/grav/user/plugins`. Then, rename the folder to `ganalytics`. You can find these files on [GitHub](https://github.com/escopecz/grav-ganalytics) or via [GetGrav.org](https://getgrav.org/downloads/plugins). 30 | 31 | You should now have all the plugin files under 32 | 33 | /your/site/grav/user/plugins/ganalytics 34 | 35 | > NOTE: This plugin is a modular component for Grav which requires [Grav](http://github.com/getgrav/grav) to operate. 36 | 37 | ## Configuration 38 | 39 | Before configuring this plugin, you should copy the `user/plugins/ganalytics/ganalytics.yaml` to `user/config/plugins/ganalytics.yaml` and only edit that copy. 40 | 41 | Here is the default configuration and an explanation of available options: 42 | 43 | ```yaml 44 | enabled: true 45 | trackingId: "" 46 | 47 | position: "head" 48 | objectName: "gtag" 49 | dnt: true 50 | blockedIps: [] 51 | blockedIpRanges: ["private", "loopback", "link-local"] 52 | blockingCookie: "blockGA" 53 | 54 | cookieConfig: false 55 | cookiePrefix: "" 56 | cookieDomain: "" 57 | cookieExpires: 63072000 58 | 59 | optOutEnabled: false 60 | optOutMessage: "Google tracking is now disabled." 61 | 62 | debugMode: false 63 | ``` 64 | 65 | * `enabled` Toggles if the Google Analytics plugin is turned on or off. 66 | * `trackingId` The Google Analytics Tracking ID. This value is **required**. 67 | _(You can also use environment variables by entering `env:VAR_NAME` as value)_ 68 | * `position` Code Position in the HTML document (`head` or `body`). Default is `head`. 69 | * `objectName` The name for the global (gtag) object. Default is `gtag`. 70 | * `dnt` Enables [Do Not Track header](https://www.w3.org/TR/tracking-dnt/#dnt-header-field) support. When enabled, Google Analytics code will not be embedded if a client sends DNT header. Most browsers do not send this header by default. Header support in the plugin is `enabled` by default though. 71 | * `blockedIps` Here you can blacklist IP addresses. For those the Google Analytics script will not be embedded. 72 | * `blockedIpRanges` Here you can blacklist IPv4 and/or IPv6 address ranges in the form `["192.177.204.1-192.177.204.254", "2001:db8::1-2001:db8::fe", ...]`. In addition to numerical ranges, the keywords "private", "loopback", "link-local" designate special IPv4 and IPv6 ranges (see RFCs 6890, 4193, 4291). For blacklisted ranges the Google Analytics script will not be embedded. By default, all three ranges are blocked. If you are using a reverse proxy that redirects traffic to the grav installation, you may need to remove "private". 73 | * `blockingCookie` The name of a blocking cookie. When such a cookie is set, the Google Analytics script will not be embedded. Default ist `blockGA` 74 | 75 | * `cookieConfig`: Toggles if the a custom cookie configuration should be used. 76 | * `cookiePrefix` The cookie name prefix. 77 | * `cookieDomain` The cookie domain. Optional, Google default is top level domain plus one subdomain (eTLD +1). For example Grav site under https://example.com would use example.com for the cookie domain, and https://subdomain.example.com would also use example.com for the cookie domain. 78 | * `cookieExpires` The cookie expiration time in seconds. Google default is 2 years (`63072000` seconds) 79 | 80 | * `optOutEnabled` Toggles if opt out function is turned on or off. 81 | * `optOutMessage` Confirmation message shown to the user when opt out function is called 82 | 83 | * `debugMode` Toggles if Google Analytics debug mode is enabled or disabled. 84 | 85 | ## Usage 86 | 87 | 1. Sign in to your [Google Analytics account](https://analytics.google.com/). 88 | 2. Select the **Admin** tab. 89 | 3. Select an account from the dropdown in the _ACCOUNT_ column. 90 | 4. Select a property from the dropdown in the _PROPERTY_ column. 91 | 5. Under _PROPERTY_, click **Data Streams > you_data_stream_name**. 92 | 6. Copy the **MEASUREMENT ID** (a string like _G-XXXXXXXXXX_) 93 | 7. Add it to the configuration of this plugin. 94 | 95 | To give your users the possibility to disable Google Analytics tracking you have to enable "opt out" in this plugin and put the following link somewhere in your pages, e.g. in your Privacy Declaration: 96 | 97 | ```html 98 | Disable Google Analytics 99 | ``` 100 | 101 | The link must be inserted as HTML tags and not in markdown syntax. 102 | When this link is clicked, then the official ga-disable-cookie is set and Google stopps tracking this visitor. 103 | For more Info about disabling the Google Analytics tracking see: https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out 104 | 105 | ## Upgrading from 1.x 106 | 107 | First versions of the plugin were compatible only with Universal Analytics (analytics.js). Version 2.0 onwards only supports Google Analytics 4 (gtag.js). Universal Analytics is no longer supported. This means you have to migrate your Universal Analytics properties to Google Analytics 4 data streams before performing the upgrade. 108 | 109 | 1. Sign in to your [Google Analytics account](https://analytics.google.com/) and migrate a property used by this plugin to GA4 data stream. Keep in mind that GA4 uses totally different data model and gathering techniques. Google provides [detailed guide](https://support.google.com/analytics/answer/10759417?hl=en&ref_topic=10737980) on what to expect form GA4, how it compares to UA, and what exact steps you need to take to migrate your property. 110 | 2. After migration is complete on Google side, upgrade Grav Google Analytics plugin. 111 | 3. Set new tracking ID in the plugin's configuration. It needs to match _MEASUREMENT ID_ of you GA4 data stream. Old UA tracking ID won't work anymore. 112 | 4. If you were using opt-out configuration it will be automatically reset for all your users. They will need to make opt-out decision again based on your configured policy. 113 | 114 | After upgrade you will probably notice that a lot of old plugin configuration options are gone. That's because Google has changed how these options work in GA4. In particular: 115 | 116 | * `anonymizeIp` and `forceSsl` options are removed because they are now enforced on Google side and cannot be disabled. 117 | * `async` option is removed because GA4 always uses async mode. 118 | * `cookieName` option was renamed to `cookiePrefix` because you cannot change full cookie name anymore. 119 | * `objectName` default value was renamed from `ga` to `gtag` to keep it inline with standard GA4 snippet. If you were using custom `objectName` it won't be changed. 120 | * `debugTrace` option was removed and `debugStatus` was renamed to `debugMode`. GA4 doesn't have debug tracing mode. 121 | 122 | **Note: due to a bug in Grav CMS framework all these changes are not migrated automatically. At the moment these configuration options need to be removed/renamed manually.** 123 | -------------------------------------------------------------------------------- /ganalytics.php: -------------------------------------------------------------------------------- 1 | ['onPluginsInitialized', 0], 27 | 'onAssetsInitialized' => ['onAssetsInitialized', 0] 28 | ]; 29 | } 30 | 31 | /** 32 | * Returns the Google Analytics cookie configuration. 33 | * @return array 34 | */ 35 | private function getCookieConfiguration(){ 36 | $cookie_config = $this->config->get('plugins.ganalytics.cookieConfig', false); 37 | if (!$cookie_config) return []; 38 | 39 | $cookie_config = [ 40 | 'cookie_prefix' => $this->config->get('plugins.ganalytics.cookiePrefix', ''), 41 | 'cookie_expires' => $this->config->get('plugins.ganalytics.cookieExpires', 63072000), 42 | ]; 43 | 44 | // cookie domain 45 | $cookie_domain = trim($this->config->get('plugins.ganalytics.cookieDomain')); 46 | if (!empty($cookie_domain)) $cookie_config['cookie_domain'] = $cookie_domain; 47 | 48 | return $cookie_config; 49 | } 50 | 51 | /** 52 | * Returns the Google Analytics opt out configuration. 53 | * @return array 54 | */ 55 | private function getOptOutConfiguration(){ 56 | $optout_config = $this->config->get('plugins.ganalytics.optOutEnabled', false); 57 | if (!$optout_config) return []; 58 | 59 | $optout_config = [ 60 | 'optoutMessage' => addslashes(trim($this->config->get('plugins.ganalytics.optOutMessage', 'Google tracking is now disabled.'))), 61 | 'cookieExpires' => gmdate ("D, d-M-Y H:i:s \U\T\C", $this->config->get('plugins.ganalytics.cookieExpires', 63072000) + time()), 62 | ]; 63 | 64 | return $optout_config; 65 | } 66 | 67 | /** 68 | * Return the Google Analytics Tracking Code 69 | * @param string $objectName Global variable name for the GA object 70 | * @return string 71 | */ 72 | private function getTrackingCode($objectName) 73 | { 74 | $code = 75 | "window.dataLayer = window.dataLayer || [];\n". 76 | "function {$objectName}(){dataLayer.push(arguments);}\n". 77 | "{$objectName}('js', new Date());\n" 78 | ; 79 | 80 | return $code; 81 | } 82 | 83 | /** 84 | * Return the Google Analytics Opt Out Code 85 | * @param string $trackingId Google Analytics Tracking ID 86 | * @param array $config Out Out settings 87 | * @return string 88 | */ 89 | private function getOptOutCode($trackingId, $config) 90 | { 91 | $code = << -1) { 94 | window[disableStr] = true; 95 | } 96 | function gaOptout() { 97 | document.cookie = disableStr + '=true; expires={$config['cookieExpires']}; path=/'; 98 | window[disableStr] = true; 99 | alert('{$config['optoutMessage']}'); 100 | } 101 | 102 | JSCODE; 103 | return $code; 104 | } 105 | 106 | /** 107 | * Return all personalized GA settings 108 | * @param string $trackingId Google Analytics Tracking ID 109 | * @param string $objectName Global variable name for the GA object 110 | * @return string 111 | */ 112 | private function getTrackingSettings($trackingId, $objectName) 113 | { 114 | if ($this->config->get('plugins.ganalytics.debugMode', false)) { 115 | $settings['debug_mode'] = true; 116 | } else { 117 | $settings = []; 118 | } 119 | 120 | $settings = array_merge($settings, $this->getCookieConfiguration()); 121 | if (!empty($settings)) { 122 | try { 123 | $settings = json_encode($settings, JSON_THROW_ON_ERROR); 124 | return "{$objectName}('config', '{$trackingId}', {$settings});"; 125 | } catch (\JsonException $e) { 126 | $this->grav['log']->error("plugin.{$this->name}: Invalid cookie settings - {$e->getMessage()}"); 127 | } 128 | } 129 | 130 | return "{$objectName}('config', '{$trackingId}');"; 131 | } 132 | 133 | /** 134 | * Do something with deprecated settings 135 | * 136 | * Due to https://github.com/getgrav/grav/issues/3697 137 | * this method doesn't store modified settings back to 138 | * YAML file. One needs to migrate deprecated configuration 139 | * options manually. 140 | */ 141 | private function processDeprecatedSettings() 142 | { 143 | // 1.3.0 => 1.4.0 144 | // Field: "renameGa" => "objectName" 145 | $renameGa = trim($this->config->get('plugins.ganalytics.renameGa', '')); 146 | if (!empty($renameGa)) { 147 | $settings = $this->config->get('plugins.ganalytics', []); 148 | $settings['objectName'] = $renameGa; 149 | unset($settings['renameGa']); 150 | $this->config->set('plugins.ganalytics', $settings); 151 | // Plugin::saveConfig('ganalytics'); 152 | } 153 | 154 | // 1.x => 2.0 155 | // Remove unused fields 156 | $fields = ['async', 'anonymizeIp', 'forceSsl', 'cookieName', 'debugTrace']; 157 | $settings = $this->config(); 158 | if (array_intersect_key(array_flip($fields), $settings)) { 159 | unset( 160 | $settings['async'], $settings['anonymizeIp'], $settings['forceSsl'], 161 | $settings['cookieName'], $settings['debugTrace'] 162 | ); 163 | $this->config->set('plugins.ganalytics', $settings); 164 | // $this->saveConfig('ganalytics'); 165 | } 166 | // Rename default "objectName" value from "ga" to "gtag" 167 | $objectName = $this->config->get('plugins.ganalytics.objectName'); 168 | if ($objectName == 'ga') { 169 | $this->config->set('plugins.ganalytics.objectName', 'gtag'); 170 | // Plugin::saveConfig('ganalytics'); 171 | } 172 | // Rename "debugStatus" field to "debugMode" 173 | $debugStatus = $this->config->get('plugins.ganalytics.debugStatus'); 174 | if (!is_null($debugStatus)) { 175 | $settings = $this->config->get('plugins.ganalytics', []); 176 | $settings['debugMode'] = $debugStatus; 177 | unset($settings['debugStatus']); 178 | $this->config->set('plugins.ganalytics', $settings); 179 | // Plugin::saveConfig('ganalytics'); 180 | } 181 | } 182 | 183 | // Handle deprecated stuff when the plugin is initialized 184 | public function onPluginsInitialized() 185 | { 186 | $this->processDeprecatedSettings(); 187 | } 188 | 189 | /** 190 | * Returns a packed IP address which can be directly compared to another packed IP address 191 | * @param string $humanReadableIPAddress IPv4 or IPv6 adress in human readable notation 192 | * @return string (16 byte packed representation) 193 | */ 194 | private function packedIPAddress($humanReadableIPAddress) 195 | { 196 | $result = inet_pton($humanReadableIPAddress); 197 | 198 | if ($result == FALSE) 199 | return $this->packedIPAddress('::0'); 200 | elseif (strlen($result) == 16) 201 | return $result; // IPv6 native 202 | else 203 | return "\0\0\0\0\0\0\0\0\0\0\0\0" . $result; // IPv4, expanded to IPv6 compatible length 204 | } 205 | 206 | /** 207 | * Returns TRUE, if a packed IP address is within the specified address range 208 | * @param string $packedAddress 209 | * @param string $range 210 | * @return boolean 211 | */ 212 | private function inIPAdressRange($packedAddress, $range) 213 | { 214 | if ($range === 'private') { // RFC 6890, RFC 4193 215 | return ($this->inIPAdressRange($packedAddress, "10.0.0.0-10.255.255.255") 216 | || $this->inIPAdressRange($packedAddress, "172.16.0.0-172.31.255.255") 217 | || $this->inIPAdressRange($packedAddress, "192.168.0.0-192.168.255.255") 218 | || $this->inIPAdressRange($packedAddress, "fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); 219 | } elseif ($range === 'loopback') { // RFC 6890 220 | return ($this->inIPAdressRange($packedAddress, "127.0.0.1-127.255.255.255") 221 | || $this->inIPAdressRange($packedAddress, "::1-::1")); 222 | } elseif ($range === 'link-local') { // RFC 6890, RFC 4291 223 | return ($this->inIPAdressRange($packedAddress, "169.254.0.0-169.254.255.255") 224 | || $this->inIPAdressRange($packedAddress, "fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff")); 225 | } else { 226 | $rangeLimits = explode('-', $range); 227 | if (count($rangeLimits) == 2) { 228 | $lowerLimit = $this->packedIPAddress($rangeLimits[0]); 229 | $upperLimit = $this->packedIPAddress($rangeLimits[1]); 230 | return $lowerLimit <= $packedAddress && $packedAddress <= $upperLimit; 231 | } 232 | } 233 | 234 | return FALSE; 235 | } 236 | 237 | /** 238 | * Documents the reason for blocking GA tracking in a JavaScript comment 239 | * @param string $reason 240 | */ 241 | private function documentBlockingReason($reason) 242 | { 243 | $this->grav['assets']->addInlineJs("/* GA tracking blocked, reason: $reason */"); 244 | } 245 | 246 | /** 247 | * Add GA tracking JS when the assets are initialized 248 | */ 249 | public function onAssetsInitialized() 250 | { 251 | // Don't proceed if we are in the admin plugin 252 | if ($this->isAdmin()) { 253 | $this->documentBlockingReason('admin plugin active'); 254 | return; 255 | } 256 | 257 | // Don't proceed if there is no GA Tracking ID 258 | $trackingId = trim($this->config->get('plugins.ganalytics.trackingId', '')); 259 | 260 | // Add support for environment variables: 261 | if (preg_match('/env:(.*)/', $trackingId, $match)) { 262 | $trackingId = getenv($match[1]); 263 | } 264 | 265 | if (empty($trackingId)) { 266 | $this->documentBlockingReason('trackingId not configured'); 267 | return; 268 | } 269 | 270 | $dntRespected = $this->config->get('plugins.ganalytics.dnt', true); 271 | if ($dntRespected && !empty($_SERVER['HTTP_DNT'])) { 272 | $this->documentBlockingReason("Do Not Track header sent by the client"); 273 | return; 274 | } 275 | 276 | // Don't proceed if a blocking cookie is set 277 | $blockingCookieName = $this->config->get('plugins.ganalytics.blockingCookie', ''); 278 | if (!empty($blockingCookieName) && !empty($_COOKIE[$blockingCookieName])) { 279 | $this->documentBlockingReason("blocking cookie \"$blockingCookieName\" is set"); 280 | return; 281 | } 282 | 283 | // Don't proceed if the IP address is blocked 284 | $blockedIps = $this->config->get('plugins.ganalytics.blockedIps', []); 285 | if (in_array($_SERVER['REMOTE_ADDR'], $blockedIps)) { 286 | $this->documentBlockingReason("client ip " . $_SERVER['REMOTE_ADDR'] . " is in blockedIps"); 287 | return; 288 | } 289 | 290 | // Don't proceed if the IP address is within a blocked range 291 | $packedClientIpAddress = $this->packedIPAddress($_SERVER['REMOTE_ADDR']); 292 | $blockedIpRanges = $this->config->get('plugins.ganalytics.blockedIpRanges', []); 293 | foreach ($blockedIpRanges as $blockedIpRange) { 294 | if ($this->inIPAdressRange($packedClientIpAddress, $blockedIpRange)) { 295 | $this->documentBlockingReason("client ip " . $_SERVER['REMOTE_ADDR'] . " is in range \"" . $blockedIpRange . "\""); 296 | return; 297 | } 298 | } 299 | 300 | // Parameters 301 | $objectName = trim($this->config->get('plugins.ganalytics.objectName', 'gtag')); 302 | $position = trim($this->config->get('plugins.ganalytics.position', 'head')); 303 | 304 | // Opt Out and Tracking Code and settings 305 | $code = ''; // init 306 | $optout_config = $this->getOptOutConfiguration(); 307 | if (!empty($optout_config)) { 308 | $code .= $this->getOptOutCode($trackingId, $optout_config); 309 | } 310 | $settings = $this->getTrackingSettings($trackingId, $objectName); 311 | $code .= $this->getTrackingCode($objectName); 312 | $code .= $settings; 313 | 314 | // Embed Google Analytics script 315 | $group = ($position == 'body') ? 'bottom' : null; 316 | 317 | $this->grav['assets']->addJs("https://www.googletagmanager.com/gtag/js?id={$trackingId}", 9, true, 'async', $group); 318 | $this->grav['assets']->addInlineJs($code, null, $group); 319 | } 320 | } 321 | --------------------------------------------------------------------------------