Files
interblue.pl/modules/cookiesplus/controllers/admin/AdminCookiesPlusGTMController.php

409 lines
16 KiB
PHP

<?php
/**
* ISC License
*
* Copyright (c) 2024 idnovate.com
* idnovate is a Registered Trademark & Property of idnovate.com, innovación y desarrollo SCP
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* @author idnovate
* @copyright 2024 idnovate
* @license https://www.isc.org/licenses/ https://opensource.org/licenses/ISC ISC License
*/
if (!defined('_PS_VERSION_')) {
exit;
}
class AdminCookiesPlusGTMController extends ModuleAdminController
{
protected $isShopSelected = true;
public function __construct()
{
$this->bootstrap = true;
$this->tabClassName = 'AdminCookiesPlusGTM';
parent::__construct();
if (Shop::isFeatureActive() && (Shop::getContext() == Shop::CONTEXT_ALL || Shop::getContext() == Shop::CONTEXT_GROUP)) {
$this->isShopSelected = false;
}
$this->shopLinkType = 'shop';
}
public function setMedia($isNewTheme = false)
{
parent::setMedia($isNewTheme);
// CodeMirror
$this->addCSS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/lib/codemirror.css');
$this->addCSS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/theme/monokai.css');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/lib/codemirror.js');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/addon/display/autorefresh.js');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/mode/css/css.js');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/lib/CodeMirror/mode/javascript/javascript.js');
$this->addCSS(_MODULE_DIR_ . $this->module->name . '/views/css/cookiesplus-back.css');
$this->addJS(_MODULE_DIR_ . $this->module->name . '/views/js/cookiesplus-back.js');
}
public function initContent()
{
if (!$this->isShopSelected && !$this->display) {
$this->errors[] = $this->l('You have to select a shop.');
parent::initContent();
return;
}
if (version_compare($this->module->version, $this->module->getDatabaseVersion(), '>')) {
return $this->errors[] = $this->l('Upgrade available');
}
if ($this->isShopSelected
&& (
(version_compare(_PS_VERSION_, '1.5.0.13', '<')
&& !Module::isInstalled($this->module->name))
|| (version_compare(_PS_VERSION_, '1.5.0.13', '>=')
&& !Module::isEnabled($this->module->name))
)
) {
$this->warnings[] = $this->l('Module is not enabled in this shop.');
}
if ($warnings = $this->module->getWarnings(false)) {
$this->warnings[] = $warnings;
}
if (((bool) Tools::isSubmit('submitCookiesPlusModule')) == true) {
if (!Tools::getValue('C_P_GTM_ENABLE') && !Tools::getValue('gtmFireConfiguration')) {
$this->errors[] = $this->l('You have to define the needed consents to fire the Google Tag Manager script.');
}
// Check if the keys inside the "gtmFinality" subarrays are unique across all elements in your array
// Array to store unique keys
$uniqueKeys = [];
// Flag to indicate if keys are unique
$keysAreUnique = true;
foreach (Tools::getValue('gtmConfiguration') as $item) {
if (isset($item["gtmFinality"]) && is_array($item["gtmFinality"])) {
foreach ($item["gtmFinality"] as $key => $value) {
// Check if the key is already in the unique keys array
if (in_array($key, $uniqueKeys)) {
$keysAreUnique = false;
// Optionally, you can break out of the loop or handle the duplication as needed
// break;
} else {
// Add the key to the unique keys array
$uniqueKeys[] = $key;
}
}
}
}
if (!$keysAreUnique) {
$this->errors[] = $this->l('You can not enable the same consent tag in more than one finality.');
}
if (!count($this->errors)) {
$fields = $this->getConfigFormValues();
foreach (array_keys($fields) as $key) {
if ($key === 'C_P_GTM_CONSENT') {
$value = json_encode(Tools::getValue('gtmConfiguration'));
Configuration::updateValue($key, $value);
} elseif ($key === 'C_P_GTM_FIRE_CONSENT') {
$value = json_encode(Tools::getValue('gtmFireConfiguration'));
Configuration::updateValue($key, $value);
} else {
// Workaround to avoid the modification of the HTML code
Configuration::updateValue('PS_USE_HTMLPURIFIER', false);
Configuration::updateValue($key, $fields[$key], true);
Configuration::updateValue('PS_USE_HTMLPURIFIER', true);
}
}
$this->confirmations[] = $this->l('Settings saved successfully');
}
}
$this->content .= $this->renderGlobalConfigForm();
$this->content .= $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/disclaimer.tpl');
if (version_compare(_PS_VERSION_, '1.6', '>=')) {
$module = $this->module;
$default_iso_code = 'en';
$local_path = $module->getLocalPath();
$readme = null;
if (file_exists($local_path . '/readme_' . $this->context->language->iso_code . '.pdf')) {
$readme = 'readme_' . $this->context->language->iso_code . '.pdf';
} elseif (file_exists($local_path . '/readme_' . $default_iso_code . '.pdf')) {
$readme = 'readme_' . $default_iso_code . '.pdf';
}
$this->context->smarty->assign([
'support_id' => $module->addons_id_product,
'readme' => $readme,
'this_path' => $module->getPathUri(),
]);
if (file_exists($local_path . '/views/templates/admin/company/information_' . $this->context->language->iso_code . '.tpl')) {
$this->content .= $this->context->smarty->fetch($local_path . '/views/templates/admin/company/information_' . $this->context->language->iso_code . '.tpl');
} elseif (file_exists($local_path . '/views/templates/admin/company/information_' . $default_iso_code . '.tpl')) {
$this->content .= $this->context->smarty->fetch($local_path . '/views/templates/admin/company/information_' . $default_iso_code . '.tpl');
}
}
parent::initContent();
}
public function initToolbar()
{
parent::initToolbar();
unset($this->toolbar_btn['new']);
}
public function initPageHeaderToolbar()
{
parent::initPageHeaderToolbar();
if (empty($this->display)) {
/*$this->page_header_toolbar_btn['desc-module-new'] = array(
'href' => 'index.php?controller='.$this->tabClassName.'&add'.$this->table.'&token='.Tools::getAdminTokenLite($this->tabClassName),
'desc' => $this->l('New'),
'icon' => 'process-icon-new'
);*/
$this->page_header_toolbar_btn['desc-module-translate'] = [
'href' => '#',
'desc' => $this->l('Translate'),
'modal_target' => '#moduleTradLangSelect',
'icon' => 'process-icon-flag',
];
$this->page_header_toolbar_btn['desc-module-hook'] = [
'href' => 'index.php?tab=AdminModulesPositions&token=' . Tools::getAdminTokenLite('AdminModulesPositions') . '&show_modules=' . Module::getModuleIdByName($this->module->name),
'desc' => $this->l('Manage hooks'),
'icon' => 'process-icon-anchor',
];
}
if (!$this->isShopSelected) {
unset($this->page_header_toolbar_btn['desc-module-new']);
}
$this->context->smarty->clearAssign('help_link', '');
}
public function initModal()
{
parent::initModal();
$languages = Language::getLanguages(false);
$translateLinks = [];
if (version_compare(_PS_VERSION_, '1.7.2.1', '>=')) {
$module = Module::getInstanceByName($this->module->name);
$isNewTranslateSystem = $module->isUsingNewTranslationSystem();
$link = Context::getContext()->link;
foreach ($languages as $lang) {
if ($isNewTranslateSystem) {
$translateLinks[$lang['iso_code']] = $link->getAdminLink('AdminTranslationSf', true, [
'lang' => $lang['iso_code'],
'type' => 'modules',
'selected' => $module->name,
'locale' => $lang['locale'],
]);
} else {
$translateLinks[$lang['iso_code']] = $link->getAdminLink('AdminTranslations', true, [], [
'type' => 'modules',
'module' => $module->name,
'lang' => $lang['iso_code'],
]);
}
}
}
$this->context->smarty->assign([
'trad_link' => 'index.php?tab=AdminTranslations&token=' . Tools::getAdminTokenLite('AdminTranslations') . '&type=modules&module=' . $this->module->name . '&lang=',
'module_languages' => $languages,
'module_name' => $this->module->name,
'translateLinks' => $translateLinks,
]);
$modal_content = $this->context->smarty->fetch('controllers/modules/modal_translation.tpl');
$this->modals[] = [
'modal_id' => 'moduleTradLangSelect',
'modal_class' => 'modal-sm',
'modal_title' => $this->l('Translate this module'),
'modal_content' => $modal_content,
];
}
protected function renderGlobalConfigForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->module = $this->module;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->currentIndex = self::$currentIndex;
$helper->submit_action = 'submitCookiesPlusModule';
$helper->token = Tools::getAdminTokenLite($this->tabClassName);
$helper->tpl_vars = [
'fields_value' => array_merge($this->getConfigFormValues(), $this->getConfigFormTPLs()),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
];
return $helper->generateForm($this->getConfigForm());
}
protected function getConfigForm()
{
$fields_form = [];
$fieldsFormIndex = 0;
$fields_form[$fieldsFormIndex]['form'] = [
'legend' => [
'title' => $this->l('Google Tag Manager (GTM) settings'),
'icon' => 'icon-cogs',
],
'input' => [
[
'col' => 12,
'type' => 'html',
'label' => '',
'name' => $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/C_P_GTM.tpl'),
],
[
'col' => 8,
'type' => 'html',
'label' => '',
'name' => $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/C_P_GTM_SCRIPT.tpl'),
],
[
'cols' => 110,
'rows' => 4,
'type' => 'textarea',
'label' => $this->l('HEAD code'),
'name' => 'C_P_GTM_HEAD',
'class' => 't codemirror codemirror-js',
],
[
'cols' => 110,
'rows' => 4,
'type' => 'textarea',
'label' => $this->l('BODY code'),
'name' => 'C_P_GTM_BODY',
'class' => 't codemirror codemirror-js',
],
[
'col' => 8,
'type' => 'html',
'label' => '',
'name' => $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/C_P_GTM_ENABLE.tpl'),
],
[
'type' => (version_compare(_PS_VERSION_, '1.6', '>=')) ? 'switch' : 'radio',
'label' => $this->l('Enable the integration with Google Consent Mode'),
'name' => 'C_P_GTM_ENABLE',
'class' => 't',
'is_bool' => true,
'values' => [
[
'id' => 'C_P_GTM_ENABLE_on',
'value' => 1,
'label' => $this->l('Yes'), ],
[
'id' => 'C_P_GTM_ENABLE_off',
'value' => 0,
'label' => $this->l('No'), ],
],
],
[
'col' => 8,
'type' => 'html',
'label' => 'Cookie finalities needed to include the GTM script in the page',
'name' => $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/C_P_GTM_FIRE_CONSENT.tpl'),
],
[
'col' => 8,
'type' => 'html',
'label' => 'Cookie finality <> Google consent type',
'name' => $this->context->smarty->fetch($this->module->getLocalPath() . 'views/templates/admin/C_P_GTM_CONSENT.tpl'),
],
],
'submit' => [
'title' => $this->l('Save'),
'type' => 'submit',
'name' => 'submitCookiesPlusModule',
],
];
return $fields_form;
}
protected function getConfigFormValues()
{
$fields = [];
$configFields = [
'C_P_GTM_ENABLE',
'C_P_GTM_HEAD',
'C_P_GTM_BODY',
'C_P_GTM_FIRE_CONSENT',
'C_P_GTM_CONSENT',
];
foreach ($configFields as $field) {
$fields[$field] = Tools::getValue($field, Configuration::get($field));
}
return $fields;
}
protected function getConfigFormTPLs()
{
$fields = [];
$this->context->smarty->assign([
'cookiesPlusFinalities' => CookiesPlusFinality::getCookiesPlusFinalities((int) $this->context->language->id, false, false),
'gtmFinalities' => [
'ad_storage',
'ad_user_data',
'ad_personalization',
'analytics_storage',
'functionality_storage',
'personalization_storage',
'security_storage',
],
'fieldNameGtm' => 'gtmConfiguration',
'valuesGtm' => json_decode(Configuration::get('C_P_GTM_CONSENT'), true),
'fieldNameGtmFire' => 'gtmFireConfiguration',
'valuesGtmFire' => json_decode(Configuration::get('C_P_GTM_FIRE_CONSENT'), true),
]);
return $fields;
}
}