Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: MA Content Consent
- Description: Shortcode for requesting user consent before loading external content.
- Author: <a href="https://www.altmann.de/">Matthias Altmann</a>
- Project: Code Snippet: MA Content Consent
- Version: 1.1.0
- Plugin URI: https://www.altmann.de/en/blog-en/code-snippet-shortcode-content-consent/
- Description: en: https://www.altmann.de/en/blog-en/code-snippet-consent-for-external-content/
- de: https://www.altmann.de/blog/code-snippet-zustimmung-fuer-externe-inhalte/
- Copyright: © 2021-2022, Matthias Altmann
- Version History:
- Date Version Description
- --------------------------------------------------------------------------------------------------------------
- 2022-10-21 1.1.0 Changes:
- - Added new shortcode parameters block-class, text-class, button-class
- - Migrated JavaScript from jQuery to vanilla JS (ES6) to eliminate jQuery dependency.
- (Thanks to André Slotta for the provided code sample)
- Fixes:
- - Removed double '.' for German GDPR text.
- (Thanks to Tobias Maximilian Hietsch for reporting)
- 2022-02-04 1.0.1 - Added Dansk translations for notice text and button label
- (Thanks to Theis L. Soelberg)
- - Evaluating nested shortcodes
- (Thanks to Anja Kretzer)
- 2022-02-03 1.0.0 Initial release as Code Snippet
- 2021-12-29 0.0.1 Initial version for client project
- --------------------------------------------------------------------------------------------------------------
- */
- if (!class_exists('MA_Content_Consent')) :
- class MA_Content_Consent {
- const TITLE = 'MA Content Consent';
- const SLUG = 'ma-content-consent';
- const VERSION = '1.1.0';
- // ===== CONFIGURATION ==============================================================================================
- public static $timing = false; // Write timing info to wordpress debug.log if WP_DEBUG enabled
- public static $debug = false; // Write debug info to wordpress debug.log if WP_DEBUG enabled
- private static $default_consent_text = [ // consent text in different languages
- 'da' => ['Når du har trykket, vil indholdet blive hentet fra eksterne servere. Se vores %s for flere informationer.','privatlivspolitik'],
- 'de' => ['Bei Klick wird dieser Inhalt von externen Servern geladen. Details siehe %s.', 'Datenschutzerklärung'],
- 'en' => ['When clicked, this content is loaded from external servers. See our %s for details.', 'privacy policy'],
- 'es' => ['Al hacer clic, este contenido se carga desde servidores externos. Consulte la %s para más detalles.', 'política de privacidad'],
- 'fr' => ['En cliquant, ce contenu est chargé depuis des serveurs externes. Voir la %s.', 'politique de confidentialité'],
- 'hu' => ['Ha rákattint, ez a tartalom külső szerverekről töltődik be. A részletekért olvassa el az %s oldalt.', 'Adatkezelési Tájékoztatót'],
- 'it' => ['Quando viene cliccato, questo contenuto viene caricato da server esterni. Vedere %s per i dettagli.', 'l\'informativa sulla privacy'],
- 'jp' => ['クリックすると、このコンテンツが外部サーバーから読み込まれます。弊社のプライバシーポリシーの詳細は、%s', 'を参照してください。'],
- ];
- private static $default_button_text = [ // button text in different languages
- 'da' => 'Indlæs eksternt indhold',
- 'de' => 'Externen Inhalt laden',
- 'en' => 'Load external content',
- 'es' => 'Cargar contenido externo',
- 'fr' => 'Charger le contenu externe',
- 'hu' => 'Külső tartalom betöltése',
- 'it' => 'Caricare il contenuto esterno',
- 'jp' => '外部のコンテンツを読み込ませます。',
- ];
- //-------------------------------------------------------------------------------------------------------------------
- public static function init() {
- $st = microtime(true);
- add_shortcode('ma-content-consent', [__CLASS__, 'shortcode']);
- $et = microtime(true);
- if (WP_DEBUG && self::$timing) {error_log(sprintf('%s%s::%s() Timing: %.5f sec.', '', __CLASS__, __FUNCTION__, $et-$st));}
- }
- //-------------------------------------------------------------------------------------------------------------------
- private static function get_current_language(){
- $retval = get_locale();
- // Is Polylang available?
- if (function_exists('wpml_current_language')) {$retval = wpml_current_language();}
- $retval = str_replace('_','-',$retval);
- $retval = explode('-',@$retval)[0];
- return $retval;
- }
- //-------------------------------------------------------------------------------------------------------------------
- private static function get_privacy_policy_link($text) {
- // return a link to the privacy policy (if configured) or just the passed text
- $pplink = get_the_privacy_policy_link();
- return $pplink ? $pplink : $text;
- }
- //-------------------------------------------------------------------------------------------------------------------
- public static function shortcode($atts, $content = '') {
- $st = microtime(true);
- $lang = self::get_current_language();
- if (!is_array($atts)) $atts = [];
- // fix Gutenberg content: remove </p> ... <p>
- $content = preg_replace('/^<\/p>[ \r\n]*/','',$content); // remove leading </p> tag, spaces, line breaks from shortcode start tag
- $content = preg_replace('/[ \r\n]*<p>$/','',$content); // remove trailing line breaks, spaces, <p> tag from shortcode end tag
- // evaluate nested shortcodes
- $content = do_shortcode($content);
- // get defaults for unspecified atts
- $atts = (object)array_merge([
- 'slug' => self::SLUG,
- 'id' => uniqid(self::SLUG . '-'),
- 'block-style' => '',
- 'block-class' => '',
- 'text' => isset(self::$default_consent_text[$lang])
- ? sprintf(self::$default_consent_text[$lang][0],self::get_privacy_policy_link(self::$default_consent_text[$lang][1]))
- : sprintf(self::$default_consent_text['en'][0],self::get_privacy_policy_link(self::$default_consent_text['en'][1])),
- 'text-style' => '',
- 'text-class' => '',
- 'button-text' => self::$default_button_text[$lang] ?? self::$default_button_text['en'],
- 'button-style' => '',
- 'button-class' => '',
- 'background-image' => null,
- 'contentb64' => base64_encode($content),
- ], $atts);
- $atts->{'background-style'} = $atts->{'background-image'} ? 'background-image:url('.$atts->{'background-image'}.'); background-size:cover; background-position:center center;' : '';
- $atts->{'text'} = str_replace('{privacy-policy-url}', get_privacy_policy_url(), $atts->{'text'});
- $atts->{'text'} = str_replace('{privacy-policy-link}', get_the_privacy_policy_link(), $atts->{'text'});
- $html = <<<END_OF_HTML
- <div id="{$atts->id}" class="{$atts->slug} {$atts->{'block-class'}}" style="display:flex; flex-direction:column; justify-content:center; align-content:center; background-color:#efefef; border: 1px solid lightgray; padding:1em; width: 100%; {$atts->{'background-style'}} {$atts->{'block-style'}} ">
- <div style="text-align:center">
- <p class="{$atts->slug}__text {$atts->{'text-class'}}" style="font-size:.7em; {$atts->{'text-style'}}">{$atts->{'text'}}</p>
- <a id="{$atts->id}__button" class="wp-block-button__link {$atts->slug}__button {$atts->{'button-class'}}" style="{$atts->{'button-style'}}">{$atts->{'button-text'}}</a>
- </div>
- <div id="{$atts->id}__content" class="{$atts->slug}__content" style="display:none">{$atts->contentb64}</div>
- <script>
- document.querySelectorAll('#{$atts->id}__button').forEach(function(btn){
- btn.addEventListener('click',function(){
- let id = this.closest('div.{$atts->slug}').id;
- let content = atob(document.querySelector('#'+id+'__content').innerText);
- this.closest('div.{$atts->slug}').outerHTML = content;
- });
- });
- </script>
- </div>
- END_OF_HTML;
- $et = microtime(true);
- if (WP_DEBUG && self::$timing) {error_log(sprintf('%s%s::%s() Timing: %.5f sec.', '-> ', __CLASS__, __FUNCTION__, $et-$st));}
- return $html;
- }
- }
- //===================================================================================================================
- // Initialize
- // Warn about incompatibilities (currently none)
- add_action('wp_loaded',function(){
- if (is_admin()) {
- if (!isset($GLOBALS['MA_Content_Consent_Incompatibilities'])) {$GLOBALS['MA_Content_Consent_Incompatibilities'] = [];}
- if (count($GLOBALS['MA_Content_Consent_Incompatibilities'])) {
- if (WP_DEBUG && (MA_Content_Consent::$debug || MA_Content_Consent::$timing))
- {error_log('MA_Content_Consent / Incompatibilities: '.print_r($GLOBALS['MA_Content_Consent_Incompatibilities'],true));}
- add_action('admin_notices', function(){
- if (WP_DEBUG ) {error_log('MA_Content_Consent / Incompatibilities: '.print_r($GLOBALS['MA_Content_Consent_Incompatibilities'],true));}
- $implementation = basename(__FILE__) == 'ma-content-consent.php' ? 'Plugin' : 'Code Snippet';
- echo '<div class="notice notice-warning xis-dismissible">
- <p>The '.$implementation.' "MA Content Consent" is skipped: '.implode(' or ',$GLOBALS['MA_Content_Consent_Incompatibilities']).'</p>
- </div>';
- });
- }
- }
- }, 1000);
- add_action('wp_loaded',function(){
- if (isset($GLOBALS['MA_Content_Consent_Incompatibilities']) && count($GLOBALS['MA_Content_Consent_Incompatibilities'])) return;
- if (wp_doing_ajax()) return; // don't run for AJAX requests
- if (wp_doing_cron()) return; // don't run for CRON requests
- if (wp_is_json_request()) return; // don't run for JSON requests
- if (is_favicon()) return; // don't run for favicon request
- if (isset($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] == 'service-worker')) return; // don't run for service-worker
- if (isset($_SERVER['REQUEST_URI']) && ($_SERVER['REQUEST_URI'] == '/favicon.ico')) return; // don't run for favicon
- if (isset($_SERVER['REQUEST_URI']) && (strpos($_SERVER['REQUEST_URI'],'/wp-content/') === 0)) return; // don't run for dynamic wp-content file
- if (is_admin()) {
- global $pagenow;
- if ( ($pagenow != 'post-new.php')
- && ( ($pagenow != 'post.php') || ($pagenow == 'post.php' && isset($_REQUEST['action']) && ($_REQUEST['action'] != 'edit')) )
- ) return; // only load on specific requests where Gutenberg is involved
- }
- $implementation = basename(__FILE__) == 'ma-content-consent.php' ? 'Plugin' : 'Code Snippet';
- if (WP_DEBUG && (MA_Content_Consent::$debug || MA_Content_Consent::$timing))
- {error_log(sprintf('MA_Content_Consent: Initializing %s for request URI="%s" action="%s"', $implementation, $_SERVER['REQUEST_URI']??'', $_REQUEST['action']??''));}
- MA_Content_Consent::init();
- }, 1200);
- endif;
Add Comment
Please, Sign In to add comment