zephir / kirby-cookieconsent
Kirby cookieconsent plugin
Package info
github.com/zephir/kirby-cookieconsent
Type:kirby-plugin
pkg:composer/zephir/kirby-cookieconsent
Requires
- php: >=8.1
- getkirby/composer-installer: ^1.1
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
- getkirby/cms: <4.0
Replaces
None
README
Important
Looking for a maintainer: we're looking for someone to take over this repository. If you're interested, please open an issue.
Note
Claude (an AI assistant) was used to optimize the code of this plugin. All changes were validated by a human.
A plugin to implement cookieconsent in Kirby.
- Uses the open source cookieconsent library
- Provides default translations for 5 cookie categories
- Multilingual support (EN/DE/FR/NL/ES/CA/PT-PT)
- Customizable
Table of Contents
- Kirby Cookieconsent plugin
Requirements
- Kirby 4, 5 or 6
- PHP 8.1 or newer (and the PHP version your Kirby release requires)
Version 4 of this plugin drops support for Kirby 3. If you are still on Kirby 3, stay on version 3.x of this plugin.
Upgrading from 3.x to 4.0
- Requirements: Kirby 4, 5 or 6 and PHP 8.1+. Composer refuses to install 4.x into a Kirby 3 site.
- cookieconsent 3.3.0: the bundled library moves from 3.0.0 to 3.3.0 (also in
cdnmode). Its markup and CSS changed slightly (accessibility fixes), so re-check custom CSS for#cc-main. Source maps are no longer shipped. - Asset URLs: CSS and JS are linked through Kirby's plugin asset API (
/media/plugins/zephir/cookieconsent/<hash>/index.js), bypassingcss()/js()components such as cachebuster plugins. With Kirby's pages cache on, clear the cache after updating the plugin./cookieconsent.jsnow has a?v=query that changes with the config. See 2.1. - Removed categories: a category set to
falseis no longer passed to cookieconsent, so "Accept all" no longer stores it. Visitors who accepted before keep it in their cookie until you increaserevision. A preferences section whoselinkedCategoryis not incategoriesis now hidden too. See 3.4. - Language: the translation is picked by the Kirby language's locale first (
pt_PT), then its code (pt), then the same base language, then thelanguage.localeoption, thenen. A custom translation registered under the code (e.g.'pt') now loses to a shipped one for the locale (pt_PT): move it to the locale key. Unmatched languages fall back to English instead of German. The cookieconsent language key (and the consent cookie'slanguageCode) is now the translation key (de,pt_PT) instead ofkirby. See 4. - Translation files are loaded with
requireinstead ofrequire_once. Userequirein your own overrides too (see 5.1). - JavaScript in the config: callbacks, service
onAccept/onRejectand cookie-name regexes are now possible withJs::raw()andJs::regex(). Root callback options must beJsvalues; plain strings throw an exception. See 7. rootnow defaults to'body'(the old'document.body'never matched anything and only worked through the library's fallback).
1. Installation
The recommended way of installing is by using Composer.
1.1 Composer
composer require zephir/kirby-cookieconsent
1.2 Download
Download and copy this repository to /site/plugins/kirby-cookieconsent.
1.3 Git submodule
git submodule add https://github.com/zephir/kirby-cookieconsent.git site/plugins/kirby-cookieconsent
2. Setup
Add snippet('cookieconsentCss') to your header and snippet('cookieconsentJs') to your footer.
2.1 How the assets are loaded
The snippets output three tags:
<link rel="stylesheet" href="https://example.com/media/plugins/zephir/cookieconsent/4205341454-1732460000/index.css"> <script defer src="https://example.com/media/plugins/zephir/cookieconsent/2046731778-1732460000/index.js"></script> <script defer src="https://example.com/cookieconsent.js?v=99b40bdf"></script>
index.cssandindex.jsare the compiled cookieconsent library. They are Kirby plugin assets, so their URLs come from Kirby ($kirby->plugin('zephir/cookieconsent')->asset('index.js')->url()) and contain a hash that changes when the files change. Kirby links them intomedia/pluginson the first request, so an empty or deletedmediafolder is fine./cookieconsent.jsis the configuration built from your options. Thevparameter changes whenever your options change, so visitors get the new configuration right away (for example after you raiserevision). On multi-language sites the URL starts with the language prefix (/de/cookieconsent.js).- The tags are written directly, not through Kirby's
css()/js()helpers. That way cache-buster plugins such as schnti/cachebuster leave these URLs alone; they are already versioned. - With
'cdn' => true, the library comes from jsDelivr (cookieconsent v3.3.0, pinned with Subresource Integrity hashes) and/media/pluginsis not used. The configuration script is always served by your site.
If you use Kirby's pages cache, clear it after updating the plugin, as after any deploy. Cached pages otherwise still point to the hash of the old files.
2.2 Troubleshooting: 403 on /media/plugins/zephir/cookieconsent/...
Kirby publishes plugin assets by creating a symlink in media/plugins/ that points to the file in site/plugins/kirby-cookieconsent/assets/. The first request is answered by Kirby itself; later requests are served by the web server through that symlink. On some shared hosts (reported on Mittwald), PHP sees the site under a different path than the web server (for example /html/... instead of /home/www/p123456/html/...). The symlink then points to a path the web server cannot resolve, and Apache answers 403 Forbidden ("Symbolic link not allowed or link target not accessible"). This happens to every Kirby plugin's frontend assets on such a host, and the plugin cannot change how Kirby creates the symlink. Adding Options +FollowSymLinks does not help here.
What you can do:
- Ask your host to make the paths match, or to follow these symlinks.
- Use
'zephir.cookieconsent.cdn' => trueto load the library from jsDelivr. Note that jsDelivr is a third party; check whether that fits your privacy policy. - Host the two files yourself: copy
assets/index.cssandassets/index.jsfrom the plugin into your ownassetsfolder. Then copy the plugin'ssnippets/cookieconsent_css.phpandsnippets/cookieconsent_js.phptosite/snippets/cookieconsentCss.phpandsite/snippets/cookieconsentJs.php(your snippets take precedence over the plugin's), and replace the asset URL in them with yours, e.g.url('assets/cookieconsent/index.js'). You need to copy the files again after each plugin update.
3. Options
3.1 Available options
3.2 Defaults
'zephir.cookieconsent' => [ 'cdn' => false, 'revision' => 1, 'root' => 'body', // a CSS selector 'autoClearCookies' => true, // Only works when the categories have an autoClear array 'autoShow' => true, 'hideFromBots' => true, 'disablePageInteraction' => false, 'lazyHtmlGeneration' => true, 'guiOptions' => [ 'consentModal' => [ 'layout' => 'box', 'position' => 'bottom right', 'flipButtons' => false, 'equalWeightButtons' => true ], 'preferencesModal' => [ 'layout' => 'box', // 'position' => 'left', // only relevant with the "bar" layout 'flipButtons' => false, 'equalWeightButtons' => true ] ], 'categories' => [ 'necessary' => [ 'enabled' => true, 'readOnly' => true ], 'measurement' => [], 'functionality' => [], 'experience' => [], 'marketing' => [] ], 'translations' => [ 'de' => require(__DIR__ . '/translations/de.php'), 'en' => require(__DIR__ . '/translations/en.php'), 'fr' => require(__DIR__ . '/translations/fr.php'), 'nl' => require(__DIR__ . '/translations/nl.php'), 'es' => require(__DIR__ . '/translations/es.php'), 'ca' => require(__DIR__ . '/translations/ca.php'), 'pt_PT' => require(__DIR__ . '/translations/pt_PT.php') ], 'language' => [ 'locale' => 'en', 'direction' => 'ltr' ] ]
3.3 Predefined cookie categories
Each cookie category can be used to control certain scripts. To learn how to manage scripts, head over to the CookieConsent documentation.
Categories that are predefined by this plugin:
| Name | Enabled | Description |
|---|---|---|
| necessary | ✅ | The necessary cookies, can't be disabled by the user. |
| functionality | ✅ | Cookies for basic functionality and communication. |
| experience | ✅ | Cookies to improve the quality of the user experience and enable the user to interact with external content, networks and platforms. |
| measurement | ✅ | Cookies that help to measure traffic and analyze behavior. |
| marketing | ✅ | These cookies help us to deliver personalized ads or marketing content to you, and to measure their performance. |
Predefined means that there are translations in all languages for each category.
To enable/disable categories you can use the categories option of the plugin.
'zephir.cookieconsent' => [ 'categories' => [ 'necessary' => [ 'enabled' => true, // marks the category as enabled by default 'readOnly' => true ], 'measurement' => [], 'functionality' => [], 'experience' => [], 'marketing' => [] ], ]
An empty array defines the category with the default options. You can pass additional options like
enabledorreadOnlyin the array. Learn more about those options in the CookieConsent Documentation.
3.4 Removing a category
To remove a category you have to set its value to false.
'zephir.cookieconsent' => [ 'categories' => [ 'necessary' => [ 'enabled' => true, 'readOnly' => true ], 'measurement' => [], 'functionality' => false, // will not be shown 'experience' => false, // will not be shown 'marketing' => [] ], ]
A removed category is not passed to CookieConsent at all: its section is hidden in the preferences modal, and neither "Accept all" button stores it in the consent cookie.
Up to version 3 of this plugin, "Accept all" also stored removed categories in the cookie. Visitors who accepted under that behaviour keep these extra categories in their cookie until they consent again. To ask them for consent again, increase the revision option.
4. Language
The plugin picks one of the registered translations for the current page.
Multi-language sites (kirby option languages set to true) need no setup. The translation is chosen from the current Kirby language, in this order:
- The language's locale, e.g.
pt_PTfor a language with'locale' => 'pt_PT.UTF-8'. Codeset and modifier are ignored and-matches_, sopt_PT.UTF-8,pt-PTandpt_ptall find thept_PTtranslation. - The language's code, e.g.
de. - A translation for the same base language, e.g. a language
ptorpt_BRusespt_PT, andde_CHusesde. - The fallback: the
language.localeoption below if you set it, elseen, else the first registered translation.
The text direction follows the Kirby language's direction.
Single-language sites (or languages on but no language created yet) use the language option. locale is matched the same way (steps 1, 3 and 4), so de_CH uses de.
'zephir.cookieconsent' => [ 'language' => [ 'locale' => 'de', // The translation to use, default is en 'direction' => 'ltr' // Either ltr or rtl, default is ltr ] ]
On multi-language sites language.locale is only used as the fallback, for languages without a matching translation.
5. Translations
The translations are a central part of the plugin. By default, we provide translations for en, de, fr, nl, es, ca and pt_PT, and for the categories mentioned in 3.3 Predefined cookie categories.
To customise or override the default translations, or to add a language, you will need to use the translations option.
Each translation is registered under a key, which is matched against your languages as described in 4. Language. Use the language code ('de' => ...) or a locale ('pt_BR' => ...). When both match, the locale key wins: a language pt with locale pt_PT uses the pt_PT translation even if you also registered 'pt' => ..., so override a shipped translation under its own key (pt_PT).
5.1 Overriding specific translations
For this example we are overriding one string and adding a new category in the sections part of the EN translation.
- Create a new folder in your project. For this example we call it
cc-translations. - In that folder, create a new file
en.php.
<?php // site/cc-translations/en.php return array_replace_recursive( // We assume the plugin was installed as suggested in the installation section of the readme. require(__DIR__ . '/../plugins/kirby-cookieconsent/translations/en.php'), [ 'consentModal' => [ 'title' => 'Lorem ipsum dolor!', // Override consentModal title ], "preferencesModal" => [ "sections" => [ [ // Add a new category in sections "title" => "Custom scripts", "description" => "Diese Cookies helfen uns, Ihnen personalisierte Werbung oder Marketinginhalte bereitzustellen und deren Leistung zu messen.", "linkedCategory" => "custom-scripts", ], ] ] ] );
- Now you need to require (or include) this file in
config.php. Because we want to see the new categorycustom-scriptswe also need to update thecategoriesoption.
'zephir.cookieconsent' => [ 'categories' => [ 'custom-scripts' => [] ], 'translations' => [ 'en' => require(__DIR__ . '/../cc-translations/en.php') ] ]
You can override the whole translation file by copying the default file and adjusting the values. You can also require the default translation and manually alter the array by modifying, adding or deleting entries.
6. Events
You can find all available events in the CookieConsent Documentation.
The CookieConsent object is available through the window object (
window.CookieConsent).
7. JavaScript in the config: callbacks, services and regexes
The plugin builds the CookieConsent config in PHP and outputs it as JSON. Most of the config is plain data and works as a normal PHP array, for example a service with a label and cookies with string names.
Some parts of the CookieConsent configuration have to be JavaScript: the service callbacks onAccept/onReject, the root callbacks (onFirstConsent, onConsent, onChange, onModalReady, onModalShow, onModalHide) and cookie names given as a regular expression.
For those, wrap the value in Zephir\Cookieconsent\Js. You can use it anywhere in the zephir.cookieconsent options:
Js::raw('function () { ... }')outputs the JavaScript expression as is, unquoted.Js::regex('^_ga')outputs a regular expression, the same as/^_ga/. The pattern is written without the slashes; flags go in the second argument:Js::regex('^_ga', 'i').
Everything else is still JSON encoded.
<?php // site/config/config.php use Zephir\Cookieconsent\Js; return [ // `ready` runs after the plugins are loaded, so the Js class is available // with every installation method (see the note below) 'ready' => fn () => [ 'zephir.cookieconsent' => [ 'categories' => [ 'necessary' => [ 'enabled' => true, 'readOnly' => true ], 'measurement' => [ // Clears these cookies when the user rejects the category 'autoClear' => [ 'cookies' => [ ['name' => Js::regex('^_ga')], // _ga, _ga_XXXXXXXXXX, ... ['name' => '_gid'] ] ], 'services' => [ 'ga' => [ 'label' => 'Google Analytics', 'onAccept' => Js::raw('function () { // load Google Analytics here }'), 'onReject' => Js::raw('function () { // runs when the user turns off this service after accepting it }'), 'cookies' => [ ['name' => Js::regex('^_ga')] ] ] ] ], 'functionality' => [], 'experience' => [], 'marketing' => [] ], 'onConsent' => Js::raw('function ({ cookie }) { console.log("Accepted categories:", cookie.categories); }') ] ] ];
The service shows up as its own toggle in the preferences modal, below the measurement category.
onAccept runs when the service is accepted ("Accept all", or the toggle on) and on every page load after it. onReject runs when a service the user had accepted is turned off. With autoClearCookies (on by default), the cookies listed in autoClear are deleted when the category is rejected, also on "Reject all" at the first visit.
Why
ready? Kirby readsconfig.phpbefore it loads the plugins. If you installed the plugin with Composer, theJsclass is autoloaded already and you can use it directly in thezephir.cookieconsentoption. If you installed it by download or as a git submodule, the class only exists once the plugin is loaded, so put the options that useJsin Kirby'sreadyoption, as above.
Js::raw() puts your code into the page unchanged: only use it with your own code, never with content from editors or visitors. The callbacks receive the same arguments as in the CookieConsent documentation.
License
MIT
