<?php

/*
Plugin Name: Simple GDPR
Plugin URI: http://cellarweb.com/wordpress-plugins/
Description: Simple process to create a 'cookies are OK' banner/button; assumes that site cannot be accessed unless you agree. Creates a privacy page based on US Better Business Bureau recommendations (your country might have different requirements). Also allows for use of Google Analytics via server-side request, to allow analytics tracking if ad-blocking is enabled by the visitor.
Version: 1.51
Tested up to: 6.3
Requires at least: 4.9.6
PHP Version: 7.2
Author: Rick Hellewell - CellarWeb.com
Author URI: http://CellarWeb.com
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
License for CookieConsent code: MIT License https://cookieconsent.insites.com/documentation/license/
 */

/*
Copyright (c) 2016-2022 by Rick Hellewell and CellarWeb.com
All Rights Reserved

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA02110-1301USA

 */

define("SGDPR_VERSION", "1.51 (7 May 2022)");
// check for required versions of WP and PHP
$min_wp  = '4.9.6';
$min_php = '7.2';
if (!SGDPR_is_requirements_met($min_wp, $min_php)) {
	add_action('admin_init', 'SGDPR_disable_plugin');
	add_action('admin_notices', 'SGDPR_show_notice_disabled_plugin');
	add_action('network_admin_init', 'SGDPR_disable_plugin');
	add_action('network_admin_notices', 'SGDPR_show_notice_disabled_plugin');
	SGDPR_deregister();
	return;
}
// create page after theme and other stuff loaded
add_filter('after_setup_theme', 'SGDPR_create_privacy_page');
function SGDPR_create_privacy_page() {
	$create_privacy_page = (isset($_POST['create_privacy_page'])) ? true : false;
	if ($create_privacy_page == 'Create Generic Privacy Page') {
		$blog_page_content = SGDPR_privacy_page_content();
		$blog_page         = array(
			'post_type' => 'page',
			'post_title' => 'Privacy Page',
			'post_content' => $blog_page_content,
			'post_status' => 'publish',
			'post_author' => 1,
			'post_slug' => 'privacy_page'
		);
		$blog_page_id = wp_insert_post($blog_page);
		if ($blog_page_id) {
			add_action('admin_notices', 'SGDPR_page_created_notice');
			add_action('network_admin_notices', 'SGDPR_page_created_notice');
			return $blog_page_id;
		} else {
			add_action('admin_notices', 'SGDPR_page_not_created_notice');
			add_action('network_admin_notices', 'SGDPR_page_not_created_notice');
			return false;
		}
	}
	return;
}

// insert into the header the code to display the banner
add_action('wp_footer', 'SGDPR_the_footer');
add_action('admin_init', 'SGDPR_save_wp_core_privacy_page_id'); // save privacy page id if set

// Check whether the button on the admin/settings page has been pressed
if (isset($_POST['SGDPR_button']) == 'SGDPR_button') {
	// SGDPR_sanitize all POST variables
	$_POST = filter_input_array(INPUT_POST, FILTER_SGDPR_sanitize_STRING);
	$_GET  = filter_input_array(INPUT_GET, FILTER_SGDPR_sanitize_STRING);
	// the button has been pressed, so we do something that the button is supposed to do
	add_action('admin_init', "SGDPR_site_show_posts");
}

// if we want to display an admin notice     (NOT USED)
function SGDPR_notice_page_created($msg = "an admin message") {
	echo '<div class="notice notice-success is-dismissible">' . $msg . '</div>';
	return;
}

// ----------------------------------------------------------------
function SGDPR_output_empty() // (NOT USED)
{
	return;
}

/**
 * Generated by the WordPress Option Page generator
 * at http://jeremyhixon.com/wp-tools/option-page/
 */

class SimpleGDPR {
	private $simple_gdpr_options;

	public function __construct() {
		add_action('admin_menu', array($this, 'simple_gdpr_add_plugin_page'));
		add_action('admin_init', array($this, 'simple_gdpr_page_init'));
	}

	public function simple_gdpr_add_plugin_page() {
		add_options_page(
			'Simple GDPR', // page_title
			'Simple GDPR', // menu_title
			'manage_options', // capability
			'simple-gdpr', // menu_slug
			array($this, 'simple_gdpr_create_admin_page') // function
		);
	}

	public function simple_gdpr_create_admin_page() {
		$this->simple_gdpr_options = get_option('SGDPR_options');?>

        <div >
    <div class="SGDPR_options">
    <?php SGDPR_info_top();?>

            <form method="post" action="options.php">
                <?php
settings_fields('simple_gdpr_option_group');
		do_settings_sections('simple-gdpr-admin');
		submit_button();
		?>
            </form>
            <?php SGDPR_create_page_button(); // show the create the privacy page button ?>
            <?php SGDPR_footer(); // display bottom info stuff
		?>
</div>
    </div>
    <div class='SGDPR_sidebar'>
        <?php SGDPR_sidebar();?>
    </div>

<?php
}

	public function simple_gdpr_page_init() {
		wp_register_style('SGDPR_namespace', plugins_url('/css/settings.css', __FILE__), array(), SGDPR_VERSION);
		wp_enqueue_style('SGDPR_namespace'); // gets the above css file in the proper spot
		register_setting(
			'simple_gdpr_option_group', // option_group
			'SGDPR_options', // option_name
			array($this, 'simple_gdpr_sanitize') // sanitize_callback
		);

		add_settings_section(
			'simple_gdpr_setting_section', // id
			'Information and Settings', // title
			array($this, 'simple_gdpr_section_info'), // callback
			'simple-gdpr-admin' // page
		);

		add_settings_field(
			'SGDPR_privacy_page_name', // id
			'Privacy Page', // title
			array($this, 'SGDPR_privacy_page_name_callback'), // callback
			'simple-gdpr-admin', // page
			'simple_gdpr_setting_section' // section
		);

		add_settings_field(
			'SGDPR_add_link_to_footer', // id
			'Add link to Privacy page in footer', // title
			array($this, 'SGDPR_add_link_to_footer_callback'), // callback
			'simple-gdpr-admin', // page
			'simple_gdpr_setting_section' // section
		);

		add_settings_field(
			'SGDPR_GA_ID_number', // id
			'Google Analytics Universal Analytics (UA) ID number', // title
			array($this, 'SGDPR_GA_ID_number_callback'), // callback
			'simple-gdpr-admin', // page
			'simple_gdpr_setting_section' // section
		);
	}

	public function simple_gdpr_sanitize($input) {
		$sanitary_values = array();
		if (isset($input['SGDPR_privacy_page_name'])) {
			$sanitary_values['SGDPR_privacy_page_name'] = $input['SGDPR_privacy_page_name'];
		}

		if (isset($input['SGDPR_add_link_to_footer'])) {
			$sanitary_values['SGDPR_add_link_to_footer'] = sanitize_text_field($input['SGDPR_add_link_to_footer']);
		}

		if (isset($input['SGDPR_GA_ID_number'])) {
			$sanitary_values['SGDPR_GA_ID_number'] = sanitize_text_field($input['SGDPR_GA_ID_number']);
		}

		return $sanitary_values;
	}

	public function simple_gdpr_section_info() {
		print '<p>Simple GDPR creates the "Cookie and Privacy Terms" Acceptance message and button at the top of all pages on your site, and stores a cookie that keeps track of that setting for the user. The message will continue to display on all pages until the visitor clicks the "OK" button. It will redisplay once a year, or after the visitor removes or deletes the "acceptance" cookie.</p>
    <p>You can specify the page that contains your Privacy Page terms. You can also display the Privacy Page link in the footer of all pages. The Privacy Page information is also stored in the Settings, Privacy page screen.</p>
    <p>You can easily create a generic Privacy Page; you can create that page by clicking the yellow button. After creation, you can modify the page content if you wish. The generated page uses the guidance from the US Better Business Bureau at <a href="https://www.bbb.org/reno/for-businesses/sample-privacy-policy/" target="_blank">https://www.bbb.org/reno/for-businesses/sample-privacy-policy/</a>. </p>
<p>If you enter a Google Analytics ID Number, the plugin will use server-side commands to capture basic Google Analytics information to your GA account. This allows analytics tracking for visitors that have ad-blockers, an advantagethat gives you more accurate analytics data over the \'normal\' GA process of using client-side JavaScript code. And our GA process does not store any visitor\'s personal information anywhere.</p>
    <p>If you use Google Analytics, then you should be aware of their privacy policy, which could apply to your use of GA; see it here <a href="https://www.google.com/analytics/terms/us.html" target="_blank">https://www.google.com/analytics/terms/us.html</a> </p>
<p>Please see the Disclaimer information below for additional information.</p>';
	}

	public function SGDPR_privacy_page_name_callback() {

		// get privacy page id from core options and echo here
		$policy_page_id = get_option( 'wp_page_for_privacy_policy' ) ;
		$policy_page_name = get_the_title( $policy_page_id ) ;
		if ($policy_page_id) {
			$selected_page = get_the_title($policy_page_id);
		}
		printf(
/*			wp_dropdown_pages(array('echo' => 0, 'post_type' => 'page', 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'selected' => $policy_page_id, 'name' => "SGDPR_options[SGDPR_privacy_page_name]", 'show_option_none' => 'Select Your Privacy Page')),
			isset($this->options['SGDPR_privacy_page_name']) ? esc_attr($this->options['SGDPR_privacy_page_name']) : '');*/

		wp_dropdown_pages(array('echo' => 0, 'post_type' => 'page', 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'selected' => $policy_page_id, 'name' => "SGDPR_options[SGDPR_privacy_page_name]", 'show_option_none' => 'Select Your Privacy Page')),
			isset($policy_page_name) ? esc_attr($policy_page_name) : '');
		print(' Select the name of your Privacy Page. This will be used to create the link in the GDPR message.The value selected here is the same as on the Settings, Privacy page. Setting this value on one page will sync to the other page.');
	}

	public function SGDPR_add_link_to_footer_callback() {
		$selected_page_option = get_option('SGDPR_options');
		$add_link_to_footer   = (isset($selected_page_option['SGDPR_add_link_to_footer'])) ? $selected_page_option['SGDPR_add_link_to_footer'] : false;
		$checked              = $add_link_to_footer ? "checked" : "";
		printf(
			'<input type="checkbox" name="SGDPR_options[SGDPR_add_link_to_footer]" id="SGDPR_add_link_to_footer" value="%s"  ' . $checked . '> <label for="SGDPR_add_link_to_footer">Enable to add Privacy Page link to site footer. The link will use the Privacy Page specified above, as stored in Settings, Privacy.</label>',
			isset($checked) ? '1' : '0'
		);
	}

	public function SGDPR_GA_ID_number_callback() {
		$selected_page_option = get_option('SGDPR_options');
		$GA_ID                = $selected_page_option['SGDPR_GA_ID_number'];
		printf(
			'<input class="regular-text" type="text" name="SGDPR_options[SGDPR_GA_ID_number]" id="SGDPR_GA_ID_number" value="%s">',
			$GA_ID
		);
		print(' Enter your GA ID UA (Universal Analytics) number; it is not verified. If you don\'t want GA tracking, or use another process, leave this blank (although that\'s the whole point of this plugin). Note that the standard GA JavaScript code might be blocked by ad blockers, so we use a server-side process to allow basic tracking for visitors with ad blocking enabled on their browser. Note there is no support for GA4 at this time (but we plan to add that in the future). If you have another process that does your GA, don\'t use this option, or you will get inaccurate analytics numbers.' );
	}
}
if (is_admin()) {
	$simple_gdpr = new SimpleGDPR();
}

// ----------------------------------------------------------------------------
// supporting functions
// ----------------------------------------------------------------------------
//  display the top info part of the settings page
// ----------------------------------------------------------------------------
function SGDPR_info_top() {
	?>
<div class="wrap" >
    <h2></h2>
<div align='center' class = 'SGDPR_header'>
    <div align='center'>
    <img src="<?php echo plugin_dir_url(__FILE__); ?>assets/banner-1000x200.jpg" width="100%"  alt="" class='SGDPR_shadow'>
        <h2 align="center">Adds a simple GDPR Compliance message and button to your site. <br>Optionally allows you to add server-side Google Analytics.</h2>
        <h5>Version <?php echo SGDPR_VERSION; ?></h5>
    </div>
    <hr />
</div>
</div>
<?php
}

// ----------------------------------------------------------------------------
//  settings page sidebar content
// ----------------------------------------------------------------------------
function SGDPR_sidebar() {
	?>
    <h3 align="center">But wait, there's more!</h3>
    <p><b>Need to stop Comment spam?</b> We've got a plugin that does that - install it and comment spam will stop immediately. Very effective. Does not require any other actions or configuration, and your comment form will look the same. It just works! See details here: <a href="https://wordpress.org/plugins/block-comment-spam-bots/" target="_blank" title="Block Comment Spam Bots">Block Comment Spam Bots</a> .</p>
<p><b>Plus these Contact Form spam-blocking plugins:</b></p>
<p><b>If you want to block bots from your contact form</b>, head over to our <a href="https://www.FormSpammerTrap.com" target="_blank" title="FormSpammerTrap - blocks Contact form spammers">FormSpammerTrap</a> site. <i>Works on WP and non-WP sites.</i> Takes a bit of programming, but we can help with that. Full docs and implementation instructions. Just request the free code via the site's Contact form. It's the most powerful and effective way to block Contact Form spammers!</p>
    <p><a href="https://wordpress.org/plugins/formspammertrap-for-comments/" target="_blank"><strong>FormSpammerTrap for Comments</strong></a>: reduces spam without captchas, silly questions, or hidden fields - which don't always work. You can also customize the look of your comment form. Uses the same techniques as our Block Comment Spam Bots plugin. </p>
    <p><a href="https://wordpress.org/plugins/formspammertrap-for-contact-form-7/" target="_blank"><strong>FormSpammerTrap for Contact Form 7</strong></a>: reduces spam when you use Contact Form 7 forms. All you do is add a little shortcode to the contact form.</p>
    <hr />
   <p>For <strong>multisites</strong>, we've got:
    <ul>
        <li><strong><a href="https://wordpress.org/plugins/multisite-comment-display/" target="_blank">Multisite Comment Display</a></strong> to show all comments from all subsites.</li>
        <li><strong><a href="https://wordpress.org/plugins/multisite-post-reader/" target="_blank">Multisite Post Reader</a></strong> to show all posts from all subsites.</li>
        <li><strong><a href="https://wordpress.org/plugins/multisite-media-display/" target="_blank">Multisite Media Display</a></strong> shows all media from all subsites with a simple shortcode. You can click on an item to edit that item. </li>
    </ul>
    </p>
    <hr />
    <p><b>Other Plugins</b></p>
     <p>We've got a <a href="https://wordpress.org/plugins/simple-gdpr/" target="_blank"><strong>Simple GDPR</strong></a> plugin that displays a GDPR banner ('cookie consent') for the user to acknowledge. And it creates a generic Privacy page, and will put that Privacy Page link at the bottom of all pages.</p>
<p><b>An option will do server-side Google Analytics (GA).</b> Did you know what GA is blocked by many ad-blockers - diluting the accuracy of your analytics? This will ensure that every visitor access is captured by GA - and with anonymized information that doesn't store personal information.</p>
    <p>How about our <strong><a href="https://wordpress.org/plugins/url-smasher/" target="_blank">URL Smasher</a></strong> which automatically shortens URLs in pages/posts/comments?</p>
<p><b>Or one that automatically adds your Affiliate link to all Amazon links - in posts and comments?</b> That's what our Amazolinkentor plugin does, and you can get it <a href="https://wordpress.org/plugins/amazolinkenator/" target="_blank" title="Automatic Affiliate Code Insertion">here</a>.</p>
    <hr />
    <p><strong>They are all free and fully featured!</strong></p>
    <hr />
    <p>I don't drink coffee, but if you are inclined to donate any amount because you like my WordPress plugins, go right ahead! I'll grab a nice hot chocolate, and maybe a blueberry muffin.  Maybe another bag of Cherry Jelly Belliees. And a nice <a href="https://wordpress.org/plugins/simple-gdpr/#reviews" target="_blank" title="Simple GDPR Plugin Reviews page">review on the plugin page</a> is always appreciated! Or just contact us at <a href="https://cellarweb.com/contactus/" target="_blank">https://cellarweb.com/contactus/</a>. </p>
    <div align="center">
        <?php SGDPR_donate_button();?>
    </div>
    <p align='center'><b>Thanks!  <a href="https://www.RichardHellewell.com" target="_blank" title="Richard Hellewell author site">Richard Hellewell</a>, somewhere opposite Mutiny Bay WA.</b></p>
    <hr />
    <p><strong>Privacy Notice</strong>: This plugin does not store or use any personal information or cookies.</p>
<?php
SGDPR_cellarweb_logo();

	return;
}

// ============================================================================
// footer for settings page
// ----------------------------------------------------------------------------
function SGDPR_footer() {
	?>
    <hr><h3 align='center' class='SGDPR_larger_text'><b>Thanks for using Simple GDPR!  Tell your friends!</b></h3>
<hr><div style="background-color:#9FE8FF !important; padding:10px;color:black !important; ">
    <p align="center"><strong>Copyright &copy; 2016- <?php echo date('Y'); ?> by Rick Hellewell and <a href="http://CellarWeb.com" title="CellarWeb" >CellarWeb.com</a> , All Rights Reserved. Released under GPL2 license. <a href="http://cellarweb.com/contact-us/" target="_blank" title="Contact Us">Contact us page</a>.</strong></p>
</div>
<hr><br>
<?php
return;
}

// ----------------------------------------------------------------------------
// display the copyright info part of the adminpage
// ----------------------------------------------------------------------------
function SGDPR_info_bottom() {
	SGDPR_create_page_button(); // show the create the privacy page button
	// print copyright with current year, never needs updating
	$xstartyear    = "2016";
	$xname         = "Rick Hellewell";
	$xcompanylink1 = ' <a href="http://CellarWeb.com" title="CellarWeb" >CellarWeb.com</a>';
	echo '<hr><div style="background-color:#9FE8FF;padding-left:15px;padding:10px 0 10px 0;margin:15px 0 15px 0;">
    <p align="center"><strong>Copyright &copy; ' . $xstartyear . '- ' . date("Y") . ' by ' . $xname . ' and ' . $xcompanylink1;
	echo ' , All Rights Reserved. Released under GPL2 license. <a href="http://cellarweb.com/contact-us/" target="_blank" title="Contact Us">Contact us page</a>.</strong></p></div><hr>';
	return;
}

// ----------------------------------------------------------------------------
function SGDPR_cellarweb_logo() {
	?>
 <p align="center"><a href="https://www.cellarweb.com" target="_blank" title="CellarWeb.com site"><img src="<?php echo plugin_dir_url(__FILE__); ?>assets/cellarweb-logo-2022.jpg"  width="90%" class="SGDPR_shadow" ></a></p>
 <?php
return;
}

// ============================================================================
// PayPal donation button for settings sidebar (as of 25 Jan 2022)
// ----------------------------------------------------------------------------
function SGDPR_donate_button() {
	?>
<form action="https://www.paypal.com/donate" method="post" target="_top">
	<input type="hidden" name="hosted_button_id" value="TT8CUV7DJ2SRN" />
	<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" title="PayPal - The safer, easier way to pay online!" alt="Donate with PayPal button" />
	<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1" />
</form>

<?php
return;
}

// ----------------------------------------------------------------------------
function SGDPR_button_admin_page() {
	// This function creates the output for the admin page.
	// It also checks the value of the $_POST variable to see whether
	// there has been a form submission.
	// The check_admin_referer is a WordPress function that does some security
	// checking and is recommended good practice.
	global $SGDPR_submit_html; // text for html button
	global $SGDPR_submit_create_page; // text for html button
	// General check for user permissions.
	if (!current_user_can('manage_options')) {
		wp_die(__('You do not have sufficient privileges to access this page.'));
	}
	// Start building the page
	echo '<div class="wrap">';
	echo '<hr>';
	echo '<div style="border:thin solid #000; padding: 5px 15px 5px 15px;margin-left: 15px;max-width:800px;list-style:none !important;">';
	echo "<p>A simple way to add GDPR compliance to your site. Adds a banner to all pages that must be clicked to 'actively acknowledge' acceptance of use of cookies and tracking. Will also add server-side Google Anlaytics, for those visitors that use ad-blocking, if you fill in your GA user ID below and Save Settings.</p>";

	// form starts here if we want a button to do anything
	echo '<form action="options.php" method="post">';
	settings_fields('SGDPR_options');
	do_settings_section('SGDPR_options');

	?>
<?php
submit_button($SGDPR_submit_html, 'button-primary', 'SGDPR_button');
	echo '</form>';
	echo "<hr style=\"border-top: 3px solid #2ebc57;\" />";
	echo '<hr>';
}

// ----------------------------------------------------------------------------
// register/deregister/uninstall options (even though there aren't options)
function SGDPR_register() {
	return;
}

function SGDPR_deregister() {
	return;
}

function SGDPR_uninstall() {
	return;
}

//----------------------------------------------------------------------------
// delete old generated files
function SGDPR_delete_old_files() {
	return true;
}

// ----------------------------------------------------------------------------
// check if at least WP 4.6 and PHP version at least 5.3
// based on https://www.sitepoint.com/preventing-wordpress-plugin-incompatibilities/
function SGDPR_is_requirements_met($min_wp = '4.6', $min_php = '5.4') {
	// Check for WordPress version
	if (version_compare(get_bloginfo('version'), $min_wp, '<')) {
		return false;
	}
	// Check the PHP version
	if (version_compare(PHP_VERSION, $min_php, '<')) {
		return false;
	}
	return true;
}

// ----------------------------------------------------------------------------
// disable plugin if WP/PHP versions are not enough
function SGDPR_disable_plugin() {
	if (is_plugin_active(plugin_basename(__FILE__))) {
		deactivate_plugins(plugin_basename(__FILE__));
		// Hide the default "Plugin activated" notice
		if (isset($_GET['activate'])) {
			unset($_GET['activate']);
		}
	}
}

// ----------------------------------------------------------------------------
// show notice that plugin was deactivated because WP/PHP versions not enough
function SGDPR_show_notice_disabled_plugin() {
	echo '<div class="notice notice-error is-dismissible"><h3><strong>Simple GDPR</strong></h3><p> cannot be activated - requires at least WordPress 4.6 and PHP 5.4.&nbsp;&nbsp;&nbsp;Plugin automatically deactivated.</p></div>';
	return;
}

// ----------------------------------------------------------------------------
// admin notice if something failed
function SGDPR_admin_notice_generic_error($theerrors = array('Something did not work correctly!')) {
	foreach ($the_errors as $the_error) {
		echo "<div class='notice notice-error is-dismissible'><h3><strong>Simple GDPR</strong></h3><p> - Error: $the_error .</p></div>";
	}
	return;
}

// ----------------------------------------------------------------------------
// this adds the two functions to the head section via the hook for public pages
function SGDPR_the_footer() {
	SGDPR_cookie_compliance(); // shows the cookie acceptance notice if needed
	$SGDPR_analytics_ID = '';
	$SGDPR_options      = get_option('SGDPR_options');
	$SGDPR_GA_ID        = $SGDPR_options['SGDPR_GA_ID_number'];
	// do se rver-side analytics if enabled by a GA ID on settings screen
	if ($SGDPR_GA_ID) {
		SGDPR_analytics($SGDPR_GA_ID);
	}
	return;
}

//------------------------------------------------------------------------------
// new version to allow analytics on adblock pages by using server-side post
function SGDPR_analytics() {
	$options = get_option('SGDPR_options');
	// SGDPR_print_array($options);
	$GA_code = $options['SGDPR_GA_ID_number']; // SGDPR_GA_ID_number
	// get the GA ID from the options table
	$url = 'https://www.google-analytics.com/collect?';
	if (empty($GA_code)) {;return false;}
	$pagename = basename(get_permalink()); // current page name, WP-style
	if (wp_get_referer()) {$page_referrer = wp_get_referer();} else { $page_referrer = "";}
	$page_referrer = urlencode($page_referrer);
	$current_url =  $_SERVER['REQUEST_URI']; // can't use get_permalink, which doesn't work for the home page. And it is secure (not modifiable by visitor) so doesn't need sanitation. See https://stackoverflow.com/a/6474936/1466973 
	// create a unique value to send with the request
	//   use session_id value set in SGDPR_session_init()
	//       or SGDPR_guidv4()  if seesion not started (should never happen)
	$user_id = (session_id()) ? session_id() : SGDPR_guidv4();
	// force anoymize IP addresses just in case GA doesn't do it right
	$uip = SGDPR_anon_IP($_SERVER['REMOTE_ADDR']);
	// build the data array that GA wants
	$referer = wp_validate_redirect(wp_get_referer()) ;

	// build the data array that GA wants
	$data = array(
		'v' => 1,
		'tid' => $GA_code, // site GA id code UA-xxxxxxxxxx ; change this
		'cid' => $user_id, // customer ID (cookie or session id)
		't' => 'pageview', // type of access
		'dp' => $current_url, // page name
		'aip' => '0', //anonymize the IP address   - don't need to, since we already did, so force no anonymize
		'uip' => $uip, // used for geo data in analytics , pre-anonymized just in case
		'ds' => 'web', // datasource, optional, set to 'web'
		'dr' => $referer, // referring page
		'z' => SGDPR_guidv4(), // cache buster, MUST BE LAST parameter!
	);
	$fields_string = http_build_query($data);
	// do the request the "WordPress way"  (don't use CURL)
	// send the post via wp_remote_post

	$response = wp_remote_post($url . $fields_string);
	return $response;
}

function SGDPR_anon_IP($ip) {
	return preg_replace(
		array('/\.\d*$/', '/[\da-f]*:[\da-f]*$/'),
		array('.0', '0000:0000'),
		$ip
	);
}

//------------------------------------------------------------------------------
// creates a guid for use by the GA post to send unique user id
function SGDPR_guidv4() {
	if (function_exists('com_create_guid') === true) {
		return trim(com_create_guid(), '{}');
	}

	$data    = openssl_random_pseudo_bytes(16);
	$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
	$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
	return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

//------------------------------------------------------------------------------
// if we can't find the consent cookie, then ...
if (!isset($_COOKIE['cookieconsent_status'])) {
	add_action('after_header', 'SGDPR_cookie_compliance'); // add the compliance message
	add_action('wp_enqueue_scripts', 'SGDPR_cookie_script'); // add the compliance script
	add_action('wp_enqueue_scripts', 'SGDPR_cookie_css'); // add the compliance css
}

//------------------------------------------------------------------------------
// GDPF compliance from https://cookieconsent.insites.com/
// their javascript used under MIT license
function SGDPR_cookie_compliance() {
	global $SGDPR_learn_more_url;
	// figure out the privacy page name from the saved options
 /*	$selected_page_option = get_option('SGDPR_options');
	$selected_page_id     = $selected_page_option['SGDPR_privacy_page_name'];
*/
// new get privacy page ID from the privacy page, not the plugins options
			$selected_page_id = (int) get_option( 'wp_page_for_privacy_policy' ) ;
		if ($selected_page_id) {
			$selected_page = get_the_title($selected_page_id);
		}


	if ($selected_page_id) {
		$SGDPR_learn_more_url = site_url() . '/' . get_the_title($selected_page_id);
	} else { $SGDPR_learn_more_url = site_url();}
	?>
<!-- display the consent message using the API after page is loaded -->
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
 "palette": {
 "popup": {
"background": "#237afc"
 },
 "button": {
"background": "#f1d600",
"text": "#000"
 }
 },
 "position": "top",
 "content": {
 "dismiss": "I agree - OK with me! (Click here)",
    "message": "This website uses cookies to ensure you get the best experience on our website. We may also store personal information (name, email) if you add comments to the site, or if you use our Contact form. By browsing our site, you agree to our use of cookies and storage of other personal information. Click the 'I agree' button to agree and continue viewing our site. Or, ",
    "href" : "<?php echo $SGDPR_learn_more_url; ?>",
 }
})});
</script>
<?php

	return;
}

//------------------------------------------------------------------------------
// these enqueue the JS and CSS; included in the plugin dist
function SGDPR_cookie_script() {
	wp_enqueue_script('cookieconsent_js', plugin_dir_url(__FILE__) . 'js/cookieconsent/cookieconsent.min.js');
}

function SGDPR_cookie_css() {
	wp_enqueue_style('cookieconsent_css', plugin_dir_url(__FILE__) . 'js/cookieconsent/cookieconsent.min.css');
	wp_enqueue_style('cookieconsent_css_extra', plugin_dir_url(__FILE__) . 'css/consent_extra.css');
}

//------------------------------------------------------------------------------
// generic content if we create the privacy page
function SGDPR_privacy_page_content() {
	$page_content = "
<h3>Privacy Notice</h3>
<p>This privacy notice discloses the privacy practices for this site. This privacy notice applies solely to information collected by this website. It will notify you of the following: What personally identifiable information is collected from you through the website, how it is used and with whom it may be shared.
<ul>
    <li>What choices are available to you regarding the use of your data.</li>
    <li>The security procedures in place to protect the misuse of your information.</li>
    <li>How you can correct any inaccuracies in the information.</li>
</ul>
<h3>Information Collection, Use, and Sharing</h3>
<p>We are the sole owners of the information collected on this site. We only have access to/collect information that you voluntarily give us via email, of by accessing our site, or other direct contact from you. We will not sell or rent this information to anyone. We will use your information to respond to you, regarding the reason you contacted us.</p>

<p>We will not share your information with any third party outside of our organization, other than as necessary to fulfill your request, e.g. to ship an order. Unless you ask us not to, we may contact you via email in the future to tell you about specials, new products or services, or changes to this privacy policy.</p>
<h3>Your Access to and Control Over Information</h3>
<p>You may opt out of any future contacts from us at any time. You can do the following at any time by contacting us via the email address or phone number given on our website:</p>
<ul>
    <li>See what data we have about you, if any.</li>
    <li>Change/correct any data we have about you.</li>
    <li>Have us delete any data we have about you.</li>
    <li>Express any concern you have about our use of your data.</li>
</ul>
<h3>Security</h3>
<p>We take precautions to protect your information. When you submit sensitive information via the website, your information is protected both online and offline.
</p>
<p>Wherever we collect sensitive information (such as credit card data), that information is encrypted and transmitted to us in a secure way. You can verify this by looking for a lock icon in the address bar and looking for <strong>https</strong> at the beginning of the address of the Web page.</p>
<p>While we use encryption to protect sensitive information transmitted online, we also protect your information offline. Only employees who need the information to perform a specific job (for example, billing or customer service) are granted access to personally identifiable information.</p>
<p>The computers/servers in which we store personally identifiable information are kept in a secure environment.</p>
<h3>Cookies</h3>
<p>We use cookies on this site. A cookie is a piece of data stored on a site visitor hard drive to help us improve your access to our site and identify repeat visitors to our site. For instance, when we use a cookie to identify you, you would not have to log in a password more than once, thereby saving time while on our site. Cookies can also enable us to track and target the interests of our users to enhance the experience on our site. Usage of a cookie is in no way linked to any personally identifiable information on our site.</p>
<h3>Sharing</h3>
<p>We share aggregated demographic information with our partners and advertisers. This is not linked to any personal information that can identify any individual person.</p>
<h3>Links</h3>
<p>This website contains links to other sites. Please be aware that we are not responsible for the content or privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of any other site that collects personally identifiable information.</p>
<h3>Contacting Us</h3>
<p>If you feel that we are not abiding by this privacy policy, you should contact us immediately via our Contact page.
</p>";

	return $page_content;
}

// ----------------------------------------------------------------------------
// creates the button to create the generic privacy page
function SGDPR_create_page_button() {; //  SGDPR_show_test_button($SGDPR_bitly_token);
	?>
<hr />
<h2>Create a Generic Privacy Page</h2>
<p>Click this button to create a generic Privacy Page. <i>Note: each button press will create a new page called 'Privacy Page', so you may get extra ones.</i> Save changes first.</p>
<form method="post" name="create_privacy_page" id="create_privacy_page" action="" >
    <input type="submit" name="create_privacy_page" id="create_privacy_page" value="Create Generic Privacy Page" style="background-color:yellow;"/>
</form>
<?php
SGDPR_disclaimer();
  /*	return $blog_page_id;}  */
	return ;}

// ----------------------------------------------------------------------------
// created the page successfully, so show an admin notice
function SGDPR_page_created_notice() {
	echo '<div class="notice notice-success is-dismissible"><p><strong>Success!</strong> Created the new page called "Privacy Page". You can edit this page if needed; just don\'t create it again. Check for duplicate pages if you have done this more than once.</p><p>Make sure you select the Privacy Page to use in the settings and save changes. You should also add the new Privacy Page to your main menu.</div>';
	return;
}

// ----------------------------------------------------------------------------
// whoops! didn't create the privacy page, so show the admin notice
function SGDPR_page_not_created_notice() {
	echo '<div class="notice notice-error is-dismissible"><strong>Yikes!</strong>Wasn\'t able to create the Privacy Page !</p></div>';
	return;
}

// ----------------------------------------------------------------------------
// show the disclaimer text on the plugin settings page
function SGDPR_disclaimer() {
	?>
<hr>
<h2>Disclaimer</h2>
<p>This plugin may not provide full protection for your site, depending on how your site stores and uses personal data. We think our technique meets the basic notification requirements of GDPR, but you should consult with your legal advisors for guidance on what your site needs to do for GDPR compliance. The plugin does not have reporting capabilities; use the WP Settings, Privacy page for managing your visitor's personal information. Here is the 'official' GDPR site: <a href="https://www.eugdpr.org/" target="_blank">https://www.eugdpr.org/</a> . </p>
<p>For reference:</p>
<ul style="list-style:disc;margin-left:15px;">
    <li>We use the code from the Cookie Consent site at <a href="https://cookieconsent.insites.com/" target="_blank">https://cookieconsent.insites.com/</a> to display the acceptance message and track user preference (via a 'yes/no' cookie) for the message notice.</li>

    <li>This plugin does not store any visitor's personal information on your server, except the "Cookie Consent" cookie on the visitor's browser. </li>
</ul>
<p>We suggest that you consult with your legal advisor for specific methods and messages needed for GDPR compliance on your site.<em> We provide no warranty or guarantee of GDPR compliance. We are not providing any legal advice. We are not responsible in any way for your use of our suggested GDPR solution.</em> (Your mileage may vary. Objects in mirror are closer than you expect. All aspirin is alike. Professional driver on a closed course.)</p>
<?php

	return;
}

// ----------------------------------------------------------------------------
// update the WP/core privacy page ID in options

function SGDPR_save_wp_core_privacy_page_id() {
	//plugin settings have been saved. This updates the WP/core privacy page id number

	// get the page id of the page in the plugin
	$SGDPR_options = get_option('SGDPR_options');
	  //  $privacy_page_info = get_page_by_title($SGDPR_options['SGDPR_privacy_page_name'] );
	// get core privacy page ID
	$core_privacy_id = get_option('wp_page_for_privacy_policy');
	// set the new value if there, otherwise use old value
    $privacy_page_id = (!isset($_POST['SGDPR_options']['SGDPR_privacy_page_name'] )) ? $core_privacy_id : $_POST['SGDPR_options']['SGDPR_privacy_page_name'] ;

	// update settings, privacy privacy page ID in core
		update_option('wp_page_for_privacy_policy', $privacy_page_id);
	return;
}

// ----------------------------------------------------------------------------------
// enable footer display of privacy page link, only if set
$SGDPR_options = get_option('SGDPR_options');
$insert_footer = (isset($SGDPR_options['SGDPR_add_link_to_footer'])) ? true : false ;
if ($insert_footer) {
	add_action('wp_footer', 'SGDPR_add_privacy_to_footer');
}
function SGDPR_add_privacy_to_footer() {
	// was get_the_privacy_policy_link
	$the_privacy_link = the_privacy_policy_link('<div align="center"><p>', '</p></div>');
	echo $the_privacy_link;

	return;
}

// --------------------------------------------------------------------------
// for debugging array contents
// --------------------------------------------------------------------------
function SGDPR_print_array($the_array = array()) {
	echo "<div style='color:black;background-color:white;width=90%;display:block;'>";
	echo "<pre> ";
	print_r($the_array);
	echo "</pre> ";
	echo "</div>";
	return;
}

function SGDPR_show_globals() {
	echo "<table border='1'><tr><td>GET</td><td>POST</td><td>FILES</td><td>REQUEST</td><td>SESSION</td></tr>";
	echo "<tr><td><pre>";
	print_r($_GET);
	echo "</pre></td>";
	echo "<td><pre>";
	print_r($_POST);
	echo "</pre></td>";
	echo "<td><pre>";
	print_r($_FILES);
	echo "</pre></td>";
	echo "<td><pre>";
	print_r($_REQUEST);
	echo "</pre></td>";
	echo "<td><pre>";
	print_r($_SESSION);
	echo "</pre></td></tr></table>";
	// for server variables
	// echo '<table border="1">';
	//foreach ($_SERVER as $k => $v){
	//echo "<tr><td>" . $k ."</td><td>" . $v . "</td></tr>";
	//}
	//
	//echo "</table>";
	return;
}

// -------------------------------------------------------------------------------
// -------------------------------------------------------------------------------

// ===============================================================================
// ALL DONE!!
// ===============================================================================
