added additional plugins

This commit is contained in:
Rodolfo Martinez 2025-12-12 19:05:48 -05:00
parent c85895d306
commit 00e60ec1b7
132 changed files with 27514 additions and 0 deletions

View file

@ -0,0 +1,117 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
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 Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice

View file

@ -0,0 +1,107 @@
# Maple GDPR Cookies - FIXED VERSION v4.0.1
## 🔧 Critical Fix Applied
### Issue Fixed:
**Fatal Error:** Call to undefined function `wp_cache_delete_group()`
### Root Cause:
The function `wp_cache_delete_group()` does not exist in WordPress core. This was causing a fatal error during plugin activation at line 273.
### Solution Implemented:
Completely rewrote the `mgc_clear_all_caches()` function (lines 145-190) to use proper WordPress cache functions:
1. **wp_cache_flush()** - Clears all WordPress object cache
2. **delete_transient()** - Removes plugin-specific transients
3. **wp_cache_delete()** - Deletes specific cache keys
4. **Database query** - Cleans up orphaned transient entries
5. **Action hooks** - Allows other plugins to integrate
### What Changed:
#### BEFORE (Lines 145-150 - BROKEN):
```php
function mgc_clear_all_caches() {
wp_cache_delete_group('maple-gdpr-cookies'); // ❌ Doesn't exist
delete_transient('mgc_settings');
}
```
#### AFTER (Lines 145-190 - FIXED):
```php
function mgc_clear_all_caches() {
// Method 1: Clear WordPress object cache
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
// Method 2: Clear plugin-specific transients
global $wpdb;
$transients = $wpdb->get_col(
"SELECT option_name FROM $wpdb->options
WHERE option_name LIKE '_transient_mgc_%'"
);
foreach ($transients as $transient) {
$transient_key = str_replace('_transient_', '', $transient);
delete_transient($transient_key);
}
// Method 3: Clear specific plugin caches
$cache_keys = array('mgc_settings', 'mgc_stats', 'mgc_consent_logs');
foreach ($cache_keys as $key) {
wp_cache_delete($key, 'maple-gdpr-cookies');
delete_transient($key);
}
// Method 4: WooCommerce compatibility
if (function_exists('wc_delete_shop_order_transients')) {
wc_delete_shop_order_transients();
}
// Method 5: Extensibility hook
do_action('mgc_clear_caches');
}
```
## ✅ Benefits of the Fix:
1. **Works Everywhere** - Compatible with all WordPress installations
2. **No Fatal Errors** - Uses only existing WordPress functions
3. **Comprehensive** - Clears all types of caches (object, transient, database)
4. **Plugin Compatibility** - Includes WooCommerce integration
5. **Extensible** - Developers can hook into cache clearing
## 🚀 Installation:
1. **Deactivate** the old version (if active)
2. **Delete** the old plugin folder
3. **Upload** this fixed version
4. **Activate** the plugin
The plugin will now activate successfully without fatal errors!
## 📋 Version History:
- **v4.0.1** (Oct 24, 2025) - CRITICAL FIX: Replaced wp_cache_delete_group() with proper cache functions
- **v4.0.0** - Original version with cache bug
## 🔒 No Other Changes:
All other functionality remains identical:
- GDPR compliance features ✅
- Security measures ✅
- WooCommerce/LearnDash compatibility ✅
- Consent logging ✅
- Cookie management ✅
## 📞 Support:
If you encounter any issues with this fix, please check:
1. WordPress version 5.0+ ✅
2. PHP version 7.2+ ✅
3. MySQL version 5.5.3+ ✅
---
**This is a critical hotfix that resolves the activation fatal error while maintaining all plugin functionality.**

View file

@ -0,0 +1,75 @@
/* Maple GDPR Cookies - Admin Styles */
.mgc-admin-wrap {
max-width: 1200px;
margin: 20px 0;
}
.mgc-panel {
background: #fff;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
margin-bottom: 20px;
}
.mgc-panel-header {
background: #f6f7f7;
border-bottom: 1px solid #ccd0d4;
padding: 15px 20px;
}
.mgc-panel-header h3 {
margin: 0;
font-size: 16px;
font-weight: 600;
}
.mgc-panel-body {
padding: 20px;
}
.mgc-form-row {
margin-bottom: 20px;
}
.mgc-form-row label {
display: block;
margin-bottom: 8px;
font-weight: 600;
}
.mgc-form-row input[type="text"],
.mgc-form-row input[type="url"],
.mgc-form-row input[type="number"],
.mgc-form-row textarea,
.mgc-form-row select {
width: 100%;
max-width: 600px;
}
.mgc-form-row input[type="text"]#mgc_custom_button_color,
.mgc-form-row input[type="text"]#mgc_custom_button_hover_color {
max-width: 200px;
font-family: monospace;
font-size: 14px;
}
.mgc-form-row .description {
margin-top: 5px;
font-style: italic;
color: #666;
}
.mgc-form-row textarea {
min-height: 100px;
}
.mgc-preview {
border: 1px solid #ddd;
padding: 20px;
background: #f9f9f9;
margin-top: 20px;
}
.mgc-save-button {
margin-top: 20px;
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,120 @@
/* Maple GDPR Cookies - Admin JavaScript */
(function ($) {
"use strict";
$(document).ready(function () {
// Initialize color picker
if ($.fn.wpColorPicker) {
$(".mgc-color-picker").wpColorPicker();
}
// Custom color input preview
function updateColorPreview(input) {
var color = $(input).val();
var hexPattern = /^#[0-9A-F]{6}$/i;
if (hexPattern.test(color)) {
$(input).css({
"border-left": "5px solid " + color,
"border-color": color,
});
} else {
$(input).css({
"border-left": "",
"border-color": "",
});
}
}
// Add event listeners for custom color inputs
$("#mgc_custom_button_color, #mgc_custom_button_hover_color").on(
"input change",
function () {
updateColorPreview(this);
},
);
// Initialize preview on page load
$("#mgc_custom_button_color, #mgc_custom_button_hover_color").each(
function () {
updateColorPreview(this);
},
);
// Preview functionality
$("#mgc-preview-button").on("click", function (e) {
e.preventDefault();
// Trigger preview update
updatePreview();
});
function updatePreview() {
// Simple preview update logic
console.log("Preview updated");
}
// Handle preference display type radio buttons
var $preferenceRadios = $('input[name="mgc_preference_display_type"]');
var $gdprWarning = $("#mgc-gdpr-warning");
// Function to toggle GDPR warning visibility
function toggleGdprWarning() {
var selectedType = $(
'input[name="mgc_preference_display_type"]:checked',
).val();
if (selectedType === "neither") {
// Create warning if it doesn't exist
if ($gdprWarning.length === 0) {
var warningHtml =
'<div id="mgc-gdpr-warning" style="background: #fff3cd; padding: 12px; border-left: 4px solid #ffc107; margin-top: 10px; margin-bottom: 15px;">' +
'<strong style="color: #856404;">⚠️ GDPR Compliance Reminder:</strong>' +
'<p style="margin: 5px 0; color: #856404;">To remain GDPR compliant, you must add this shortcode to your footer or make it easily accessible on all pages:</p>' +
'<code style="background: #fff; padding: 6px 10px; border-radius: 3px; display: inline-block; font-size: 14px; border: 1px solid #ffc107;">[mgc_cookie_preferences]</code>' +
'<p style="margin: 10px 0 0 0; font-size: 12px; color: #856404;">GDPR requires users to have easy access to withdraw their consent at any time.</p>' +
"</div>";
$(warningHtml).insertAfter($preferenceRadios.last().parent());
$gdprWarning = $("#mgc-gdpr-warning");
}
$gdprWarning.slideDown(200);
} else {
if ($gdprWarning.length > 0) {
$gdprWarning.slideUp(200);
}
}
}
// Initialize warning on page load
toggleGdprWarning();
// Handle radio button changes
$preferenceRadios.on("change", function () {
toggleGdprWarning();
});
// Form validation
$("form").on("submit", function (e) {
// Validate hex colors
var customColor = $("#mgc_custom_button_color").val();
var customHoverColor = $("#mgc_custom_button_hover_color").val();
var hexPattern = /^#[0-9A-F]{6}$/i;
if (customColor && !hexPattern.test(customColor)) {
alert("Custom Button Color must be a valid hex color (e.g., #3498db)");
$("#mgc_custom_button_color").focus();
return false;
}
if (customHoverColor && !hexPattern.test(customHoverColor)) {
alert(
"Custom Button Hover Color must be a valid hex color (e.g., #2980b9)",
);
$("#mgc_custom_button_hover_color").focus();
return false;
}
return true;
});
});
})(jQuery);

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,106 @@
<?php
/**
* Consent Logs View
*/
if (!defined('ABSPATH')) {
exit;
}
global $wpdb;
$table_name = $wpdb->prefix . 'mgc_consent_logs';
// Get logs with pagination
$per_page = 50;
$page = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
$offset = ($page - 1) * $per_page;
$logs = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name ORDER BY consent_date DESC LIMIT %d OFFSET %d",
$per_page,
$offset
)
);
$total_logs = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
$total_pages = ceil($total_logs / $per_page);
?>
<div class="wrap mgc-admin-wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<div class="mgc-panel">
<div class="mgc-panel-header">
<h3><?php _e('Consent Logs', 'maple-gdpr-cookies'); ?></h3>
</div>
<div class="mgc-panel-body">
<p><?php printf(__('Total logs: %d', 'maple-gdpr-cookies'), $total_logs); ?></p>
<?php if (!empty($logs)) : ?>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th><?php _e('Date', 'maple-gdpr-cookies'); ?></th>
<th><?php _e('User', 'maple-gdpr-cookies'); ?></th>
<th><?php _e('IP Address', 'maple-gdpr-cookies'); ?></th>
<th><?php _e('Consent Type', 'maple-gdpr-cookies'); ?></th>
<th><?php _e('Categories', 'maple-gdpr-cookies'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($logs as $log) : ?>
<tr>
<td><?php echo esc_html($log->consent_date); ?></td>
<td>
<?php
if ($log->user_id) {
$user = get_userdata($log->user_id);
echo $user ? esc_html($user->display_name) : __('Unknown', 'maple-gdpr-cookies');
} else {
echo __('Guest', 'maple-gdpr-cookies');
}
?>
</td>
<td><?php echo esc_html($log->ip_address); ?></td>
<td>
<span class="mgc-consent-<?php echo esc_attr($log->consent_type); ?>">
<?php echo esc_html(ucfirst($log->consent_type)); ?>
</span>
</td>
<td>
<?php
$categories = json_decode($log->categories, true);
if (!empty($categories) && is_array($categories)) {
echo esc_html(implode(', ', $categories));
} else {
echo __('N/A', 'maple-gdpr-cookies');
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if ($total_pages > 1) : ?>
<div class="tablenav">
<div class="tablenav-pages">
<?php
echo paginate_links(array(
'base' => add_query_arg('paged', '%#%'),
'format' => '',
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'total' => $total_pages,
'current' => $page
));
?>
</div>
</div>
<?php endif; ?>
<?php else : ?>
<p><?php _e('No consent logs found.', 'maple-gdpr-cookies'); ?></p>
<?php endif; ?>
</div>
</div>
</div>

View file

@ -0,0 +1,172 @@
<?php
/**
* Admin Settings View
*/
if (!defined('ABSPATH')) {
exit;
}
?>
<div class="wrap mgc-admin-wrap">
<h1><?php echo esc_html(get_admin_page_title()); ?></h1>
<?php settings_errors('mgc_messages'); ?>
<form method="post" action="">
<?php wp_nonce_field('mgc_settings_nonce'); ?>
<!-- General Settings Panel -->
<div class="mgc-panel">
<div class="mgc-panel-header">
<h3><?php _e('General Settings', 'maple-gdpr-cookies'); ?></h3>
</div>
<div class="mgc-panel-body">
<div class="mgc-form-row">
<label>
<input type="checkbox" name="mgc_enabled" value="1" <?php checked(get_option('mgc_enabled', true), true); ?>>
<?php _e('Enable Cookie Notice', 'maple-gdpr-cookies'); ?>
</label>
</div>
<div class="mgc-form-row">
<label for="mgc_notice_text"><?php _e('Notice Text', 'maple-gdpr-cookies'); ?></label>
<textarea id="mgc_notice_text" name="mgc_notice_text" rows="4"><?php echo esc_textarea(get_option('mgc_notice_text')); ?></textarea>
</div>
<div class="mgc-form-row">
<label for="mgc_accept_button_text"><?php _e('Accept Button Text', 'maple-gdpr-cookies'); ?></label>
<input type="text" id="mgc_accept_button_text" name="mgc_accept_button_text" value="<?php echo esc_attr(get_option('mgc_accept_button_text')); ?>">
</div>
<div class="mgc-form-row">
<label for="mgc_reject_button_text"><?php _e('Reject Button Text', 'maple-gdpr-cookies'); ?></label>
<input type="text" id="mgc_reject_button_text" name="mgc_reject_button_text" value="<?php echo esc_attr(get_option('mgc_reject_button_text')); ?>">
</div>
<div class="mgc-form-row">
<label for="mgc_privacy_policy_url"><?php _e('Privacy Policy URL', 'maple-gdpr-cookies'); ?></label>
<input type="url" id="mgc_privacy_policy_url" name="mgc_privacy_policy_url" value="<?php echo esc_url(get_option('mgc_privacy_policy_url')); ?>">
</div>
<div class="mgc-form-row">
<label for="mgc_cookie_expiry"><?php _e('Cookie Expiry (days)', 'maple-gdpr-cookies'); ?></label>
<input type="number" id="mgc_cookie_expiry" name="mgc_cookie_expiry" value="<?php echo esc_attr(get_option('mgc_cookie_expiry', 365)); ?>" min="1" max="365">
</div>
</div>
</div>
<!-- Appearance Panel -->
<div class="mgc-panel">
<div class="mgc-panel-header">
<h3><?php _e('Appearance', 'maple-gdpr-cookies'); ?></h3>
</div>
<div class="mgc-panel-body">
<div class="mgc-form-row">
<label for="mgc_position"><?php _e('Position', 'maple-gdpr-cookies'); ?></label>
<select id="mgc_position" name="mgc_position">
<option value="bottom" <?php selected(get_option('mgc_position', 'bottom'), 'bottom'); ?>><?php _e('Bottom', 'maple-gdpr-cookies'); ?></option>
<option value="top" <?php selected(get_option('mgc_position'), 'top'); ?>><?php _e('Top', 'maple-gdpr-cookies'); ?></option>
<option value="center" <?php selected(get_option('mgc_position'), 'center'); ?>><?php _e('Center Modal', 'maple-gdpr-cookies'); ?></option>
</select>
</div>
<div class="mgc-form-row">
<label for="mgc_theme"><?php _e('Theme', 'maple-gdpr-cookies'); ?></label>
<select id="mgc_theme" name="mgc_theme">
<option value="light" <?php selected(get_option('mgc_theme', 'light'), 'light'); ?>><?php _e('Light', 'maple-gdpr-cookies'); ?></option>
<option value="dark" <?php selected(get_option('mgc_theme'), 'dark'); ?>><?php _e('Dark', 'maple-gdpr-cookies'); ?></option>
</select>
</div>
<div class="mgc-form-row">
<label for="mgc_button_color"><?php _e('Button Color', 'maple-gdpr-cookies'); ?></label>
<select id="mgc_button_color" name="mgc_button_color">
<option value="black" <?php selected(get_option('mgc_button_color', 'blue'), 'black'); ?>><?php _e('Black', 'maple-gdpr-cookies'); ?></option>
<option value="dark-grey" <?php selected(get_option('mgc_button_color', 'blue'), 'dark-grey'); ?>><?php _e('Dark Grey', 'maple-gdpr-cookies'); ?></option>
<option value="blue" <?php selected(get_option('mgc_button_color', 'blue'), 'blue'); ?>><?php _e('Blue', 'maple-gdpr-cookies'); ?></option>
<option value="red" <?php selected(get_option('mgc_button_color', 'blue'), 'red'); ?>><?php _e('Red', 'maple-gdpr-cookies'); ?></option>
<option value="green" <?php selected(get_option('mgc_button_color', 'blue'), 'green'); ?>><?php _e('Green', 'maple-gdpr-cookies'); ?></option>
</select>
<p class="description"><?php _e('Select the color for all cookie notice buttons.', 'maple-gdpr-cookies'); ?></p>
</div>
<div class="mgc-form-row">
<label for="mgc_custom_button_color"><?php _e('Custom Button Color', 'maple-gdpr-cookies'); ?></label>
<input type="text" id="mgc_custom_button_color" name="mgc_custom_button_color" value="<?php echo esc_attr(get_option('mgc_custom_button_color', '')); ?>" placeholder="#3498db" pattern="^#[a-fA-F0-9]{6}$" maxlength="7">
<p class="description"><?php _e('Enter a hex color code (e.g., #3498db). If set, this overrides the dropdown selection above.', 'maple-gdpr-cookies'); ?></p>
</div>
<div class="mgc-form-row">
<label for="mgc_custom_button_hover_color"><?php _e('Custom Button Hover Color', 'maple-gdpr-cookies'); ?></label>
<input type="text" id="mgc_custom_button_hover_color" name="mgc_custom_button_hover_color" value="<?php echo esc_attr(get_option('mgc_custom_button_hover_color', '')); ?>" placeholder="#2980b9" pattern="^#[a-fA-F0-9]{6}$" maxlength="7">
<p class="description"><?php _e('Enter a hex color code for button hover state (e.g., #2980b9). If set, this overrides the default hover color.', 'maple-gdpr-cookies'); ?></p>
</div>
<div class="mgc-form-row">
<label for="mgc_custom_css"><?php _e('Custom CSS', 'maple-gdpr-cookies'); ?></label>
<textarea id="mgc_custom_css" name="mgc_custom_css" rows="10" placeholder=".mgc-notice { /* your styles */ }"><?php echo esc_textarea(get_option('mgc_custom_css')); ?></textarea>
</div>
<div class="mgc-form-row">
<label><?php _e('Preference Display Type', 'maple-gdpr-cookies'); ?></label>
<p class="description" style="margin-bottom: 10px;"><?php _e('Choose how users can access cookie preferences after giving consent (GDPR requirement for easy withdrawal).', 'maple-gdpr-cookies'); ?></p>
<label style="display: block; margin-bottom: 8px;">
<input type="radio" name="mgc_preference_display_type" value="icon" <?php checked(get_option('mgc_preference_display_type', 'icon'), 'icon'); ?>>
<?php _e('Floating Cookie Icon - A circular button with cookie icon in the bottom-left corner', 'maple-gdpr-cookies'); ?>
</label>
<label style="display: block; margin-bottom: 8px;">
<input type="radio" name="mgc_preference_display_type" value="footer" <?php checked(get_option('mgc_preference_display_type', 'icon'), 'footer'); ?>>
<?php _e('Footer Text Link - A small "Cookie Preferences" link in the bottom-left corner', 'maple-gdpr-cookies'); ?>
</label>
<label style="display: block; margin-bottom: 10px;">
<input type="radio" name="mgc_preference_display_type" value="neither" <?php checked(get_option('mgc_preference_display_type', 'icon'), 'neither'); ?>>
<?php _e('Neither - I will use the shortcode instead', 'maple-gdpr-cookies'); ?>
</label>
<div style="background: #f0f0f1; padding: 12px; border-left: 4px solid #2271b1; margin-top: 15px;">
<strong><?php _e('Shortcode Option:', 'maple-gdpr-cookies'); ?></strong>
<p style="margin: 5px 0;"><?php _e('You can also place a cookie preferences link anywhere using the shortcode:', 'maple-gdpr-cookies'); ?></p>
<code style="background: #fff; padding: 4px 8px; border-radius: 3px; display: inline-block; font-size: 13px;">[mgc_cookie_preferences]</code>
<p style="margin: 10px 0 5px 0; font-size: 13px;"><?php _e('Customize the text:', 'maple-gdpr-cookies'); ?></p>
<code style="background: #fff; padding: 4px 8px; border-radius: 3px; display: inline-block; font-size: 13px;">[mgc_cookie_preferences text="Manage Cookies"]</code>
<p style="margin: 10px 0 0 0; font-size: 12px; color: #666;"><?php _e('Perfect for adding to your footer widget, pages, or posts.', 'maple-gdpr-cookies'); ?></p>
</div>
</div>
</div>
</div>
<!-- Advanced Settings Panel -->
<div class="mgc-panel">
<div class="mgc-panel-header">
<h3><?php _e('Advanced Settings', 'maple-gdpr-cookies'); ?></h3>
</div>
<div class="mgc-panel-body">
<div class="mgc-form-row">
<label>
<input type="checkbox" name="mgc_enable_logging" value="1" <?php checked(get_option('mgc_enable_logging', true), true); ?>>
<?php _e('Enable Consent Logging', 'maple-gdpr-cookies'); ?>
</label>
<p class="description"><?php _e('Log all consent decisions for GDPR compliance.', 'maple-gdpr-cookies'); ?></p>
</div>
<div class="mgc-form-row">
<label>
<input type="checkbox" name="mgc_show_reject_button" value="1" <?php checked(get_option('mgc_show_reject_button', true), true); ?>>
<?php _e('Show Reject Button', 'maple-gdpr-cookies'); ?>
</label>
</div>
<div class="mgc-form-row">
<label>
<input type="checkbox" name="mgc_show_settings_button" value="1" <?php checked(get_option('mgc_show_settings_button', true), true); ?>>
<?php _e('Show Settings Button', 'maple-gdpr-cookies'); ?>
</label>
</div>
</div>
</div>
<div class="mgc-save-button">
<?php submit_button(__('Save Settings', 'maple-gdpr-cookies'), 'primary', 'mgc_save_settings'); ?>
</div>
</form>
</div>

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,721 @@
<?php
/**
* Plugin Name: Maple GDPR Cookies
* Plugin URI: https://mapleopentech.ca/maple-gdpr-cookies
* Description: A lightweight, secure, and fully GDPR-compliant cookie consent plugin with script blocking
* Version: 4.1.3
* Requires at least: 5.0
* Requires PHP: 7.2
* Author: Your Name
* License: GPL v2 or later
* Text Domain: maple-gdpr-cookies
* WC requires at least: 3.0
* WC tested up to: 8.5
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Define plugin constants
define('MGC_PLUGIN_FILE', __FILE__);
define('MGC_PLUGIN_PATH', plugin_dir_path(__FILE__));
define('MGC_PLUGIN_URL', plugin_dir_url(__FILE__));
define('MGC_PLUGIN_VERSION', '4.1.3');
define('MGC_DB_VERSION', '2.0');
define('MGC_MIN_PHP_VERSION', '7.2');
define('MGC_MIN_WP_VERSION', '5.0');
/**
* Plugin activation checks
*/
function mgc_check_requirements() {
$errors = array();
// Check PHP version
if (version_compare(PHP_VERSION, MGC_MIN_PHP_VERSION, '<')) {
$errors[] = sprintf(
__('Maple GDPR Cookies requires PHP %s or higher. Your server is running PHP %s.', 'maple-gdpr-cookies'),
MGC_MIN_PHP_VERSION,
PHP_VERSION
);
}
// Check WordPress version
if (version_compare(get_bloginfo('version'), MGC_MIN_WP_VERSION, '<')) {
$errors[] = sprintf(
__('Maple GDPR Cookies requires WordPress %s or higher. You are running WordPress %s.', 'maple-gdpr-cookies'),
MGC_MIN_WP_VERSION,
get_bloginfo('version')
);
}
// Check for MySQL version if using utf8mb4
global $wpdb;
if ($wpdb->db_version() && version_compare($wpdb->db_version(), '5.5.3', '<')) {
$errors[] = __('Maple GDPR Cookies requires MySQL 5.5.3 or higher for utf8mb4 support.', 'maple-gdpr-cookies');
}
return $errors;
}
/**
* Create database tables on activation
*/
function mgc_create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'mgc_consent_logs';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_id bigint(20) UNSIGNED NULL,
ip_address varchar(45) NOT NULL,
user_agent varchar(255) NOT NULL,
consent_type varchar(20) NOT NULL,
categories text NULL,
consent_given tinyint(1) NOT NULL,
consent_date datetime NOT NULL,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY ip_address (ip_address),
KEY consent_date (consent_date)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// Store database version
update_option('mgc_db_version', MGC_DB_VERSION);
}
/**
* Set default options on activation
*/
function mgc_set_defaults() {
$default_options = array(
'enabled' => true,
'notice_text' => __('We use cookies to make this site work properly and to understand how you use it. This includes <strong>essential cookies</strong> (required), <strong>analytics cookies</strong> (to understand site usage), and <strong>marketing cookies</strong> (for personalized content). You can accept all, reject optional cookies, or customize your preferences.', 'maple-gdpr-cookies'),
'accept_button_text' => __('Accept All', 'maple-gdpr-cookies'),
'reject_button_text' => __('Reject Optional', 'maple-gdpr-cookies'),
'settings_button_text' => __('Cookie Settings', 'maple-gdpr-cookies'),
'privacy_policy_url' => get_privacy_policy_url(),
'privacy_policy_text' => __('Privacy Policy', 'maple-gdpr-cookies'),
'cookie_expiry' => 365,
'position' => 'bottom',
'theme' => 'light',
'animation' => 'slide',
'button_color' => 'blue',
'custom_button_color' => '',
'custom_button_hover_color' => '',
'show_reject_button' => true,
'show_settings_button' => true,
'preference_display_type' => 'icon',
'custom_css' => '',
'enable_analytics' => true,
'enable_marketing' => true,
'enable_functional' => true,
'enable_logging' => true
);
foreach ($default_options as $key => $value) {
if (get_option('mgc_' . $key) === false) {
add_option('mgc_' . $key, $value);
}
}
}
/**
* Clear all plugin caches - FIXED VERSION
*/
function mgc_clear_all_caches() {
// Method 1: Clear WordPress object cache (if available)
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
// Method 2: Clear plugin-specific transients
global $wpdb;
// Get all mgc transients
$transients = $wpdb->get_col(
"SELECT option_name FROM $wpdb->options
WHERE option_name LIKE '_transient_mgc_%'
OR option_name LIKE '_transient_timeout_mgc_%'"
);
// Delete each transient
foreach ($transients as $transient) {
if (strpos($transient, '_transient_timeout_') === 0) {
continue; // Skip timeout entries, they'll be deleted with the transient
}
$transient_key = str_replace('_transient_', '', $transient);
delete_transient($transient_key);
}
// Method 3: Clear specific plugin caches
$cache_keys = array(
'mgc_settings',
'mgc_stats',
'mgc_consent_logs'
);
foreach ($cache_keys as $key) {
wp_cache_delete($key, 'maple-gdpr-cookies');
delete_transient($key);
}
// Method 4: Clear WooCommerce cache if present
if (function_exists('wc_delete_shop_order_transients')) {
wc_delete_shop_order_transients();
}
// Method 5: Trigger cache clear hooks for other plugins
do_action('mgc_clear_caches');
}
/**
* Plugin activation
*/
function mgc_activate() {
// Check requirements
$errors = mgc_check_requirements();
if (!empty($errors)) {
deactivate_plugins(plugin_basename(__FILE__));
wp_die(
implode('<br>', $errors),
__('Plugin Activation Error', 'maple-gdpr-cookies'),
array('back_link' => true)
);
}
// Create database tables
mgc_create_tables();
// Set default options
mgc_set_defaults();
// Clear all caches - now using fixed function
mgc_clear_all_caches();
// Set activation flag
set_transient('mgc_activation_redirect', true, 30);
}
register_activation_hook(__FILE__, 'mgc_activate');
/**
* Plugin deactivation
*/
function mgc_deactivate() {
// Clear all caches
mgc_clear_all_caches();
// Clear scheduled events
wp_clear_scheduled_hook('mgc_cleanup_logs');
wp_clear_scheduled_hook('mgc_optimize_database');
}
register_deactivation_hook(__FILE__, 'mgc_deactivate');
/**
* Plugin uninstall - only if user chooses to delete data
*/
function mgc_uninstall() {
global $wpdb;
// Always clear scheduled tasks even if keeping data
wp_clear_scheduled_hook('mgc_cleanup_logs');
wp_clear_scheduled_hook('mgc_optimize_database');
// Check if user wants to keep data
if (get_option('mgc_keep_data_on_uninstall', false)) {
return;
}
// Drop database tables
$table_name = $wpdb->prefix . 'mgc_consent_logs';
$wpdb->query("DROP TABLE IF EXISTS $table_name");
// Delete all plugin options
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'mgc_%'");
// Clear all caches
mgc_clear_all_caches();
}
register_uninstall_hook(__FILE__, 'mgc_uninstall');
/**
* Load plugin textdomain for translations
*/
function mgc_load_textdomain() {
load_plugin_textdomain(
'maple-gdpr-cookies',
false,
dirname(plugin_basename(__FILE__)) . '/languages'
);
}
add_action('plugins_loaded', 'mgc_load_textdomain');
/**
* Enqueue frontend scripts and styles
*/
function mgc_enqueue_frontend_assets() {
// Only load if enabled
if (!get_option('mgc_enabled', true)) {
return;
}
// Check if user already has consent cookie
$has_consent = isset($_COOKIE['mgc_consent']);
// Enqueue CSS
wp_enqueue_style(
'mgc-frontend',
MGC_PLUGIN_URL . 'public/css/frontend.css',
array(),
MGC_PLUGIN_VERSION
);
// Add custom CSS if provided
$custom_css = get_option('mgc_custom_css');
if (!empty($custom_css)) {
wp_add_inline_style('mgc-frontend', $custom_css);
}
// Add custom button colors if provided
$custom_button_color = get_option('mgc_custom_button_color');
$custom_button_hover_color = get_option('mgc_custom_button_hover_color');
if (!empty($custom_button_color) || !empty($custom_button_hover_color)) {
$color_css = '';
if (!empty($custom_button_color)) {
$color_css .= '.mgc-button { background: ' . esc_attr($custom_button_color) . ' !important; }';
$color_css .= '.mgc-floating-button { background: ' . esc_attr($custom_button_color) . ' !important; }';
}
if (!empty($custom_button_hover_color)) {
$color_css .= '.mgc-button:hover { background: ' . esc_attr($custom_button_hover_color) . ' !important; }';
$color_css .= '.mgc-floating-button:hover { background: ' . esc_attr($custom_button_hover_color) . ' !important; }';
}
wp_add_inline_style('mgc-frontend', $color_css);
}
// Enqueue the compliant JS (blocks scripts before consent)
wp_enqueue_script(
'mgc-frontend-compliant',
MGC_PLUGIN_URL . 'public/js/frontend-compliant.js',
array(),
MGC_PLUGIN_VERSION,
false // Load in head for early script blocking
);
// Localize script with settings
wp_localize_script('mgc-frontend-compliant', 'mgcSettings', array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('mgc_consent_nonce'),
'noticeText' => get_option('mgc_notice_text'),
'acceptButtonText' => get_option('mgc_accept_button_text'),
'rejectButtonText' => get_option('mgc_reject_button_text'),
'settingsButtonText' => get_option('mgc_settings_button_text'),
'privacyPolicyUrl' => get_option('mgc_privacy_policy_url'),
'privacyPolicyText' => get_option('mgc_privacy_policy_text'),
'cookieExpiry' => intval(get_option('mgc_cookie_expiry', 365)),
'position' => get_option('mgc_position', 'bottom'),
'theme' => get_option('mgc_theme', 'light'),
'animation' => get_option('mgc_animation', 'slide'),
'buttonColor' => get_option('mgc_button_color', 'blue'),
'showRejectButton' => (bool) get_option('mgc_show_reject_button', true),
'showSettingsButton' => (bool) get_option('mgc_show_settings_button', true),
'preferenceDisplayType' => get_option('mgc_preference_display_type', 'icon')
));
}
add_action('wp_enqueue_scripts', 'mgc_enqueue_frontend_assets');
/**
* Enqueue admin scripts and styles
*/
function mgc_enqueue_admin_assets($hook) {
// Only load on plugin settings pages
if (strpos($hook, 'maple-gdpr-cookies') === false) {
return;
}
// Enqueue WordPress color picker
wp_enqueue_style('wp-color-picker');
// Enqueue admin CSS
wp_enqueue_style(
'mgc-admin',
MGC_PLUGIN_URL . 'admin/css/admin.css',
array(),
MGC_PLUGIN_VERSION
);
// Enqueue admin JS
wp_enqueue_script(
'mgc-admin',
MGC_PLUGIN_URL . 'admin/js/admin.js',
array('jquery', 'wp-color-picker'),
MGC_PLUGIN_VERSION,
true
);
}
add_action('admin_enqueue_scripts', 'mgc_enqueue_admin_assets');
/**
* Add admin menu
*/
function mgc_add_admin_menu() {
add_menu_page(
__('Maple GDPR Cookies', 'maple-gdpr-cookies'),
__('Cookie Settings', 'maple-gdpr-cookies'),
'manage_options',
'maple-gdpr-cookies',
'mgc_admin_page',
'dashicons-shield',
100
);
add_submenu_page(
'maple-gdpr-cookies',
__('Settings', 'maple-gdpr-cookies'),
__('Settings', 'maple-gdpr-cookies'),
'manage_options',
'maple-gdpr-cookies',
'mgc_admin_page'
);
add_submenu_page(
'maple-gdpr-cookies',
__('Consent Logs', 'maple-gdpr-cookies'),
__('Consent Logs', 'maple-gdpr-cookies'),
'manage_options',
'maple-gdpr-cookies-logs',
'mgc_logs_page'
);
}
add_action('admin_menu', 'mgc_add_admin_menu');
/**
* Admin page callback
*/
function mgc_admin_page() {
if (!current_user_can('manage_options')) {
return;
}
// Handle form submission
if (isset($_POST['mgc_save_settings']) && check_admin_referer('mgc_settings_nonce')) {
mgc_save_settings();
}
include MGC_PLUGIN_PATH . 'admin/views/settings.php';
}
/**
* Logs page callback
*/
function mgc_logs_page() {
if (!current_user_can('manage_options')) {
return;
}
include MGC_PLUGIN_PATH . 'admin/views/logs.php';
}
/**
* Save settings
*/
function mgc_save_settings() {
$settings = array(
'enabled',
'notice_text',
'accept_button_text',
'reject_button_text',
'settings_button_text',
'privacy_policy_url',
'privacy_policy_text',
'cookie_expiry',
'position',
'theme',
'animation',
'button_color',
'custom_button_color',
'custom_button_hover_color',
'show_reject_button',
'show_settings_button',
'preference_display_type',
'custom_css',
'enable_analytics',
'enable_marketing',
'enable_functional',
'enable_logging'
);
// List of checkbox fields (need special handling since unchecked = no POST data)
$checkbox_fields = array(
'enabled',
'show_reject_button',
'show_settings_button',
'enable_analytics',
'enable_marketing',
'enable_functional',
'enable_logging'
);
foreach ($settings as $setting) {
// Special handling for checkboxes
if (in_array($setting, $checkbox_fields)) {
// Checkbox: if it's in POST and = '1', it's checked. Otherwise it's unchecked.
$value = (isset($_POST['mgc_' . $setting]) && $_POST['mgc_' . $setting] == '1') ? true : false;
} else {
$value = isset($_POST['mgc_' . $setting]) ? $_POST['mgc_' . $setting] : '';
// Sanitize based on type
if ($setting === 'cookie_expiry') {
$value = absint($value);
// Enforce minimum and maximum values for GDPR compliance
if ($value < 1) $value = 1;
if ($value > 365) $value = 365;
} elseif ($setting === 'custom_css') {
$value = wp_strip_all_tags($value);
// Remove any javascript: or data: URLs to prevent CSS injection attacks
$value = preg_replace('/url\s*\(\s*[\'"]?\s*(?:javascript|data):/i', 'url(blocked:', $value);
// Limit length to prevent abuse (10KB should be more than enough for custom CSS)
$value = substr($value, 0, 10000);
} elseif (in_array($setting, array('custom_button_color', 'custom_button_hover_color'))) {
// Sanitize hex color
$value = sanitize_text_field($value);
// Validate hex color format
if (!empty($value) && !preg_match('/^#[a-fA-F0-9]{6}$/', $value)) {
$value = ''; // Clear invalid hex colors
}
} elseif ($setting === 'preference_display_type') {
// Validate preference display type
$value = sanitize_text_field($value);
if (!in_array($value, array('icon', 'footer', 'neither'))) {
$value = 'icon'; // Default to icon if invalid
}
} else {
$value = sanitize_text_field($value);
}
}
update_option('mgc_' . $setting, $value);
}
// Clear caches after saving
mgc_clear_all_caches();
add_settings_error(
'mgc_messages',
'mgc_message',
__('Settings saved successfully.', 'maple-gdpr-cookies'),
'updated'
);
}
/**
* AJAX handler for saving consent
*/
function mgc_save_consent() {
check_ajax_referer('mgc_consent_nonce', 'nonce');
// Rate limiting - max 10 consent saves per hour per IP to prevent abuse
$ip = mgc_get_ip_address();
$rate_key = 'mgc_consent_rate_' . md5($ip);
$attempts = get_transient($rate_key);
if ($attempts && $attempts >= 10) {
wp_send_json_error(array(
'message' => __('Too many requests. Please try again later.', 'maple-gdpr-cookies')
), 429);
return;
}
// Increment rate limit counter
set_transient($rate_key, ($attempts ? $attempts + 1 : 1), HOUR_IN_SECONDS);
$consent_type = sanitize_text_field($_POST['consent_type']);
$categories = isset($_POST['categories']) ? array_map('sanitize_text_field', $_POST['categories']) : array();
// Log consent if enabled
if (get_option('mgc_enable_logging', true)) {
mgc_log_consent($consent_type, $categories);
}
wp_send_json_success(array(
'message' => __('Consent saved successfully', 'maple-gdpr-cookies')
));
}
add_action('wp_ajax_mgc_save_consent', 'mgc_save_consent');
add_action('wp_ajax_nopriv_mgc_save_consent', 'mgc_save_consent');
/**
* Log user consent
*/
function mgc_log_consent($consent_type, $categories = array()) {
global $wpdb;
$table_name = $wpdb->prefix . 'mgc_consent_logs';
// Get and anonymize IP address (GDPR compliance)
$ip_address = mgc_anonymize_ip(mgc_get_ip_address());
$wpdb->insert(
$table_name,
array(
'user_id' => get_current_user_id(),
'ip_address' => $ip_address,
'user_agent' => sanitize_text_field(substr($_SERVER['HTTP_USER_AGENT'], 0, 255)),
'consent_type' => $consent_type,
'categories' => json_encode($categories),
'consent_given' => ($consent_type === 'accept'),
'consent_date' => current_time('mysql')
),
array('%d', '%s', '%s', '%s', '%s', '%d', '%s')
);
}
/**
* Get user IP address
*/
function mgc_get_ip_address() {
$ip = '';
// Check if behind a proxy and validate
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// X-Forwarded-For can contain multiple IPs, get the first one (original client)
$ip_list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim($ip_list[0]);
} elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
// Validate it's a real IP address
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
// If invalid, fall back to direct connection IP
$ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
}
return sanitize_text_field($ip);
}
/**
* Anonymize IP address (GDPR compliance)
* Removes last octet for IPv4, last segment for IPv6
*/
function mgc_anonymize_ip($ip) {
// Validate and anonymize IPv4
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
return preg_replace('/\.\d+$/', '.0', $ip);
}
// Validate and anonymize IPv6
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return preg_replace('/:[^:]+$/', ':0', $ip);
}
// If invalid IP, return masked version
return '0.0.0.0';
}
/**
* Schedule cleanup tasks
*/
function mgc_schedule_cleanup() {
if (!wp_next_scheduled('mgc_cleanup_logs')) {
wp_schedule_event(time(), 'daily', 'mgc_cleanup_logs');
}
if (!wp_next_scheduled('mgc_optimize_database')) {
wp_schedule_event(time(), 'weekly', 'mgc_optimize_database');
}
}
add_action('wp', 'mgc_schedule_cleanup');
/**
* Cleanup old consent logs
*/
function mgc_cleanup_old_logs() {
global $wpdb;
$table_name = $wpdb->prefix . 'mgc_consent_logs';
$retention_days = apply_filters('mgc_log_retention_days', 365);
$wpdb->query(
$wpdb->prepare(
"DELETE FROM $table_name WHERE consent_date < DATE_SUB(NOW(), INTERVAL %d DAY)",
$retention_days
)
);
}
add_action('mgc_cleanup_logs', 'mgc_cleanup_old_logs');
/**
* Optimize database tables
*/
function mgc_optimize_database_tables() {
global $wpdb;
$table_name = $wpdb->prefix . 'mgc_consent_logs';
$wpdb->query("OPTIMIZE TABLE $table_name");
}
add_action('mgc_optimize_database', 'mgc_optimize_database_tables');
/**
* Add settings link on plugins page
*/
function mgc_add_settings_link($links) {
$settings_link = '<a href="' . admin_url('admin.php?page=maple-gdpr-cookies') . '">' . __('Settings', 'maple-gdpr-cookies') . '</a>';
array_unshift($links, $settings_link);
return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'mgc_add_settings_link');
/**
* Redirect to settings page on activation
*/
function mgc_activation_redirect() {
if (get_transient('mgc_activation_redirect')) {
delete_transient('mgc_activation_redirect');
if (!isset($_GET['activate-multi'])) {
wp_safe_redirect(admin_url('admin.php?page=maple-gdpr-cookies'));
exit;
}
}
}
add_action('admin_init', 'mgc_activation_redirect');
/**
* Cookie Preferences Shortcode
* Usage: [mgc_cookie_preferences] or [mgc_cookie_preferences text="Manage Cookies"]
*/
function mgc_cookie_preferences_shortcode($atts) {
// Only show if plugin is enabled
if (!get_option('mgc_enabled', true)) {
return '';
}
// Parse attributes
$atts = shortcode_atts(array(
'text' => __('Cookie Preferences', 'maple-gdpr-cookies'),
'class' => 'mgc-preferences-link'
), $atts);
// Return link with data attribute that JavaScript will handle
return sprintf(
'<a href="#" class="%s" data-mgc-preferences-trigger aria-label="%s">%s</a>',
esc_attr($atts['class']),
esc_attr($atts['text']),
esc_html($atts['text'])
);
}
add_shortcode('mgc_cookie_preferences', 'mgc_cookie_preferences_shortcode');

View file

@ -0,0 +1,303 @@
/* Maple GDPR Cookies - Frontend Styles */
.mgc-notice {
position: fixed;
z-index: 999999;
background: #fff;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
padding: 20px;
max-width: 100%;
box-sizing: border-box;
}
.mgc-notice.mgc-position-bottom {
bottom: 0;
left: 0;
right: 0;
}
.mgc-notice.mgc-position-top {
top: 0;
left: 0;
right: 0;
}
.mgc-notice.mgc-position-center {
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 600px;
border-radius: 8px;
}
.mgc-notice.mgc-theme-dark {
background: #2c3e50;
color: #fff;
}
.mgc-notice-content {
margin-bottom: 15px;
line-height: 1.6;
}
.mgc-notice-buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.mgc-button {
padding: 10px 20px;
border: 2px solid #222222;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
transition: all 0.3s ease;
background: #3498db;
color: #fff;
}
.mgc-button:hover {
background: #2980b9;
border-color: #222222;
}
/* Button Color Variants */
.mgc-button-color-blue {
background: #3498db;
}
.mgc-button-color-blue:hover {
background: #2980b9;
}
.mgc-button-color-black {
background: #000000;
}
.mgc-button-color-black:hover {
background: #1a1a1a;
}
.mgc-button-color-dark-grey {
background: #4a4a4a;
}
.mgc-button-color-dark-grey:hover {
background: #5a5a5a;
}
.mgc-button-color-red {
background: #e74c3c;
}
.mgc-button-color-red:hover {
background: #c0392b;
}
.mgc-button-color-green {
background: #27ae60;
}
.mgc-button-color-green:hover {
background: #229954;
}
.mgc-button-accept {
color: #fff;
}
.mgc-button-reject {
color: #fff;
}
.mgc-button-settings {
color: #fff;
}
.mgc-privacy-link {
color: #3498db;
text-decoration: none;
margin-left: 5px;
}
.mgc-privacy-link:hover {
text-decoration: underline;
}
/* Animation: Slide */
.mgc-animation-slide.mgc-position-bottom {
animation: mgc-slide-up 0.5s ease-out;
}
.mgc-animation-slide.mgc-position-top {
animation: mgc-slide-down 0.5s ease-out;
}
@keyframes mgc-slide-up {
from {
transform: translateY(100%);
}
to {
transform: translateY(0);
}
}
@keyframes mgc-slide-down {
from {
transform: translateY(-100%);
}
to {
transform: translateY(0);
}
}
/* Animation: Fade */
.mgc-animation-fade {
animation: mgc-fade-in 0.5s ease-out;
}
@keyframes mgc-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Mobile responsive */
@media (max-width: 768px) {
.mgc-notice {
padding: 15px;
}
.mgc-notice-buttons {
flex-direction: column;
}
.mgc-button {
width: 100%;
}
}
/* Hidden state */
.mgc-hidden {
display: none !important;
}
/* Persistent Floating Cookie Settings Button */
.mgc-floating-button {
position: fixed;
bottom: 20px;
left: 20px;
width: 50px;
height: 50px;
border-radius: 50%;
background: #3498db;
color: #fff;
border: 2px solid #222222;
cursor: pointer;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
display: flex;
align-items: center;
justify-content: center;
z-index: 999998;
transition: all 0.3s ease;
font-size: 24px;
}
.mgc-floating-button:hover {
background: #2980b9;
transform: scale(1.1);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}
.mgc-floating-button svg {
width: 24px;
height: 24px;
}
/* Footer Preference Link */
.mgc-footer-preference-link {
position: fixed;
bottom: 10px;
left: 10px;
font-size: 8pt;
color: #666;
text-decoration: none;
z-index: 999998;
background: rgba(255, 255, 255, 0.9);
padding: 4px 8px;
border-radius: 3px;
transition: all 0.2s ease;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.mgc-footer-preference-link:hover {
color: #3498db;
text-decoration: underline;
background: rgba(255, 255, 255, 1);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
}
/* Shortcode Preference Link */
.mgc-preferences-link {
color: #666;
text-decoration: none;
font-size: 14px;
cursor: pointer;
transition: color 0.2s ease;
}
.mgc-preferences-link:hover {
color: #3498db;
text-decoration: underline;
}
/* Settings Modal */
.mgc-settings-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999999;
animation: mgc-fade-in 0.3s ease-out;
}
.mgc-settings-content {
background: #fff;
padding: 30px;
border-radius: 8px;
max-width: 600px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
animation: mgc-scale-in 0.3s ease-out;
}
@keyframes mgc-scale-in {
from {
transform: scale(0.9);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
.mgc-category {
transition: all 0.2s ease;
}
.mgc-category:hover {
background: #f9f9f9;
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}

View file

@ -0,0 +1,500 @@
/* Maple GDPR Cookies - Script Blocker (GDPR Compliant) */
(function () {
"use strict";
// Check consent status immediately
const consentCookie = getCookie("mgc_consent");
const consentCategories = getCookie("mgc_consent_categories");
// If user has given consent, enable scripts
if (consentCookie === "accept" && consentCategories) {
const categories = JSON.parse(consentCategories || "[]");
enableScripts(categories);
}
// Block scripts on initial load (GDPR compliance - prior consent)
document.addEventListener("DOMContentLoaded", function () {
blockScripts();
// Show notice if no consent given
if (!consentCookie) {
createNotice();
} else {
// Add persistent cookie settings button or footer text
addPersistentPreferenceLink();
}
// Handle clicks on shortcode preference links
document.addEventListener("click", function (e) {
if (
e.target.matches("[data-mgc-preferences-trigger]") ||
e.target.closest("[data-mgc-preferences-trigger]")
) {
e.preventDefault();
showSettingsModal();
}
});
});
/**
* Block all non-essential scripts until consent is given
* CRITICAL for GDPR compliance
*/
function blockScripts() {
// Find all scripts with data-category attribute
const scripts = document.querySelectorAll("script[data-cookie-category]");
scripts.forEach(function (script) {
const category = script.getAttribute("data-cookie-category");
// Check if this category is allowed
if (!isCategoryAllowed(category)) {
// Block the script by changing type
if (script.type !== "text/plain") {
script.type = "text/plain";
script.setAttribute("data-original-type", "text/javascript");
}
}
});
}
/**
* Enable scripts for allowed categories
*/
function enableScripts(allowedCategories) {
// Always allow functional
if (!allowedCategories.includes("functional")) {
allowedCategories.push("functional");
}
// Find all blocked scripts
const scripts = document.querySelectorAll(
'script[data-cookie-category][type="text/plain"]',
);
scripts.forEach(function (script) {
const category = script.getAttribute("data-cookie-category");
// If category is allowed, re-enable script
if (allowedCategories.includes(category)) {
const originalType =
script.getAttribute("data-original-type") || "text/javascript";
// Create new script element (changing type on existing doesn't execute)
const newScript = document.createElement("script");
newScript.type = originalType;
// Copy attributes
Array.from(script.attributes).forEach(function (attr) {
if (attr.name !== "type" && attr.name !== "data-original-type") {
newScript.setAttribute(attr.name, attr.value);
}
});
// Copy content
if (script.src) {
newScript.src = script.src;
} else {
newScript.textContent = script.textContent;
}
// Replace old script with new one
script.parentNode.replaceChild(newScript, script);
}
});
// Trigger event for other integrations
document.dispatchEvent(
new CustomEvent("mgc_scripts_loaded", {
detail: { categories: allowedCategories },
}),
);
}
/**
* Check if a category is currently allowed
*/
function isCategoryAllowed(category) {
const consentCookie = getCookie("mgc_consent");
if (consentCookie !== "accept") {
return false;
}
const categories = JSON.parse(getCookie("mgc_consent_categories") || "[]");
return categories.includes(category) || category === "functional";
}
/**
* Add persistent cookie preference link (GDPR requirement - easy withdrawal)
* Can be either a floating icon button or footer text link based on settings
*/
function addPersistentPreferenceLink() {
// Check what type of display is preferred
const displayType = window.mgcSettings?.preferenceDisplayType || "icon";
// If 'neither', don't add anything - user will use shortcode
if (displayType === "neither") {
return;
}
// Check if element already exists
if (
document.querySelector(".mgc-floating-button") ||
document.querySelector(".mgc-footer-preference-link")
) {
return;
}
if (displayType === "footer") {
// Create footer text link
const footerLink = document.createElement("a");
footerLink.className = "mgc-footer-preference-link";
footerLink.href = "#";
footerLink.textContent = "Cookie Preferences";
footerLink.setAttribute("aria-label", "Cookie Preferences");
footerLink.onclick = function (e) {
e.preventDefault();
showSettingsModal();
};
document.body.appendChild(footerLink);
} else {
// Create floating icon button (default)
const button = document.createElement("button");
button.className = "mgc-floating-button";
button.setAttribute("aria-label", "Cookie Settings");
button.innerHTML =
'<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/></svg>';
button.title = "Cookie Settings";
button.onclick = function () {
showSettingsModal();
};
document.body.appendChild(button);
}
}
function createNotice() {
const settings = window.mgcSettings || {};
// Create notice container
const notice = document.createElement("div");
notice.className =
"mgc-notice mgc-position-" +
(settings.position || "bottom") +
" mgc-theme-" +
(settings.theme || "light") +
" mgc-animation-" +
(settings.animation || "slide");
// Create content
const content = document.createElement("div");
content.className = "mgc-notice-content";
const noticeText = (
settings.noticeText ||
"We use cookies to enhance your browsing experience."
)
.replace(/\\"/g, '"')
.replace(/\\\\/g, "\\")
.replace(/&quot;/g, '"')
.replace(/"Accept All"/g, "<strong>Accept All</strong>")
.replace(/"Reject All"/g, "<strong>Reject All</strong>");
content.innerHTML = noticeText;
// Add privacy policy link if provided
if (settings.privacyPolicyUrl) {
content.innerHTML +=
' <a href="' +
settings.privacyPolicyUrl +
'" class="mgc-privacy-link" target="_blank">' +
(settings.privacyPolicyText || "Privacy Policy") +
"</a>";
}
// Create buttons container
const buttons = document.createElement("div");
buttons.className = "mgc-notice-buttons";
// Accept button
const acceptBtn = document.createElement("button");
acceptBtn.className =
"mgc-button mgc-button-accept mgc-button-color-" +
(settings.buttonColor || "blue");
acceptBtn.textContent = settings.acceptButtonText || "Accept All";
acceptBtn.onclick = function () {
handleConsent("accept", ["analytics", "marketing", "functional"]);
};
buttons.appendChild(acceptBtn);
// Reject button (optional)
if (settings.showRejectButton) {
const rejectBtn = document.createElement("button");
rejectBtn.className =
"mgc-button mgc-button-reject mgc-button-color-" +
(settings.buttonColor || "blue");
rejectBtn.textContent = settings.rejectButtonText || "Reject All";
rejectBtn.onclick = function () {
handleConsent("reject", ["functional"]); // Only functional cookies
};
buttons.appendChild(rejectBtn);
}
// Settings button (optional)
if (settings.showSettingsButton) {
const settingsBtn = document.createElement("button");
settingsBtn.className =
"mgc-button mgc-button-settings mgc-button-color-" +
(settings.buttonColor || "blue");
settingsBtn.textContent =
settings.settingsButtonText || "Cookie Settings";
settingsBtn.onclick = function () {
showSettingsModal();
};
buttons.appendChild(settingsBtn);
}
// Append elements
notice.appendChild(content);
notice.appendChild(buttons);
document.body.appendChild(notice);
}
function showSettingsModal() {
// Remove initial notice if present
const initialNotice = document.querySelector(".mgc-notice");
if (initialNotice) {
initialNotice.classList.add("mgc-hidden");
}
// Create settings modal
const modal = document.createElement("div");
modal.className = "mgc-settings-modal";
const modalContent = document.createElement("div");
modalContent.className = "mgc-settings-content";
// Modal title
const title = document.createElement("h3");
title.textContent = "Cookie Settings";
title.style.marginTop = "0";
modalContent.appendChild(title);
// Description
const desc = document.createElement("p");
desc.textContent = "Choose which types of cookies you want to allow:";
modalContent.appendChild(desc);
// Get current consent
const currentCategories = JSON.parse(
getCookie("mgc_consent_categories") || '["functional"]',
);
// Cookie categories
const categories = [
{
id: "functional",
label: "Functional Cookies",
description:
"These cookies are essential for the website to function properly. They enable basic features like page navigation, security, and access to secure areas. The website cannot function properly without these cookies.",
required: true,
},
{
id: "analytics",
label: "Analytics Cookies",
description:
"These cookies help us understand how visitors interact with our website by collecting and reporting information anonymously. They help us improve our website performance.",
required: false,
},
{
id: "marketing",
label: "Marketing Cookies",
description:
"These cookies are used to track visitors across websites and display personalized advertisements. They may be set by third-party advertising networks.",
required: false,
},
];
const checkboxes = [];
categories.forEach(function (cat) {
const categoryDiv = document.createElement("div");
categoryDiv.className = "mgc-category";
categoryDiv.style.marginBottom = "15px";
categoryDiv.style.padding = "10px";
categoryDiv.style.border = "1px solid #ddd";
categoryDiv.style.borderRadius = "4px";
const label = document.createElement("label");
label.style.display = "flex";
label.style.alignItems = "flex-start";
label.style.cursor = cat.required ? "not-allowed" : "pointer";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "mgc-cat-" + cat.id;
checkbox.value = cat.id;
checkbox.checked = currentCategories.includes(cat.id);
checkbox.disabled = cat.required;
checkbox.style.marginRight = "10px";
checkbox.style.marginTop = "3px";
if (!cat.required) {
checkboxes.push(checkbox);
}
const textDiv = document.createElement("div");
const labelText = document.createElement("strong");
labelText.textContent = cat.label;
if (cat.required) {
labelText.textContent += " (Always Active)";
}
const descText = document.createElement("div");
descText.textContent = cat.description;
descText.style.fontSize = "13px";
descText.style.color = "#666";
descText.style.marginTop = "3px";
textDiv.appendChild(labelText);
textDiv.appendChild(descText);
label.appendChild(checkbox);
label.appendChild(textDiv);
categoryDiv.appendChild(label);
modalContent.appendChild(categoryDiv);
});
// Buttons
const buttonRow = document.createElement("div");
buttonRow.className = "mgc-notice-buttons";
buttonRow.style.marginTop = "20px";
// Save Preferences button
const saveBtn = document.createElement("button");
saveBtn.className =
"mgc-button mgc-button-accept mgc-button-color-" +
(window.mgcSettings?.buttonColor || "blue");
saveBtn.textContent = "Save Preferences";
saveBtn.onclick = function () {
const selectedCategories = ["functional"];
checkboxes.forEach(function (cb) {
if (cb.checked) {
selectedCategories.push(cb.value);
}
});
handleConsent("accept", selectedCategories);
modal.remove();
};
buttonRow.appendChild(saveBtn);
// Accept All button
const acceptAll = document.createElement("button");
acceptAll.className =
"mgc-button mgc-button-accept mgc-button-color-" +
(window.mgcSettings?.buttonColor || "blue");
acceptAll.textContent = "Accept All";
acceptAll.onclick = function () {
handleConsent("accept", ["functional", "analytics", "marketing"]);
modal.remove();
};
buttonRow.appendChild(acceptAll);
// Reject Optional button
const rejectOptional = document.createElement("button");
rejectOptional.className =
"mgc-button mgc-button-settings mgc-button-color-" +
(window.mgcSettings?.buttonColor || "blue");
rejectOptional.textContent = "Reject Optional";
rejectOptional.onclick = function () {
handleConsent("accept", ["functional"]);
modal.remove();
};
buttonRow.appendChild(rejectOptional);
modalContent.appendChild(buttonRow);
modal.appendChild(modalContent);
document.body.appendChild(modal);
}
function handleConsent(type, categories) {
// Set cookies
const expiry = window.mgcSettings?.cookieExpiry || 365;
setCookie("mgc_consent", type, expiry);
setCookie("mgc_consent_categories", JSON.stringify(categories), expiry);
// Enable scripts for allowed categories
enableScripts(categories);
// Send to server
if (window.mgcSettings?.ajaxUrl) {
const formData = new FormData();
formData.append("action", "mgc_save_consent");
formData.append("nonce", window.mgcSettings.nonce);
formData.append("consent_type", type);
categories.forEach(function (cat) {
formData.append("categories[]", cat);
});
fetch(window.mgcSettings.ajaxUrl, {
method: "POST",
body: formData,
}).catch(function () {
// Silently fail
});
}
// Remove notice
const notice = document.querySelector(".mgc-notice");
if (notice) {
notice.classList.add("mgc-hidden");
setTimeout(function () {
notice.remove();
}, 300);
}
// Add persistent preference link
addPersistentPreferenceLink();
// Trigger event
document.dispatchEvent(
new CustomEvent("mgc_consent_saved", {
detail: { type: type, categories: categories },
}),
);
// Reload page to apply changes
if (type === "accept") {
setTimeout(function () {
window.location.reload();
}, 500);
}
}
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
const expires = "expires=" + d.toUTCString();
const secure = window.location.protocol === "https:" ? ";Secure" : "";
document.cookie =
name +
"=" +
encodeURIComponent(value) +
";" +
expires +
";path=/;SameSite=Lax" +
secure;
}
function getCookie(name) {
const nameEQ = name + "=";
const ca = document.cookie.split(";");
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0)
return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
})();

View file

@ -0,0 +1,288 @@
/* Maple GDPR Cookies - Frontend JavaScript */
(function() {
'use strict';
// Check if consent already given
if (getCookie('mgc_consent')) {
return;
}
// Create and show cookie notice
document.addEventListener('DOMContentLoaded', function() {
createNotice();
});
function createNotice() {
const settings = window.mgcSettings || {};
// Create notice container
const notice = document.createElement('div');
notice.className = 'mgc-notice mgc-position-' + (settings.position || 'bottom') +
' mgc-theme-' + (settings.theme || 'light') +
' mgc-animation-' + (settings.animation || 'slide');
// Create content
const content = document.createElement('div');
content.className = 'mgc-notice-content';
// Decode HTML entities and strip slashes
const noticeText = (settings.noticeText || 'We use cookies to enhance your browsing experience.')
.replace(/\\"/g, '"')
.replace(/\\\\/g, '\\')
.replace(/&quot;/g, '"')
.replace(/"Accept All"/g, '<strong>Accept All</strong>')
.replace(/"Reject All"/g, '<strong>Reject All</strong>');
content.innerHTML = noticeText;
// Add privacy policy link if provided
if (settings.privacyPolicyUrl) {
content.innerHTML += ' <a href="' + settings.privacyPolicyUrl + '" class="mgc-privacy-link" target="_blank">' +
(settings.privacyPolicyText || 'Privacy Policy') + '</a>';
}
// Create buttons container
const buttons = document.createElement('div');
buttons.className = 'mgc-notice-buttons';
// Accept button
const acceptBtn = document.createElement('button');
acceptBtn.className = 'mgc-button mgc-button-accept mgc-button-color-' + (settings.buttonColor || 'blue');
acceptBtn.textContent = settings.acceptButtonText || 'Accept All';
acceptBtn.onclick = function() {
handleConsent('accept', ['analytics', 'marketing', 'functional']);
};
buttons.appendChild(acceptBtn);
// Reject button (optional)
if (settings.showRejectButton) {
const rejectBtn = document.createElement('button');
rejectBtn.className = 'mgc-button mgc-button-reject mgc-button-color-' + (settings.buttonColor || 'blue');
rejectBtn.textContent = settings.rejectButtonText || 'Reject All';
rejectBtn.onclick = function() {
handleConsent('reject', []);
};
buttons.appendChild(rejectBtn);
}
// Settings button (optional)
if (settings.showSettingsButton) {
const settingsBtn = document.createElement('button');
settingsBtn.className = 'mgc-button mgc-button-settings mgc-button-color-' + (settings.buttonColor || 'blue');
settingsBtn.textContent = settings.settingsButtonText || 'Cookie Settings';
settingsBtn.onclick = function() {
showSettingsModal();
};
buttons.appendChild(settingsBtn);
}
// Append elements
notice.appendChild(content);
notice.appendChild(buttons);
document.body.appendChild(notice);
}
function showSettingsModal() {
// Remove initial notice
const initialNotice = document.querySelector('.mgc-notice');
if (initialNotice) {
initialNotice.classList.add('mgc-hidden');
}
// Create settings modal
const modal = document.createElement('div');
modal.className = 'mgc-settings-modal';
const modalContent = document.createElement('div');
modalContent.className = 'mgc-settings-content';
// Modal title
const title = document.createElement('h3');
title.textContent = 'Cookie Settings';
title.style.marginTop = '0';
modalContent.appendChild(title);
// Description
const desc = document.createElement('p');
desc.textContent = 'Choose which types of cookies you want to allow:';
modalContent.appendChild(desc);
// Cookie categories
const categories = [
{
id: 'functional',
label: 'Functional Cookies',
description: 'These cookies are essential for the website to function properly.',
required: true
},
{
id: 'analytics',
label: 'Analytics Cookies',
description: 'Help us understand how visitors interact with our website.',
required: false
},
{
id: 'marketing',
label: 'Marketing Cookies',
description: 'Used to track visitors across websites for marketing purposes.',
required: false
}
];
const checkboxes = [];
categories.forEach(function(cat) {
const categoryDiv = document.createElement('div');
categoryDiv.className = 'mgc-category';
categoryDiv.style.marginBottom = '15px';
categoryDiv.style.padding = '10px';
categoryDiv.style.border = '1px solid #ddd';
categoryDiv.style.borderRadius = '4px';
const label = document.createElement('label');
label.style.display = 'flex';
label.style.alignItems = 'flex-start';
label.style.cursor = cat.required ? 'not-allowed' : 'pointer';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = 'mgc-cat-' + cat.id;
checkbox.value = cat.id;
checkbox.checked = true;
checkbox.disabled = cat.required;
checkbox.style.marginRight = '10px';
checkbox.style.marginTop = '3px';
if (!cat.required) {
checkboxes.push(checkbox);
}
const textDiv = document.createElement('div');
const labelText = document.createElement('strong');
labelText.textContent = cat.label;
if (cat.required) {
labelText.textContent += ' (Required)';
}
const descText = document.createElement('div');
descText.textContent = cat.description;
descText.style.fontSize = '13px';
descText.style.color = '#666';
descText.style.marginTop = '3px';
textDiv.appendChild(labelText);
textDiv.appendChild(descText);
label.appendChild(checkbox);
label.appendChild(textDiv);
categoryDiv.appendChild(label);
modalContent.appendChild(categoryDiv);
});
// Buttons
const buttonRow = document.createElement('div');
buttonRow.className = 'mgc-notice-buttons';
buttonRow.style.marginTop = '20px';
// Accept Selected button
const acceptSelected = document.createElement('button');
acceptSelected.className = 'mgc-button mgc-button-accept mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
acceptSelected.textContent = 'Save Preferences';
acceptSelected.onclick = function() {
const selectedCategories = ['functional']; // Always include functional
checkboxes.forEach(function(cb) {
if (cb.checked) {
selectedCategories.push(cb.value);
}
});
handleConsent('accept', selectedCategories);
modal.remove();
};
buttonRow.appendChild(acceptSelected);
// Accept All button
const acceptAll = document.createElement('button');
acceptAll.className = 'mgc-button mgc-button-accept mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
acceptAll.textContent = 'Accept All';
acceptAll.onclick = function() {
handleConsent('accept', ['functional', 'analytics', 'marketing']);
modal.remove();
};
buttonRow.appendChild(acceptAll);
// Reject All button
const rejectAll = document.createElement('button');
rejectAll.className = 'mgc-button mgc-button-settings mgc-button-color-' + (window.mgcSettings?.buttonColor || 'blue');
rejectAll.textContent = 'Reject Optional';
rejectAll.onclick = function() {
handleConsent('accept', ['functional']);
modal.remove();
};
buttonRow.appendChild(rejectAll);
modalContent.appendChild(buttonRow);
modal.appendChild(modalContent);
document.body.appendChild(modal);
}
function handleConsent(type, categories) {
// Set cookie
const expiry = window.mgcSettings?.cookieExpiry || 365;
setCookie('mgc_consent', type, expiry);
setCookie('mgc_consent_categories', JSON.stringify(categories), expiry);
// Send to server (fire and forget)
if (window.mgcSettings?.ajaxUrl) {
const formData = new FormData();
formData.append('action', 'mgc_save_consent');
formData.append('nonce', window.mgcSettings.nonce);
formData.append('consent_type', type);
categories.forEach(function(cat) {
formData.append('categories[]', cat);
});
fetch(window.mgcSettings.ajaxUrl, {
method: 'POST',
body: formData
}).catch(function() {
// Silently fail - consent is saved in cookie anyway
});
}
// Remove notice
const notice = document.querySelector('.mgc-notice');
if (notice) {
notice.classList.add('mgc-hidden');
setTimeout(function() {
notice.remove();
}, 300);
}
// Trigger custom event
const event = new CustomEvent('mgc_consent_saved', {
detail: {
type: type,
categories: categories
}
});
document.dispatchEvent(event);
}
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = 'expires=' + d.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/;SameSite=Lax';
}
function getCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
})();

View file

@ -0,0 +1,12 @@
<?php
/**
* Silence is golden.
*
* Prevent direct access to this file.
*
* @package WordPress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}