WebOrbiton

Code

StocketBase

Self-hosted digital commerce, without commission fees or SaaS lock-in.

Version history

Version 1.0.0.3 2026-11-19

Browse files
Files changed20
Lines added+593
Lines removed-86
ads.php Modified +43 -4
⋮ 23 unchanged lines ⋮
          $flashMessage = 'Your session expired. Please try again.';
          $flashType = 'error';
      } else {
+         $adsError = null;
          require __DIR__ . '/dashboard-actions/manage-ads.php';
-         ActivityLog::record('ads.' . (string) ($_POST['action'] ?? ''));
-         $flashMessage = 'Changes saved.';
+         if ($adsError !== null) {
+             $flashMessage = $adsError;
+             $flashType = 'error';
+         } else {
+             ActivityLog::record('ads.' . (string) ($_POST['action'] ?? ''));
+             $flashMessage = 'Changes saved.';
+         }
      }
  }
  
⋮ 7 unchanged lines ⋮
  
  $ads = $db->query('SELECT * FROM ads ORDER BY created_at DESC')->fetchAll();
  
+ SiteFront::resetSettings();
+ $adsConsentEnabled = (SiteFront::settings()['consent_manager_enabled'] ?? '0') === '1';
+ $adsBannerCategories = SiteFront::bannerConsentCategories();
+ $adTypeLabels = ['static_text' => 'Text', 'static_image' => 'Image', 'script' => 'Ad network code'];
+ $adConsentLabels = [
+     'always' => 'Always',
+     'analytics' => 'After consent: Analytics',
+     'marketing' => 'After consent: Marketing',
+     'preferences' => 'After consent: Preferences',
+ ];
+ $editingConsentRun = $editingAd !== null ? SiteFront::adConsentRun($editingAd) : 'always';
+ 
  $dashActivePage = 'ads';
  $dashPageTitle = 'Ads';
  
⋮ 16 unchanged lines ⋮
              <th><?= Icons::icon('heading', 'icon icon-sm') ?>Name</th>
              <th><?= Icons::icon('ads', 'icon icon-sm') ?>Type</th>
              <th><?= Icons::icon('flag', 'icon icon-sm') ?>Placement</th>
+             <th><?= Icons::icon('shield', 'icon icon-sm') ?>Shows</th>
              <th><?= Icons::icon('eye', 'icon icon-sm') ?>Active</th>
              <th></th>
          </tr>
⋮ 2 unchanged lines ⋮
          <?php foreach ($ads as $ad): ?>
              <tr>
                  <td><?= htmlspecialchars($ad['name']) ?></td>
-                 <td><?= htmlspecialchars($ad['type']) ?></td>
+                 <td><?= htmlspecialchars($adTypeLabels[$ad['type']] ?? $ad['type']) ?></td>
                  <td><?= htmlspecialchars(SiteFront::AD_PLACEMENTS[$ad['placement']] ?? $ad['placement']) ?></td>
+                 <td><?= htmlspecialchars($adsConsentEnabled ? $adConsentLabels[SiteFront::adConsentRun($ad)] : 'Always (cookie consent is off)') ?></td>
                  <td><?= $ad['is_active'] ? 'Yes' : 'No' ?></td>
                  <td class="dash-table-actions">
                      <button type="button" class="dash-btn-small js-edit-ad"
⋮ 3 unchanged lines ⋮
                          data-placement="<?= htmlspecialchars($ad['placement'], ENT_QUOTES) ?>"
                          data-content="<?= htmlspecialchars($ad['content'], ENT_QUOTES) ?>"
                          data-link-url="<?= htmlspecialchars((string) $ad['link_url'], ENT_QUOTES) ?>"
+                         data-consent-run="<?= htmlspecialchars(SiteFront::adConsentRun($ad), ENT_QUOTES) ?>"
                          data-is-active="<?= (int) $ad['is_active'] ?>"><?= Icons::icon('edit', 'icon icon-sm') ?>Edit</button>
                      <form method="post" style="display:inline;" onsubmit="return confirm('Delete this ad? It will disappear from your store.');">
                          <?= Csrf::field() ?>
⋮ 6 unchanged lines ⋮
          <?php endforeach; ?>
          <?php if (empty($ads)): ?>
              <tr>
-                 <td colspan="5">No ads yet. Use them to promote a sale or show a banner.</td>
+                 <td colspan="6">No ads yet. Use them to promote a sale or show a banner.</td>
              </tr>
          <?php endif; ?>
      </tbody>
⋮ 29 unchanged lines ⋮
          <label><?= Icons::icon('external', 'icon icon-sm') ?>Link (optional, not used for ad code)</label>
          <input type="text" name="link_url" id="ad_link_url_input" value="<?= htmlspecialchars($editingAd['link_url'] ?? '') ?>">
  
+         <label><?= Icons::icon('shield', 'icon icon-sm') ?>When should it show?</label>
+         <select name="consent_run" id="ad_consent_run_select">
+             <option value="always" <?= $editingConsentRun === 'always' ? 'selected' : '' ?>>Always, no consent needed</option>
+             <?php foreach (SiteFront::CONSENT_CATEGORIES as $consentCategoryKey): ?>
+                 <option value="<?= htmlspecialchars($consentCategoryKey) ?>" <?= $editingConsentRun === $consentCategoryKey ? 'selected' : '' ?>>After the visitor allows <?= htmlspecialchars(ucfirst($consentCategoryKey)) ?><?= in_array($consentCategoryKey, $adsBannerCategories, true) ? '' : ' (not shown under Manage, only "Accept" turns it on)' ?></option>
+             <?php endforeach; ?>
+         </select>
+         <p style="font-size:12px;color:var(--muted);margin:6px 0 0;"><?= $adsConsentEnabled ? 'Ads from ad networks usually use cookies, so pick Marketing for those. Until the visitor agrees, the ad simply doesn\'t appear.' : 'Cookie consent is turned off in Analytics, so every ad shows right away. This choice starts working when you turn it on.' ?></p>
+ 
          <label><input type="checkbox" name="is_active" id="ad_is_active_input" <?= ($editingAd['is_active'] ?? 1) ? 'checked' : '' ?>> Show it on the store</label>
  
          <div class="publish-actions">
⋮ 14 unchanged lines ⋮
              document.getElementById('ad_id_input').value = '';
              document.getElementById('ad_placement_input').value = 'header';
              document.getElementById('ad_is_active_input').checked = true;
+             document.getElementById('ad_consent_run_select').value = 'always';
              formTitle.textContent = 'New ad';
          }
  
+         document.getElementById('ad_type_select').addEventListener('change', function() {
+             var consentSelect = document.getElementById('ad_consent_run_select');
+             if (this.value === 'script' && consentSelect.value === 'always') {
+                 consentSelect.value = 'marketing';
+             }
+         });
+ 
          function showForm() {
              wrapper.style.display = '';
              wrapper.scrollIntoView({
⋮ 21 unchanged lines ⋮
                  document.getElementById('ad_content_input').value = this.dataset.content;
                  document.getElementById('ad_link_url_input').value = this.dataset.linkUrl;
                  document.getElementById('ad_is_active_input').checked = this.dataset.isActive === '1';
+                 document.getElementById('ad_consent_run_select').value = this.dataset.consentRun || 'always';
                  formTitle.textContent = 'Edit ad';
                  showForm();
              });
⋮ 5 unchanged lines ⋮
analytics.php Modified +47 -13
⋮ 6 unchanged lines ⋮
  require_once __DIR__ . '/includes/auth.php';
  require_once __DIR__ . '/includes/csrf.php';
  require_once __DIR__ . '/includes/activity-log.php';
+ require_once __DIR__ . '/includes/site-front.php';
  
  Auth::boot();
  Auth::requireRoleAtLeast(Auth::ROLE_STORE_OWNER);
⋮ 10 unchanged lines ⋮
          $flashMessage = 'Your session expired. Please try again.';
          $flashType = 'error';
      } else {
+         $analyticsError = null;
          require __DIR__ . '/dashboard-actions/manage-analytics.php';
-         ActivityLog::record('analytics.' . (string) ($_POST['action'] ?? ''));
-         $flashMessage = 'Changes saved.';
+         if ($analyticsError !== null) {
+             $flashMessage = $analyticsError;
+             $flashType = 'error';
+         } else {
+             ActivityLog::record('analytics.' . (string) ($_POST['action'] ?? ''));
+             $flashMessage = 'Changes saved.';
+         }
      }
  }
  
⋮ 7 unchanged lines ⋮
  
  $scripts = $db->query('SELECT * FROM analytics_scripts ORDER BY created_at DESC')->fetchAll();
  
- $db->prepare('INSERT IGNORE INTO site_settings (setting_key, setting_value) VALUES (:key, :value)')
-     ->execute(['key' => 'consent_footer_icon_enabled', 'value' => '0']);
+ SiteFront::resetSettings();
+ $consentSettings = SiteFront::settings();
+ $consentEnabled = ($consentSettings['consent_manager_enabled'] ?? '0') === '1';
+ $consentFooterIconEnabled = ($consentSettings['consent_footer_icon_enabled'] ?? '0') === '1';
+ $consentManageEnabled = ($consentSettings['consent_manage_enabled'] ?? '1') === '1';
+ $consentShown = SiteFront::bannerConsentCategories();
  
- $consentSetting = $db->prepare('SELECT setting_value FROM site_settings WHERE setting_key = :key LIMIT 1');
- $consentSetting->execute(['key' => 'consent_manager_enabled']);
- $consentEnabled = ($consentSetting->fetch()['setting_value'] ?? '0') === '1';
- $consentSetting->execute(['key' => 'consent_footer_icon_enabled']);
- $consentFooterIconEnabled = ($consentSetting->fetch()['setting_value'] ?? '0') === '1';
+ $consentCategoryLabels = [
+     'analytics' => 'Analytics (like Google Analytics)',
+     'marketing' => 'Marketing (like a Meta or TikTok pixel)',
+     'preferences' => 'Preferences (remembering choices, chat widgets)',
+ ];
+ $scriptRunLabel = static function (array $script) use ($consentCategoryLabels): string {
+     if (!(int) $script['requires_consent']) {
+         return 'Always';
+     }
+     $category = (string) ($script['consent_category'] ?? 'analytics');
  
+     return 'After consent: ' . strtok($consentCategoryLabels[$category] ?? $consentCategoryLabels['analytics'], ' ');
+ };
+ $editingRun = $editingScript === null
+     ? 'analytics'
+     : ((int) $editingScript['requires_consent'] ? (string) ($editingScript['consent_category'] ?? 'analytics') : 'always');
+ 
  $dashActivePage = 'analytics';
  $dashPageTitle = 'Analytics';
  
⋮ 13 unchanged lines ⋮
  <input type="hidden" name="action" value="save_consent_settings">
  <label><input type="checkbox" name="consent_manager_enabled" <?= $consentEnabled ? 'checked' : '' ?>> Ask visitors for cookie consent (scripts marked below only run after they agree)</label>
  <label><input type="checkbox" name="consent_footer_icon_enabled" <?= $consentFooterIconEnabled ? 'checked' : '' ?>> Show a cookie icon in the footer so visitors can change their mind</label>
+ <label><input type="checkbox" name="consent_manage_enabled" <?= $consentManageEnabled ? 'checked' : '' ?>> Add a "Manage" button so visitors can choose which kinds of cookies they allow</label>
+ <p style="font-size:12.5px;color:var(--muted);margin:14px 0 6px;">Choices shown after "Manage" (only tick what your store actually uses). "Necessary" is always shown.</p>
+ <?php foreach ($consentCategoryLabels as $categoryKey => $categoryLabel): ?>
+ <label><input type="checkbox" name="consent_show_<?= htmlspecialchars($categoryKey) ?>" <?= in_array($categoryKey, $consentShown, true) ? 'checked' : '' ?>> <?= htmlspecialchars($categoryLabel) ?></label>
+ <?php endforeach; ?>
  <button type="submit" class="dash-btn dash-btn-primary" style="margin-top:12px;"><?= Icons::icon('check', 'icon icon-sm') ?>Save</button>
  </form>
  </div>
  
  <table class="dash-table">
- <thead><tr><th><?= Icons::icon('heading', 'icon icon-sm') ?>Name</th><th><?= Icons::icon('layout', 'icon icon-sm') ?>Placement</th><th><?= Icons::icon('shield', 'icon icon-sm') ?>Requires consent</th><th><?= Icons::icon('toggle', 'icon icon-sm') ?>Active</th><th></th></tr></thead>
+ <thead><tr><th><?= Icons::icon('heading', 'icon icon-sm') ?>Name</th><th><?= Icons::icon('layout', 'icon icon-sm') ?>Placement</th><th><?= Icons::icon('shield', 'icon icon-sm') ?>Runs</th><th><?= Icons::icon('toggle', 'icon icon-sm') ?>Active</th><th></th></tr></thead>
  <tbody>
  <?php foreach ($scripts as $script): ?>
  <tr>
  <td><?= htmlspecialchars($script['name']) ?></td>
- <td><?= htmlspecialchars($script['placement']) ?></td>
- <td><?= $script['requires_consent'] ? 'Yes' : 'No' ?></td>
+ <td><?= htmlspecialchars(['head' => 'Page head', 'body_start' => 'Top of the page', 'body_end' => 'Bottom of the page'][$script['placement']] ?? (string) $script['placement']) ?></td>
+ <td><?= htmlspecialchars($scriptRunLabel($script)) ?></td>
  <td><?= $script['is_active'] ? 'Yes' : 'No' ?></td>
  <td class="dash-table-actions">
  <a href="analytics.php?edit=<?= (int) $script['id'] ?>" class="dash-btn-small"><?= Icons::icon('edit', 'icon icon-sm') ?>Edit</a>
⋮ 33 unchanged lines ⋮
  <option value="body_end" <?= ($editingScript['placement'] ?? '') === 'body_end' ? 'selected' : '' ?>>Bottom of the page (&lt;body&gt; end)</option>
  </select>
  
- <label><input type="checkbox" name="requires_consent" <?= ($editingScript['requires_consent'] ?? 1) ? 'checked' : '' ?>> Only run after the visitor accepts cookies</label>
+ <label>When should it run?</label>
+ <select name="consent_run">
+ <option value="always" <?= $editingRun === 'always' ? 'selected' : '' ?>>Always, no consent needed (only for things the store can't work without)</option>
+ <?php foreach ($consentCategoryLabels as $categoryKey => $categoryLabel): ?>
+ <option value="<?= htmlspecialchars($categoryKey) ?>" <?= $editingRun === $categoryKey ? 'selected' : '' ?>>After the visitor allows: <?= htmlspecialchars($categoryLabel) ?><?= in_array($categoryKey, $consentShown, true) ? '' : ' (not shown under Manage, only "Accept" turns it on)' ?></option>
+ <?php endforeach; ?>
+ </select>
+ <p style="font-size:12px;color:var(--muted);margin:6px 0 0;">Visitors who use "Manage" can allow some kinds and block others. Pick the kind that fits this script best.</p>
  <label><input type="checkbox" name="is_active" <?= ($editingScript['is_active'] ?? 1) ? 'checked' : '' ?>> Turned on</label>
  
  <button type="submit" class="dash-btn dash-btn-primary" style="margin-top:16px;"><?= Icons::icon('check', 'icon icon-sm') ?>Save script</button>
⋮ 4 unchanged lines ⋮
assets/block-editor.js Modified

Not shown (binary file or too large to diff).

assets/dashboard.css Modified

Not shown (binary file or too large to diff).

assets/shortcuts.js Modified +1 -1
⋮ 8 unchanged lines ⋮
      underline: { label: 'Underline', combo: 'Ctrl+U' },
      strikethrough: { label: 'Strikethrough', combo: 'Ctrl+Shift+X' },
      add_block: { label: 'Add block below', combo: 'Ctrl+Enter' },
-     remove_block: { label: 'Remove block', combo: 'Ctrl+Backspace' },
+     remove_block: { label: 'Remove block', combo: 'Ctrl+Shift+Backspace' },
      move_block_up: { label: 'Move block up', combo: 'Ctrl+Shift+ArrowUp' },
      move_block_down: { label: 'Move block down', combo: 'Ctrl+Shift+ArrowDown' },
      save: { label: 'Save', combo: 'Ctrl+S' },
⋮ 122 unchanged lines ⋮
assets/site.css Modified

Not shown (binary file or too large to diff).

assets/site.js Modified +186 -33
⋮ 25 unchanged lines ⋮
  
    function initConsent() {
      var banner = document.getElementById('consent-banner');
+     if (!banner) {
+       return;
+     }
+ 
+     var consentKey = 'stocketbase_consent';
+     var categories = ['analytics', 'marketing', 'preferences'];
      var acceptBtn = document.getElementById('consent-accept');
      var declineBtn = document.getElementById('consent-decline');
-     var consentKey = 'stocketbase_consent';
+     var manageBtn = document.getElementById('consent-manage');
+     var saveBtn = document.getElementById('consent-save');
+     var options = document.getElementById('consent-options');
+     var reopenBtn = document.getElementById('consent-reopen-btn');
+     var ran = {};
  
-     function runGatedScripts() {
-       document.querySelectorAll('script.consent-gated-script').forEach(function (oldScript) {
-         var newScript = document.createElement('script');
-         Array.from(oldScript.attributes).forEach(function (attr) {
-           if (attr.name !== 'type') {
-             newScript.setAttribute(attr.name, attr.value);
+     function allAs(value) {
+       var state = {};
+       categories.forEach(function (category) {
+         state[category] = value;
+       });
+       return state;
+     }
+ 
+     function readConsent() {
+       var raw = null;
+       try {
+         raw = localStorage.getItem(consentKey);
+       } catch (error) {
+         return null;
+       }
+       if (raw === 'accepted') {
+         return allAs(true);
+       }
+       if (raw === 'declined') {
+         return allAs(false);
+       }
+       if (!raw) {
+         return null;
+       }
+       try {
+         var parsed = JSON.parse(raw);
+         if (!parsed || typeof parsed !== 'object') {
+           return null;
+         }
+         var state = {};
+         categories.forEach(function (category) {
+           state[category] = parsed[category] === true;
+         });
+         return state;
+       } catch (error) {
+         return null;
+       }
+     }
+ 
+     function writeConsent(state) {
+       var record = { v: 2, at: Date.now() };
+       categories.forEach(function (category) {
+         record[category] = state[category] === true;
+       });
+       try {
+         localStorage.setItem(consentKey, JSON.stringify(record));
+       } catch (error) {
+       }
+     }
+ 
+     function activate(node) {
+       if (node.nodeType !== 1) {
+         return node;
+       }
+       if (node.tagName === 'SCRIPT') {
+         var fresh = document.createElement('script');
+         Array.prototype.forEach.call(node.attributes, function (attr) {
+           fresh.setAttribute(attr.name, attr.value);
+         });
+         if (fresh.src) {
+           fresh.async = node.hasAttribute('async');
+         }
+         fresh.text = node.text;
+         return fresh;
+       }
+       Array.prototype.forEach.call(node.querySelectorAll('script'), function (inner) {
+         inner.parentNode.replaceChild(activate(inner), inner);
+       });
+       return node;
+     }
+ 
+     function insertInOrder(nodes, parent, anchor, done) {
+       if (!nodes.length) {
+         done();
+         return;
+       }
+       var node = activate(nodes.shift());
+       var waits = node.nodeType === 1 && node.tagName === 'SCRIPT' && node.src && !node.async && !node.defer;
+       var next = function () {
+         insertInOrder(nodes, parent, anchor, done);
+       };
+       if (waits) {
+         node.addEventListener('load', next);
+         node.addEventListener('error', next);
+       }
+       parent.insertBefore(node, anchor);
+       if (!waits) {
+         next();
+       }
+     }
+ 
+     function runCategory(category) {
+       if (ran[category]) {
+         return;
+       }
+       ran[category] = true;
+       document.querySelectorAll('template.consent-gated[data-category="' + category + '"]').forEach(function (template) {
+         var nodes = Array.prototype.slice.call(template.content.cloneNode(true).childNodes);
+         var parent = template.parentNode;
+         insertInOrder(nodes, parent, template, function () {
+           if (template.parentNode) {
+             template.parentNode.removeChild(template);
            }
          });
-         newScript.textContent = oldScript.textContent;
-         oldScript.parentNode.replaceChild(newScript, oldScript);
        });
      }
  
-     var reopenBtn = document.getElementById('consent-reopen-btn');
-     var storedConsent = localStorage.getItem(consentKey);
-     var scriptsRan = false;
+     function apply(state) {
+       var revoked = categories.some(function (category) {
+         return ran[category] && !state[category];
+       });
+       writeConsent(state);
+       if (revoked) {
+         window.location.reload();
+         return;
+       }
+       categories.forEach(function (category) {
+         if (state[category]) {
+           runCategory(category);
+         }
+       });
+       closeBanner();
+     }
  
-     function hideBanner() {
-       if (banner) { banner.style.display = 'none'; }
+     function syncCheckboxes(state) {
+       if (!options) {
+         return;
+       }
+       options.querySelectorAll('input[data-consent-category]').forEach(function (input) {
+         input.checked = !!(state && state[input.dataset.consentCategory]);
+       });
      }
  
-     if (storedConsent === 'accepted') {
-       runGatedScripts();
-       scriptsRan = true;
+     function setManageMode(on) {
+       if (!options) {
+         return;
+       }
+       options.hidden = !on;
+       if (manageBtn) {
+         manageBtn.hidden = on;
+       }
+       if (saveBtn) {
+         saveBtn.hidden = !on;
+       }
      }
-     if (storedConsent) {
-       hideBanner();
+ 
+     function openBanner(manage) {
+       syncCheckboxes(readConsent());
+       setManageMode(!!manage);
+       banner.hidden = false;
      }
  
+     function closeBanner() {
+       banner.hidden = true;
+       setManageMode(false);
+     }
+ 
+     var stored = readConsent();
+     if (stored) {
+       categories.forEach(function (category) {
+         if (stored[category]) {
+           runCategory(category);
+         }
+       });
+     } else {
+       openBanner(false);
+     }
+ 
      if (acceptBtn) {
        acceptBtn.addEventListener('click', function () {
-         localStorage.setItem(consentKey, 'accepted');
-         if (!scriptsRan) {
-           runGatedScripts();
-           scriptsRan = true;
-         }
-         hideBanner();
+         apply(allAs(true));
        });
      }
      if (declineBtn) {
        declineBtn.addEventListener('click', function () {
-         localStorage.setItem(consentKey, 'declined');
-         if (scriptsRan) {
-           window.location.reload();
-           return;
-         }
-         hideBanner();
+         apply(allAs(false));
        });
      }
-     if (reopenBtn && banner) {
+     if (manageBtn) {
+       manageBtn.addEventListener('click', function () {
+         setManageMode(true);
+       });
+     }
+     if (saveBtn) {
+       saveBtn.addEventListener('click', function () {
+         var state = allAs(false);
+         options.querySelectorAll('input[data-consent-category]').forEach(function (input) {
+           state[input.dataset.consentCategory] = input.checked;
+         });
+         apply(state);
+       });
+     }
+     if (reopenBtn) {
        reopenBtn.addEventListener('click', function () {
-         banner.style.display = '';
+         openBanner(!!options);
        });
      }
    }
⋮ 403 unchanged lines ⋮
dashboard-actions/manage-ads.php Modified +25 -3
⋮ 17 unchanged lines ⋮
      $content = (string) ($_POST['content'] ?? '');
      $linkUrl = trim((string) ($_POST['link_url'] ?? ''));
      $isActive = isset($_POST['is_active']) ? 1 : 0;
+     $consentRun = (string) ($_POST['consent_run'] ?? 'always');
+     if ($consentRun !== 'always' && !in_array($consentRun, SiteFront::CONSENT_CATEGORIES, true)) {
+         $consentRun = 'always';
+     }
  
-     if ($name === '' || $content === '') {
+     if ($name === '' || trim($content) === '') {
+         $adsError = 'Please fill in the name and the content.';
          return;
      }
  
+     if ($linkUrl !== '' && SiteFront::safeAdUrl($linkUrl) === '') {
+         $adsError = 'The link should start with http:// or https://.';
+         return;
+     }
+ 
+     if ($type === 'static_image' && SiteFront::safeAdUrl(trim($content)) === '') {
+         $adsError = 'The image address should start with http:// or https://, or be a file from your store.';
+         return;
+     }
+ 
+     if ($consentRun !== 'always' && stripos($content, '</template') !== false) {
+         $adsError = 'This code contains a </template> tag, which can\'t be used with a consent requirement.';
+         return;
+     }
+ 
      if ($adId !== null) {
          $statement = $db->prepare(
-             'UPDATE ads SET name = :name, type = :type, placement = :placement, content = :content, link_url = :link_url, is_active = :is_active WHERE id = :id'
+             'UPDATE ads SET name = :name, type = :type, placement = :placement, content = :content, link_url = :link_url, consent_run = :consent_run, is_active = :is_active WHERE id = :id'
          );
          $statement->execute([
              'name' => $name,
⋮ 1 unchanged line ⋮
              'placement' => $placement,
              'content' => $content,
              'link_url' => $linkUrl !== '' ? $linkUrl : null,
+             'consent_run' => $consentRun,
              'is_active' => $isActive,
              'id' => $adId,
          ]);
      } else {
          $statement = $db->prepare(
-             'INSERT INTO ads (name, type, placement, content, link_url, is_active, created_by) VALUES (:name, :type, :placement, :content, :link_url, :is_active, :created_by)'
+             'INSERT INTO ads (name, type, placement, content, link_url, consent_run, is_active, created_by) VALUES (:name, :type, :placement, :content, :link_url, :consent_run, :is_active, :created_by)'
          );
          $statement->execute([
              'name' => $name,
⋮ 1 unchanged line ⋮
              'placement' => $placement,
              'content' => $content,
              'link_url' => $linkUrl !== '' ? $linkUrl : null,
+             'consent_run' => $consentRun,
              'is_active' => $isActive,
              'created_by' => $currentUser['id'],
          ]);
⋮ 11 unchanged lines ⋮
dashboard-actions/manage-analytics.php Modified +19 -4
⋮ 14 unchanged lines ⋮
      $name = trim((string) ($_POST['name'] ?? ''));
      $scriptCode = (string) ($_POST['script_code'] ?? '');
      $placement = in_array($_POST['placement'] ?? '', ['head', 'body_start', 'body_end'], true) ? $_POST['placement'] : 'head';
-     $requiresConsent = isset($_POST['requires_consent']) ? 1 : 0;
+     $consentRun = (string) ($_POST['consent_run'] ?? 'analytics');
+     $requiresConsent = $consentRun === 'always' ? 0 : 1;
+     $consentCategory = SiteFront::consentCategory($consentRun);
      $isActive = isset($_POST['is_active']) ? 1 : 0;
  
-     if ($name === '' || $scriptCode === '') {
+     if ($name === '' || trim($scriptCode) === '') {
+         $analyticsError = 'Please fill in the name and paste the code.';
          return;
      }
  
+     if (stripos($scriptCode, '</template') !== false) {
+         $analyticsError = 'This code contains a </template> tag, which can\'t be used here.';
+         return;
+     }
+ 
      if ($scriptId !== null) {
          $statement = $db->prepare(
-             'UPDATE analytics_scripts SET name = :name, script_code = :script_code, placement = :placement, requires_consent = :requires_consent, is_active = :is_active WHERE id = :id'
+             'UPDATE analytics_scripts SET name = :name, script_code = :script_code, placement = :placement, requires_consent = :requires_consent, consent_category = :consent_category, is_active = :is_active WHERE id = :id'
          );
          $statement->execute([
              'name' => $name,
              'script_code' => $scriptCode,
              'placement' => $placement,
              'requires_consent' => $requiresConsent,
+             'consent_category' => $consentCategory,
              'is_active' => $isActive,
              'id' => $scriptId,
          ]);
      } else {
          $statement = $db->prepare(
-             'INSERT INTO analytics_scripts (name, script_code, placement, requires_consent, is_active) VALUES (:name, :script_code, :placement, :requires_consent, :is_active)'
+             'INSERT INTO analytics_scripts (name, script_code, placement, requires_consent, consent_category, is_active) VALUES (:name, :script_code, :placement, :requires_consent, :consent_category, :is_active)'
          );
          $statement->execute([
              'name' => $name,
              'script_code' => $scriptCode,
              'placement' => $placement,
              'requires_consent' => $requiresConsent,
+             'consent_category' => $consentCategory,
              'is_active' => $isActive,
          ]);
      }
⋮ 14 unchanged lines ⋮
      );
      $statement->execute(['key' => 'consent_manager_enabled', 'value' => $consentEnabled]);
      $statement->execute(['key' => 'consent_footer_icon_enabled', 'value' => isset($_POST['consent_footer_icon_enabled']) ? '1' : '0']);
+     $statement->execute(['key' => 'consent_manage_enabled', 'value' => isset($_POST['consent_manage_enabled']) ? '1' : '0']);
+     foreach (SiteFront::CONSENT_CATEGORIES as $consentCategory) {
+         $statement->execute(['key' => 'consent_show_' . $consentCategory, 'value' => isset($_POST['consent_show_' . $consentCategory]) ? '1' : '0']);
+     }
+     SiteFront::resetSettings();
  }
  
dashboard-views/reviews.php Modified +7 -2
⋮ 14 unchanged lines ⋮
  $usersDb = Database::users();
  $db = Database::site();
  
- $statusFilter = in_array($_GET['status'] ?? '', ['visible', 'hidden', 'flagged'], true) ? $_GET['status'] : 'flagged';
+ $statusFilter = in_array($_GET['status'] ?? '', ['visible', 'hidden', 'flagged'], true) ? $_GET['status'] : 'visible';
  
  $statement = $usersDb->prepare(
      'SELECT r.*, u.display_name, u.email FROM product_reviews r LEFT JOIN user_accounts u ON u.id = r.user_account_id
⋮ 1 unchanged line ⋮
  );
  $statement->execute(['status' => $statusFilter]);
  $reviews = $statement->fetchAll();
+ $flaggedCount = (int) $usersDb->query("SELECT COUNT(*) FROM product_reviews WHERE status = 'flagged'")->fetchColumn();
  
  $productIds = array_values(array_unique(array_map(static fn(array $review) => (int) $review['product_id'], $reviews)));
  $productTitles = [];
⋮ 12 unchanged lines ⋮
  </div>
  
  <div class="settings-tabs">
- <a href="dashboard.php?view=reviews&status=flagged" class="<?= $statusFilter === 'flagged' ? 'active' : '' ?>">Reported</a>
  <a href="dashboard.php?view=reviews&status=visible" class="<?= $statusFilter === 'visible' ? 'active' : '' ?>">Visible</a>
  <a href="dashboard.php?view=reviews&status=hidden" class="<?= $statusFilter === 'hidden' ? 'active' : '' ?>">Hidden</a>
+ <?php if ($flaggedCount > 0): ?>
+ <a href="dashboard.php?view=reviews&status=flagged" class="<?= $statusFilter === 'flagged' ? 'active' : '' ?>">Reported (<?= $flaggedCount ?>)</a>
+ <?php endif; ?>
  </div>
  
  <table class="dash-table">
⋮ 21 unchanged lines ⋮
  <form method="post" style="display:inline;">
  <?= Csrf::field() ?>
  <input type="hidden" name="action" value="moderate_review">
+ <input type="hidden" name="tab" value="<?= htmlspecialchars($statusFilter, ENT_QUOTES) ?>">
  <input type="hidden" name="review_id" value="<?= (int) $review['id'] ?>">
  <input type="hidden" name="decision" value="show">
  <button type="submit" class="dash-btn-small dash-btn-success"><?= Icons::icon('check', 'icon icon-sm') ?>Approve</button>
⋮ 3 unchanged lines ⋮
  <form method="post" style="display:inline;">
  <?= Csrf::field() ?>
  <input type="hidden" name="action" value="moderate_review">
+ <input type="hidden" name="tab" value="<?= htmlspecialchars($statusFilter, ENT_QUOTES) ?>">
  <input type="hidden" name="review_id" value="<?= (int) $review['id'] ?>">
  <input type="hidden" name="decision" value="hide">
  <button type="submit" class="dash-btn-small dash-btn-danger"><?= Icons::icon('x', 'icon icon-sm') ?>Hide</button>
⋮ 11 unchanged lines ⋮
dashboard.php Modified +2 -1
⋮ 187 unchanged lines ⋮
  
          if ($action === 'moderate_review') {
              require __DIR__ . '/dashboard-actions/moderate-review.php';
-             header('Location: dashboard.php?view=reviews&moderated=1');
+             $reviewTab = in_array($_POST['tab'] ?? '', ['visible', 'hidden', 'flagged'], true) ? $_POST['tab'] : 'visible';
+             header('Location: dashboard.php?view=reviews&status=' . $reviewTab . '&moderated=1');
              exit;
          }
      }
⋮ 73 unchanged lines ⋮
includes/block-editor.php Modified +75 -7
⋮ 291 unchanged lines ⋮
          }
  
          if (!class_exists(\DOMDocument::class)) {
-             return strip_tags($text, '<b><strong><i><em><a><br><u><s><code>');
+             return strip_tags($text, '<b><strong><i><em><a><br><u><s><code><ul><ol><li>');
          }
  
-         $allowedTags = ['b', 'strong', 'i', 'em', 'u', 's', 'code', 'a', 'span', 'br'];
+         $allowedTags = ['b', 'strong', 'i', 'em', 'u', 's', 'code', 'a', 'span', 'br', 'ul', 'ol', 'li'];
          $allowedColors = '/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/';
  
          $wrapped = '<?xml encoding="utf-8"?><div>' . $text . '</div>';
⋮ 16 unchanged lines ⋮
              $html .= $dom->saveHTML($child);
          }
  
-         return $html;
+         return self::decodeTextEntities($html);
      }
  
+     private static function decodeTextEntities(string $html): string
+     {
+         return (string) preg_replace_callback('/&(#[0-9]+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/', static function (array $match): string {
+             $char = html_entity_decode($match[0], ENT_QUOTES | ENT_HTML5, 'UTF-8');
+             if ($char === $match[0] || $char === "\u{00A0}" || mb_strlen($char, 'UTF-8') !== 1 || ord($char[0]) < 128) {
+                 return $match[0];
+             }
+ 
+             return $char;
+         }, $html);
+     }
+ 
      private static function sanitizeNode(\DOMDocument $dom, \DOMNode $node, array $allowedTags, string $allowedColors): void
      {
          $children = iterator_to_array($node->childNodes);
⋮ 9 unchanged lines ⋮
              }
  
              $tag = strtolower($child->tagName);
+             $parentTag = $node instanceof \DOMElement ? strtolower($node->tagName) : '';
+             $misplacedItem = $tag === 'li' && !in_array($parentTag, ['ul', 'ol'], true);
  
-             if (!in_array($tag, $allowedTags, true)) {
+             if ($misplacedItem || !in_array($tag, $allowedTags, true)) {
+                 $previousSibling = $child->previousSibling;
+                 if (in_array($tag, ['div', 'p', 'li'], true) && $previousSibling !== null
+                     && !($previousSibling instanceof \DOMElement && in_array(strtolower($previousSibling->tagName), ['br', 'ul', 'ol'], true))) {
+                     $node->insertBefore($dom->createElement('br'), $child);
+                 }
                  while ($child->firstChild) {
                      $node->insertBefore($child->firstChild, $child);
                  }
                  $node->removeChild($child);
-                 continue;
+                 self::sanitizeNode($dom, $node, $allowedTags, $allowedColors);
+                 return;
              }
  
              self::sanitizeAttributes($child, $tag, $allowedColors);
⋮ 147 unchanged lines ⋮
          $data = $block['data'] ?? [];
  
          return match ($type) {
-             'paragraph' => '<p>' . ($data['text'] ?? '') . '</p>',
+             'paragraph' => self::renderParagraph((string) ($data['text'] ?? '')),
              'quote' => '<blockquote>' . ($data['text'] ?? '') . '</blockquote>',
              'heading2' => '<h2>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h2>',
              'heading3' => '<h3>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h3>',
⋮ 26 unchanged lines ⋮
              '</div>';
      }
  
+     private static function renderParagraph(string $html): string
+     {
+         if (stripos($html, '<ul') === false && stripos($html, '<ol') === false) {
+             return '<p>' . $html . '</p>';
+         }
+ 
+         if (!class_exists(\DOMDocument::class)) {
+             return '<div class="paragraph-group">' . $html . '</div>';
+         }
+ 
+         $previous = libxml_use_internal_errors(true);
+         $dom = new \DOMDocument();
+         $dom->loadHTML('<?xml encoding="utf-8"?><div>' . $html . '</div>', LIBXML_NOERROR | LIBXML_NOWARNING);
+         libxml_clear_errors();
+         libxml_use_internal_errors($previous);
+ 
+         $root = $dom->getElementsByTagName('div')->item(0);
+         if ($root === null) {
+             return '<p>' . $html . '</p>';
+         }
+ 
+         $parts = [];
+         $buffer = '';
+         $flush = static function () use (&$buffer, &$parts): void {
+             $trimmed = preg_replace('#^(\s|<br\s*/?>)+|(\s|<br\s*/?>)+$#i', '', $buffer);
+             if ($trimmed !== null && trim(strip_tags($trimmed)) !== '') {
+                 $parts[] = '<p>' . $trimmed . '</p>';
+             }
+             $buffer = '';
+         };
+ 
+         foreach (iterator_to_array($root->childNodes) as $child) {
+             $outer = (string) $dom->saveHTML($child);
+             if ($child instanceof \DOMElement && in_array(strtolower($child->tagName), ['ul', 'ol'], true)) {
+                 $flush();
+                 $parts[] = $outer;
+                 continue;
+             }
+             $buffer .= $outer;
+         }
+         $flush();
+ 
+         return self::decodeTextEntities(implode('', $parts));
+     }
+ 
      private static function renderList(array $data): string
      {
          $tag = ($data['style'] ?? 'unordered') === 'ordered' ? 'ol' : 'ul';
          $items = '';
          foreach ($data['items'] ?? [] as $item) {
+             if (trim((string) $item) === '') {
+                 continue;
+             }
              $items .= '<li>' . htmlspecialchars((string) $item) . '</li>';
          }
-         return '<' . $tag . '>' . $items . '</' . $tag . '>';
+         return $items === '' ? '' : '<' . $tag . '>' . $items . '</' . $tag . '>';
      }
  
      private static function renderTable(array $data): string
⋮ 23 unchanged lines ⋮
includes/database.php Modified +41 -0
⋮ 56 unchanged lines ⋮
          ]);
      }
  
+     private static function ensureSettingsKey(PDO $pdo, string $dbName): void
+     {
+         $tableCheck = $pdo->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = :db AND TABLE_NAME = 'site_settings'");
+         $tableCheck->execute(['db' => $dbName]);
+         if ((int) $tableCheck->fetchColumn() === 0) {
+             return;
+         }
+ 
+         $keyCheck = $pdo->prepare(
+             "SELECT COUNT(*) FROM information_schema.STATISTICS
+              WHERE TABLE_SCHEMA = :db AND TABLE_NAME = 'site_settings' AND COLUMN_NAME = 'setting_key' AND NON_UNIQUE = 0 AND SEQ_IN_INDEX = 1"
+         );
+         $keyCheck->execute(['db' => $dbName]);
+         if ((int) $keyCheck->fetchColumn() > 0) {
+             return;
+         }
+ 
+         try {
+             $helperCheck = $pdo->prepare(
+                 "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = :db AND TABLE_NAME = 'site_settings' AND COLUMN_NAME = 'sb_row_id'"
+             );
+             $helperCheck->execute(['db' => $dbName]);
+             if ((int) $helperCheck->fetchColumn() === 0) {
+                 $pdo->exec('ALTER TABLE site_settings ADD COLUMN sb_row_id INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE');
+             }
+             $pdo->exec('DELETE older FROM site_settings older JOIN site_settings newer ON newer.setting_key = older.setting_key AND newer.sb_row_id > older.sb_row_id');
+             $pdo->exec('ALTER TABLE site_settings ADD PRIMARY KEY (setting_key)');
+             $pdo->exec('ALTER TABLE site_settings DROP COLUMN sb_row_id');
+         } catch (PDOException $e) {
+             error_log('StocketBase: could not repair site_settings key: ' . $e->getMessage());
+         }
+     }
+ 
      private static function ensureSiteSchema(PDO $pdo): void
      {
          if (self::$schemaChecked) {
⋮ 27 unchanged lines ⋮
                  'pages' => [
                      'is_home' => "ALTER TABLE pages ADD COLUMN is_home TINYINT(1) NOT NULL DEFAULT 0",
                  ],
+                 'ads' => [
+                     'consent_run' => "ALTER TABLE ads ADD COLUMN consent_run VARCHAR(20) NULL AFTER link_url",
+                 ],
+                 'analytics_scripts' => [
+                     'consent_category' => "ALTER TABLE analytics_scripts ADD COLUMN consent_category VARCHAR(20) NOT NULL DEFAULT 'analytics' AFTER requires_consent",
+                 ],
                  'categories' => [
                      'show_in_menu' => "ALTER TABLE categories ADD COLUMN show_in_menu TINYINT(1) NOT NULL DEFAULT 1 AFTER sort_order",
                  ],
⋮ 29 unchanged lines ⋮
                      }
                  }
              }
+ 
+             self::ensureSettingsKey($pdo, (string) $dbName);
  
              $authorColumns = ['products' => 'created_by', 'pages' => 'author_id', 'ads' => 'created_by', 'discounts' => 'created_by'];
              $authorState = $pdo->prepare(
⋮ 181 unchanged lines ⋮
includes/front-footer.php Modified +21 -1
⋮ 108 unchanged lines ⋮
  <?php endif; ?>
  
  <?php if (($settings['consent_manager_enabled'] ?? '0') === '1'): ?>
-     <div class="consent-banner" id="consent-banner">
+     <?php $consentBannerCategories = SiteFront::bannerConsentCategories(); ?>
+     <?php $consentManageEnabled = ($settings['consent_manage_enabled'] ?? '1') === '1' && $consentBannerCategories !== []; ?>
+     <div class="consent-banner" id="consent-banner" role="dialog" aria-label="<?= htmlspecialchars(Language::get('consent_title', 'Cookie settings'), ENT_QUOTES) ?>" hidden>
          <p><?= htmlspecialchars(Language::get('consent_text', 'We use cookies and similar technologies to improve your experience.')) ?></p>
+         <?php if ($consentManageEnabled): ?>
+             <div class="consent-options" id="consent-options" hidden>
+                 <label class="consent-option consent-option-locked">
+                     <input type="checkbox" checked disabled>
+                     <span><strong><?= htmlspecialchars(Language::get('consent_necessary_title', 'Necessary')) ?></strong><small><?= htmlspecialchars(Language::get('consent_necessary_desc', 'Needed for the store to work, for example your cart and these choices. Always on.')) ?></small></span>
+                 </label>
+                 <?php foreach ($consentBannerCategories as $consentCategory): ?>
+                     <label class="consent-option">
+                         <input type="checkbox" data-consent-category="<?= htmlspecialchars($consentCategory, ENT_QUOTES) ?>">
+                         <span><strong><?= htmlspecialchars(Language::get('consent_' . $consentCategory . '_title', ucfirst($consentCategory))) ?></strong><small><?= htmlspecialchars(Language::get('consent_' . $consentCategory . '_desc', '')) ?></small></span>
+                     </label>
+                 <?php endforeach; ?>
+             </div>
+         <?php endif; ?>
          <div class="consent-banner-actions">
              <button type="button" id="consent-decline"><?= htmlspecialchars(Language::get('consent_decline', 'Decline')) ?></button>
+             <?php if ($consentManageEnabled): ?>
+                 <button type="button" id="consent-manage"><?= htmlspecialchars(Language::get('consent_manage_button', 'Manage')) ?></button>
+                 <button type="button" id="consent-save" hidden><?= htmlspecialchars(Language::get('consent_save', 'Save choices')) ?></button>
+             <?php endif; ?>
              <button type="button" id="consent-accept"><?= htmlspecialchars(Language::get('consent_accept', 'Accept')) ?></button>
          </div>
      </div>
⋮ 17 unchanged lines ⋮
includes/language.php Modified +11 -0
⋮ 60 unchanged lines ⋮
          'subscription_status_incomplete' => 'waiting for payment',
          'subscription_status_incomplete_expired' => 'expired',
          'subscription_status_paused' => 'paused',
+         'consent_title' => 'Cookie settings',
+         'consent_manage_button' => 'Manage',
+         'consent_save' => 'Save choices',
+         'consent_necessary_title' => 'Necessary',
+         'consent_necessary_desc' => 'Needed for the store to work, for example your cart and these choices. Always on.',
+         'consent_analytics_title' => 'Analytics',
+         'consent_analytics_desc' => 'Helps us see which products people look at, so we can make the store better.',
+         'consent_marketing_title' => 'Marketing',
+         'consent_marketing_desc' => 'Lets advertising partners show ads that fit your interests.',
+         'consent_preferences_title' => 'Preferences',
+         'consent_preferences_desc' => 'Remembers your choices and powers extras like chat.',
      ];
  
      public static function ensureKeys(array $defaults): void
⋮ 33 unchanged lines ⋮
includes/site-front.php Modified +75 -8
⋮ 113 unchanged lines ⋮
              'reviews_enabled' => '1',
              'consent_manager_enabled' => '0',
              'consent_footer_icon_enabled' => '0',
+             'consent_manage_enabled' => '1',
+             'consent_show_analytics' => '1',
+             'consent_show_marketing' => '1',
+             'consent_show_preferences' => '0',
              'heading_font' => 'Plus Jakarta Sans',
              'body_font' => 'PT Serif',
              'interface_font' => 'Plus Jakarta Sans',
⋮ 396 unchanged lines ⋮
          return $statement->fetchAll();
      }
  
+     public static function adConsentRun(array $ad): string
+     {
+         $run = (string) ($ad['consent_run'] ?? '');
+         if ($run === 'always' || in_array($run, self::CONSENT_CATEGORIES, true)) {
+             return $run;
+         }
+ 
+         return ($ad['type'] ?? '') === 'script' ? 'marketing' : 'always';
+     }
+ 
+     public static function safeAdUrl(string $url): string
+     {
+         $url = trim($url);
+         if ($url === '') {
+             return '';
+         }
+         if (preg_match('#^https?://#i', $url) === 1) {
+             return $url;
+         }
+         if (preg_match('#^[a-z][a-z0-9+.-]*:#i', $url) === 1 || str_starts_with($url, '//')) {
+             return '';
+         }
+ 
+         return $url;
+     }
+ 
      public static function renderAd(array $ad): string
      {
+         $inner = '';
+         $slotClass = '';
+         $content = (string) $ad['content'];
+ 
          switch ($ad['type']) {
              case 'static_text':
-                 $html = '<div class="ad-slot ad-text">' . nl2br(htmlspecialchars($ad['content'])) . '</div>';
+                 $slotClass = 'ad-text';
+                 $inner = nl2br(htmlspecialchars($content));
                  break;
              case 'static_image':
-                 $img = '<img src="' . htmlspecialchars($ad['content']) . '" alt="' . htmlspecialchars($ad['name']) . '">';
-                 $html = '<div class="ad-slot ad-image">' . ($ad['link_url'] ? '<a href="' . htmlspecialchars($ad['link_url']) . '" rel="sponsored noopener" target="_blank">' . $img . '</a>' : $img) . '</div>';
+                 $imageUrl = self::safeAdUrl($content);
+                 if ($imageUrl === '') {
+                     return '';
+                 }
+                 $slotClass = 'ad-image';
+                 $linkUrl = self::safeAdUrl((string) ($ad['link_url'] ?? ''));
+                 $img = '<img src="' . htmlspecialchars($imageUrl) . '" alt="' . htmlspecialchars($ad['name']) . '">';
+                 $inner = $linkUrl !== '' ? '<a href="' . htmlspecialchars($linkUrl) . '" rel="sponsored noopener" target="_blank">' . $img . '</a>' : $img;
                  break;
              case 'script':
-                 $html = '<div class="ad-slot ad-script" data-requires-consent="0">' . $ad['content'] . '</div>';
+                 $slotClass = 'ad-script';
+                 $inner = $content;
                  break;
              default:
-                 $html = '';
+                 return '';
          }
  
-         return $html;
+         $run = self::adConsentRun($ad);
+         if ($run !== 'always' && (self::settings()['consent_manager_enabled'] ?? '0') === '1') {
+             if (stripos($inner, '</template') !== false) {
+                 return '';
+             }
+             $inner = '<template class="consent-gated" data-category="' . $run . '">' . $inner . '</template>';
+         }
+ 
+         return '<div class="ad-slot ' . $slotClass . '">' . $inner . '</div>';
      }
  
      public static function activeAnalyticsScripts(string $placement): array
⋮ 5 unchanged lines ⋮
          return $statement->fetchAll();
      }
  
+     public const CONSENT_CATEGORIES = ['analytics', 'marketing', 'preferences'];
+ 
+     public static function consentCategory(string $category): string
+     {
+         return in_array($category, self::CONSENT_CATEGORIES, true) ? $category : 'analytics';
+     }
+ 
+     public static function bannerConsentCategories(): array
+     {
+         $settings = self::settings();
+ 
+         return array_values(array_filter(
+             self::CONSENT_CATEGORIES,
+             static fn (string $category): bool => ($settings['consent_show_' . $category] ?? '0') === '1'
+         ));
+     }
+ 
      public static function renderAnalyticsScripts(string $placement): string
      {
          $scripts = self::activeAnalyticsScripts($placement);
⋮ 10 unchanged lines ⋮
              }
  
              if ($script['requires_consent'] && $consentManagerEnabled) {
-                 $safeCode = str_replace('</script>', '<\/script>', $code);
-                 $html .= '<script type="text/plain" class="consent-gated-script" data-placement="' . htmlspecialchars($placement) . '">' . $safeCode . '</script>';
+                 $category = self::consentCategory((string) ($script['consent_category'] ?? 'analytics'));
+                 $html .= '<template class="consent-gated" data-category="' . $category . '">' . $code . '</template>';
              } else {
                  $html .= $code;
              }
⋮ 280 unchanged lines ⋮
product.php Modified +24 -6
⋮ 145 unchanged lines ⋮
      } else {
          $rating = (int) ($_POST['rating'] ?? 0);
          $body = trim((string) ($_POST['body'] ?? ''));
+         $reviewerId = (int) UserAuth::user()['id'];
+         $reviewLockName = 'sb_review_' . (int) $product['id'] . '_' . $reviewerId;
+         $reviewLockStatement = $reviewsDb->prepare('SELECT GET_LOCK(:name, 5)');
+         $reviewLockStatement->execute(['name' => $reviewLockName]);
+         $reviewLocked = (int) $reviewLockStatement->fetchColumn() === 1;
+         $reviewUnlock = $reviewsDb->prepare('SELECT RELEASE_LOCK(:name)');
  
          $existingReview = $reviewsDb->prepare('SELECT id FROM product_reviews WHERE product_id = :product_id AND user_account_id = :user_id LIMIT 1');
-         $existingReview->execute(['product_id' => $product['id'], 'user_id' => UserAuth::user()['id']]);
+         $existingReview->execute(['product_id' => $product['id'], 'user_id' => $reviewerId]);
  
-         if ($existingReview->fetch()) {
+         if (!$reviewLocked) {
+             $reviewError = Language::get('form_security_failed', 'Security check failed, please try again.');
+         } elseif ($existingReview->fetch()) {
              $reviewError = Language::get('review_already_posted', 'You have already reviewed this product.');
          } elseif ($rating < 1 || $rating > 5) {
              $reviewError = Language::get('review_rating_required', 'Please select a star rating from 1 to 5.');
⋮ 5 unchanged lines ⋮
              );
              $insert->execute([
                  'product_id' => $product['id'],
-                 'user_id' => UserAuth::user()['id'],
+                 'user_id' => $reviewerId,
                  'rating' => $rating,
                  'body' => mb_substr($body, 0, 2000),
              ]);
-             $reviewSuccess = Language::get('review_posted', 'Thanks — your review has been posted.');
-             $reviews = $loadReviews();
+             $reviewUnlock->execute(['name' => $reviewLockName]);
+             $reviewUrl = SiteFront::productUrl((string) $product['slug']);
+             header('Location: ' . $reviewUrl . (str_contains($reviewUrl, '?') ? '&' : '?') . 'reviewed=1#reviews', true, 303);
+             exit;
          }
+ 
+         if ($reviewLocked) {
+             $reviewUnlock->execute(['name' => $reviewLockName]);
+         }
      }
  }
  
+ if ($reviewSuccess === null && $reviewError === null && isset($_GET['reviewed'])) {
+     $reviewSuccess = Language::get('review_posted', 'Thanks, your review is now live.');
+ }
+ 
  $averageRating = 0.0;
  if (!empty($reviews)) {
      $ratedReviews = array_filter($reviews, static fn (array $review): bool => $review['rating'] !== null);
⋮ 233 unchanged lines ⋮
  <?php endif; ?>
  
  <?php if ($reviewsEnabled && !$isPreview): ?>
-     <section class="reviews-section">
+     <section class="reviews-section" id="reviews">
          <h2><?= htmlspecialchars(Language::get('product_reviews_title', 'Reviews')) ?></h2>
  
          <?php if (empty($reviews)): ?>
⋮ 54 unchanged lines ⋮
sql/schema_site.sql Modified +2 -0
⋮ 142 unchanged lines ⋮
      placement VARCHAR(60) NOT NULL,
      content LONGTEXT NOT NULL,
      link_url VARCHAR(255) NULL,
+     consent_run VARCHAR(20) NULL,
      is_active TINYINT(1) NOT NULL DEFAULT 1,
      created_by INT UNSIGNED NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
⋮ 7 unchanged lines ⋮
      script_code LONGTEXT NOT NULL,
      placement ENUM('head','body_start','body_end') NOT NULL DEFAULT 'head',
      requires_consent TINYINT(1) NOT NULL DEFAULT 1,
+     consent_category VARCHAR(20) NOT NULL DEFAULT 'analytics',
      is_active TINYINT(1) NOT NULL DEFAULT 1,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
⋮ 57 unchanged lines ⋮
translations/language.php Modified +13 -2
⋮ 188 unchanged lines ⋮
      'consent_text' => 'We use cookies and similar technologies to improve your experience.',
      'consent_accept' => 'Accept',
      'consent_decline' => 'Decline',
-     'consent_manage' => 'Manage preferences',
+     'consent_manage' => 'Cookie settings',
+     'consent_title' => 'Cookie settings',
+     'consent_manage_button' => 'Manage',
+     'consent_save' => 'Save choices',
+     'consent_necessary_title' => 'Necessary',
+     'consent_necessary_desc' => 'Needed for the store to work, for example your cart and these choices. Always on.',
+     'consent_analytics_title' => 'Analytics',
+     'consent_analytics_desc' => 'Helps us see which products people look at, so we can make the store better.',
+     'consent_marketing_title' => 'Marketing',
+     'consent_marketing_desc' => 'Lets advertising partners show ads that fit your interests.',
+     'consent_preferences_title' => 'Preferences',
+     'consent_preferences_desc' => 'Remembers your choices and powers extras like chat.',
  
      'code_copy' => 'Copy',
      'code_copied' => 'Copied',
⋮ 16 unchanged lines ⋮
      'review_already_posted' => 'You have already reviewed this product.',
      'review_rating_required' => 'Please select a star rating from 1 to 5.',
      'review_body_required' => 'Please write a short review.',
-     'review_posted' => 'Thanks — your review has been posted.',
+     'review_posted' => 'Thanks, your review is now live.',
      'review_star_label' => '%d / 5',
  
      'cart_added' => 'Added to cart.',
⋮ 104 unchanged lines ⋮
version.txt Modified +1 -1
- 1.0.0.1
+ 1.0.0.3