From dce849610c10f1c0ff43bb95a18fa4e36cda6fa0 Mon Sep 17 00:00:00 2001 From: Alexandre Gain <270117159+alexandregain-xprl@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:47:36 +0100 Subject: [PATCH] Merge the Smartlinks plugin (SmartlinksBundle 0.6.0) into the bundle as the Smart Links domain (0.18.0) Two domains, one MT3S bundle: Marketing Programs (unchanged) and the imported Smart Links (smart links + UTM taxonomies), each keeping its own menu, tables, routes and translations. - Code moved from MauticPlugin\SmartlinksBundle\ to MauticPlugin\MT3SMarketingProgramBundle\; template namespace @Smartlinks/ -> @MT3SMarketingProgram/; smartlinks.js -> Assets/js/mt3s-mp-smartlinks.js; icon -> Assets/img/smartlinks-icon.svg. - Incoming migrations renamed Version_0_X_0_SmartLinks.php to avoid the class-name collision; schema untouched, data intact. - Permissions folded into MT3SMarketingProgramPermissions: smart_links + taxonomies under the mt3smarketingprogram: base (roles that had the old smartlinks: grants must be re-granted). - config.php: Smart Links routes + menu group, public /l/{slug}, SmartlinksIntegration services, smartlinks_* parameters (legacy utm_manager_* keys still readable), version 0.18.0. The 0.17.0 placeholder /s/marketing-program-utm-taxonomies is replaced by the real /s/utm-taxonomies. - Translations merged (en_US) and added (fr_FR); Tests/ + phpunit moved in; readme documents both domains and the 0.18.0 merge history. Verified live: menus, both config tabs, both lists + forms, program pages, public redirect with taxonomy UTM values, host + unknown-slug 404s, 90/90 unit tests, full php -l, all ini catalogs parse. --- .gitignore | 4 +- Assets/img/smartlinks-icon.svg | 1 + Assets/js/mt3s-mp-smartlinks.js | 240 +++++++ Catalog/SmartLinkRedirectCode.php | 35 + Catalog/SmartLinkRedirectEnumHelper.php | 32 + Catalog/SmartLinkRedirectType.php | 34 + Catalog/UtmParameterCatalog.php | 109 ++++ Catalog/UtmParameterDefinition.php | 59 ++ Catalog/UtmParameterMode.php | 26 + Config/config.php | 91 ++- Config/services.php | 7 + Controller/PublicController.php | 72 +++ Controller/SmartLinkController.php | 165 +++++ Controller/UtmTaxonomyController.php | 123 +++- Entity/SmartLink.php | 304 +++++++++ Entity/SmartLinkHit.php | 118 ++++ Entity/SmartLinkHitRepository.php | 57 ++ Entity/SmartLinkRepository.php | 104 +++ Entity/UtmTaxonomy.php | 143 +++++ Entity/UtmTaxonomyRepository.php | 63 ++ EventListener/SmartLinksConfigSubscriber.php | 36 ++ .../UtmSettingsTransformer.php | 146 +++++ Form/Extension/UtmTagsTypeExtension.php | 39 ++ Form/Type/SmartLinkType.php | 606 ++++++++++++++++++ Form/Type/SmartLinksConfigType.php | 50 ++ Form/Type/SmartlinksSettingsType.php | 90 +++ Form/Type/UtmParameterType.php | 219 +++++++ Form/Type/UtmTaxonomyType.php | 368 +++++++++++ Form/Type/UtmValueType.php | 66 ++ Form/UtmFieldsApplicator.php | 253 ++++++++ Form/Validator/SmartLinkValidator.php | 177 +++++ Form/Validator/UtmSettingsValidator.php | 100 +++ Form/Validator/UtmTaxonomyValidator.php | 73 +++ Integration/SmartlinksIntegration.php | 32 + Integration/Support/ConfigSupport.php | 14 + MERGE-TO-MT3S-MARKETING.md | 200 ++++++ Migrations/Version_0_2_0_SmartLinks.php | 54 ++ Migrations/Version_0_3_0_SmartLinks.php | 72 +++ Migrations/Version_0_4_0_SmartLinks.php | 97 +++ Migrations/Version_0_5_0_SmartLinks.php | 208 ++++++ Migrations/Version_0_6_0_SmartLinks.php | 100 +++ Model/SmartLinkModel.php | 347 ++++++++++ Model/UtmTaxonomyModel.php | 149 +++++ .../_config_smartlinksconfig_widget.html.twig | 169 +++++ Resources/views/SmartLink/form.html.twig | 71 ++ Resources/views/SmartLink/list.html.twig | 149 +++++ Resources/views/UtmTaxonomy/form.html.twig | 43 ++ Resources/views/UtmTaxonomy/list.html.twig | 128 +++- .../MT3SMarketingProgramPermissions.php | 4 + Service/SmartLinkShortUrlBuilder.php | 70 ++ Service/UtmConfigurationNormalizer.php | 136 ++++ Service/UtmConfigurationProvider.php | 128 ++++ .../Unit/Catalog/UtmParameterCatalogTest.php | 147 +++++ Tests/Unit/Entity/SmartLinkHitTest.php | 29 + Tests/Unit/Entity/SmartLinkTest.php | 82 +++ .../Unit/Form/SmartlinksSettingsTypeTest.php | 275 ++++++++ Tests/Unit/Form/UtmFieldsApplicatorTest.php | 267 ++++++++ Tests/Unit/Form/UtmSettingsValidatorTest.php | 82 +++ .../Form/Validator/SmartLinkValidatorTest.php | 155 +++++ Tests/Unit/Model/SmartLinkModelTest.php | 250 ++++++++ Tests/Unit/Model/UtmTaxonomyModelTest.php | 67 ++ .../Service/UtmConfigurationProviderTest.php | 193 ++++++ Tests/bootstrap.php | 19 + Translations/en_US/messages.ini | 197 ++++++ Translations/en_US/validators.ini | 38 ++ Translations/fr_FR/messages.ini | 210 ++++++ Translations/fr_FR/validators.ini | 40 ++ phpunit.xml.dist | 13 + readme.md | 23 +- 69 files changed, 8225 insertions(+), 43 deletions(-) create mode 100644 Assets/img/smartlinks-icon.svg create mode 100644 Assets/js/mt3s-mp-smartlinks.js create mode 100644 Catalog/SmartLinkRedirectCode.php create mode 100644 Catalog/SmartLinkRedirectEnumHelper.php create mode 100644 Catalog/SmartLinkRedirectType.php create mode 100644 Catalog/UtmParameterCatalog.php create mode 100644 Catalog/UtmParameterDefinition.php create mode 100644 Catalog/UtmParameterMode.php create mode 100644 Controller/PublicController.php create mode 100644 Controller/SmartLinkController.php create mode 100644 Entity/SmartLink.php create mode 100644 Entity/SmartLinkHit.php create mode 100644 Entity/SmartLinkHitRepository.php create mode 100644 Entity/SmartLinkRepository.php create mode 100644 Entity/UtmTaxonomy.php create mode 100644 Entity/UtmTaxonomyRepository.php create mode 100644 EventListener/SmartLinksConfigSubscriber.php create mode 100644 Form/DataTransformer/UtmSettingsTransformer.php create mode 100644 Form/Extension/UtmTagsTypeExtension.php create mode 100644 Form/Type/SmartLinkType.php create mode 100644 Form/Type/SmartLinksConfigType.php create mode 100644 Form/Type/SmartlinksSettingsType.php create mode 100644 Form/Type/UtmParameterType.php create mode 100644 Form/Type/UtmTaxonomyType.php create mode 100644 Form/Type/UtmValueType.php create mode 100644 Form/UtmFieldsApplicator.php create mode 100644 Form/Validator/SmartLinkValidator.php create mode 100644 Form/Validator/UtmSettingsValidator.php create mode 100644 Form/Validator/UtmTaxonomyValidator.php create mode 100644 Integration/SmartlinksIntegration.php create mode 100644 Integration/Support/ConfigSupport.php create mode 100644 MERGE-TO-MT3S-MARKETING.md create mode 100644 Migrations/Version_0_2_0_SmartLinks.php create mode 100644 Migrations/Version_0_3_0_SmartLinks.php create mode 100644 Migrations/Version_0_4_0_SmartLinks.php create mode 100644 Migrations/Version_0_5_0_SmartLinks.php create mode 100644 Migrations/Version_0_6_0_SmartLinks.php create mode 100644 Model/SmartLinkModel.php create mode 100644 Model/UtmTaxonomyModel.php create mode 100644 Resources/views/FormTheme/Config/_config_smartlinksconfig_widget.html.twig create mode 100644 Resources/views/SmartLink/form.html.twig create mode 100644 Resources/views/SmartLink/list.html.twig create mode 100644 Resources/views/UtmTaxonomy/form.html.twig create mode 100644 Service/SmartLinkShortUrlBuilder.php create mode 100644 Service/UtmConfigurationNormalizer.php create mode 100644 Service/UtmConfigurationProvider.php create mode 100644 Tests/Unit/Catalog/UtmParameterCatalogTest.php create mode 100644 Tests/Unit/Entity/SmartLinkHitTest.php create mode 100644 Tests/Unit/Entity/SmartLinkTest.php create mode 100644 Tests/Unit/Form/SmartlinksSettingsTypeTest.php create mode 100644 Tests/Unit/Form/UtmFieldsApplicatorTest.php create mode 100644 Tests/Unit/Form/UtmSettingsValidatorTest.php create mode 100644 Tests/Unit/Form/Validator/SmartLinkValidatorTest.php create mode 100644 Tests/Unit/Model/SmartLinkModelTest.php create mode 100644 Tests/Unit/Model/UtmTaxonomyModelTest.php create mode 100644 Tests/Unit/Service/UtmConfigurationProviderTest.php create mode 100644 Tests/bootstrap.php create mode 100644 Translations/fr_FR/messages.ini create mode 100644 Translations/fr_FR/validators.ini create mode 100644 phpunit.xml.dist diff --git a/.gitignore b/.gitignore index 1f5bb70..eaf3190 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ .idea/ *.log .vscode/ -.claude/ \ No newline at end of file +.claude/ +.phpunit.result.cache +.phpunit.result/ diff --git a/Assets/img/smartlinks-icon.svg b/Assets/img/smartlinks-icon.svg new file mode 100644 index 0000000..7cc9d34 --- /dev/null +++ b/Assets/img/smartlinks-icon.svg @@ -0,0 +1 @@ +UTM diff --git a/Assets/js/mt3s-mp-smartlinks.js b/Assets/js/mt3s-mp-smartlinks.js new file mode 100644 index 0000000..4db09ec --- /dev/null +++ b/Assets/js/mt3s-mp-smartlinks.js @@ -0,0 +1,240 @@ +/** + * UTM Manager + * + * - Settings > Configuration > UTM Manager tab: delegated handlers only (the configuration + * page is loaded through Ajax). Showing / hiding the value editor by mode is done by + * Mautic's own data-show-on switcher. + * - Smart Link form: short link preview, "Generate" a random slug, destination URL shown + * only for external redirects. Started by Mautic.smartlinksSmartLinkOnLoad(), which Mautic + * calls after it loads any page whose mauticContent is "smartlinksSmartLink". + */ +(function ($) { + 'use strict'; + + if (typeof $ === 'undefined') { + return; + } + + var NS = '.smartlinks'; + + /** + * Rows are renumbered 0..n-1 in DOM order after every change, so the submitted order is the + * displayed order (Symfony collections keep the order of their keys). + */ + var reindexValues = function ($list) { + $list.children('.utm-value-row').each(function (index) { + $(this).find('input, select, textarea').each(function () { + var $input = $(this); + var name = $input.attr('name'); + var id = $input.attr('id'); + if (name) { + $input.attr('name', name.replace(/^(.*\[values\]\[)[^\]]+(\].*)$/, '$1' + index + '$2')); + } + if (id) { + $input.attr('id', id.replace(/^(.*_values_)[^_]+(_.*)$/, '$1' + index + '$2')); + } + }); + }); + refreshEditor($list.closest('.utm-values-editor')); + }; + + var refreshEditor = function ($editor) { + var count = $editor.find('.utm-value-row').length; + $editor.find('.utm-values-empty').toggleClass('hide', count > 0); + $editor.find('[data-utm-load-suggestions]').toggleClass('hide', count > 0); + }; + + var getList = function ($editor) { + return $editor.find('.utm-values-list').first(); + }; + + var existingValues = function ($editor) { + var values = {}; + $editor.find('.utm-value-input').each(function () { + values[$.trim($(this).val())] = true; + }); + + return values; + }; + + var addValueRow = function ($editor, value, label) { + var $list = getList($editor); + var index = $list.children('.utm-value-row').length; + var $row = $($list.attr('data-prototype').replace(/__value__/g, index)); + + $list.append($row); + if (typeof value !== 'undefined') { + $row.find('.utm-value-input').val(value); + $row.find('.utm-label-input').val(label || value); + } + reindexValues($list); + + return $row; + }; + + /** + * Appends rows for the given {value, label} items, skipping values already in the list. + */ + var appendValues = function ($editor, items) { + var existing = existingValues($editor); + $.each(items, function (i, item) { + if (item.value === '' || existing[item.value]) { + return; + } + existing[item.value] = true; + addValueRow($editor, item.value, item.label); + }); + }; + + var refreshFieldStates = function ($element) { + // Re-runs Mautic's data-show-on switcher (bound to the form's change event). + $element.closest('form').trigger('change'); + }; + + $(document) + .on('click' + NS, '.smartlinks-utm-config [data-utm-add-value]', function () { + var $row = addValueRow($(this).closest('.utm-values-editor')); + $row.find('.utm-value-input').trigger('focus'); + }) + .on('click' + NS, '.smartlinks-utm-config [data-utm-remove-value]', function () { + var $list = $(this).closest('.utm-values-list'); + $(this).closest('.utm-value-row').remove(); + reindexValues($list); + }) + .on('change' + NS, '.smartlinks-utm-config .utm-value-default', function () { + // Only one default value per parameter. + if ($(this).is(':checked')) { + $(this).closest('.utm-values-list').find('.utm-value-default').not(this).prop('checked', false); + } + }) + .on('mouseenter' + NS, '.smartlinks-utm-config .utm-values-list', function () { + var $list = $(this); + if ($list.data('utmSortable') || typeof $list.sortable !== 'function') { + return; + } + $list.data('utmSortable', true).sortable({ + items: '> .utm-value-row', + handle: '.utm-value-handle', + axis: 'y', + stop: function () { + reindexValues($list); + } + }); + }) + .on('click' + NS, '.smartlinks-utm-config [data-utm-import]', function () { + var $editor = $(this).closest('.utm-values-editor'); + var $text = $editor.find('.utm-import-text'); + var items = []; + + $.each(($text.val() || '').split(/\r?\n/), function (i, line) { + var parts = line.split(';'); + var value = $.trim(parts.shift()); + if (value !== '') { + items.push({value: value, label: $.trim(parts.join(';')) || value}); + } + }); + + appendValues($editor, items); + $text.val(''); + }) + .on('click' + NS, '.smartlinks-utm-config [data-utm-load-suggestions]', function () { + appendValues($(this).closest('.utm-values-editor'), JSON.parse($(this).attr('data-utm-suggestions') || '[]')); + }) + .on('click' + NS, '.smartlinks-utm-config [data-utm-add-parameter]', function () { + var $config = $(this).closest('.smartlinks-utm-config'); + var $container = $config.find('.utm-custom-parameters'); + var index = parseInt($container.attr('data-index'), 10) || 0; + var $panel = $($container.attr('data-prototype').replace(/__param__/g, index)); + + $container.attr('data-index', index + 1).append($panel); + $config.find('.utm-custom-empty').addClass('hide'); + refreshFieldStates($container); + $panel.find('.utm-custom-key').trigger('focus'); + }) + .on('click' + NS, '.smartlinks-utm-config [data-utm-remove-parameter]', function () { + var $config = $(this).closest('.smartlinks-utm-config'); + $(this).closest('[data-utm-parameter]').remove(); + $config.find('.utm-custom-empty').toggleClass('hide', $config.find('.utm-custom-parameters [data-utm-parameter]').length > 0); + }) + .on('input' + NS, '.smartlinks-utm-config .utm-custom-key', function () { + var key = $.trim($(this).val()); + var $code = $(this).closest('[data-utm-parameter]').find('.utm-parameter-key').first(); + $code.text(key !== '' ? key : $code.text()); + }); + + // --------------------------------------------------------------------------- + // Smart Link form (menu: Smart Links) + // --------------------------------------------------------------------------- + + /** + * The short link the user is building: https://{short link domain}/l/{slug}. Spaces are + * replaced by the configured character, uppercase turned to lowercase, exactly like the + * server does on save (SmartLinkModel::applySlugRules). + */ + Mautic.smartLinkPreview = function ($wrapper) { + var $slugInput = $wrapper.find('.smart-link-slug'); + var domain = $.trim($('#smartLinkDomainReminder').attr('data-domain') || ''); + var slug = $.trim($slugInput.val() || ''); + var replacement = $.trim($('#smartLinkDomainReminder').attr('data-separator') || '-'); + + slug = slug.replace(/\s+/g, replacement); + if (parseInt($('#smartLinkDomainReminder').attr('data-lowercase') || '1', 10)) { + slug = slug.toLowerCase(); + } + + $('#smartLinkPreview').text(domain !== '' && slug !== '' ? domain + '/l/' + slug : ''); + }; + + /** + * The destination depends on the redirect type: the URL for external redirects, the + * landing page or the standalone form for Mautic ones. + */ + Mautic.smartLinkToggleDestination = function ($wrapper) { + var type = $wrapper.find('.smart-link-redirect-type').val(); + $('#smartLinkDestinationUrlWrapper').toggleClass('hide', type === 'mautic'); + $('#smartLinkMauticDestinationWrapper').toggleClass('hide', type !== 'mautic'); + }; + + Mautic.smartlinksSmartLinkOnLoad = function (container) { + var $wrapper = $(container).find('.smart-link-slug-group').first(); + + if ($wrapper.length) { + Mautic.smartLinkPreview($wrapper); + // The redirect type lives outside the slug group: scope the toggle to the form. + Mautic.smartLinkToggleDestination($wrapper.closest('form')); + } + }; + + $(document) + .on('input', '.smart-link-slug', function () { + Mautic.smartLinkPreview($(this).closest('.smart-link-slug-group')); + }) + .on('change', '.smart-link-redirect-type', function () { + Mautic.smartLinkToggleDestination($(this).closest('form')); + }) + .on('click', '#smartLinkGenerateSlug', function () { + var $button = $(this); + var generated = $.trim($button.attr('data-generated') || ''); + var $slugInput = $button.closest('.smart-link-slug-group').find('.smart-link-slug'); + + if (generated !== '') { + $slugInput.val(generated).trigger('input'); + // The next click proposes a different slug; the page isn't reloaded between clicks. + $button.attr('data-generated', Mautic.smartLinkRandomSlug()); + } + }); + + /** + * Random slug of 4 letters and digits for the "Generate" button (client-side fallback; the + * server proposes one on each page load and the validator checks uniqueness on submit). + */ + Mautic.smartLinkRandomSlug = function () { + var alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'; + var slug = ''; + for (var i = 0; i < 4; i++) { + slug += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); + } + + return slug; + }; +})(window.mQuery); diff --git a/Catalog/SmartLinkRedirectCode.php b/Catalog/SmartLinkRedirectCode.php new file mode 100644 index 0000000..684a0d1 --- /dev/null +++ b/Catalog/SmartLinkRedirectCode.php @@ -0,0 +1,35 @@ +value; + } + + public function isPermanent(): bool + { + return in_array($this->value, [self::MOVED_PERMANENTLY, self::PERMANENT_REDIRECT], true); + } +} diff --git a/Catalog/SmartLinkRedirectEnumHelper.php b/Catalog/SmartLinkRedirectEnumHelper.php new file mode 100644 index 0000000..d747030 --- /dev/null +++ b/Catalog/SmartLinkRedirectEnumHelper.php @@ -0,0 +1,32 @@ +.") + * gives "301 - Moved permanently (permanent)" style labels shared by the form and the list view. + */ +trait SmartLinkRedirectEnumHelper +{ + /** + * @return array value (as string) => label + */ + public static function getChoices(TranslatorInterface $translator): array + { + $choices = []; + foreach (self::cases() as $case) { + $choices[$translator->trans($case->getLabelKey())] = $case->value; + } + + return $choices; + } + + public function getTranslatedLabel(TranslatorInterface $translator): string + { + return $translator->trans($this->getLabelKey()); + } +} diff --git a/Catalog/SmartLinkRedirectType.php b/Catalog/SmartLinkRedirectType.php new file mode 100644 index 0000000..376f5d7 --- /dev/null +++ b/Catalog/SmartLinkRedirectType.php @@ -0,0 +1,34 @@ +isMautic() ? self::MAUTIC : self::EXTERNAL); + } + + public function isMautic(): bool + { + return self::MAUTIC === $this->value; + } + + public function isExternal(): bool + { + return self::EXTERNAL === $this->value; + } +} diff --git a/Catalog/UtmParameterCatalog.php b/Catalog/UtmParameterCatalog.php new file mode 100644 index 0000000..6deddff --- /dev/null +++ b/Catalog/UtmParameterCatalog.php @@ -0,0 +1,109 @@ + [default mode, suggested values]. + */ + private const STANDARD = [ + 'utm_source' => [UtmParameterMode::DROPDOWN, ['newsletter', 'linkedin', 'facebook', 'instagram', 'google', 'youtube', 'x', 'tiktok', 'partner', 'direct']], + 'utm_medium' => [UtmParameterMode::DROPDOWN, ['email', 'cpc', 'social', 'social_paid', 'display', 'affiliate', 'referral', 'qr', 'sms', 'print', 'event']], + 'utm_campaign' => [UtmParameterMode::FREE, []], + 'utm_term' => [UtmParameterMode::FREE, []], + 'utm_content' => [UtmParameterMode::FREE, []], + 'utm_id' => [UtmParameterMode::FREE, []], + 'utm_source_platform' => [UtmParameterMode::DROPDOWN, ['google_ads', 'meta_ads', 'linkedin_ads', 'microsoft_ads', 'tiktok_ads']], + 'utm_creative_format' => [UtmParameterMode::DROPDOWN, ['banner', 'video', 'carousel', 'text', 'native']], + 'utm_marketing_tactic' => [UtmParameterMode::DROPDOWN, ['prospecting', 'remarketing', 'retargeting', 'brand', 'nurturing']], + ]; + + /** + * Click IDs appended automatically by ad platforms. Disabled by default. + */ + private const PLATFORM = ['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid', 'epik']; + + /** + * @var array + */ + private array $definitions = []; + + public function __construct() + { + foreach (self::STANDARD as $key => [$mode, $suggestions]) { + $this->definitions[$key] = new UtmParameterDefinition($key, self::GROUP_STANDARD, $mode, false, $suggestions); + } + + foreach (self::PLATFORM as $key) { + $this->definitions[$key] = new UtmParameterDefinition($key, self::GROUP_PLATFORM, UtmParameterMode::DISABLED, true); + } + } + + /** + * @return array In display order + */ + public function all(): array + { + return $this->definitions; + } + + /** + * @return array + */ + public function getByGroup(string $group): array + { + return array_filter($this->definitions, fn (UtmParameterDefinition $definition): bool => $definition->group === $group); + } + + public function has(string $key): bool + { + return isset($this->definitions[$key]); + } + + public function get(string $key): ?UtmParameterDefinition + { + return $this->definitions[$key] ?? null; + } + + /** + * Keys that a custom parameter can't use: catalog keys, Mautic query keys and reserved prefixes. + */ + public function isReservedKey(string $key): bool + { + if ($this->has($key) || in_array($key, self::RESERVED_KEYS, true)) { + return true; + } + + foreach (self::RESERVED_PREFIXES as $prefix) { + if (str_starts_with($key, $prefix)) { + return true; + } + } + + return false; + } + + public function isValidCustomKey(string $key): bool + { + return 1 === preg_match(self::CUSTOM_KEY_PATTERN, $key) && !$this->isReservedKey($key); + } +} diff --git a/Catalog/UtmParameterDefinition.php b/Catalog/UtmParameterDefinition.php new file mode 100644 index 0000000..acce473 --- /dev/null +++ b/Catalog/UtmParameterDefinition.php @@ -0,0 +1,59 @@ +key.'.label'; + } + + public function getDescriptionKey(): string + { + return self::TRANSLATION_PREFIX.$this->key.'.description'; + } + + /** + * Auto-generated click IDs can't be restricted to a list of values. + * + * @return string[] + */ + public function getAllowedModes(): array + { + if ($this->autoGenerated) { + return [UtmParameterMode::FREE, UtmParameterMode::DISABLED]; + } + + return UtmParameterMode::ALL; + } + + public function isModeAllowed(string $mode): bool + { + return in_array($mode, $this->getAllowedModes(), true); + } + + public static function getSuggestionLabelKey(string $value): string + { + return 'mautic.smartlinks.config.suggestion.'.$value; + } +} diff --git a/Catalog/UtmParameterMode.php b/Catalog/UtmParameterMode.php new file mode 100644 index 0000000..5ff467b --- /dev/null +++ b/Catalog/UtmParameterMode.php @@ -0,0 +1,26 @@ + 'MT3S Marketing Program', - 'description' => 'Marketing Program for Mautic.', - 'version' => '0.17.0', + 'description' => 'MT3S Marketing: programs, tasks, audiences, and smart links with their UTM taxonomies.', + 'version' => '0.18.0', 'author' => 'Experiential', 'routes' => [ @@ -46,12 +46,24 @@ return [ 'path' => '/marketing-program-audiences/{objectAction}/{objectId}', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\AudienceController::executeAction', ], - // UTM Taxonomies: a placeholder page for the coming feature, kept out of the menu - // (the route stays; the page is reachable at /s/marketing-program-utm-taxonomies). - 'mt3s_marketing_program_utm_taxonomy_index' => [ - 'path' => '/marketing-program-utm-taxonomies/{page}', + // Smart Links domain: the list and its object actions. + 'mautic_smartlinks_index' => [ + 'path' => '/smart-links/{page}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\SmartLinkController::indexAction', + ], + 'mautic_smartlinks_action' => [ + 'path' => '/smart-links/{objectAction}/{objectId}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\SmartLinkController::executeAction', + ], + // UTM Taxonomies: the list and its object actions. + 'mautic_smartlinks_taxonomies' => [ + 'path' => '/utm-taxonomies/{page}', 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\UtmTaxonomyController::indexAction', ], + 'mautic_smartlinks_taxonomy_action' => [ + 'path' => '/utm-taxonomies/{objectAction}/{objectId}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\UtmTaxonomyController::executeAction', + ], // The type lists of the plugin's items (Insights, allocations, objectives, tasks, // stakeholders, audience values), moved out of Settings > Configuration. 'mt3s_marketing_program_item_types_index' => [ @@ -59,6 +71,14 @@ return [ 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\ItemTypesController::indexAction', ], ], + // https://{short_link_domain}/l/{slug}: the public entry point of the Smart Links. + // Public routes are served without the /s/ prefix and without authentication. + 'public' => [ + 'mautic_smartlinks_go' => [ + 'path' => '/l/{slug}', + 'controller' => 'MauticPlugin\MT3SMarketingProgramBundle\Controller\PublicController::goAction', + ], + ], ], // Top-level "Programs" menu. Future program objects go in its children, after Programs. @@ -102,6 +122,37 @@ return [ ], ], ], + + // Top-level "Smart Links" menu: UTM Taxonomies above the Smart Links list. The two + // domains (Marketing Program and Smart Links) stay separate menu groups. + 'mautic.smartlinks.menu.root' => [ + 'id' => 'mautic_smartlinks', + 'route' => 'mautic_smartlinks_index', + 'iconClass' => 'ri-links-line', + 'access' => [ + 'mt3smarketingprogram:smart_links:viewown', + 'mt3smarketingprogram:smart_links:viewother', + 'mt3smarketingprogram:taxonomies:viewown', + 'mt3smarketingprogram:taxonomies:viewother', + ], + 'priority' => 4, + 'children' => [ + 'mautic.smartlinks.menu.taxonomies' => [ + 'id' => 'mautic_smartlinks_taxonomies', + 'route' => 'mautic_smartlinks_taxonomies', + 'iconClass' => 'ri-price-tag-3-line', + 'access' => ['mt3smarketingprogram:taxonomies:viewown', 'mt3smarketingprogram:taxonomies:viewother'], + 'priority' => 5, + ], + 'mautic.smartlinks.menu.smartlinks' => [ + 'id' => 'mautic_smartlinks_index', + 'route' => 'mautic_smartlinks_index', + 'iconClass' => 'ri-link', + 'access' => ['mt3smarketingprogram:smart_links:viewown', 'mt3smarketingprogram:smart_links:viewother'], + 'priority' => 4, + ], + ], + ], ], ], @@ -120,6 +171,19 @@ return [ 'mautic.config_integration', ], ], + 'mt3s.smart_links.integration' => [ + 'class' => MauticPlugin\MT3SMarketingProgramBundle\Integration\SmartlinksIntegration::class, + 'tags' => [ + 'mautic.integration', + 'mautic.basic_integration', + ], + ], + 'mt3s.smart_links.integration.configuration' => [ + 'class' => MauticPlugin\MT3SMarketingProgramBundle\Integration\Support\ConfigSupport::class, + 'tags' => [ + 'mautic.config_integration', + ], + ], ], ], @@ -169,5 +233,20 @@ return [ // ItemTypeProvider (kinds "audience_decision_role" and "audience_tone"). 'mt3s_marketing_program_audience_decision_roles' => [], 'mt3s_marketing_program_audience_tones' => [], + + // Stored by Settings > Configuration > Smart Links Settings (SmartLinksConfigSubscriber). + // Read through UtmConfigurationProvider; the default stays empty, the catalog + // defaults are applied by UtmConfigurationNormalizer. + 'smartlinks_utm_config' => [], + 'smartlinks_config' => [ + 'short_link_domain' => '', + ], + // Legacy keys of the standalone Smartlinks plugin era (< 0.18.0). Declared so the + // read fallbacks can serve upgrades from local.php until the settings are saved + // again; new values are always written to the new keys. + 'utm_manager_config' => [], + 'utm_manager_smart_links' => [ + 'short_link_domain' => '', + ], ], ]; diff --git a/Config/services.php b/Config/services.php index aeb5792..86acc71 100644 --- a/Config/services.php +++ b/Config/services.php @@ -13,6 +13,8 @@ return function (ContainerConfigurator $configurator): void { ->public(); $excludes = [ + 'Catalog/UtmParameterDefinition.php', + 'Catalog/UtmParameterMode.php', 'Tests', ]; @@ -34,5 +36,10 @@ return function (ContainerConfigurator $configurator): void { $services->alias('mautic.mt3smp.model.stakeholder', MauticPlugin\MT3SMarketingProgramBundle\Model\StakeholderModel::class); // getModel('mt3smp.audience'). $services->alias('mt3s.marketing_program.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class); + // Smart Links domain: getModel('smartlinks.smart_link') / getModel('smartlinks.utm_taxonomy'). + $services->alias('mt3s.smart_links.model.smart_link', MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel::class); + $services->alias('mautic.smartlinks.model.smart_link', MauticPlugin\MT3SMarketingProgramBundle\Model\SmartLinkModel::class); + $services->alias('mt3s.smart_links.model.utm_taxonomy', MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel::class); + $services->alias('mautic.smartlinks.model.utm_taxonomy', MauticPlugin\MT3SMarketingProgramBundle\Model\UtmTaxonomyModel::class); $services->alias('mautic.mt3smp.model.audience', MauticPlugin\MT3SMarketingProgramBundle\Model\AudienceModel::class); }; diff --git a/Controller/PublicController.php b/Controller/PublicController.php new file mode 100644 index 0000000..b561812 --- /dev/null +++ b/Controller/PublicController.php @@ -0,0 +1,72 @@ + Configuration > Smart Links Settings): the call is redirected to + * the link's destination — its external URL, or its landing page / standalone form for + * Mautic redirects — with its UTM parameters, and one hit is recorded for the statistics. + * On any other host, unknown slug, unpublished link or link without destination the + * short link doesn't exist: 404. + */ +class PublicController extends CommonController +{ + private SmartLinkModel $smartLinkModel; + + #[Required] + public function autowirePublicController(SmartLinkModel $smartLinkModel): void + { + $this->smartLinkModel = $smartLinkModel; + } + + public function goAction(Request $request, string $slug): Response + { + // The "if and only if" rule: only the short link domain is an entry point for /l/. + $domain = $this->smartLinkModel->getShortLinkDomain(); + if ('' === $domain || 0 !== strcasecmp(trim($request->getHost()), $domain)) { + return $this->notFound(); + } + + $slug = trim($slug); + if ('' === $slug) { + return $this->notFound(); + } + + $link = $this->smartLinkModel->getRepository()->findOneBy(['slug' => $slug]); + + if (null === $link || !$link->isPublished()) { + return $this->notFound(); + } + + // A link without destination goes nowhere, whatever its type. + if ($link->getRedirectType()->isMautic()) { + if (null === $link->getPage() && null === $link->getForm()) { + return $this->notFound(); + } + } elseif ('' === trim((string) $link->getDestinationUrl())) { + return $this->notFound(); + } + + try { + $this->smartLinkModel->recordHit($link, $request); + } catch (\Throwable $e) { + // Statistics must never block the redirect. + error_log('Smart Link hit could not be recorded for slug "'.$slug.'": '.$e->getMessage().' in '.$e->getFile().':'.$e->getLine()); + } + + return new RedirectResponse($this->smartLinkModel->buildRedirectUrl($link), $link->getRedirectCode()->value); + } +} diff --git a/Controller/SmartLinkController.php b/Controller/SmartLinkController.php new file mode 100644 index 0000000..950c41f --- /dev/null +++ b/Controller/SmartLinkController.php @@ -0,0 +1,165 @@ + Smart Links), using core's standard CRUD flow. + * + * Model smartlinks.smart_link (mautic.smartlinks.model.smart_link), permission base + * smartlinks:smart_links, translation base mautic.smartlinks.smart_links. + * + * The slug of a saved link is immutable: the form disables the field, the model refuses another + * slug, and this controller drops the submitted value (nothing to re-check). There is no clone: + * a new link gets a new slug (the "Generate" button offers one). + */ +class SmartLinkController extends AbstractStandardFormController +{ + public const ROUTE_INDEX = 'mautic_smartlinks_index'; + public const ROUTE_ACTION = 'mautic_smartlinks_action'; + + protected function getModelName(): string + { + return 'smartlinks.smart_link'; + } + + protected function getTemplateBase(): string + { + return '@MT3SMarketingProgram/SmartLink'; + } + + protected function getIndexRoute(): string + { + return self::ROUTE_INDEX; + } + + protected function getActionRoute(): string + { + return self::ROUTE_ACTION; + } + + /** + * Core builds mautic_smartlinkssmartlink from the model name; the JS loader relies on this prefix. + */ + protected function getJsLoadMethodPrefix(): string + { + return 'smartlinksSmartLink'; + } + + /** + * Core builds mautic. (singular smart_link); every key of the feature lives + * under mautic.smartlinks.smart_links. + */ + protected function getTranslationBase(): string + { + return 'mautic.smartlinks.smart_links'; + } + + /** + * @param int $page + */ + public function indexAction(Request $request, $page = 1): Response + { + return $this->indexStandard($request, $page); + } + + public function newAction(Request $request): Response + { + return $this->newStandard($request); + } + + /** + * @param int $objectId + * @param bool $ignorePost + */ + public function editAction(Request $request, $objectId, $ignorePost = false): Response + { + return $this->editStandard($request, $objectId, $ignorePost); + } + + /** + * @param int $objectId + */ + public function deleteAction(Request $request, $objectId): Response + { + return $this->deleteStandard($request, $objectId); + } + + public function batchDeleteAction(Request $request): Response + { + return $this->batchDeleteStandard($request); + } + + /** + * Never save the slug of an existing link: it is immutable once created. The field is + * disabled in the form, so nothing is submitted for it, this is a safety net. + */ + protected function beforeEntitySave($entity, Form $form, $action, $objectId = null, $isClone = false): bool + { + if ($entity instanceof SmartLink && null !== $entity->getId()) { + $formSlug = $form->has('slug') ? (string) $form->get('slug')->getData() : ''; + if ('' !== $formSlug && $formSlug !== (string) $entity->getSlug()) { + $this->addFlashMessage('mautic.smartlinks.smart_links.error.slug_immutable', ['%slug%' => $formSlug], \Mautic\CoreBundle\FlashBag::LEVEL_ERROR); + + return false; + } + } + + return parent::beforeEntitySave($entity, $form, $action, $objectId, $isClone); + } + + /** + * The list shows the short link, built from the configured domain (a reminder of it is + * also displayed above the form of a link), and the number of hits of each link. + * + * @param array $args + * + * @return array + */ + protected function getViewArguments(array $args, $action): array + { + $args = parent::getViewArguments($args, $action); + + if ('index' === $action) { + $model = $this->getModel($this->getModelName()); + \assert($model instanceof SmartLinkModel); + + $args['viewParameters']['shortLinkDomain'] = $model->getShortLinkDomain(); + $args['viewParameters']['hitCounts'] = $model->getHitCounts(); + } + + return $args; + } + + /** + * Order by slug: the entity has no "name" column. + */ + protected function getDefaultOrderColumn(): string + { + return 'slug'; + } + + /** + * Smart Links don't have a detail page; after Save or Cancel go back to the list. + */ + protected function getPostActionControllerAction($action): string + { + return 'index'; + } + + /** + * A saved Smart Link is never cloned: its slug is immutable, and a clone would need a new one. + */ + public function cloneAction(Request $request, $objectId): Response + { + $this->accessDenied(); + } +} diff --git a/Controller/UtmTaxonomyController.php b/Controller/UtmTaxonomyController.php index 16e6558..dd17c4b 100644 --- a/Controller/UtmTaxonomyController.php +++ b/Controller/UtmTaxonomyController.php @@ -4,37 +4,118 @@ declare(strict_types=1); namespace MauticPlugin\MT3SMarketingProgramBundle\Controller; -use Mautic\CoreBundle\Controller\CommonController; +use Mautic\CoreBundle\Controller\AbstractStandardFormController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** - * UTM Taxonomies: a placeholder page for the coming feature, kept out of the menu since - * 0.17.0 (the route stays; the page is reachable at /s/marketing-program-utm-taxonomies). - * The content (classifying the UTM parameters of the programs' campaigns and links) comes - * later; until then the page shows an empty content block. + * Create, edit and delete UTM Taxonomies (Smart Links > UTM Taxonomies), using core's standard + * CRUD flow. + * + * Model smartlinks.utm_taxonomy (mautic.smartlinks.model.utm_taxonomy), permission base + * smartlinks:taxonomies, translation base mautic.smartlinks.taxonomies. + * + * A taxonomy is never cloned: its name is unique, and a clone would collide immediately. A new + * taxonomy is created from scratch. */ -class UtmTaxonomyController extends CommonController +class UtmTaxonomyController extends AbstractStandardFormController { - public const ROUTE_INDEX = 'mt3s_marketing_program_utm_taxonomy_index'; + public const ROUTE_INDEX = 'mautic_smartlinks_taxonomies'; + public const ROUTE_ACTION = 'mautic_smartlinks_taxonomy_action'; + + protected function getModelName(): string + { + return 'smartlinks.utm_taxonomy'; + } + + protected function getTemplateBase(): string + { + return '@MT3SMarketingProgram/UtmTaxonomy'; + } + + protected function getIndexRoute(): string + { + return self::ROUTE_INDEX; + } + + protected function getActionRoute(): string + { + return self::ROUTE_ACTION; + } + + /** + * Core derives the JS loader method from the model name; no Mautic.OnLoad exists for + * taxonomies (the form needs none), but the prefix stays deterministic for future use. + */ + protected function getJsLoadMethodPrefix(): string + { + return 'smartlinksUtmTaxonomy'; + } + + /** + * Core builds mautic.; every key of the feature lives under mautic.smartlinks.taxonomies. + */ + protected function getTranslationBase(): string + { + return 'mautic.smartlinks.taxonomies'; + } /** * @param int $page */ public function indexAction(Request $request, $page = 1): Response { - $tmpl = $request->isXmlHttpRequest() ? $request->get('tmpl', 'index') : 'index'; - - return $this->delegateView([ - 'viewParameters' => [ - 'tmpl' => $tmpl, - ], - 'contentTemplate' => '@MT3SMarketingProgram/UtmTaxonomy/list.html.twig', - 'passthroughVars' => [ - 'activeLink' => '#'.self::ROUTE_INDEX, - 'mauticContent' => 'mt3sMpProgramUtmTaxonomy', - 'route' => $this->generateUrl(self::ROUTE_INDEX), - ], - ]); + return $this->indexStandard($request, $page); } -} + + public function newAction(Request $request): Response + { + return $this->newStandard($request); + } + + /** + * @param int $objectId + * @param bool $ignorePost + */ + public function editAction(Request $request, $objectId, $ignorePost = false): Response + { + return $this->editStandard($request, $objectId, $ignorePost); + } + + /** + * @param int $objectId + */ + public function deleteAction(Request $request, $objectId): Response + { + return $this->deleteStandard($request, $objectId); + } + + public function batchDeleteAction(Request $request): Response + { + return $this->batchDeleteStandard($request); + } + + /** + * Taxonomies don't have a detail page; after Save or Cancel go back to the list. + */ + protected function getPostActionControllerAction($action): string + { + return 'index'; + } + + /** + * Order by name: the taxonomy has no other sortable business column. + */ + protected function getDefaultOrderColumn(): string + { + return 'name'; + } + + /** + * A saved taxonomy is never cloned: its name is unique, and a clone would collide on save. + */ + public function cloneAction(Request $request, $objectId): Response + { + $this->accessDenied(); + } +} \ No newline at end of file diff --git a/Entity/SmartLink.php b/Entity/SmartLink.php new file mode 100644 index 0000000..7940159 --- /dev/null +++ b/Entity/SmartLink.php @@ -0,0 +1,304 @@ + value. + * + * @var array + */ + private array $utmParameters = []; + + /** + * The landing page of a Mautic redirect (null for external ones). + */ + private ?Page $page = null; + + /** + * The standalone form of a Mautic redirect (null for external ones). + */ + private ?Form $form = null; + + /** + * The UTM Taxonomy of the link: every UTM value is chosen among its allowed values. + * Null only on links that predate the feature; the form then demands one. + */ + private ?UtmTaxonomy $taxonomy = null; + + public static function loadMetadata(OrmClassMetadata $metadata): void + { + $builder = new ClassMetadataBuilder($metadata); + + $builder->setTable(self::TABLE_NAME) + ->setCustomRepositoryClass(SmartLinkRepository::class) + ->addIndex(['slug'], 'smart_link_slug'); + + $builder->addId(); + + $builder->createField('slug', Types::STRING) + ->length(self::SLUG_MAX_LENGTH) + ->unique() + ->build(); + + // Mapped on the raw metadata: ClassMetadataBuilder::addField() forces VARCHAR(191) on strings + // and doesn't accept enum types. + $metadata->mapField([ + 'fieldName' => 'redirectType', + 'columnName'=> 'redirect_type', + 'type' => Types::STRING, + 'length' => 20, + 'enumType' => SmartLinkRedirectType::class, + 'options' => ['default' => SmartLinkRedirectType::External->value], + ]); + $metadata->mapField([ + 'fieldName' => 'redirectCode', + 'columnName'=> 'redirect_code', + 'type' => Types::INTEGER, + 'enumType' => SmartLinkRedirectCode::class, + 'options' => ['default' => SmartLinkRedirectCode::Found->value], + ]); + $metadata->mapField([ + 'fieldName' => 'destinationUrl', + 'columnName'=> 'destination_url', + 'type' => Types::TEXT, + 'nullable' => true, + ]); + $metadata->mapField([ + 'fieldName' => 'utmParameters', + 'columnName'=> 'utm_parameters', + 'type' => Types::JSON, + ]); + + // Mautic destinations: a landing page or a standalone form. Deleting the page or the + // form keeps the link (the column becomes null, the link then 404s until reconfigured). + $builder->createManyToOne('page', Page::class) + ->addJoinColumn('page_id', 'id', true, false, 'SET NULL') + ->build(); + + $builder->createManyToOne('form', Form::class) + ->addJoinColumn('form_id', 'id', true, false, 'SET NULL') + ->build(); + + // The UTM Taxonomy of the link. Deleting the taxonomy keeps the link (the column becomes + // null): it keeps redirecting with the values it already carries, and its next edit + // demands a new taxonomy. + $builder->createManyToOne('taxonomy', UtmTaxonomy::class) + ->addJoinColumn('utm_taxonomy_id', 'id', true, false, 'SET NULL') + ->build(); + } + + public static function loadValidatorMetadata(ClassMetadata $metadata): void + { + $metadata->addPropertyConstraint('slug', new NotBlank(message: 'mautic.smartlinks.smart_links.error.slug_required')); + $metadata->addPropertyConstraint('slug', new Length( + max: self::SLUG_MAX_LENGTH, + maxMessage: 'mautic.smartlinks.smart_links.error.slug_length', + )); + } + + public function getId(): ?int + { + return $this->id; + } + + /** + * Core's standard list actions and flash messages call getName(); the slug is the + * link's name. + */ + public function getName(): string + { + return (string) $this->slug; + } + + /** + * The short link, for example https://lnk.example.com/l/ab3x. Empty when no domain is set. + */ + public function getShortLink(string $domain): string + { + $domain = trim((string) $domain); + + return '' === $domain || '' === (string) $this->slug ? '' : 'https://'.rtrim($domain, '/').'/l/'.$this->slug; + } + + public function getSlug(): ?string + { + return $this->slug; + } + + /** + * The slug of a saved link is immutable: once set at creation time, it can't change. + */ + public function setSlug(?string $slug): static + { + $immutable = null !== $this->id && null !== $this->slug && '' !== $this->slug; + if ($immutable && null !== $slug && $slug !== $this->slug) { + throw new \LogicException('The slug of a saved smart link cannot be changed.'); + } + + $this->isChanged('slug', $slug); + $this->slug = $slug; + + return $this; + } + + public function getRedirectType(): SmartLinkRedirectType + { + return $this->redirectType; + } + + public function setRedirectType(SmartLinkRedirectType $redirectType): static + { + if ($redirectType !== $this->redirectType) { + // isChanged() can't log enums (they aren't stringable), so log the backing values. + $this->addChange('redirectType', [$this->redirectType->value, $redirectType->value]); + $this->redirectType = $redirectType; + } + + // The destination only exists for external redirects. + if ($redirectType->isMautic()) { + $this->setDestinationUrl(null); + } + + return $this; + } + + public function getRedirectCode(): SmartLinkRedirectCode + { + return $this->redirectCode; + } + + public function setRedirectCode(SmartLinkRedirectCode $redirectCode): static + { + if ($redirectCode !== $this->redirectCode) { + $this->addChange('redirectCode', [$this->redirectCode->value, $redirectCode->value]); + $this->redirectCode = $redirectCode; + } + + return $this; + } + + public function getDestinationUrl(): ?string + { + return $this->destinationUrl; + } + + public function setDestinationUrl(?string $destinationUrl): static + { + if (null !== $destinationUrl && '' === trim($destinationUrl)) { + $destinationUrl = null; + } + + $this->isChanged('destinationUrl', $destinationUrl); + $this->destinationUrl = $destinationUrl; + + return $this; + } + + /** + * @return array + */ + public function getUtmParameters(): array + { + return $this->utmParameters; + } + + /** + * @param array|null $utmParameters + */ + public function setUtmParameters(?array $utmParameters): static + { + $this->isChanged('utmParameters', $utmParameters); + $this->utmParameters = $utmParameters ?? []; + + return $this; + } + + public function getPage(): ?Page + { + return $this->page; + } + + public function setPage(?Page $page): static + { + $this->isChanged('page', $page); + $this->page = $page; + + return $this; + } + + public function getForm(): ?Form + { + return $this->form; + } + + public function setForm(?Form $form): static + { + $this->isChanged('form', $form); + $this->form = $form; + + return $this; + } + + public function getTaxonomy(): ?UtmTaxonomy + { + return $this->taxonomy; + } + + public function setTaxonomy(?UtmTaxonomy $taxonomy): static + { + $this->isChanged('taxonomy', $taxonomy); + $this->taxonomy = $taxonomy; + + return $this; + } + + /** + * The title of the destination, whatever its type: the slug for external links, the page + * title or the form name for Mautic ones. Used by the list and the flash messages. + */ + public function getDestinationLabel(): string + { + if ($this->redirectType->isMautic()) { + return $this->page?->getTitle() ?? $this->form?->getName() ?? ''; + } + + return (string) ($this->destinationUrl ?? ''); + } +} diff --git a/Entity/SmartLinkHit.php b/Entity/SmartLinkHit.php new file mode 100644 index 0000000..6e46f7f --- /dev/null +++ b/Entity/SmartLinkHit.php @@ -0,0 +1,118 @@ +setTable(self::TABLE_NAME) + ->setCustomRepositoryClass(SmartLinkHitRepository::class) + ->addIndex(['smart_link_id'], 'smart_link_hit_link'); + + $builder->addId(); + + // Deleting the link deletes its hits. + $builder->createManyToOne('smartLink', SmartLink::class) + ->addJoinColumn('smart_link_id', 'id', false, false, 'CASCADE') + ->build(); + + $builder->createField('ipAddress', 'string') + ->columnName('ip_address') + ->length(45) // IPv6 + ->nullable() + ->build(); + + $builder->createField('referer', 'text') + ->nullable() + ->build(); + + $builder->createField('userAgent', 'text') + ->columnName('user_agent') + ->nullable() + ->build(); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getSmartLink(): ?SmartLink + { + return $this->smartLink; + } + + public function setSmartLink(?SmartLink $smartLink): static + { + $this->isChanged('smartLink', $smartLink); + $this->smartLink = $smartLink; + + return $this; + } + + public function getIpAddress(): ?string + { + return $this->ipAddress; + } + + public function setIpAddress(?string $ipAddress): static + { + $this->isChanged('ipAddress', $ipAddress); + $this->ipAddress = $ipAddress; + + return $this; + } + + public function getReferer(): ?string + { + return $this->referer; + } + + public function setReferer(?string $referer): static + { + $this->isChanged('referer', $referer); + $this->referer = $referer; + + return $this; + } + + public function getUserAgent(): ?string + { + return $this->userAgent; + } + + public function setUserAgent(?string $userAgent): static + { + $this->isChanged('userAgent', $userAgent); + $this->userAgent = $userAgent; + + return $this; + } +} diff --git a/Entity/SmartLinkHitRepository.php b/Entity/SmartLinkHitRepository.php new file mode 100644 index 0000000..3a889ac --- /dev/null +++ b/Entity/SmartLinkHitRepository.php @@ -0,0 +1,57 @@ + + */ +class SmartLinkHitRepository extends CommonRepository +{ + public function getTableAlias(): string + { + return 'slh'; + } + + /** + * Hit counts of every Smart Link, in one query (list view): link id => number of hits. + * + * @return array + */ + public function getHitCounts(): array + { + $alias = $this->getTableAlias(); + + $rows = $this->createQueryBuilder($alias) + ->select('IDENTITY('.$alias.'.smartLink) AS link_id, COUNT('.$alias.'.id) AS hit_count') + ->groupBy($alias.'.smartLink') + ->getQuery() + ->getArrayResult(); + + $counts = []; + foreach ($rows as $row) { + $counts[(int) $row['link_id']] = (int) $row['hit_count']; + } + + return $counts; + } + + /** + * The last hits of a link, most recent first. + * + * @return SmartLinkHit[] + */ + public function findRecentBySmartLink(SmartLink $smartLink, int $limit = 10): array + { + return $this->createQueryBuilder($this->getTableAlias()) + ->where($this->getTableAlias().'.smartLink = :link') + ->setParameter('link', $smartLink) + ->orderBy($this->getTableAlias().'.dateAdded', 'DESC') + ->setMaxResults($limit) + ->getQuery() + ->getResult(); + } +} diff --git a/Entity/SmartLinkRepository.php b/Entity/SmartLinkRepository.php new file mode 100644 index 0000000..f25e587 --- /dev/null +++ b/Entity/SmartLinkRepository.php @@ -0,0 +1,104 @@ + + */ +class SmartLinkRepository extends CommonRepository +{ + public function getTableAlias(): string + { + return 'sl'; + } + + /** + * Loads the page and the form with the links, so that the list doesn't query them one by one. + * + * @param array $args + */ + public function getEntities(array $args = []) + { + $alias = $this->getTableAlias(); + + // The hit count of each link as a HIDDEN scalar: not hydrated into the entities, but + // available as an order by column ("sl.hitCount") for the Hits column of the list. + $hitCount = '(SELECT COUNT(h.id) FROM '.SmartLinkHit::class.' h WHERE h.smartLink = '.$alias.'.id) AS HIDDEN hitCount'; + + $args['qb'] = $this->createQueryBuilder($alias) + ->select($alias, 'pg', 'fm', $hitCount) + ->leftJoin($alias.'.page', 'pg') + ->leftJoin($alias.'.form', 'fm'); + + return parent::getEntities($args); + } + + /** + * True when another link already uses this slug. A link being edited never collides with itself. + */ + public function slugExists(string $slug, ?int $ignoreId = null): bool + { + if ('' === $slug) { + return false; + } + + $qb = $this->createQueryBuilder($this->getTableAlias()) + ->select('COUNT('.$this->getTableAlias().'.id)') + ->where($this->getTableAlias().'.slug = :slug') + ->setParameter('slug', $slug); + + if (null !== $ignoreId) { + $qb->andWhere($this->getTableAlias().'.id != :id') + ->setParameter('id', $ignoreId); + } + + return (int) $qb->getQuery()->getSingleScalarResult() > 0; + } + + /** + * The list's search box matches the slug and the destination URL. + * + * @return array + */ + protected function addCatchAllWhereClause($q, $filter): array + { + return $this->addStandardCatchAllWhereClause($q, $filter, [ + $this->getTableAlias().'.slug', + $this->getTableAlias().'.destinationUrl', + ]); + } + /** + * The Hits column of the list sorts by the number of hits of each link: the virtual + * "hitCount" order by maps to the HIDDEN hitCount scalar of the list query. Everything + * else falls back to core's column handling. + */ + protected function buildOrderByClause($q, array $args): void + { + $alias = $this->getTableAlias(); + $orderBy = (string) ($args['orderBy'] ?? ''); + $virtual = $alias.'.hitCount' === $orderBy || 'hitCount' === $orderBy; + + if ($virtual && $q instanceof \Doctrine\ORM\QueryBuilder) { + $orderByDir = $this->sanitize((string) ($args['orderByDir'] ?? 'ASC')); + + $q->addOrderBy('hitCount', $orderByDir); + + return; + } + + parent::buildOrderByClause($q, $args); + } + /** + * @return array + */ + protected function getDefaultOrder(): array + { + return [ + [$this->getTableAlias().'.slug', 'ASC'], + ]; + } +} diff --git a/Entity/UtmTaxonomy.php b/Entity/UtmTaxonomy.php new file mode 100644 index 0000000..af5a634 --- /dev/null +++ b/Entity/UtmTaxonomy.php @@ -0,0 +1,143 @@ + list of + * {value, label} rows. Only the parameters enabled in Settings > Configuration + * > Smart Links Settings can be given values (the form only offers those). + */ +class UtmTaxonomy extends FormEntity +{ + public const TABLE_NAME = 'utm_taxonomies'; + + public const NAME_MAX_LENGTH = 50; + + private ?int $id = null; + + private ?string $name = null; + + private ?string $description = null; + + /** + * Allowed values per parameter: parameter key => list of {value, label}. + * + * @var array> + */ + private array $parameters = []; + + public static function loadMetadata(OrmClassMetadata $metadata): void + { + $builder = new ClassMetadataBuilder($metadata); + + $builder->setTable(self::TABLE_NAME) + ->setCustomRepositoryClass(UtmTaxonomyRepository::class) + ->addIndex(['name'], 'utm_taxonomy_name'); + + $builder->addId(); + + $builder->createField('name', Types::STRING) + ->length(self::NAME_MAX_LENGTH) + ->unique() + ->build(); + + $builder->createField('description', Types::TEXT) + ->nullable() + ->build(); + + // Mapped on the raw metadata: ClassMetadataBuilder::addField() forces VARCHAR(191) on strings. + $metadata->mapField([ + 'fieldName' => 'parameters', + 'columnName' => 'parameters', + 'type' => Types::JSON, + ]); + } + + public function getId(): ?int + { + return $this->id; + } + + public function getName(): ?string + { + return $this->name; + } + + public function setName(?string $name): static + { + $this->isChanged('name', $name); + $this->name = '' !== trim((string) $name) ? $name : null; + + return $this; + } + + public function getDescription(): ?string + { + return $this->description; + } + + public function setDescription(?string $description): static + { + if (null !== $description && '' === trim($description)) { + $description = null; + } + + $this->isChanged('description', $description); + $this->description = $description; + + return $this; + } + + /** + * @return array> + */ + public function getParameters(): array + { + return $this->parameters; + } + + /** + * @param array>|null $parameters + */ + public function setParameters(?array $parameters): static + { + $this->isChanged('parameters', $parameters); + $this->parameters = $parameters ?? []; + + ksort($this->parameters); + + return $this; + } + + /** + * The allowed values of one parameter, keyed by value (labels are unique per value). + * + * @return list + */ + public function getParameterValues(string $key): array + { + return $this->parameters[$key] ?? []; + } + + /** + * The parameter keys the taxonomy defines, in display order. + * + * @return list + */ + public function getParameterKeys(): array + { + return array_keys($this->parameters); + } +} \ No newline at end of file diff --git a/Entity/UtmTaxonomyRepository.php b/Entity/UtmTaxonomyRepository.php new file mode 100644 index 0000000..8d55eec --- /dev/null +++ b/Entity/UtmTaxonomyRepository.php @@ -0,0 +1,63 @@ + + */ +class UtmTaxonomyRepository extends CommonRepository +{ + public function getTableAlias(): string + { + return 'ut'; + } + + /** + * True when another taxonomy already uses this name. A taxonomy being edited never collides with itself. + */ + public function nameExists(string $name, ?int $ignoreId = null): bool + { + if ('' === $name) { + return false; + } + + $qb = $this->createQueryBuilder($this->getTableAlias()) + ->select('COUNT('.$this->getTableAlias().'.id)') + ->where($this->getTableAlias().'.name = :name') + ->setParameter('name', $name); + + if (null !== $ignoreId) { + $qb->andWhere($this->getTableAlias().'.id != :id') + ->setParameter('id', $ignoreId); + } + + return (int) $qb->getQuery()->getSingleScalarResult() > 0; + } + + /** + * The list's search box matches the name and the description. + * + * @return array + */ + protected function addCatchAllWhereClause($q, $filter): array + { + return $this->addStandardCatchAllWhereClause($q, $filter, [ + $this->getTableAlias().'.name', + $this->getTableAlias().'.description', + ]); + } + + /** + * @return array + */ + protected function getDefaultOrder(): array + { + return [ + [$this->getTableAlias().'.name', 'ASC'], + ]; + } +} \ No newline at end of file diff --git a/EventListener/SmartLinksConfigSubscriber.php b/EventListener/SmartLinksConfigSubscriber.php new file mode 100644 index 0000000..e3fe9c3 --- /dev/null +++ b/EventListener/SmartLinksConfigSubscriber.php @@ -0,0 +1,36 @@ + Configuration. + */ +final class SmartLinksConfigSubscriber implements EventSubscriberInterface +{ + public const FORM_ALIAS = 'smartlinksconfig'; + + public static function getSubscribedEvents(): array + { + return [ + ConfigEvents::CONFIG_ON_GENERATE => ['onConfigGenerate', 0], + ]; + } + + public function onConfigGenerate(ConfigBuilderEvent $event): void + { + $event->addForm([ + 'bundle' => 'MT3SMarketingProgramBundle', + 'formAlias' => self::FORM_ALIAS, + 'formType' => SmartLinksConfigType::class, + 'formTheme' => '@MT3SMarketingProgram/FormTheme/Config/_config_smartlinksconfig_widget.html.twig', + 'parameters' => $event->getParametersFromConfig('MT3SMarketingProgramBundle'), + ]); + } +} \ No newline at end of file diff --git a/Form/DataTransformer/UtmSettingsTransformer.php b/Form/DataTransformer/UtmSettingsTransformer.php new file mode 100644 index 0000000..96c8fe7 --- /dev/null +++ b/Form/DataTransformer/UtmSettingsTransformer.php @@ -0,0 +1,146 @@ +> + */ +final class UtmSettingsTransformer implements DataTransformerInterface +{ + public function __construct( + private readonly UtmConfigurationNormalizer $normalizer, + private readonly UtmParameterCatalog $catalog, + private readonly TranslatorInterface $translator, + ) { + } + + /** + * Stored configuration => form data. + * + * @return array + */ + public function transform(mixed $value): array + { + $config = $this->normalizer->normalize($value); + + $parameters = []; + $custom = []; + foreach ($config['parameters'] as $key => $parameter) { + $definition = $this->catalog->get($key); + + $row = [ + 'enabled' => $parameter['enabled'], + 'label' => $parameter['label'], + 'mode' => $parameter['mode'], + 'values' => $this->valuesToForm($parameter['values'] ?? [], $parameter['default'] ?? null), + ]; + + if (null === $definition) { + $custom[] = ['key' => $key] + $row; + continue; + } + + if ('' === $row['label']) { + $row['label'] = $this->translator->trans($definition->getLabelKey()); + } + $parameters[$key] = $row; + } + + return [ + 'enforce_lowercase' => $config['enforce_lowercase'], + 'separator_replacement' => $config['separator_replacement'], + 'parameters' => $parameters, + 'custom_parameters' => $custom, + ]; + } + + /** + * Form data => stored configuration. + * + * @return array + */ + public function reverseTransform(mixed $value): array + { + $value = is_array($value) ? $value : []; + + $parameters = []; + foreach ($value['parameters'] ?? [] as $key => $parameter) { + $parameters[(string) $key] = $this->parameterToStorage($parameter); + } + + foreach ($value['custom_parameters'] ?? [] as $parameter) { + $key = trim((string) ($parameter['key'] ?? '')); + if ('' !== $key) { + $parameters[$key] = $this->parameterToStorage($parameter); + } + } + + return [ + 'enforce_lowercase' => UtmConfigurationNormalizer::toBool($value['enforce_lowercase'] ?? true), + 'separator_replacement' => (string) ($value['separator_replacement'] ?? UtmConfigurationNormalizer::DEFAULT_SEPARATOR), + 'parameters' => $parameters, + ]; + } + + /** + * Only `dropdown` parameters keep values and a default; nothing else is stored for the other modes. + * + * @param array $parameter + * + * @return array + */ + private function parameterToStorage(array $parameter): array + { + $mode = (string) ($parameter['mode'] ?? UtmParameterMode::DISABLED); + + $stored = [ + 'enabled' => UtmConfigurationNormalizer::toBool($parameter['enabled'] ?? false), + 'label' => trim((string) ($parameter['label'] ?? '')), + 'mode' => $mode, + ]; + + if (UtmParameterMode::DROPDOWN !== $mode) { + return $stored; + } + + $stored['values'] = []; + $stored['default'] = ''; + foreach ($parameter['values'] ?? [] as $row) { + $rowValue = trim((string) ($row['value'] ?? '')); + if ('' === $rowValue) { + continue; + } + + $stored['values'][] = ['value' => $rowValue, 'label' => trim((string) ($row['label'] ?? ''))]; + if ('' === $stored['default'] && !empty($row['is_default'])) { + $stored['default'] = $rowValue; + } + } + + return $stored; + } + + /** + * @param list $values + * + * @return list + */ + private function valuesToForm(array $values, ?string $default): array + { + return array_map( + fn (array $row): array => $row + ['is_default' => $row['value'] === $default], + $values + ); + } +} diff --git a/Form/Extension/UtmTagsTypeExtension.php b/Form/Extension/UtmTagsTypeExtension.php new file mode 100644 index 0000000..d17f58e --- /dev/null +++ b/Form/Extension/UtmTagsTypeExtension.php @@ -0,0 +1,39 @@ + + */ +final class UtmTagsTypeExtension extends AbstractTypeExtension +{ + public function __construct( + private readonly UtmFieldsApplicator $applicator, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + $this->applicator->apply($builder); + } + + /** + * @return iterable + */ + public static function getExtendedTypes(): iterable + { + return [EmailUtmTagsType::class]; + } +} diff --git a/Form/Type/SmartLinkType.php b/Form/Type/SmartLinkType.php new file mode 100644 index 0000000..ed70615 --- /dev/null +++ b/Form/Type/SmartLinkType.php @@ -0,0 +1,606 @@ + + */ +final class SmartLinkType extends AbstractType +{ + /** + * The values the link carried when the form was built: a value outside its taxonomy stays + * acceptable (it was chosen when the taxonomy allowed it), so a plain re-save never errors. + * + * @var array + */ + private array $originalUtmParameters = []; + + public function __construct( + private readonly SmartLinkValidator $validator, + private readonly SmartLinkShortUrlBuilder $shortUrlBuilder, + private readonly UtmConfigurationProvider $utmConfiguration, + private readonly SmartLinkModel $smartLinkModel, + private readonly TranslatorInterface $translator, + private readonly EntityManagerInterface $entityManager, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + /** @var SmartLink $smartLink */ + $smartLink = $options['data']; + $isSaved = null !== $smartLink->getId(); + + $this->originalUtmParameters = $smartLink->getUtmParameters(); + + // -- Slug -------------------------------------------------------------- + // Spaces are replaced by the configured character and lowercase is enforced by the model + // on save, exactly like the live preview does. The constraints only guard the raw input; + // spaces are allowed here because they are turned into the separator on save. + $builder->add('slug', TextType::class, [ + 'label' => 'mautic.smartlinks.smart_links.slug', + 'required' => true, + 'disabled' => $isSaved, + 'attr' => [ + 'class' => 'form-control smart-link-slug', + 'maxlength' => SmartLink::SLUG_MAX_LENGTH, + 'tooltip' => 'mautic.smartlinks.smart_links.slug.tooltip', + // Live preview of the short link: the JS fills the span next to the field. + 'data-preview' => 'smart-link-preview', + ], + 'constraints' => $isSaved ? [] : [ + new NotBlank(message: 'mautic.smartlinks.smart_links.error.slug_required'), + new Length(max: SmartLink::SLUG_MAX_LENGTH, maxMessage: 'mautic.smartlinks.smart_links.error.slug_length'), + new Regex( + pattern: '/^[\p{L}0-9\-_. ]*$/u', + message: 'mautic.smartlinks.smart_links.error.slug_characters' + ), + new Callback(callback: $this->validateSlug(...)), + ], + ]); + + // -- Redirect ------------------------------------------------------------ + $builder->add('redirectType', EnumType::class, [ + 'label' => 'mautic.smartlinks.smart_links.redirect_type', + 'class' => SmartLinkRedirectType::class, + 'choice_label' => fn (SmartLinkRedirectType $type): string => $this->translator->trans($type->getLabelKey()), + 'attr' => ['class' => 'form-control smart-link-redirect-type'], + ]); + + $builder->add('redirectCode', EnumType::class, [ + 'label' => 'mautic.smartlinks.smart_links.redirect_code', + 'class' => SmartLinkRedirectCode::class, + 'choice_label' => fn (SmartLinkRedirectCode $code): string => $code->getTranslatedLabel($this->translator), + 'attr' => ['class' => 'form-control smart-link-redirect-code'], + ]); + + $builder->add('destinationUrl', UrlType::class, [ + 'label' => 'mautic.smartlinks.smart_links.destination_url', + 'required' => false, + 'attr' => [ + 'class' => 'form-control smart-link-destination', + 'tooltip' => 'mautic.smartlinks.smart_links.destination_url.tooltip', + ], + 'constraints' => [new Callback(callback: $this->validateDestination(...))], + ]); + + // -- Mautic destination: a landing page or a standalone form ------------------------- + $builder->add('destination', ChoiceType::class, [ + 'label' => 'mautic.smartlinks.smart_links.destination', + 'required' => false, + 'mapped' => false, + 'attr' => [ + 'class' => 'form-control smart-link-mautic-destination', + 'tooltip' => 'mautic.smartlinks.smart_links.destination.tooltip', + ], + 'choices' => $this->buildMauticDestinationChoices($smartLink), + 'placeholder' => 'mautic.smartlinks.form.choose', + 'data' => $this->currentMauticDestination($smartLink), + ]); + + // -- UTM Taxonomy ------------------------------------------------------------ + // The taxonomy of the link drives its UTM values. Required: a link always carries one + // from now on; a link that predates the feature picks one on its next edit. A stored + // taxonomy that is no longer published stays selectable, so an old link is still + // editable (a new one can always be chosen instead). + $builder->add('taxonomy', ChoiceType::class, [ + 'label' => 'mautic.smartlinks.smart_links.taxonomy', + 'required' => true, + 'placeholder' => 'mautic.smartlinks.form.choose', + 'choices' => $this->buildTaxonomyChoices($smartLink), + 'choice_value' => fn (?UtmTaxonomy $taxonomy): string => (string) ($taxonomy?->getId() ?? ''), + 'attr' => [ + 'class' => 'form-control smart-link-taxonomy', + 'tooltip' => 'mautic.smartlinks.smart_links.taxonomy.tooltip', + ], + 'constraints' => [new NotBlank(message: 'mautic.smartlinks.smart_links.error.taxonomy_required')], + ]); + + // -- UTM parameters ------------------------------------------------------------ + // One fieldset per taxonomy, one select per parameter the taxonomy defines: the choices + // are the values the taxonomy allows. All the fieldsets are rendered at once; + // Mautic's data-show-on switcher (form.vars.smart_link_utm_fieldsets) shows the one of + // the chosen taxonomy, and the SUBMIT listener below drops the values of the others. + $builder->add('utmParameters', FormType::class, [ + 'label' => false, + 'constraints' => [new Callback(callback: $this->validateUtmParameters(...))], + ]); + + $taxonomies = $this->getFormTaxonomies($smartLink); + + foreach ($taxonomies as $taxonomy) { + // The dropdown parameters the taxonomy limits: a select with its subset as choices. + foreach ($this->getTaxonomyParameterKeys($taxonomy) as $key) { + $builder->get('utmParameters')->add( + self::fieldsetChildName($taxonomy, $key), + ChoiceType::class, + $this->buildTaxonomyFieldOptions($taxonomy, $key, $smartLink) + ); + } + + } + + // The stored values (parameter key => value) feed the fieldset children + // (t_): every select shows what the link already carries. + $builder->get('utmParameters')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($taxonomies): void { + $stored = is_array($event->getData()) ? $event->getData() : []; + $expanded = []; + + foreach ($taxonomies as $taxonomy) { + foreach ($this->getTaxonomyFieldsetKeys($taxonomy) as $key) { + $expanded[self::fieldsetChildName($taxonomy, $key)] = (string) ($stored[$key] ?? ''); + } + } + + $event->setData($expanded); + }); + + // Back to the stored shape: only the fieldset of the chosen taxonomy survives, + // stripped of its prefix, without the empty values, keys in display order. + $builder->get('utmParameters')->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void { + $data = $event->getData(); + if (!is_array($data)) { + $event->setData([]); + + return; + } + + $taxonomy = $this->submittedTaxonomy($event->getForm()); + $flat = []; + + if (null !== $taxonomy) { + $prefix = self::fieldsetPrefix($taxonomy); + foreach ($data as $name => $value) { + if (\is_string($value) && '' !== trim($value) && str_starts_with((string) $name, $prefix)) { + $flat[substr((string) $name, \strlen($prefix))] = trim($value); + } + } + } + + ksort($flat); + $event->setData($flat); + }); + + $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($isSaved): void { + $data = $event->getData(); + if (!is_array($data)) { + return; + } + + $type = SmartLinkRedirectType::tryFrom((string) ($data['redirectType'] ?? '')); + + // The URL only exists for external redirects; the Mautic destination only for + // Mautic ones. Drop whatever doesn't apply before the form is processed. + if (null === $type || $type->isMautic()) { + unset($data['destinationUrl']); + } else { + unset($data['destination']); + } + + // Never accept a modified slug from a stale form (the field is disabled on edit). + if ($isSaved && \array_key_exists('slug', $data)) { + unset($data['slug']); + } + + $event->setData($data); + }); + + // The unmapped "destination" choice becomes the page or the form of the link. + $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void { + $link = $event->getData(); + $form = $event->getForm(); + $value = $form->has('destination') ? $form->get('destination')->getData() : null; + + if (!$link instanceof SmartLink) { + return; + } + + [$kind, $id] = false !== strpos((string) $value, ':') ? explode(':', (string) $value, 2) : [null, null]; + + $page = 'page' === $kind && null !== $id ? $this->getPageRepository()->find($id) : null; + $form = 'form' === $kind && null !== $id ? $this->getFormRepository()->find($id) : null; + + $link->setPage($page instanceof Page ? $page : null); + $link->setForm($form instanceof MauticForm ? $form : null); + }); + + $builder->add('buttons', FormButtonsType::class); + + if (!empty($options['action'])) { + $builder->setAction($options['action']); + } + } + + /** + * The taxonomies rendered on the form: the published ones, plus the taxonomy the link + * carries even when it is no longer published (so an old link stays editable). + * + * @return list + */ + private function getFormTaxonomies(SmartLink $smartLink): array + { + $taxonomies = $this->getTaxonomyRepository()->findBy(['isPublished' => true], ['name' => 'ASC']); + + $stored = $smartLink->getTaxonomy(); + if (null !== $stored && !\in_array($stored, $taxonomies, true)) { + $taxonomies[] = $stored; + } + + return $taxonomies; + } + + /** + * The parameter keys a taxonomy offers on the Smart Link form: the ones it defines values + * for and that are still enabled in Smart Links Settings. + * + * @return list + */ + private function getTaxonomyParameterKeys(UtmTaxonomy $taxonomy): array + { + return array_values(array_intersect( + $taxonomy->getParameterKeys(), + array_keys($this->utmConfiguration->getEnabledParameters()) + )); + } + + /** + * The choices of the taxonomy select: the published taxonomies (label = name), plus the + * taxonomy the link carries even when it is no longer published. + * + * @return array + */ + private function buildTaxonomyChoices(SmartLink $smartLink): array + { + $choices = []; + + foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) { + $label = (string) $taxonomy->getName(); + if (!$taxonomy->isPublished()) { + $label = $this->translator->trans('mautic.smartlinks.taxonomies.unpublished_choice', ['%name%' => $label]); + } + + $choices[$label] = $taxonomy; + } + + return $choices; + } + + /** + * One UTM parameter select of a taxonomy fieldset: the choices are the values the taxonomy + * allows. A stored value outside the list stays selectable, labelled "(not in taxonomy)", + * so an old link is still editable (it is rejected on save by SmartLinkValidator). + * + * @return array + */ + private function buildTaxonomyFieldOptions(UtmTaxonomy $taxonomy, string $key, SmartLink $smartLink): array + { + $choices = []; + foreach ($taxonomy->getParameterValues($key) as $row) { + $choices[$row['label']] = $row['value']; + } + + $stored = (string) ($smartLink->getUtmParameters()[$key] ?? ''); + if ('' !== $stored && !\in_array($stored, $choices, true)) { + $choices = [ + $this->translator->trans('mautic.smartlinks.form.legacy_choice', ['%value%' => $stored]) => $stored, + ] + $choices; + } + + $parameter = $this->utmConfiguration->getParameter($key); + + return [ + 'label' => (string) ($parameter['label'] ?? $key), + 'required' => false, + 'choices' => $choices, + 'placeholder' => 'mautic.smartlinks.form.choose', + 'attr' => ['class' => 'form-control smart-link-utm'], + ]; + } + + /** + * The keys of one taxonomy fieldset: the dropdown parameters the taxonomy limits plus the + * parameters the admin left free, in display order. + * + * @return list + */ + private function getTaxonomyFieldsetKeys(UtmTaxonomy $taxonomy): array + { + return $this->getTaxonomyParameterKeys($taxonomy); + } + + /** + * The prefix of the utmParameters children of one taxonomy fieldset: t_. + */ + private static function fieldsetPrefix(UtmTaxonomy $taxonomy): string + { + return 't'.(string) $taxonomy->getId().'_'; + } + + private static function fieldsetChildName(UtmTaxonomy $taxonomy, string $key): string + { + return self::fieldsetPrefix($taxonomy).$key; + } + + /** + * The submitted taxonomy of the form (null when none was chosen). + */ + private function submittedTaxonomy(FormInterface $utmParameters): ?UtmTaxonomy + { + $taxonomy = $utmParameters->getParent()?->get('taxonomy')->getData(); + + return $taxonomy instanceof UtmTaxonomy ? $taxonomy : null; + } + + private function getTaxonomyRepository(): EntityRepository + { + $repository = $this->entityManager->getRepository(UtmTaxonomy::class); + \assert($repository instanceof EntityRepository); + + return $repository; + } + + public function buildView(FormView $view, FormInterface $form, array $options): void + { + /** @var SmartLink $smartLink */ + $smartLink = $form->getData(); + + $view->vars['smart_link_domain'] = $this->shortUrlBuilder->getShortLinkDomain(); + $view->vars['smart_link_is_saved'] = null !== $smartLink->getId(); + $view->vars['smart_link_slug'] = (string) ($smartLink->getSlug() ?? ''); + $view->vars['smart_link_preview'] = $this->shortUrlBuilder->buildShortUrl($smartLink); + $view->vars['smart_link_separator'] = $this->utmConfiguration->getSeparatorReplacement(); + $view->vars['smart_link_lowercase'] = $this->utmConfiguration->isLowercaseEnforced(); + // Slug proposed by the "Generate" button; the empty "new" form starts with one. + $view->vars['smart_link_generated'] = null === $smartLink->getId() ? $this->smartLinkModel->generateSlug() : ''; + + // One rendered fieldset per taxonomy: the template wraps each in a data-show-on container + // keyed by the taxonomy select, so Mautic's switcher shows the chosen one. + $view->vars['smart_link_utm_fieldsets'] = []; + foreach ($this->getFormTaxonomies($smartLink) as $taxonomy) { + $view->vars['smart_link_utm_fieldsets'][(string) $taxonomy->getId()] = [ + 'id' => (string) $taxonomy->getId(), + 'name' => (string) $taxonomy->getName(), + 'prefix' => self::fieldsetPrefix($taxonomy), + 'keys' => $this->getTaxonomyFieldsetKeys($taxonomy), + ]; + } + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults(['data_class' => SmartLink::class]); + } + + public function getBlockPrefix(): string + { + return 'smartlinks_smart_link'; + } + + private function separator(): string + { + return $this->utmConfiguration->getSeparatorReplacement(); + } + + /** + * The repositories of the Mautic destinations, resolved lazily (the entity manager is + * injected once; the repositories are cheap Doctrine lookups). + */ + private function getPageRepository(): EntityRepository + { + $repository = $this->entityManager->getRepository(Page::class); + \assert($repository instanceof EntityRepository); + + return $repository; + } + + private function getFormRepository(): EntityRepository + { + $repository = $this->entityManager->getRepository(MauticForm::class); + \assert($repository instanceof EntityRepository); + + return $repository; + } + + private function validateSlug(mixed $slug, ExecutionContextInterface $context): void + { + /** @var SmartLink $smartLink */ + $smartLink = $context->getRoot()->getData(); + if (!$smartLink instanceof SmartLink) { + return; + } + + $this->addViolations($context, $this->validator->validateSlug( + $this->normalizeSlug((string) $slug), + $smartLink->getId() + )); + } + + private function validateDestination(mixed $url, ExecutionContextInterface $context): void + { + /** @var SmartLink $smartLink */ + $smartLink = $context->getRoot()->getData(); + if (!$smartLink instanceof SmartLink) { + return; + } + + $this->addViolations($context, $this->validator->validateDestination( + $smartLink->getRedirectType(), + is_string($url) ? $url : null, + $smartLink->getPage(), + $smartLink->getForm() + )); + } + + /** + * The published landing pages and standalone forms of the instance, grouped, with the + * link's current destination preselected. Only activated (published) ones are offered. + * + * @return array + */ + private function buildMauticDestinationChoices(SmartLink $smartLink): array + { + $choices = []; + $values = []; + + $pages = $this->getPageRepository()->findBy(['isPublished' => true], ['title' => 'ASC']); + foreach ($pages as $page) { + $value = 'page:'.$page->getId(); + $choices['mautic.smartlinks.smart_links.destination.pages'][$page->getTitle()] = $value; + $values[] = $value; + } + + $forms = $this->getFormRepository()->findBy(['isPublished' => true], ['name' => 'ASC']); + foreach ($forms as $form) { + $value = 'form:'.$form->getId(); + $choices['mautic.smartlinks.smart_links.destination.forms'][$form->getName()] = $value; + $values[] = $value; + } + + // A stored destination that is no longer published stays selectable, so an old link + // is still editable (it 404s until the page or the form is activated again). The + // guard must skip the "no destination" case: a null choice would make Symfony fall + // back to index-based values for every option. + $current = $this->currentMauticDestination($smartLink); + if (null !== $current && !in_array($current, $values, true)) { + $label = $smartLink->getPage()?->getTitle() ?? $smartLink->getForm()?->getName() ?? ''; + $choices['mautic.smartlinks.smart_links.destination.unpublished'][$label] = $current; + } + + return $choices; + } + + /** + * The value of the unmapped destination field for the link's current page or form. + */ + private function currentMauticDestination(SmartLink $smartLink): ?string + { + if (null !== $smartLink->getPage()) { + return 'page:'.$smartLink->getPage()->getId(); + } + + if (null !== $smartLink->getForm()) { + return 'form:'.$smartLink->getForm()->getId(); + } + + return null; + } + + /** + * Applies the UTM Manager settings to a typed slug, the same way the model will on save, + * so the uniqueness check compares the final slug. + */ + private function normalizeSlug(string $slug): string + { + $slug = str_replace(' ', $this->separator(), trim($slug)); + if ($this->utmConfiguration->isLowercaseEnforced()) { + $slug = mb_strtolower($slug); + } + + return $slug; + } + + /** + * Runs SmartLinkValidator::validateUtmParameters() on the submitted values: against the + * chosen taxonomy, and with the values the link carried before the edit as allowed extras + * (a stored value outside the list can be saved unchanged: it was chosen when the list + * allowed it, and a plain re-save must never error). + */ + private function validateUtmParameters(mixed $values, ExecutionContextInterface $context): void + { + $form = $context->getObject(); + if (!$form instanceof FormInterface) { + return; + } + + // The model rebuilds the values (lowercase, filtered) in saveEntity(); the form hands + // the raw array: keys the user left empty are removed before validating. + $submitted = []; + foreach (is_array($values) ? $values : [] as $key => $value) { + if (\is_string($value) && '' !== trim($value)) { + $submitted[(string) $key] = trim($value); + } + } + + $this->addViolations($context, $this->validator->validateUtmParameters( + $submitted, + $this->submittedTaxonomy($form), + $this->originalUtmParameters + )); + } + + /** + * @param list}> $errors + */ + private function addViolations(ExecutionContextInterface $context, array $errors): void + { + foreach ($errors as [$key, $parameters]) { + $context->buildViolation($key)->setParameters($parameters)->addViolation(); + } + } +} diff --git a/Form/Type/SmartLinksConfigType.php b/Form/Type/SmartLinksConfigType.php new file mode 100644 index 0000000..ca46c52 --- /dev/null +++ b/Form/Type/SmartLinksConfigType.php @@ -0,0 +1,50 @@ + Configuration: the general UTM rules and + * the short link domain (section "UTM Settings"), the catalog and custom parameters (section + * "Parameters"). Each child is a local.php parameter. + * + * @extends AbstractType> + */ +final class SmartLinksConfigType extends AbstractType +{ + /** Stored in local.php under this key (an array: short_link_domain => domain). */ + public const CONFIG_PARAMETER = 'smartlinks_config'; + + /** Key of the UtmManagerBundle era (< 0.5.0); still honored until the domain is saved again. */ + public const LEGACY_CONFIG_PARAMETER = 'utm_manager_smart_links'; + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + // The general rules and the parameters: read everywhere through UtmConfigurationProvider. + $builder->add(UtmConfigurationProvider::CONFIG_PARAMETER, SmartlinksSettingsType::class); + + $builder->add(self::CONFIG_PARAMETER, FormType::class, ['label' => false]); + + $builder->get(self::CONFIG_PARAMETER)->add('short_link_domain', TextType::class, [ + 'label' => 'mautic.smartlinks.settings.short_link_domain', + 'required' => false, + 'attr' => [ + 'class' => 'form-control', + 'tooltip' => 'mautic.smartlinks.settings.short_link_domain.tooltip', + ], + ]); + } + + public function getBlockPrefix(): string + { + // The Configuration tab title key: mautic.config.tab.smartlinksconfig. + return 'smartlinksconfig'; + } +} \ No newline at end of file diff --git a/Form/Type/SmartlinksSettingsType.php b/Form/Type/SmartlinksSettingsType.php new file mode 100644 index 0000000..5f4da13 --- /dev/null +++ b/Form/Type/SmartlinksSettingsType.php @@ -0,0 +1,90 @@ +> + */ +final class SmartlinksSettingsType extends AbstractType +{ + public function __construct( + private readonly UtmParameterCatalog $catalog, + private readonly UtmSettingsTransformer $transformer, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + $builder->add('enforce_lowercase', YesNoButtonGroupType::class, [ + 'label' => 'mautic.smartlinks.config.enforce_lowercase', + 'attr' => ['tooltip' => 'mautic.smartlinks.config.enforce_lowercase.tooltip'], + ]); + + $builder->add('separator_replacement', ChoiceType::class, [ + 'label' => 'mautic.smartlinks.config.separator_replacement', + 'choices' => [ + 'mautic.smartlinks.config.separator.hyphen' => '-', + 'mautic.smartlinks.config.separator.underscore' => '_', + 'mautic.smartlinks.config.separator.dot' => '.', + ], + 'placeholder' => false, + 'attr' => [ + 'class' => 'form-control', + 'tooltip' => 'mautic.smartlinks.config.separator_replacement.tooltip', + ], + 'invalid_message' => 'mautic.smartlinks.config.error.separator_invalid', + ]); + + $parameters = $builder->create('parameters', FormType::class, ['label' => false]); + foreach ($this->catalog->all() as $key => $definition) { + $parameters->add($key, UtmParameterType::class, ['definition' => $definition]); + } + $builder->add($parameters); + + $builder->add('custom_parameters', CollectionType::class, [ + 'label' => false, + 'entry_type' => UtmParameterType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'prototype' => true, + 'prototype_name' => '__param__', + 'prototype_data' => [ + 'key' => '', + 'enabled' => true, + 'label' => '', + 'mode' => UtmParameterMode::FREE, + 'values' => [], + ], + 'by_reference' => false, + 'error_bubbling' => false, + 'required' => false, + ]); + + $builder->addModelTransformer($this->transformer); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults(['label' => false]); + } + + public function getBlockPrefix(): string + { + return 'smartlinks_utm_settings'; + } +} diff --git a/Form/Type/UtmParameterType.php b/Form/Type/UtmParameterType.php new file mode 100644 index 0000000..0eb8944 --- /dev/null +++ b/Form/Type/UtmParameterType.php @@ -0,0 +1,219 @@ +> + */ +final class UtmParameterType extends AbstractType +{ + public function __construct( + private readonly UtmSettingsValidator $validator, + private readonly TranslatorInterface $translator, + ) { + } + + /** + * Labels are written to local.php, where "%" would be read as a container parameter. + * + * @return Constraint[] + */ + public static function labelConstraints(): array + { + return [ + new NotBlank(message: 'mautic.smartlinks.config.error.label_required'), + new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mautic.smartlinks.config.error.label_length'), + new Regex(pattern: '/%/', match: false, message: 'mautic.smartlinks.config.error.label_invalid'), + ]; + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + /** @var UtmParameterDefinition|null $definition */ + $definition = $options['definition']; + $allowedModes = $definition?->getAllowedModes() ?? UtmParameterMode::ALL; + + if (null === $definition) { + $builder->add('key', TextType::class, [ + 'label' => 'mautic.smartlinks.config.parameter.key', + 'attr' => [ + 'class' => 'form-control utm-custom-key', + 'tooltip' => 'mautic.smartlinks.config.parameter.key.tooltip', + 'maxlength' => 41, + ], + 'constraints' => [ + new NotBlank(message: 'mautic.smartlinks.config.error.key_required'), + new Callback(callback: $this->validateCustomKey(...)), + ], + ]); + } + + $builder->add('enabled', YesNoButtonGroupType::class, [ + 'label' => 'mautic.smartlinks.config.parameter.enabled', + ]); + + $builder->add('label', TextType::class, [ + 'label' => 'mautic.smartlinks.config.parameter.label', + 'attr' => ['class' => 'form-control', 'maxlength' => UtmSettingsValidator::MAX_LENGTH], + 'constraints' => self::labelConstraints(), + ]); + + $modeAttr = ['class' => 'form-control utm-mode']; + if ($definition?->autoGenerated) { + $modeAttr['tooltip'] = 'mautic.smartlinks.config.auto_generated.tooltip'; + } + + $builder->add('mode', ChoiceType::class, [ + 'label' => 'mautic.smartlinks.config.parameter.mode', + 'choices' => array_combine( + array_map(fn (string $mode): string => 'mautic.smartlinks.config.mode.'.$mode, $allowedModes), + $allowedModes + ), + 'placeholder' => false, + 'attr' => $modeAttr, + 'invalid_message' => 'mautic.smartlinks.config.error.mode_invalid', + 'constraints' => [new NotBlank(message: 'mautic.smartlinks.config.error.mode_invalid')], + ]); + + // Values only exist in dropdown mode: drop anything submitted for other modes (or for parameters + // that can't be dropdowns) before it is processed. + $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void { + $data = $event->getData(); + if (is_array($data) && (UtmParameterMode::DROPDOWN !== ($data['mode'] ?? null) || !$event->getForm()->has('values'))) { + unset($data['values']); + $event->setData($data); + } + }); + + if (!in_array(UtmParameterMode::DROPDOWN, $allowedModes, true)) { + return; + } + + $builder->add('values', CollectionType::class, [ + 'label' => false, + 'entry_type' => UtmValueType::class, + 'allow_add' => true, + 'allow_delete' => true, + 'prototype' => true, + 'prototype_name' => '__value__', + 'by_reference' => false, + 'error_bubbling' => false, + 'required' => false, + 'constraints' => [new Callback(callback: $this->validateValueList(...))], + ]); + } + + public function buildView(FormView $view, FormInterface $form, array $options): void + { + /** @var UtmParameterDefinition|null $definition */ + $definition = $options['definition']; + + $view->vars['utm_custom'] = null === $definition; + $view->vars['utm_key'] = $definition?->key; + $view->vars['utm_group'] = $definition?->group ?? UtmParameterCatalog::GROUP_CUSTOM; + $view->vars['utm_description_key'] = $definition?->getDescriptionKey(); + $view->vars['utm_auto_generated'] = $definition?->autoGenerated ?? false; + $view->vars['utm_suggestions'] = array_map( + fn (string $value): array => [ + 'value' => $value, + 'label' => $this->translator->trans(UtmParameterDefinition::getSuggestionLabelKey($value)), + ], + $definition?->suggestions ?? [] + ); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'definition' => null, + 'label' => false, + ]); + $resolver->setAllowedTypes('definition', ['null', UtmParameterDefinition::class]); + } + + public function getBlockPrefix(): string + { + return 'utm_parameter'; + } + + private function validateCustomKey(mixed $key, ExecutionContextInterface $context): void + { + $key = (string) $key; + if ('' === $key) { + return; + } + + $errors = $this->validator->validateCustomKey($key); + + $keyForm = $context->getObject(); + $collection = $keyForm instanceof FormInterface ? $keyForm->getParent()?->getParent() : null; + if ([] === $errors && null !== $collection) { + $keys = []; + foreach ($collection as $parameterForm) { + if ($parameterForm->has('key')) { + $keys[] = (string) $parameterForm->get('key')->getData(); + } + } + $errors = $this->validator->validateKeyIsUnique($key, $keys); + } + + $this->addViolations($context, $errors); + } + + private function validateValueList(mixed $values, ExecutionContextInterface $context): void + { + $valuesForm = $context->getObject(); + $parameter = $valuesForm instanceof FormInterface ? $valuesForm->getParent() : null; + if (null === $parameter) { + return; + } + + $errors = $this->validator->validateValueList( + (string) $parameter->get('mode')->getData(), + (bool) $parameter->get('enabled')->getData(), + array_values(is_array($values) ? $values : []) + ); + + $this->addViolations($context, $errors); + } + + /** + * @param list}> $errors + */ + private function addViolations(ExecutionContextInterface $context, array $errors): void + { + foreach ($errors as [$message, $parameters]) { + $context->buildViolation($message) + ->setParameters($parameters) + ->setTranslationDomain('validators') + ->addViolation(); + } + } +} diff --git a/Form/Type/UtmTaxonomyType.php b/Form/Type/UtmTaxonomyType.php new file mode 100644 index 0000000..63446cc --- /dev/null +++ b/Form/Type/UtmTaxonomyType.php @@ -0,0 +1,368 @@ + + */ +final class UtmTaxonomyType extends AbstractType +{ + public function __construct( + private readonly UtmConfigurationProvider $utmConfiguration, + private readonly UtmTaxonomyValidator $validator, + ) { + } + + public function buildForm(FormBuilderInterface $builder, array $options): void + { + $builder->add('name', TextType::class, [ + 'label' => 'mautic.smartlinks.taxonomies.name', + 'required' => true, + 'attr' => [ + 'class' => 'form-control', + 'maxlength' => UtmTaxonomy::NAME_MAX_LENGTH, + 'tooltip' => 'mautic.smartlinks.taxonomies.name.tooltip', + ], + 'constraints' => [ + new NotBlank(message: 'mautic.smartlinks.taxonomies.error.name_required'), + new Length(max: UtmTaxonomy::NAME_MAX_LENGTH, maxMessage: 'mautic.smartlinks.taxonomies.error.name_length'), + new Callback(callback: $this->validateName(...)), + ], + ]); + + $builder->add('description', TextareaType::class, [ + 'label' => 'mautic.smartlinks.taxonomies.description', + 'required' => false, + 'attr' => [ + 'class' => 'form-control', + 'tooltip' => 'mautic.smartlinks.taxonomies.description.tooltip', + 'rows' => 3, + ], + ]); + + $this->buildParameters($builder); + + $builder->add('buttons', FormButtonsType::class); + + if (!empty($options['action'])) { + $builder->setAction($options['action']); + } + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => UtmTaxonomy::class, + ]); + } + + public function getBlockPrefix(): string + { + return 'smartlinks_utm_taxonomy'; + } + + /** + * The values section: one field per enabled parameter. Dropdown parameters offer the + * admin's values as checkboxes; free ones get an editable textarea (one value per line). + * A transformer maps the children shapes to the stored rows, and the textarea lines are + * validated on POST_SUBMIT (pattern, duplicates). + */ + private function buildParameters(FormBuilderInterface $builder): void + { + $builder->add('parameters', FormType::class, [ + 'label' => false, + 'error_bubbling' => false, + ]); + + $dropdowns = $this->getDropdownParameters(); + $frees = $this->getFreeParameterKeys(); + + foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) { + if (isset($dropdowns[$key])) { + $attr = ['class' => 'utm-taxonomy-values']; + if ([] === $dropdowns[$key]) { + $attr['tooltip'] = 'mautic.smartlinks.taxonomies.no_values.tooltip'; + } + + $builder->get('parameters')->add($key, ChoiceType::class, [ + 'label' => (string) $parameter['label'], + 'required' => false, + 'multiple' => true, + 'expanded' => true, + 'choices' => array_flip($dropdowns[$key]), + 'attr' => $attr, + ]); + + continue; + } + + if (in_array($key, $frees, true)) { + $builder->get('parameters')->add($key, TextareaType::class, [ + 'label' => (string) $parameter['label'], + 'required' => false, + 'attr' => [ + 'class' => 'form-control utm-taxonomy-free-values', + 'rows' => 2, + 'tooltip' => 'mautic.smartlinks.taxonomies.free_values.tooltip', + 'placeholder' => 'mautic.smartlinks.taxonomies.free_values.placeholder', + ], + ]); + } + } + + $builder->get('parameters')->addModelTransformer(new CallbackTransformer( + fn (mixed $rows): array => $this->rowsToChildren($rows, $dropdowns, $frees), + fn (mixed $children): array => $this->childrenToRows($children, $dropdowns, $frees), + )); + + $builder->get('parameters')->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($frees): void { + $form = $event->getForm(); + + foreach ($frees as $key) { + if (!$form->has($key)) { + continue; + } + + $rows = $this->parseTextarea((string) $form->get($key)->getData()); + $this->addErrorsOn($form->get($key), $this->validator->validateValues($rows)); + } + }); + } + + /** + * The admin's dropdown parameters: key => [value => label]. + * + * @return array> + */ + private function getDropdownParameters(): array + { + $dropdowns = []; + + foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) { + if (UtmParameterMode::DROPDOWN !== $parameter['mode']) { + continue; + } + + // Present even when the admin hasn't configured values yet: the parameter stays + // visible on the form (an empty checkbox list), mirroring the settings. + $dropdowns[$key] = []; + foreach ($this->utmConfiguration->getDropdownValues($key) as $row) { + $dropdowns[$key][$row['value']] = $row['label']; + } + } + + return $dropdowns; + } + + /** + * The parameters the admin left free text: they get an editable value list here. + * + * @return list + */ + private function getFreeParameterKeys(): array + { + $free = []; + + foreach ($this->utmConfiguration->getEnabledParameters() as $key => $parameter) { + if (UtmParameterMode::FREE === $parameter['mode']) { + $free[] = $key; + } + } + + return $free; + } + + /** + * The stored rows become the children data: checkbox arrays for dropdowns (only the + * values the admin still configures stay checked), one-value-per-line text for the + * free ones (a `value;Label` line when the label differs from the value). + * + * @param array> $dropdowns + * @param list $frees + * + * @return array + */ + private function rowsToChildren(mixed $rows, array $dropdowns, array $frees): array + { + $children = []; + foreach (array_keys($dropdowns) as $key) { + $children[$key] = []; + } + foreach ($frees as $key) { + $children[$key] = ''; + } + + foreach (is_array($rows) ? $rows : [] as $key => $list) { + if (!\is_array($list) || !\array_key_exists((string) $key, $children)) { + continue; + } + + if (\is_array($children[$key])) { + $children[$key] = []; + } else { + $children[$key] = ''; + } + + $lines = []; + foreach ($list as $row) { + $value = \is_array($row) ? (string) ($row['value'] ?? '') : ''; + if ('' === $value) { + continue; + } + + if (isset($dropdowns[$key])) { + if (isset($dropdowns[$key][$value])) { + $children[$key][] = $value; + } + + continue; + } + + $label = \is_array($row) ? trim((string) ($row['label'] ?? '')) : ''; + $lines[] = ('' !== $label && $label !== $value) ? $value.';'.$label : $value; + } + + if (\is_string($children[$key])) { + $children[$key] = implode("\n", $lines); + } + } + + return $children; + } + + /** + * Back to the stored shape: checkbox arrays become rows with the admin's labels, + * textarea lines become rows (labels default to the value); empty lists drop the key. + * + * @param array> $dropdowns + * @param list $frees + * + * @return array> + */ + private function childrenToRows(mixed $children, array $dropdowns, array $frees): array + { + $rows = []; + + foreach (is_array($children) ? $children : [] as $key => $data) { + if (isset($dropdowns[$key])) { + $clean = []; + foreach (\is_array($data) ? $data : [] as $value) { + $value = (string) $value; + if (isset($dropdowns[$key][$value]) && !isset($clean[$value])) { + $clean[$value] = ['value' => $value, 'label' => $dropdowns[$key][$value]]; + } + } + + if ([] !== $clean) { + $rows[$key] = array_values($clean); + } + + continue; + } + + if (!in_array((string) $key, $frees, true)) { + continue; + } + + $clean = []; + foreach ($this->parseTextarea((string) $data) as [$value, $label]) { + if (!isset($clean[$value])) { + $clean[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value]; + } + } + + if ([] !== $clean) { + $rows[$key] = array_values($clean); + } + } + + ksort($rows); + + return $rows; + } + + /** + * One value (or `value;Label`) per line. + * + * @return list + */ + private function parseTextarea(string $text): array + { + $parsed = []; + + foreach (preg_split('/\r?\n/', $text) ?: [] as $line) { + $line = trim($line); + if ('' === $line) { + continue; + } + + $parts = explode(';', $line, 2); + $parsed[] = [trim($parts[0]), isset($parts[1]) ? trim($parts[1]) : '']; + } + + return $parsed; + } + + /** + * Runs UtmTaxonomyValidator::validateName() on the typed name, skipping the entity's own. + */ + private function validateName(mixed $name, ExecutionContextInterface $context): void + { + $name = trim((string) $name); + if ('' === $name) { + return; + } + + /** @var FormInterface $form */ + $form = $context->getObject(); + $ignored = $form instanceof FormInterface && $form->getParent()?->getData() instanceof UtmTaxonomy + ? $form->getParent()->getData()->getId() + : null; + + $this->addErrorsOn($form, $this->validator->validateName($name, $ignored)); + } + + /** + * @param FormInterface|FormBuilderInterface $form + * @param list}> $errors + */ + private function addErrorsOn(object $form, array $errors): void + { + foreach ($errors as [$message, $parameters]) { + $form->addError(new FormError($message, null, $parameters)); + } + } +} \ No newline at end of file diff --git a/Form/Type/UtmValueType.php b/Form/Type/UtmValueType.php new file mode 100644 index 0000000..6d2df38 --- /dev/null +++ b/Form/Type/UtmValueType.php @@ -0,0 +1,66 @@ +> + */ +final class UtmValueType extends AbstractType +{ + public function buildForm(FormBuilderInterface $builder, array $options): void + { + $builder->add('value', TextType::class, [ + 'label' => 'mautic.smartlinks.config.values.value', + 'attr' => [ + 'class' => 'form-control utm-value-input', + 'placeholder' => 'mautic.smartlinks.config.values.value', + 'maxlength' => UtmSettingsValidator::MAX_LENGTH, + ], + 'constraints' => [ + new NotBlank(message: 'mautic.smartlinks.config.error.value_required'), + new Length(max: UtmSettingsValidator::MAX_LENGTH, maxMessage: 'mautic.smartlinks.config.error.value_length'), + new Regex(pattern: UtmSettingsValidator::VALUE_PATTERN, message: 'mautic.smartlinks.config.error.value_invalid'), + ], + ]); + + $builder->add('label', TextType::class, [ + 'label' => 'mautic.smartlinks.config.values.label', + 'attr' => [ + 'class' => 'form-control utm-label-input', + 'placeholder' => 'mautic.smartlinks.config.values.label', + 'maxlength' => UtmSettingsValidator::MAX_LENGTH, + ], + 'constraints' => UtmParameterType::labelConstraints(), + ]); + + $builder->add('is_default', CheckboxType::class, [ + 'label' => 'mautic.smartlinks.config.values.default', + 'required' => false, + 'attr' => ['class' => 'utm-value-default'], + ]); + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults(['label' => false]); + } + + public function getBlockPrefix(): string + { + return 'utm_value'; + } +} diff --git a/Form/UtmFieldsApplicator.php b/Form/UtmFieldsApplicator.php new file mode 100644 index 0000000..b4d38c6 --- /dev/null +++ b/Form/UtmFieldsApplicator.php @@ -0,0 +1,253 @@ + configuration keys. utm_term has no native field and is left alone. + */ + public const FIELDS = [ + 'utmSource' => 'utm_source', + 'utmMedium' => 'utm_medium', + 'utmCampaign' => 'utm_campaign', + 'utmContent' => 'utm_content', + ]; + + /** Native options carried over to the select. */ + private const KEPT_OPTIONS = ['label_attr', 'constraints', 'help', 'help_attr', 'help_html', 'help_translation_parameters']; + + public function __construct( + private readonly UtmConfigurationProvider $configurationProvider, + private readonly UtmParameterCatalog $catalog, + private readonly TranslatorInterface $translator, + ) { + } + + public function apply(FormBuilderInterface $builder): void + { + // Fields are rebuilt once the stored values are known, to offer legacy values as choices. + $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event): void { + $this->buildFields($event->getForm(), $event->getData()); + }); + + // A value posted for a removed field would raise an "extra fields" error: drop it. + $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event): void { + $data = $event->getData(); + if (!is_array($data)) { + return; + } + + foreach ($this->getDisabledFields() as $field) { + unset($data[$field]); + } + $event->setData($data); + }); + + // A removed field leaves its key untouched in the stored array: clear it so no stale value survives. + $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event): void { + $data = $event->getData(); + if (null !== $data && !is_array($data)) { + return; + } + + $data ??= []; + foreach ($this->getDisabledFields() as $field) { + // null, as the native empty field: an empty string would add "utm_x=" to every link. + $data[$field] = null; + } + $event->setData($data); + }); + } + + /** + * @param FormInterface $form + */ + private function buildFields(FormInterface $form, mixed $storedTags): void + { + $storedTags = is_array($storedTags) ? $storedTags : []; + $nativeOrder = array_keys($form->all()); + + foreach (self::FIELDS as $field => $key) { + if (!$form->has($field)) { + continue; + } + + $parameter = $this->configurationProvider->getParameter($key); + if (null === $parameter) { + continue; + } + + $mode = $this->getMode($parameter); + if (UtmParameterMode::DISABLED === $mode) { + $form->remove($field); + continue; + } + + $label = $this->getCustomLabel($key, $parameter); + + if (UtmParameterMode::DROPDOWN === $mode) { + $this->addDropdown($form, $field, $key, $label, $storedTags[$field] ?? null); + } elseif (null !== $label) { + $this->replaceField($form, $field, null, ['label' => $label]); + } + } + + // A replaced field is appended last: re-append every field in core's order. + foreach ($nativeOrder as $name) { + if ($form->has($name)) { + $child = $form->get($name); + $form->remove($name); + $form->add($child); + } + } + } + + /** + * @param FormInterface $form + */ + private function addDropdown(FormInterface $form, string $field, string $key, ?string $label, mixed $stored): void + { + // A non-scalar value can't be shown in a select: keep the native field rather than lose it. + if (null !== $stored && !is_scalar($stored)) { + return; + } + + // value => label, in configured order. Numeric values become int keys: compare as strings. + $labels = []; + foreach ($this->configurationProvider->getDropdownValues($key) as $row) { + $labels[(string) $row['value']] = (string) $row['label']; + } + + $options = []; + $storedValue = null === $stored ? '' : (string) $stored; + if ('' !== $storedValue && !array_key_exists($storedValue, $labels)) { + // Legacy value: kept as the last choice so it displays and re-saves without data loss. + $labels[$storedValue] = $this->translator->trans('mautic.smartlinks.form.legacy_choice', ['%value%' => $storedValue]); + $options['help'] = 'mautic.smartlinks.form.legacy_warning'; + $options['help_attr'] = ['class' => 'text-warning']; + } elseif ([] === $labels) { + $options['help'] = 'mautic.smartlinks.form.no_values'; + $options['help_attr'] = ['class' => 'text-warning']; + } + + $options += [ + 'choices' => array_map('strval', array_keys($labels)), + 'choice_label' => static fn (string $value): string => $labels[$value], + // Configured labels are shown as typed. The placeholder is translated here for the same reason. + 'choice_translation_domain' => false, + 'placeholder' => $this->translator->trans('mautic.smartlinks.form.choose'), + 'required' => false, + 'multiple' => false, + 'expanded' => false, + 'attr' => ['class' => 'form-control'], + 'invalid_message' => 'mautic.smartlinks.form.error.not_in_taxonomy', + ]; + + if (null !== $label) { + $options['label'] = $label; + } + + $this->replaceField($form, $field, ChoiceType::class, $options); + } + + /** + * Re-adds a field with its native options (label, constraints...) overridden by $options. + * + * @param FormInterface $form + * @param class-string|null $type null keeps the native type and all native options + * @param array $options + */ + private function replaceField(FormInterface $form, string $field, ?string $type, array $options): void + { + $config = $form->get($field)->getConfig(); + $native = $config->getOptions(); + + if (null === $type) { + $type = $config->getType()->getInnerType()::class; + $options = array_replace($this->getOverridableOptions($native), $options); + } else { + $kept = array_intersect_key($native, array_flip(self::KEPT_OPTIONS)); + $kept += ['label' => $native['label'] ?? null]; + // Our help (legacy warning, empty list) wins over the native one; otherwise keep the native help. + $options = array_replace($kept, $options); + } + + $form->remove($field); + $form->add($field, $type, $options); + } + + /** + * Native options a type accepts again when re-added (resolved-only options are excluded). + * + * @param array $native + * + * @return array + */ + private function getOverridableOptions(array $native): array + { + return array_intersect_key($native, array_flip(['label', 'label_attr', 'attr', 'required', 'constraints', 'help', 'help_attr', 'help_html'])); + } + + /** + * @param array $parameter + */ + private function getMode(array $parameter): string + { + return $parameter['enabled'] ? (string) $parameter['mode'] : UtmParameterMode::DISABLED; + } + + /** + * The configured label, or null when it is the catalog default (the native label is kept then). + * + * @param array $parameter + */ + private function getCustomLabel(string $key, array $parameter): ?string + { + $label = (string) ($parameter['label'] ?? ''); + $definition = $this->catalog->get($key); + + if ('' === $label || (null !== $definition && $label === $this->translator->trans($definition->getLabelKey()))) { + return null; + } + + return $label; + } + + /** + * @return list + */ + private function getDisabledFields(): array + { + $disabled = []; + foreach (self::FIELDS as $field => $key) { + $parameter = $this->configurationProvider->getParameter($key); + if (null !== $parameter && UtmParameterMode::DISABLED === $this->getMode($parameter)) { + $disabled[] = $field; + } + } + + return $disabled; + } +} diff --git a/Form/Validator/SmartLinkValidator.php b/Form/Validator/SmartLinkValidator.php new file mode 100644 index 0000000..6a67ebc --- /dev/null +++ b/Form/Validator/SmartLinkValidator.php @@ -0,0 +1,177 @@ +}> + */ + public function validateSlug(string $slug, ?int $ignoreId = null): array + { + if ('' === $slug) { + return [[self::ERROR_SLUG_REQUIRED, []]]; + } + + if ($this->smartLinkModel->isSlugTaken($slug, $ignoreId)) { + return [[self::ERROR_SLUG_TAKEN, ['%slug%' => $slug]]]; + } + + return []; + } + + /** + * A destination is required for every redirect type: an URL for external ones, a landing + * page or a standalone form for Mautic ones. Only http(s) URLs are accepted. + * + * @return list}> + */ + public function validateDestination(SmartLinkRedirectType $redirectType, ?string $url, ?Page $page = null, ?Form $form = null): array + { + if ($redirectType->isMautic()) { + if (null === $page && null === $form) { + return [[self::ERROR_DESTINATION_REQUIRED_MAUTIC, []]]; + } + + return []; + } + + $url = trim((string) $url); + + if ('' === $url) { + return [[self::ERROR_DESTINATION_REQUIRED, []]]; + } + + if (!filter_var($url, FILTER_VALIDATE_URL) + || !in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'], true)) { + return [[self::ERROR_DESTINATION_INVALID, ['%url%' => $url]]]; + } + + return []; + } + + /** + * UTM values follow the Smart Links Settings the admin defines. With a taxonomy chosen: + * every parameter the taxonomy defines limits the value -- the checkbox subset of the + * admin's values for a dropdown, the taxonomy's own list for a free parameter. The + * values the link carried before the edit stay acceptable (they were chosen when the + * taxonomy — or, before the feature, the global configuration — allowed them), so a plain + * re-save never errors. Without a taxonomy (links that predate the feature, before their + * next edit), the values follow the rules of Smart Links Settings. + * + * @param array $utmParameters + * @param array $stored the values the link carried before the edit + * + * @return list}> + */ + public function validateUtmParameters(array $utmParameters, ?UtmTaxonomy $taxonomy = null, array $stored = []): array + { + if (null === $taxonomy) { + return $this->validateAgainstGlobalConfiguration($utmParameters, $stored); + } + + $errors = []; + + foreach ($utmParameters as $key => $value) { + $parameter = $this->utmConfiguration->getParameter($key); + + if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) { + $errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]]; + + continue; + } + + // Every parameter of the taxonomy limits the value: a dropdown subset selected + // among the admin's values, or the taxonomy's own list for a free parameter. + $allowed = $taxonomy->getParameterValues($key); + + if ([] === $allowed) { + $errors[] = [self::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => $key, '%name%' => (string) $taxonomy->getName()]]; + + continue; + } + + if (in_array($value, array_column($allowed, 'value'), true) || ($stored[$key] ?? null) === $value) { + continue; + } + + $errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]]; + } + + return $errors; + } + + /** + * The rules of Smart Links Settings: the values belong to enabled parameters, respect the + * technical pattern, and dropdown values stay within the configured list — unless the link + * already carried them. + * + * @param array $utmParameters + * @param array $stored + * + * @return list}> + */ + private function validateAgainstGlobalConfiguration(array $utmParameters, array $stored): array + { + $valuePattern = UtmSettingsValidator::VALUE_PATTERN; + $errors = []; + + foreach ($utmParameters as $key => $value) { + $parameter = $this->utmConfiguration->getParameter($key); + + if (null === $parameter || (!$parameter['enabled']) || UtmParameterMode::DISABLED === $parameter['mode']) { + $errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]]; + + continue; + } + + if (1 !== preg_match($valuePattern, $value)) { + $errors[] = [self::ERROR_UTM_VALUE_INVALID, ['%key%' => $key]]; + + continue; + } + + $inList = UtmParameterMode::DROPDOWN !== $parameter['mode'] + || in_array($value, array_column($this->utmConfiguration->getDropdownValues($key), 'value'), true); + + if (!$inList && ($stored[$key] ?? null) !== $value) { + $errors[] = [self::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => $key, '%value%' => $value]]; + } + } + + return $errors; + } +} diff --git a/Form/Validator/UtmSettingsValidator.php b/Form/Validator/UtmSettingsValidator.php new file mode 100644 index 0000000..f609a3e --- /dev/null +++ b/Form/Validator/UtmSettingsValidator.php @@ -0,0 +1,100 @@ +}> + */ + public function validateCustomKey(string $key): array + { + if (1 !== preg_match(UtmParameterCatalog::CUSTOM_KEY_PATTERN, $key)) { + return [[self::ERROR_KEY_INVALID, ['%key%' => $key]]]; + } + + if ($this->catalog->isReservedKey($key)) { + return [[self::ERROR_KEY_RESERVED, ['%key%' => $key]]]; + } + + return []; + } + + /** + * @param string[] $existingKeys All custom keys of the form, including $key itself + * + * @return list}> + */ + public function validateKeyIsUnique(string $key, array $existingKeys): array + { + $occurrences = count(array_filter($existingKeys, fn (string $other): bool => $other === $key)); + + return $occurrences > 1 ? [[self::ERROR_KEY_DUPLICATE, ['%key%' => $key]]] : []; + } + + /** + * Rules that apply to the whole value list of a `dropdown` parameter. Nothing is checked + * for other modes: their values are never processed. + * + * @param array $rows + * + * @return list}> + */ + public function validateValueList(string $mode, bool $enabled, array $rows): array + { + if (UtmParameterMode::DROPDOWN !== $mode) { + return []; + } + + $errors = []; + if ($enabled && [] === $rows) { + $errors[] = [self::ERROR_VALUES_REQUIRED, []]; + } + + $seen = []; + foreach ($rows as $row) { + $value = (string) ($row['value'] ?? ''); + if ('' === $value) { + continue; + } + + if (isset($seen[$value]) && 1 === $seen[$value]) { + $errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]]; + } + $seen[$value] = ($seen[$value] ?? 0) + 1; + } + + $defaults = array_filter($rows, fn (array $row): bool => !empty($row['is_default'])); + if (count($defaults) > 1) { + $errors[] = [self::ERROR_DEFAULT_MULTIPLE, []]; + } + + return $errors; + } +} diff --git a/Form/Validator/UtmTaxonomyValidator.php b/Form/Validator/UtmTaxonomyValidator.php new file mode 100644 index 0000000..967d23a --- /dev/null +++ b/Form/Validator/UtmTaxonomyValidator.php @@ -0,0 +1,73 @@ +}> + */ + public function validateName(string $name, ?int $ignoreId = null): array + { + if (1 !== preg_match('/^[^%{}]+$/', $name)) { + return [[self::ERROR_NAME_CHARACTERS, []]]; + } + + if ($this->taxonomyModel->isNameTaken($name, $ignoreId)) { + return [[self::ERROR_NAME_TAKEN, ['%name%' => $name]]]; + } + + return []; + } + + /** + * The value list of a `free` parameter (its editable textarea): every line must respect + * the technical pattern of the URL values, and duplicates are rejected. + * + * @param list $parsed + * + * @return list}> + */ + public function validateValues(array $parsed): array + { + $errors = []; + $seen = []; + + foreach ($parsed as [$value]) { + if ('' === $value) { + continue; + } + + if (isset($seen[$value]) && 1 === $seen[$value]) { + $errors[] = [self::ERROR_VALUE_DUPLICATE, ['%value%' => $value]]; + } + $seen[$value] = ($seen[$value] ?? 0) + 1; + + if (1 !== preg_match(UtmSettingsValidator::VALUE_PATTERN, $value)) { + $errors[] = [self::ERROR_VALUE_INVALID, ['%value%' => $value]]; + } + } + + return $errors; + } +} \ No newline at end of file diff --git a/Integration/SmartlinksIntegration.php b/Integration/SmartlinksIntegration.php new file mode 100644 index 0000000..22b85fa --- /dev/null +++ b/Integration/SmartlinksIntegration.php @@ -0,0 +1,32 @@ +\Migrations\` per file; duplicate class names are fatal). + → The incoming Smart Links migrations are renamed with a suffix, e.g. + `Version_0_2_0.php` → `Version_0_2_0_SmartLinks.php` (class renamed accordingly). + Their `shouldExecute()` schema checks are unchanged, so nothing re-runs. +4. **Plugin row**: the two rows (`SmartlinksBundle` 0.6.0, `MT3SMarketingProgramBundle` 0.17.0) + become ONE: keep this repo's row (version bumped to `0.18.0`), delete the `SmartlinksBundle` + row. The engine replays every migration through its schema checks on reload — all no-op. +5. **Permissions (role re-grant)**: the categories `smart_links` and `taxonomies` move under + the host permission class, so their base becomes `mt3smarketingprogram:smart_links:*` / + `mt3smarketingprogram:taxonomies:*`. Stored role grants referencing the old + `smartlinks:*` base must be re-granted once (dev DB: admin only, zero impact; production: + one-time re-grant, same as the 0.5.0 rename). +6. **Routes keep their names** (`mautic_smartlinks_*`) and paths (`/smart-links`, `/utm-taxonomies`, + `/l/{slug}`): no session, bookmark or saved-list breakage. (Optional later cosmetic pass to + `mt3s_smart_links_*` is noted but not required.) +7. **Menu**: the "Smart Links" group is added as a second top-level entry next to "Programs" — + domains remain separately visible, no icon/id collisions. +8. **Config**: the "Smart Links Settings" tab (`smartlinksconfig` alias) is added alongside + "Program Settings"; its params (`smartlinks_utm_config`, `smartlinks_config` + legacy keys) + move into `Config/config.php` verbatim — saved local.php values keep working, including the + legacy-key fallbacks. +9. **Translations**: the `mautic.smartlinks.*` keys are appended to this repo's + `Translations/{en_US,fr_FR}/messages.ini|validators.ini` (key prefixes are globally unique — + parse-check every file after each edit; a stray quote kills the whole catalog). +10. **Assets**: `smartlinks.js` becomes `Assets/js/mt3s-mp-smartlinks.js` (host file-naming + convention; the mauticContent/OnLoad prefixes it registers are unchanged). +11. **Integrations**: the host keeps `MT3SMarketingProgramIntegration`; the Smart Links + `SmartlinksIntegration` (+ its `ConfigSupport`) move in as additional + `mautic.integration` services — one plugin may register several. +12. **Dev environment**: `docker-compose.yml` drops the `PLUGIN_SMARTLINKS_PATH` mount; this + repo remains the single `MT3SMarketingProgramBundle` mount. `.env` updated accordingly. +13. **The `mautic-plugin-smartlinks` repo** becomes obsolete after the merge: archive it, don't + delete (it carries `pre-merge-v1` and the full history). + +## Procedure (step by step) + +All work happens on a branch `merge-smartlinks` of THIS repo. The `mautic-plugin-smartlinks` +repo is read-only source material (already tagged). + +### Phase 1 — import the Smart Links code + +1. From `mautic-plugin-smartlinks`, copy into this repo (paths unchanged): + `Catalog/`, `Controller/` (the 3 Smart Links controllers), `Entity/` (3 entities + 3 + repositories), `EventListener/` (`SmartLinksConfigSubscriber`, `PluginInstallSubscriber`), + `Form/` (types, validators, transformer, applicator, extension), `Integration/` + (Smartlinks integration + ConfigSupport), `Model/` (2 models), `Resources/views/SmartLink/`, + `Resources/views/UtmTaxonomy/`, `Resources/views/FormTheme/Config/`, `Service/` (3 services), + `Assets/img/` (icon), `Tests/Unit/…` (the smartlinks tests). +2. Textual namespace remap in every copied file: + `MauticPlugin\SmartlinksBundle\` → `MauticPlugin\MT3SMarketingProgramBundle\`. +3. `Assets/js/smartlinks.js` → `Assets/js/mt3s-mp-smartlinks.js` (contents unchanged). +4. Migrations: copy `Version_0_2_0.php` … `Version_0_6_0.php` renamed to + `Version_0_2_0_SmartLinks.php` … `Version_0_6_0_SmartLinks.php` (class names likewise); + namespace remap; the `TABLE_NAME` constants they reference are unchanged. +5. Gate: `grep -rn "SmartlinksBundle" .` must return zero hits afterwards. + +### Phase 2 — merge Config/config.php + +Add to this repo's `Config/config.php` (keep every existing entry untouched): +- `routes.main`: the 4 Smart Links routes (`mautic_smartlinks_index`, `mautic_smartlinks_action`, + `mautic_smartlinks_taxonomies`, `mautic_smartlinks_taxonomy_action`), controllers re-pointed + at the new namespace; keep `routes.public` `mautic_smartlinks_go` (`/l/{slug}`). +- `menu.main`: the whole `mautic.smartlinks.menu.root` group (UTM Taxonomies above Smart Links), + access arrays re-based to `mt3smarketingprogram:smart_links:*` / `mt3smarketingprogram:taxonomies:*`. +- `services.integrations`: `mt3s.smart_links.integration` + `…integration.configuration` + (host `mt3s.*` id convention; class namespaces remapped). +- `parameters`: `smartlinks_utm_config`, `smartlinks_config`, legacy `utm_manager_config`, + `utm_manager_smart_links` — verbatim. +- Bump `'version'` to `'0.18.0'`; extend `'description'` to mention smart links. + +### Phase 3 — fold permissions, services, config tab + +- `Security/Permissions/MT3SMarketingProgramPermissions.php`: add + `$this->addExtendedPermissions('smart_links'); $this->addExtendedPermissions('taxonomies');` + and the matching `addExtendedFormFields('mt3smarketingprogram', 'smart_links'|'taxonomies', …)` + lines; do NOT copy `SmartlinksPermissions.php` into the bundle. +- `Config/services.php`: add the model aliases + `mautic.smartlinks.model.smart_link` / `mautic.smartlinks.model.utm_taxonomy` + (plus `mt3s.smart_links.model.*` aliases if wanted); nothing else — autoconfiguration + picks up the new classes. +- `SmartLinksConfigSubscriber`: verify the `'bundle' => 'MT3SMarketingProgramBundle'` entry and + the `@Smartlinks/FormTheme/Config/…` twig paths (the twig namespace follows the bundle name). + +### Phase 4 — translations + +Append the `mautic.smartlinks.*` keys from the source repo's 4 ini files into this repo's +4 ini files (same keys, no renames; the `SmartlinksConfigSubscriber` tab key +`mautic.config.tab.smartlinksconfig` comes along). **Parse-check all 4 files after every +edit** — `parse_ini_file()` must not return `false` (a single stray quote kills the whole +catalog, as happened in 0.6.0). + +### Phase 5 — dev environment + database registration + +1. `mautic-dev-env/docker-compose.yml`: remove the `PLUGIN_SMARTLINKS_PATH` mount line; + `.env` + `.env.example`: remove the variable. +2. `docker compose up -d` (recreates the containers with the single mount). +3. Database: `DELETE FROM plugins WHERE bundle='SmartlinksBundle';` and + `UPDATE plugins SET version='0.18.0' WHERE bundle='MT3SMarketingProgramBundle';` +4. Stop the background containers, then: + `./dev.sh cc && ./dev.sh console mautic:plugins:reload` + then restart them (they race the cache clear; the web container also needs a restart + afterwards when opcache validates timestamps off). +5. `./dev.sh console mautic:assets:generate`. + +### Phase 6 — verification checklist + +- [ ] `php -l` over every file; full ini parse-check (4 files) +- [ ] Plugin row: ONE `MT3SMarketingProgramBundle` 0.18.0; Plugins page shows "MT3S Marketing Program" +- [ ] Menu: "Programs" group (5 children) AND "Smart Links" group (UTM Taxonomies, Smart Links) +- [ ] Config: "Program Settings" tab AND "Smart Links Settings" tab (UTM Settings + Parameters) +- [ ] Smart Links: list/create/edit; taxonomy select + fieldsets; out-of-list value rejected +- [ ] UTM Taxonomies: list/create/edit (checkbox subsets + free-value lists) +- [ ] Public redirect: `curl -sI -H 'Host: ' http://localhost:8080/l/` + → 302 with UTM parameters on the Location; hits recorded in `smart_link_hits` +- [ ] Marketing Program pages: programs, tasks, stakeholders, audiences, item types all load +- [ ] Translations: no raw `mautic.*` keys anywhere (en + fr) +- [ ] Roles: re-grant `mt3smarketingprogram:smart_links:*` / `…:taxonomies:*` where needed +- [ ] Tests: `php /tmp/phpunit.phar --do-not-cache-result -c + docroot/plugins/MT3SMarketingProgramBundle/phpunit.xml.dist` (merged suites, both domains) +- [ ] Legacy data: `smart_links` / `utm_taxonomies` rows intact; `mt3s_mp_*` tables untouched + +### Phase 7 — finalize + +1. `readme.md`: add the Smart Links domain section (structure, short links, taxonomies, + public redirect, tests). +2. Commit `feat: merge Smartlinks into MT3S Marketing Program (smart links + UTM taxonomies)`; + push; tag `post-merge-v1`; archive `mautic-plugin-smartlinks`. +3. Rollback at any point: `git reset --hard pre-merge-v1` in this repo — the source repo is + untouched throughout the merge. + +## Risk register + +| Risk | Mitigation | +|---|---| +| Migration class-name collision → fatal reload | Phase 1.4 renames the incoming set; verify no duplicate class names in `Migrations/` | +| Broken translation catalog (stray quote) | Phase 4 parse-check after every edit | +| `cache:clear` races / opcache staleness | stop cron+worker, `dev.sh cc`, restart the web container | +| Permission base change breaks saved roles | Phase 6 re-grant checklist (documented, one-time) | +| Missed namespace reference | Phase 1.5 grep gate: zero `SmartlinksBundle` hits | +| Data loss | none by design: no schema/data migration; `pre-merge-v1` tags on both repos | \ No newline at end of file diff --git a/Migrations/Version_0_2_0_SmartLinks.php b/Migrations/Version_0_2_0_SmartLinks.php new file mode 100644 index 0000000..e4f2190 --- /dev/null +++ b/Migrations/Version_0_2_0_SmartLinks.php @@ -0,0 +1,54 @@ +hasTable($this->concatPrefix(SmartLink::TABLE_NAME)); + } + + protected function up(): void + { + $table = $this->concatPrefix(SmartLink::TABLE_NAME); + + $this->addSql(<<hasTable($this->concatPrefix(SmartLinkHit::TABLE_NAME)); + } + + protected function up(): void + { + $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); + + $table = $this->concatPrefix(SmartLinkHit::TABLE_NAME); + + $this->addSql(<<addSql($this->generateAlterTableForeignKeyStatement( + SmartLinkHit::TABLE_NAME, + ['smart_link_id'], + $this->resolveLinksTableName($schema), + ['id'], + 'ON DELETE CASCADE' + )); + } + + /** + * The links table under the name it has right now: Version_0_5_0 renames utm_smart_links to + * smart_links, and an update from 0.2.0 runs this migration before the rename. + */ + private function resolveLinksTableName(Schema $schema): string + { + return $schema->hasTable($this->concatPrefix('smart_links')) ? 'smart_links' : 'utm_smart_links'; + } +} diff --git a/Migrations/Version_0_4_0_SmartLinks.php b/Migrations/Version_0_4_0_SmartLinks.php new file mode 100644 index 0000000..09b51f4 --- /dev/null +++ b/Migrations/Version_0_4_0_SmartLinks.php @@ -0,0 +1,97 @@ + referenced core table. + */ + private const FOREIGN_KEYS = [ + 'page_id' => 'pages', + 'form_id' => 'forms', + ]; + + protected function isApplicable(Schema $schema): bool + { + $table = $this->getTable($schema); + + if (null === $table) { + return false; + } + + foreach (array_keys(self::FOREIGN_KEYS) as $column) { + if (!$table->hasColumn($column)) { + return true; + } + } + + return [] !== $this->getMissingForeignKeys($table); + } + + protected function up(): void + { + $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); + $table = $this->getTable($schema); + + if (null === $table) { + return; + } + + foreach (array_keys(self::FOREIGN_KEYS) as $column) { + if (!$table->hasColumn($column)) { + $this->addSql(sprintf( + 'ALTER TABLE %s ADD %s INT UNSIGNED DEFAULT NULL', + $this->concatPrefix(SmartLink::TABLE_NAME), + $column + )); + } + } + + foreach ($this->getMissingForeignKeys($table) as $column => $referenceTable) { + $this->addSql($this->generateAlterTableForeignKeyStatement( + SmartLink::TABLE_NAME, + [$column], + $referenceTable, + ['id'], + 'ON DELETE SET NULL' + )); + } + } + + private function getTable(Schema $schema): ?Table + { + $name = $this->concatPrefix(SmartLink::TABLE_NAME); + + return $schema->hasTable($name) ? $schema->getTable($name) : null; + } + + /** + * @return array + */ + private function getMissingForeignKeys(Table $table): array + { + $missing = self::FOREIGN_KEYS; + + foreach ($table->getForeignKeys() as $foreignKey) { + foreach ($foreignKey->getLocalColumns() as $column) { + unset($missing[$column]); + } + } + + return $missing; + } +} diff --git a/Migrations/Version_0_5_0_SmartLinks.php b/Migrations/Version_0_5_0_SmartLinks.php new file mode 100644 index 0000000..a62928d --- /dev/null +++ b/Migrations/Version_0_5_0_SmartLinks.php @@ -0,0 +1,208 @@ + Smartlinks) also renames its tables and their + * indexes: utm_smart_links -> smart_links and utm_smart_link_hits -> smart_link_hits. + * + * Mautic syncs the plugin schema before running the migrations, so the new tables usually + * already exist (empty, straight from the entity metadata) when this runs: the rows are copied + * from the old tables, which are then dropped (hits first: they still reference the old links + * table). When the new tables don't exist yet (a plugin update without the schema sync) the old + * tables are renamed instead, which keeps the rows, the foreign keys and the indexes. + * + * Installs updated from 0.3.0 skipped the Mautic destinations of Version_0_4_0, which looks for + * the table under its new name: the page_id / form_id columns and their foreign keys are + * re-checked here so every install converges to the same schema. + * + * Idempotent: runs on plugin update (core's migration engine) and right after a fresh install + * (PluginInstallSubscriber), and stops when nothing is left to rename, copy or add. + */ +class Version_0_5_0_SmartLinks extends AbstractMigration +{ + private const RENAMED_TABLES = [ + 'utm_smart_links' => 'smart_links', + 'utm_smart_link_hits' => 'smart_link_hits', + ]; + + private const RENAMED_INDEXES = [ + 'utm_smart_link_slug' => 'smart_link_slug', + 'utm_smart_link_hit_link' => 'smart_link_hit_link', + ]; + + /** Local column => referenced core table (the Mautic destinations of Version_0_4_0). */ + private const MAUTIC_DESTINATIONS = [ + 'page_id' => 'pages', + 'form_id' => 'forms', + ]; + + protected function isApplicable(Schema $schema): bool + { + foreach (array_keys(self::RENAMED_TABLES) as $old) { + if ($schema->hasTable($this->concatPrefix($old))) { + return true; + } + } + + $links = $this->findLinksTable($schema); + if (null !== $links) { + foreach (array_keys(self::MAUTIC_DESTINATIONS) as $column) { + if (!$links->hasColumn($column)) { + return true; + } + } + + if ([] !== $this->getOldIndexes($links) || [] !== $this->getMissingForeignKeys($links)) { + return true; + } + } + + $hits = $this->findHitsTable($schema); + + return null !== $hits && [] !== $this->getOldIndexes($hits); + } + + protected function up(): void + { + $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); + + $emptied = []; + + foreach (self::RENAMED_TABLES as $old => $new) { + $oldTable = $this->findTable($schema, $old); + $newTable = $this->findTable($schema, $new); + + if (null === $oldTable) { + continue; // nothing left under the old name + } + + if (null === $newTable) { + // No schema sync ran: rename keeps the rows, the foreign keys and the indexes. + $this->addSql(sprintf('RENAME TABLE %s TO %s', $this->concatPrefix($old), $this->concatPrefix($new))); + continue; + } + + // The schema sync already created the new table (empty): copy the rows over, then + // drop the old table. Hits reference links, so everything is copied before the + // first DROP (see below). + $columns = implode(', ', array_intersect( + array_keys($newTable->getColumns()), + array_keys($oldTable->getColumns()) + )); + $this->addSql(sprintf( + 'INSERT INTO %s (%s) SELECT %s FROM %s', + $this->concatPrefix($new), + $columns, + $columns, + $this->concatPrefix($old) + )); + $emptied[] = $old; + } + + // Drop the copied-from tables, hits first: their foreign key still references the old links table. + foreach (array_reverse($emptied) as $old) { + $this->addSql(sprintf('DROP TABLE %s', $this->concatPrefix($old))); + } + + $links = $this->findLinksTable($schema); + $hits = $this->findHitsTable($schema); + + if (null === $links) { + return; + } + + // The statements below run after the RENAME TABLE ones, so they target the new names. + foreach ([[SmartLink::TABLE_NAME, $links], [SmartLinkHit::TABLE_NAME, $hits]] as [$name, $table]) { + if (null === $table) { + continue; + } + + foreach ($this->getOldIndexes($table) as $old) { + $this->addSql(sprintf( + 'ALTER TABLE %s DROP INDEX %s, ADD INDEX %s (%s)', + $this->concatPrefix($name), + $old, + self::RENAMED_INDEXES[$old], + implode(', ', $table->getIndex($old)->getColumns()) + )); + } + } + + foreach (array_keys(self::MAUTIC_DESTINATIONS) as $column) { + if (!$links->hasColumn($column)) { + $this->addSql(sprintf( + 'ALTER TABLE %s ADD %s INT UNSIGNED DEFAULT NULL', + $this->concatPrefix(SmartLink::TABLE_NAME), + $column + )); + } + } + + foreach ($this->getMissingForeignKeys($links) as $column => $referenceTable) { + $this->addSql($this->generateAlterTableForeignKeyStatement( + SmartLink::TABLE_NAME, + [$column], + $referenceTable, + ['id'], + 'ON DELETE SET NULL' + )); + } + } + + /** + * The links table under the name it has right now: new on fresh installs, old on installs + * that wait for the RENAME TABLE statements queued above. + */ + private function findLinksTable(Schema $schema): ?Table + { + return $this->findTable($schema, SmartLink::TABLE_NAME) ?? $this->findTable($schema, 'utm_smart_links'); + } + + private function findHitsTable(Schema $schema): ?Table + { + return $this->findTable($schema, SmartLinkHit::TABLE_NAME) ?? $this->findTable($schema, 'utm_smart_link_hits'); + } + + private function findTable(Schema $schema, string $name): ?Table + { + $name = $this->concatPrefix($name); + + return $schema->hasTable($name) ? $schema->getTable($name) : null; + } + + /** + * @return list Indexes still carrying their pre-rename name + */ + private function getOldIndexes(Table $table): array + { + return array_values(array_filter( + array_keys(self::RENAMED_INDEXES), + fn (string $index): bool => $table->hasIndex($index) + )); + } + + /** + * @return array + */ + private function getMissingForeignKeys(Table $table): array + { + $missing = self::MAUTIC_DESTINATIONS; + + foreach ($table->getForeignKeys() as $foreignKey) { + foreach ($foreignKey->getLocalColumns() as $column) { + unset($missing[$column]); + } + } + + return $missing; + } +} diff --git a/Migrations/Version_0_6_0_SmartLinks.php b/Migrations/Version_0_6_0_SmartLinks.php new file mode 100644 index 0000000..b0dbc81 --- /dev/null +++ b/Migrations/Version_0_6_0_SmartLinks.php @@ -0,0 +1,100 @@ +hasTable($this->concatPrefix(UtmTaxonomy::TABLE_NAME)) + || !$this->hasTaxonomyColumn($schema) + || [] !== $this->getMissingForeignKeys($schema); + } + + protected function up(): void + { + $schema = $this->entityManager->getConnection()->createSchemaManager()->introspectSchema(); + + if (!$schema->hasTable($this->concatPrefix(UtmTaxonomy::TABLE_NAME))) { + $table = $this->concatPrefix(UtmTaxonomy::TABLE_NAME); + + $this->addSql(<<hasTaxonomyColumn($schema)) { + $this->addSql(sprintf( + 'ALTER TABLE %s ADD utm_taxonomy_id INT UNSIGNED DEFAULT NULL', + $this->concatPrefix(SmartLink::TABLE_NAME) + )); + } + + foreach ($this->getMissingForeignKeys($schema) as $foreignKey) { + $this->addSql($this->generateAlterTableForeignKeyStatement( + SmartLink::TABLE_NAME, + ['utm_taxonomy_id'], + UtmTaxonomy::TABLE_NAME, + ['id'], + 'ON DELETE SET NULL' + )); + } + } + + private function hasTaxonomyColumn(Schema $schema): bool + { + $links = $this->concatPrefix(SmartLink::TABLE_NAME); + + return $schema->hasTable($links) && $schema->getTable($links)->hasColumn('utm_taxonomy_id'); + } + + /** + * @return list + */ + private function getMissingForeignKeys(Schema $schema): array + { + $links = $this->concatPrefix(SmartLink::TABLE_NAME); + $missing = ['utm_taxonomy_id']; + + if ($schema->hasTable($links)) { + foreach ($schema->getTable($links)->getForeignKeys() as $foreignKey) { + $missing = array_diff($missing, $foreignKey->getLocalColumns()); + } + } + + return array_values($missing); + } +} \ No newline at end of file diff --git a/Model/SmartLinkModel.php b/Model/SmartLinkModel.php new file mode 100644 index 0000000..deaa66e --- /dev/null +++ b/Model/SmartLinkModel.php @@ -0,0 +1,347 @@ + + */ +class SmartLinkModel extends FormModel +{ + public const MODEL_NAME = 'smartlinks.smart_link'; + + /** Random slugs offered by the "Generate" button: 4 characters, letters and digits. */ + public const GENERATED_SLUG_LENGTH = 4; + + public function __construct( + EntityManagerInterface $em, + CorePermissions $security, + EventDispatcherInterface $dispatcher, + UrlGeneratorInterface $router, + TranslatorInterface $translator, + UserHelper $userHelper, + LoggerInterface $logger, + CoreParametersHelper $coreParametersHelper, + private readonly UtmConfigurationProvider $utmConfiguration, + private readonly PageModel $pageModel, + ) { + parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper); + } + + public function getRepository(): SmartLinkRepository + { + $repository = $this->em->getRepository(SmartLink::class); + \assert($repository instanceof SmartLinkRepository); + + return $repository; + } + + public function getPermissionBase(): string + { + return 'mt3smarketingprogram:smart_links'; + } + + public function getEntity($id = null): ?SmartLink + { + if (null === $id) { + return new SmartLink(); + } + + $entity = parent::getEntity($id); + + return $entity instanceof SmartLink ? $entity : null; + } + + /** + * @param array $options + */ + public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface + { + if (!$entity instanceof SmartLink) { + throw new MethodNotAllowedHttpException(['SmartLink']); + } + + if (!empty($action)) { + $options['action'] = $action; + } + + return $formFactory->create(SmartLinkType::class, $entity, $options); + } + + /** + * Applies the UTM Manager settings to everything the user typed (slug and values), then saves. + */ + public function saveEntity($entity, $unlock = true): void + { + if ($entity instanceof SmartLink) { + $this->applySlugRules($entity); + $entity->setUtmParameters($this->normalizeUtmValues($entity->getUtmParameters())); + } + + parent::saveEntity($entity, $unlock); + } + + /** + * Slug rules from Settings > Configuration > UTM Settings: spaces become the configured + * separator (or hyphen), lowercase is enforced when configured. Kept here (not in the form) + * so a manually typed slug, an imported one and a generated one all follow the same rules. + */ + public function applySlugRules(SmartLink $entity, ?string $rawSlug = null): void + { + $raw = $rawSlug ?? (string) ($entity->getSlug() ?? ''); + + $slug = str_replace(' ', $this->utmConfiguration->getSeparatorReplacement(), trim($raw)); + if ($this->utmConfiguration->isLowercaseEnforced()) { + $slug = mb_strtolower($slug); + } + + // The user never edits the slug of a saved link (the form field is disabled): the entity + // keeps the stored one. onPersistentEntityChange checks it in the background. + if (null === $entity->getId()) { + $entity->setSlug('' !== $slug ? $slug : null); + } elseif (null !== $rawSlug) { + $entity->setSlug($slug); // throws when it differs from the stored slug + } + } + + /** + * @param array $utmParameters + * + * @return array + */ + public function normalizeUtmValues(array $utmParameters): array + { + $clean = []; + foreach ($utmParameters as $key => $value) { + $key = trim((string) $key); + $value = trim((string) $value); + if ('' === $key || '' === $value) { + continue; + } + + if ($this->utmConfiguration->isLowercaseEnforced()) { + $value = mb_strtolower($value); + } + + $clean[$key] = $value; + } + ksort($clean); + + return $clean; + } + + /** + * The slug of a saved link never changes; saveEntity() only re-applies the rules to a slug + * the user could have typed on the "new" form. Drops the form value on edit so the immutable + * one is kept. + */ + public function onPersistentEntityChange(SmartLink $entity, ?string $submittedSlug): void + { + $this->applySlugRules($entity, $submittedSlug); + } + + /** + * True when another saved link already uses this slug. $ignoreId keeps a link being + * edited from colliding with itself. + */ + public function isSlugTaken(string $slug, ?int $ignoreId = null): bool + { + return $this->getRepository()->slugExists($slug, $ignoreId); + } + + /** + * The short links domain configured in Settings > Configuration > Smart Links Settings, + * without scheme or trailing slash, for example lnk.example.com. Empty when not configured. + */ + public function getShortLinkDomain(): string + { + $stored = $this->coreParametersHelper->get(\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::CONFIG_PARAMETER, []); + + // Upgrades from < 0.5.0 keep the domain in local.php under the legacy key; serve it until + // the Configuration page is saved again (which writes the new key). + if (!is_array($stored) || '' === trim((string) ($stored['short_link_domain'] ?? ''))) { + $legacy = $this->coreParametersHelper->get(\MauticPlugin\MT3SMarketingProgramBundle\Form\Type\SmartLinksConfigType::LEGACY_CONFIG_PARAMETER, []); + if (is_array($legacy) && '' !== trim((string) ($legacy['short_link_domain'] ?? ''))) { + $stored = $legacy; + } + } + + $domain = trim(is_array($stored) ? (string) ($stored['short_link_domain'] ?? '') : ''); + + return '' === $domain ? '' : rtrim($domain, '/'); + } + + /** + * A random slug of 4 lowercase letters and digits, for example a7f3, that no saved link + * uses yet. Used by the "Generate" button of the form and to prefill a new link. + */ + public function generateSlug(): string + { + $alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'; + + do { + $slug = ''; + for ($i = 0; $i < self::GENERATED_SLUG_LENGTH; ++$i) { + $slug .= $alphabet[random_int(0, strlen($alphabet) - 1)]; + } + } while ($this->isSlugTaken($slug)); + + return $slug; + } + + /** + * The final URL of the redirect, whatever the link's type: the destination with the link's + * UTM parameters appended to its query string. The link's values override same-named + * parameters of the destination; the query of the short link call itself is ignored (the + * stored parameters are the canonical ones). + * + * External redirects go to the configured URL; Mautic redirects go to the public URL of + * the linked landing page (/{slug}) or standalone form (/form/{id}). + */ + public function buildRedirectUrl(SmartLink $link): string + { + $destination = $link->getRedirectType()->isMautic() + ? $this->buildMauticDestinationUrl($link) + : trim((string) $link->getDestinationUrl()); + + return self::appendUtmParameters($destination, $link->getUtmParameters()); + } + + /** + * The public URL of the Mautic destination: the landing page or the standalone form. + * Empty when the link has no (or no longer a) destination. + */ + public function buildMauticDestinationUrl(SmartLink $link): string + { + if (null !== $link->getPage()) { + // PageModel::generateUrl() handles variants, category and language slugs. + return $this->pageModel->generateUrl($link->getPage()); + } + + if (null !== $link->getForm()) { + // Standalone forms have no alias URL: their landing page is the form preview. + return $this->router->generate( + 'mautic_form_preview', + ['id' => $link->getForm()->getId()], + UrlGeneratorInterface::ABSOLUTE_URL + ); + } + + return ''; + } + + /** + * Appends the UTM parameters to a destination URL. Pure static method, unit-testable. + * + * @param array $utms + */ + public static function appendUtmParameters(string $destination, array $utms): string + { + if ([] === $utms || '' === $destination) { + return $destination; + } + + $parts = parse_url($destination); + $query = []; + if (isset($parts['query']) && '' !== $parts['query']) { + parse_str($parts['query'], $query); + } + + // The link's parameters win over the destination's own ones. + $parts['query'] = http_build_query(array_merge($query, $utms)); + + return self::unparseUrl($parts); + } + + /** + * Records one call of the short link (date, IP, referer, user agent). Statistics never + * block the redirect: the controller wraps the call in a try/catch. + */ + public function recordHit(SmartLink $link, Request $request): SmartLinkHit + { + $hit = new SmartLinkHit(); + $hit->setSmartLink($link); + $hit->setIpAddress($request->getClientIp()); + $hit->setReferer($request->headers->get('referer')); + $hit->setUserAgent($request->headers->get('user-agent')); + + $this->em->persist($hit); + $this->em->flush(); + + return $hit; + } + + /** + * Hit counts of every link, in one query: link id => number of hits. + * + * @return array + */ + public function getHitCounts(): array + { + return $this->getHitRepository()->getHitCounts(); + } + + private function getHitRepository(): SmartLinkHitRepository + { + $repository = $this->em->getRepository(SmartLinkHit::class); + \assert($repository instanceof SmartLinkHitRepository); + + return $repository; + } + + /** + * Rebuilds a URL from parse_url() parts (the scheme/host/path/query the destination had). + * + * @param array $parts + */ + private static function unparseUrl(array $parts): string + { + $url = ''; + if (isset($parts['scheme'])) { + $url .= $parts['scheme'].'://'; + } elseif (isset($parts['host'])) { + $url .= '//'; + } + + $url .= $parts['host'] ?? ''; + if (isset($parts['port'])) { + $url .= ':'.$parts['port']; + } + + $url .= $parts['path'] ?? ''; + + if (isset($parts['query'])) { + $url .= '?'.$parts['query']; + } + + if (isset($parts['fragment'])) { + $url .= '#'.$parts['fragment']; + } + + return $url; + } +} diff --git a/Model/UtmTaxonomyModel.php b/Model/UtmTaxonomyModel.php new file mode 100644 index 0000000..22b2ff2 --- /dev/null +++ b/Model/UtmTaxonomyModel.php @@ -0,0 +1,149 @@ + + */ +class UtmTaxonomyModel extends FormModel +{ + public const MODEL_NAME = 'smartlinks.utm_taxonomy'; + + public function __construct( + EntityManagerInterface $em, + CorePermissions $security, + EventDispatcherInterface $dispatcher, + UrlGeneratorInterface $router, + TranslatorInterface $translator, + UserHelper $userHelper, + LoggerInterface $logger, + CoreParametersHelper $coreParametersHelper, + ) { + parent::__construct($em, $security, $dispatcher, $router, $translator, $userHelper, $logger, $coreParametersHelper); + } + + public function getRepository(): UtmTaxonomyRepository + { + $repository = $this->em->getRepository(UtmTaxonomy::class); + \assert($repository instanceof UtmTaxonomyRepository); + + return $repository; + } + + public function getPermissionBase(): string + { + return 'mt3smarketingprogram:taxonomies'; + } + + public function getEntity($id = null): ?UtmTaxonomy + { + if (null === $id) { + return new UtmTaxonomy(); + } + + $entity = parent::getEntity($id); + + return $entity instanceof UtmTaxonomy ? $entity : null; + } + + /** + * @param array $options + */ + public function createForm($entity, FormFactoryInterface $formFactory, $action = null, $options = []): FormInterface + { + if (!$entity instanceof UtmTaxonomy) { + throw new MethodNotAllowedHttpException(['UtmTaxonomy']); + } + + if (!empty($action)) { + $options['action'] = $action; + } + + return $formFactory->create(UtmTaxonomyType::class, $entity, $options); + } + + /** + * Applies the canonical shape to the value lists (trimmed, de-duplicated, sorted), then saves. + */ + public function saveEntity($entity, $unlock = true): void + { + if ($entity instanceof UtmTaxonomy) { + $entity->setParameters($this->normalizeParameters($entity->getParameters())); + } + + parent::saveEntity($entity, $unlock); + } + + /** + * The canonical shape of the `parameters` array: parameter key => list of {value, label} rows. + * Empty keys and values are dropped, duplicates keep their first label, labels fall back to + * the value, keys and rows keep a stable order. The UtmTaxonomyValidator guarantees the + * technical pattern of the values; this is the safety net behind it. + * + * @param array $parameters + * + * @return array> + */ + public function normalizeParameters(array $parameters): array + { + $clean = []; + foreach ($parameters as $key => $rows) { + $key = trim((string) $key); + if ('' === $key || !is_array($rows)) { + continue; + } + + $values = []; + foreach ($rows as $row) { + if (!is_array($row)) { + continue; + } + + $value = trim((string) ($row['value'] ?? '')); + if ('' === $value || isset($values[$value])) { + continue; + } + + $label = trim((string) ($row['label'] ?? '')); + $values[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value]; + } + + if ([] !== $values) { + $clean[$key] = array_values($values); + } + } + + ksort($clean); + + return $clean; + } + + /** + * True when another saved taxonomy already uses this name. $ignoreId keeps a taxonomy being + * edited from colliding with itself. + */ + public function isNameTaken(string $name, ?int $ignoreId = null): bool + { + return $this->getRepository()->nameExists($name, $ignoreId); + } +} \ No newline at end of file diff --git a/Resources/views/FormTheme/Config/_config_smartlinksconfig_widget.html.twig b/Resources/views/FormTheme/Config/_config_smartlinksconfig_widget.html.twig new file mode 100644 index 0000000..cf82232 --- /dev/null +++ b/Resources/views/FormTheme/Config/_config_smartlinksconfig_widget.html.twig @@ -0,0 +1,169 @@ +{# Settings > Configuration > Smart Links Settings: the single tab of the plugin. Section "UTM + Settings": the general rules and the short link domain. Section "Parameters": the catalog and + custom parameters. Behaviour (rows, import, suggestions) lives in Assets/js/smartlinks.js. #} + +{% block _config_smartlinksconfig_widget %} +{% set utm = form.children.smartlinks_utm_config %} +{% set links = form.children.smartlinks_config %} +
{{ 'mautic.smartlinks.settings.description'|trans }}
+{{ form_errors(utm) }} +{{ form_errors(links) }} + + +{% endblock %} + +{# One parameter: accordion panel. #} +{% block utm_parameter_widget %} +{% set fields = form.children %} +{% set isCustom = form.vars.utm_custom %} +{% set bodyId = form.vars.id ~ '_body' %} +{% set hasErrors = formContainsErrors(form) %} +{% set keyText = isCustom ? fields.key.vars.value : form.vars.utm_key %} +
+ +
+
+ {% if form.vars.utm_description_key %} +

{{ form.vars.utm_description_key|trans }}

+ {% endif %} +
+ {% if isCustom %} +
{{ form_row(fields.key) }}
+ {% endif %} +
{{ form_row(fields.label) }}
+
{{ form_row(fields.mode) }}
+
{{ form_row(fields.enabled) }}
+
+ + {% if fields.values is defined %} + {% set values = fields.values %} +
+ {# Hidden unless mode = dropdown, by Mautic's form field state switcher (data-show-on). #} +
+ + {{ form_errors(values) }} +
+
+
{{ 'mautic.smartlinks.config.values.value'|trans }}
+
{{ 'mautic.smartlinks.config.values.label'|trans }}
+
{{ 'mautic.smartlinks.config.values.default'|trans }}
+
+
+ {% for row in values %} + {{ form_widget(row) }} + {% endfor %} +
+

{{ 'mautic.smartlinks.config.values.empty'|trans }}

+ +
+ + {% if form.vars.utm_suggestions is not empty %} + + {% endif %} +
+ + +
+ {# Not a form field: the text is never submitted, the script turns it into value rows. #} + + + + +
+
+
+ {% do values.setRendered() %} + {% endif %} + + {% if isCustom %} + + {% endif %} +
+
+
+{% endblock %} + +{# One allowed value of a dropdown parameter. #} +{% block utm_value_widget %} +{% set fields = form.children %} +
+
+ +
+
+ {{ form_widget(fields.value) }} + {{ form_errors(fields.value) }} +
+
+ {{ form_widget(fields.label) }} + {{ form_errors(fields.label) }} +
+
+ +
+
+ +
+
+{% endblock %} diff --git a/Resources/views/SmartLink/form.html.twig b/Resources/views/SmartLink/form.html.twig new file mode 100644 index 0000000..17b4200 --- /dev/null +++ b/Resources/views/SmartLink/form.html.twig @@ -0,0 +1,71 @@ +{% extends '@MauticCore/Default/content.html.twig' %} + +{% block mauticContent %}smartlinksSmartLink{% endblock %} + +{% block headerTitle %} + {% if form.vars.data.id %} + {{ 'mautic.smartlinks.smart_links.header.edit'|trans({'%slug%': form.vars.data.slug}) }} + {% else %} + {{ 'mautic.smartlinks.smart_links.header.new'|trans }} + {% endif %} +{% endblock %} + +{% block content %} + {{ form_start(form) }} +
+
+
+ {# Short link preview: the slug the user types, on the domain set in Smart Links Settings. #} +
+ {{ 'mautic.smartlinks.smart_links.domain.reminder'|trans }} + {{ form.vars.smart_link_domain ? form.vars.smart_link_domain ~ '/l/' : '' }}{{ form.vars.smart_link_slug }} +
+ + + + {# The UTM taxonomy of the link: its allowed values drive the fields on the right. #} + {{ form_row(form.taxonomy) }} + + {{ form_row(form.redirectType) }} +
+ {{ form_row(form.destinationUrl) }} +
+
+ {{ form_row(form.destination) }} +
+
+
+
+
+

{{ 'mautic.smartlinks.smart_links.utm_parameters'|trans }}

+

{{ 'mautic.smartlinks.smart_links.utm_parameters.help'|trans }}

+ {# One fieldset per taxonomy: Mautic's data-show-on switcher shows the one of the + chosen taxonomy (the container carries the col- class the switcher toggles). #} + {% for taxonomyId, fieldset in form.vars.smart_link_utm_fieldsets %} + + {% endfor %} + {% do form.utmParameters.setRendered() %} +
+
+
+ {{ form_end(form) }} +{% endblock %} diff --git a/Resources/views/SmartLink/list.html.twig b/Resources/views/SmartLink/list.html.twig new file mode 100644 index 0000000..41cec9c --- /dev/null +++ b/Resources/views/SmartLink/list.html.twig @@ -0,0 +1,149 @@ +{% set isIndex = 'index' == tmpl|default('index') ? true : false %} +{% set tmpl = 'list' %} +{% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %} + +{% block mauticContent %}smartlinksSmartLink{% endblock %} + +{% block headerTitle %}{{ 'mautic.smartlinks.smart_links.header.index'|trans }}{% endblock %} + +{% block content %} +
+ {# The toolbar belongs to the full page only: ajax reloads (sort, filter, pagination) + replace the contents of .page-list, so including it here again would duplicate it. #} + {% if isIndex %} + {{- include('@MauticCore/Helper/list_toolbar.html.twig', { + 'searchValue': searchValue, + 'action': currentRoute, + 'page_actions': { + 'templateButtons': { + 'new': permissions[permissionBase ~ ':create'], + }, + 'langVar': 'smartlinks.smart_links', + 'routeBase': 'smart_links', + }, + 'bulk_actions': { + 'langVar': 'smartlinks.smart_links', + 'templateButtons': { + 'delete': permissions[permissionBase ~ ':deleteown'] or permissions[permissionBase ~ ':deleteother'], + }, + }, + }) -}} + {% endif %} +
+ {% if items is defined and items is not empty %} +
+ + + + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'checkall': 'true', + 'target': '#smartLinkTable', + }) }} + {# Columns: Short link, Slug, Redirect, Destination, Date added. #} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.slug', + 'text': 'mautic.smartlinks.smart_links.short_link', + 'class': 'col-smart-link-slug', + 'default': true, + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'text': 'mautic.smartlinks.smart_links.taxonomy', + 'class': 'visible-md visible-lg col-smart-link-taxonomy', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.redirectType', + 'text': 'mautic.smartlinks.smart_links.redirect_type', + 'class': 'visible-md visible-lg col-smart-link-type', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.destinationUrl', + 'text': 'mautic.smartlinks.smart_links.destination_url', + 'class': 'visible-md visible-lg col-smart-link-destination', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.hitCount', + 'text': 'mautic.smartlinks.smart_links.hits', + 'class': 'col-smart-link-hits', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.dateAdded', + 'text': 'mautic.core.date.added', + 'class': 'visible-md visible-lg col-smart-link-date', + }) }} + + + + {% for item in items %} + {% set canEdit = securityHasEntityAccess(permissions[permissionBase ~ ':editown'], permissions[permissionBase ~ ':editother'], item.createdBy) %} + + + + + + + + + + {% endfor %} + +
+ {{- include('@MauticCore/Helper/list_actions.html.twig', { + 'item': item, + 'templateButtons': { + 'edit': canEdit, + 'delete': securityHasEntityAccess(permissions[permissionBase ~ ':deleteown'], permissions[permissionBase ~ ':deleteother'], item.createdBy), + }, + 'langVar': 'smartlinks.smart_links', + 'routeBase': 'smart_links', + }) -}} + + {# Shortened link https://{domain}/l/{slug}; a tooltip shows the UTM parameters it carries. #} + {% set shortLink = shortLinkDomain ? 'https://' ~ shortLinkDomain ~ '/l/' ~ item.slug : item.slug %} + {% if canEdit %} + {{ shortLink }} + {% else %} + {{ shortLink }} + {% endif %} + + {{ item.taxonomy.name|default('—') }} + + + {{ ('mautic.smartlinks.smart_links.redirect_type.' ~ item.redirectType.value)|trans ~ ' · ' ~ item.redirectCode.value }} + + + {{ item.destinationLabel|default('—') }} + + + {{ hitCounts[item.id]|default(0) }} + + {{ dateToFull(item.dateAdded) }}
+ +
+ {% elseif searchValue is not empty %} + {{ include('@MauticCore/Helper/noresults.html.twig') }} + {% else %} +
+ {{ include('@MauticCore/Components/content-block.html.twig', { + 'heading': 'mautic.smartlinks.smart_links.onboarding.heading', + 'subheading': 'mautic.smartlinks.smart_links.onboarding.subheading', + 'copy': 'mautic.smartlinks.smart_links.onboarding.copy', + }) }} +
+ {% endif %} +
+
+{% endblock %} diff --git a/Resources/views/UtmTaxonomy/form.html.twig b/Resources/views/UtmTaxonomy/form.html.twig new file mode 100644 index 0000000..09edad2 --- /dev/null +++ b/Resources/views/UtmTaxonomy/form.html.twig @@ -0,0 +1,43 @@ +{% extends '@MauticCore/Default/content.html.twig' %} + +{% block mauticContent %}smartlinksUtmTaxonomy{% endblock %} + +{% block headerTitle %} + {% if form.vars.data.id %} + {{ 'mautic.smartlinks.taxonomies.header.edit'|trans({'%name%': form.vars.data.name}) }} + {% else %} + {{ 'mautic.smartlinks.taxonomies.header.new'|trans }} + {% endif %} +{% endblock %} + +{% block content %} + {{ form_start(form) }} +
+
+
+ {{ form_row(form.name) }} + {{ form_row(form.description) }} + +

{{ 'mautic.smartlinks.taxonomies.parameters'|trans }}

+

{{ 'mautic.smartlinks.taxonomies.parameters.help'|trans }}

+ {{ form_errors(form.parameters) }} +
+
+ {# One checkbox list per dropdown parameter: the choices are exactly the + values configured in Smart Links Settings, nothing can be typed. #} + {% for key, child in form.parameters %} +
{{ form_row(child) }}
+ {% endfor %} +
+
+ {% do form.parameters.setRendered() %} +
+
+
+
+ {{ form_row(form.buttons) }} +
+
+
+ {{ form_end(form) }} +{% endblock %} diff --git a/Resources/views/UtmTaxonomy/list.html.twig b/Resources/views/UtmTaxonomy/list.html.twig index 4a4c84d..9a1cf72 100644 --- a/Resources/views/UtmTaxonomy/list.html.twig +++ b/Resources/views/UtmTaxonomy/list.html.twig @@ -1,19 +1,127 @@ -{% set isIndex = 'index' == tmpl ? true : false %} +{% set isIndex = 'index' == tmpl|default('index') ? true : false %} {% set tmpl = 'list' %} {% extends isIndex ? '@MauticCore/Default/content.html.twig' : '@MauticCore/Default/raw_output.html.twig' %} -{% block mauticContent %}mt3sMpProgramUtmTaxonomy{% endblock %} +{% block mauticContent %}smartlinksUtmTaxonomy{% endblock %} -{% block headerTitle %}{{ 'mt3s.marketing_program.utm_taxonomy.header.index'|trans }}{% endblock %} +{% block headerTitle %}{{ 'mautic.smartlinks.taxonomies.header.index'|trans }}{% endblock %} {% block content %} -
-
- {{ include('@MauticCore/Components/content-block.html.twig', { - 'heading': 'mt3s.marketing_program.utm_taxonomy.onboarding.heading', - 'subheading': 'mt3s.marketing_program.utm_taxonomy.onboarding.subheading', - 'copy': 'mt3s.marketing_program.utm_taxonomy.onboarding.copy', - }) }} +
+ {# The toolbar belongs to the full page only: ajax reloads (sort, filter, pagination) + replace the contents of .page-list, so including it here again would duplicate it. #} + {% if isIndex %} + {{- include('@MauticCore/Helper/list_toolbar.html.twig', { + 'searchValue': searchValue, + 'action': currentRoute, + 'page_actions': { + 'templateButtons': { + 'new': permissions[permissionBase ~ ':create'], + }, + 'langVar': 'smartlinks.taxonomies', + 'routeBase': 'utm_taxonomies', + }, + 'bulk_actions': { + 'langVar': 'smartlinks.taxonomies', + 'templateButtons': { + 'delete': permissions[permissionBase ~ ':deleteown'] or permissions[permissionBase ~ ':deleteother'], + }, + }, + }) -}} + {% endif %} +
+ {% if items is defined and items is not empty %} +
+ + + + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'checkall': 'true', + 'target': '#utmTaxonomyTable', + }) }} + {# Columns: Name, Description, Parameters, Date added. #} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.name', + 'text': 'mautic.smartlinks.taxonomies.name', + 'class': 'col-utm-taxonomy-name', + 'default': true, + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.description', + 'text': 'mautic.smartlinks.taxonomies.description', + 'class': 'visible-md visible-lg col-utm-taxonomy-description', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'text': 'mautic.smartlinks.taxonomies.parameter_count', + 'class': 'visible-md visible-lg col-utm-taxonomy-parameters', + }) }} + {{ include('@MauticCore/Helper/tableheader.html.twig', { + 'sessionVar': sessionVar, + 'orderBy': tablePrefix ~ '.dateAdded', + 'text': 'mautic.core.date.added', + 'class': 'visible-md visible-lg col-utm-taxonomy-date', + }) }} + + + + {% for item in items %} + {% set canEdit = securityHasEntityAccess(permissions[permissionBase ~ ':editown'], permissions[permissionBase ~ ':editother'], item.createdBy) %} + + + + + + + + {% endfor %} + +
+ {{- include('@MauticCore/Helper/list_actions.html.twig', { + 'item': item, + 'templateButtons': { + 'edit': canEdit, + 'delete': securityHasEntityAccess(permissions[permissionBase ~ ':deleteown'], permissions[permissionBase ~ ':deleteother'], item.createdBy), + }, + 'langVar': 'smartlinks.taxonomies', + 'routeBase': 'utm_taxonomies', + }) -}} + + {% if canEdit %} + {{ item.name }} + {% else %} + {{ item.name }} + {% endif %} + + {{ item.description|default('—')|slice(0, 120) }} + + + {{ item.parameters|length }} + + {{ dateToFull(item.dateAdded) }}
+ +
+ {% elseif searchValue is not empty %} + {{ include('@MauticCore/Helper/noresults.html.twig') }} + {% else %} +
+ {{ include('@MauticCore/Components/content-block.html.twig', { + 'heading': 'mautic.smartlinks.taxonomies.onboarding.heading', + 'subheading': 'mautic.smartlinks.taxonomies.onboarding.subheading', + 'copy': 'mautic.smartlinks.taxonomies.onboarding.copy', + }) }} +
+ {% endif %}
{% endblock %} diff --git a/Security/Permissions/MT3SMarketingProgramPermissions.php b/Security/Permissions/MT3SMarketingProgramPermissions.php index 046ab86..f2561cd 100644 --- a/Security/Permissions/MT3SMarketingProgramPermissions.php +++ b/Security/Permissions/MT3SMarketingProgramPermissions.php @@ -29,6 +29,8 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions $this->addExtendedPermissions('tasks'); $this->addExtendedPermissions('stakeholders'); $this->addExtendedPermissions('audiences'); + $this->addExtendedPermissions('smart_links'); + $this->addExtendedPermissions('taxonomies'); $this->addStandardPermissions('itemtypes'); } @@ -48,6 +50,8 @@ class MT3SMarketingProgramPermissions extends AbstractPermissions $this->addExtendedFormFields('mt3smarketingprogram', 'tasks', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'stakeholders', $builder, $data); $this->addExtendedFormFields('mt3smarketingprogram', 'audiences', $builder, $data); + $this->addExtendedFormFields('mt3smarketingprogram', 'smart_links', $builder, $data); + $this->addExtendedFormFields('mt3smarketingprogram', 'taxonomies', $builder, $data); $this->addStandardFormFields('mt3smarketingprogram', 'itemtypes', $builder, $data); } } diff --git a/Service/SmartLinkShortUrlBuilder.php b/Service/SmartLinkShortUrlBuilder.php new file mode 100644 index 0000000..3818c49 --- /dev/null +++ b/Service/SmartLinkShortUrlBuilder.php @@ -0,0 +1,70 @@ + Configuration > Smart Links Settings; the form shows it + * as a reminder (getShortLinkDomain(), without the scheme). + */ +final class SmartLinkShortUrlBuilder +{ + public const PATH_PREFIX = '/l/'; + + public function __construct( + private readonly CoreParametersHelper $coreParametersHelper, + ) { + } + + /** + * The configured short link domain, without scheme or trailing slash, for example lnk.example.com. + * Empty when nothing is configured yet. + */ + public function getShortLinkDomain(): string + { + $stored = $this->coreParametersHelper->get(SmartLinksConfigType::CONFIG_PARAMETER, []); + + // Upgrades from < 0.5.0 keep the domain in local.php under the legacy key; serve it until + // the Configuration page is saved again (which writes the new key). + if (!is_array($stored) || '' === trim((string) ($stored['short_link_domain'] ?? ''))) { + $legacy = $this->coreParametersHelper->get(SmartLinksConfigType::LEGACY_CONFIG_PARAMETER, []); + if (is_array($legacy) && '' !== trim((string) ($legacy['short_link_domain'] ?? ''))) { + $stored = $legacy; + } + } + + $domain = trim(is_array($stored) ? (string) ($stored['short_link_domain'] ?? '') : ''); + + return '' === $domain ? '' : rtrim($domain, '/'); + } + + /** + * The short link of a Smart Link, for example https://lnk.example.com/l/ab3x. + * Empty when no domain is configured, or when the link has no slug yet. + */ + public function buildShortUrl(SmartLink $smartLink): string + { + return $this->buildShortUrlFromSlug((string) ($smartLink->getSlug() ?? '')); + } + + /** + * Same as buildShortUrl(), for a slug that was just typed in the form (live preview). + */ + public function buildShortUrlFromSlug(string $slug): string + { + $slug = trim($slug); + $domain = $this->getShortLinkDomain(); + + if ('' === $domain || '' === $slug) { + return ''; + } + + return 'https://'.$domain.self::PATH_PREFIX.$slug; + } +} diff --git a/Service/UtmConfigurationNormalizer.php b/Service/UtmConfigurationNormalizer.php new file mode 100644 index 0000000..e789a91 --- /dev/null +++ b/Service/UtmConfigurationNormalizer.php @@ -0,0 +1,136 @@ +, default?: ?string} + * @phpstan-type UtmConfig array{enforce_lowercase: bool, separator_replacement: string, parameters: array} + */ +final class UtmConfigurationNormalizer +{ + public const SEPARATORS = ['-', '_', '.']; + public const DEFAULT_SEPARATOR = '-'; + + public function __construct( + private readonly UtmParameterCatalog $catalog, + ) { + } + + /** + * @return UtmConfig + */ + public function normalize(mixed $raw): array + { + $raw = is_array($raw) ? $raw : []; + $separator = $raw['separator_replacement'] ?? self::DEFAULT_SEPARATOR; + $stored = is_array($raw['parameters'] ?? null) ? $raw['parameters'] : []; + + $parameters = []; + foreach ($this->catalog->all() as $key => $definition) { + $parameters[$key] = $this->normalizeParameter($stored[$key] ?? null, $definition); + } + + foreach ($stored as $key => $parameter) { + $key = (string) $key; + if (isset($parameters[$key]) || !$this->catalog->isValidCustomKey($key)) { + continue; + } + + $parameters[$key] = $this->normalizeParameter($parameter, null); + } + + return [ + 'enforce_lowercase' => array_key_exists('enforce_lowercase', $raw) ? self::toBool($raw['enforce_lowercase']) : true, + 'separator_replacement' => in_array($separator, self::SEPARATORS, true) ? $separator : self::DEFAULT_SEPARATOR, + 'parameters' => $parameters, + ]; + } + + /** + * @return UtmParameter + */ + private function normalizeParameter(mixed $stored, ?UtmParameterDefinition $definition): array + { + $defaultMode = $definition?->defaultMode ?? UtmParameterMode::DISABLED; + $allowedModes = $definition?->getAllowedModes() ?? UtmParameterMode::ALL; + + if (!is_array($stored)) { + // Free parameters start enabled. Dropdown parameters start switched off: an enabled dropdown + // needs values, and an invalid default would block saving the whole Configuration page. + $stored = ['enabled' => UtmParameterMode::FREE === $defaultMode, 'mode' => $defaultMode]; + } + + $mode = (string) ($stored['mode'] ?? $defaultMode); + if (!in_array($mode, $allowedModes, true)) { + $mode = $defaultMode; + } + + $parameter = [ + 'enabled' => self::toBool($stored['enabled'] ?? false), + 'label' => trim((string) ($stored['label'] ?? '')), + 'mode' => $mode, + ]; + + if (UtmParameterMode::DROPDOWN !== $mode) { + return $parameter; + } + + $values = $this->normalizeValues($stored['values'] ?? []); + $default = (string) ($stored['default'] ?? ''); + + $parameter['values'] = $values; + $parameter['default'] = in_array($default, array_column($values, 'value'), true) ? $default : null; + + return $parameter; + } + + /** + * @return list + */ + private function normalizeValues(mixed $values): array + { + if (!is_array($values)) { + return []; + } + + $normalized = []; + foreach ($values as $row) { + if (!is_array($row)) { + continue; + } + + $value = trim((string) ($row['value'] ?? '')); + if ('' === $value || isset($normalized[$value])) { + continue; + } + + $label = trim((string) ($row['label'] ?? '')); + $normalized[$value] = ['value' => $value, 'label' => '' !== $label ? $label : $value]; + } + + return array_values($normalized); + } + + public static function toBool(mixed $value): bool + { + if (is_string($value)) { + return in_array(strtolower(trim($value)), ['1', 'true', 'yes', 'on'], true); + } + + return (bool) $value; + } +} diff --git a/Service/UtmConfigurationProvider.php b/Service/UtmConfigurationProvider.php new file mode 100644 index 0000000..42fafdc --- /dev/null +++ b/Service/UtmConfigurationProvider.php @@ -0,0 +1,128 @@ +> + */ + public function getEnabledParameters(): array + { + $enabled = []; + foreach ($this->getConfig()['parameters'] as $key => $parameter) { + if ($parameter['enabled'] && UtmParameterMode::DISABLED !== $parameter['mode']) { + $enabled[$key] = $this->decorate($key, $parameter); + } + } + + return $enabled; + } + + /** + * Any catalog or custom parameter, whatever its state. Null when the key is unknown. + * + * @return array|null + */ + public function getParameter(string $key): ?array + { + $parameter = $this->getConfig()['parameters'][$key] ?? null; + + return null === $parameter ? null : $this->decorate($key, $parameter); + } + + /** + * Allowed values of a `dropdown` parameter. Always empty for `free` and `disabled` parameters. + * + * @return list + */ + public function getDropdownValues(string $key): array + { + $parameter = $this->getConfig()['parameters'][$key] ?? null; + + if (null === $parameter || UtmParameterMode::DROPDOWN !== $parameter['mode']) { + return []; + } + + return $parameter['values'] ?? []; + } + + public function isLowercaseEnforced(): bool + { + return $this->getConfig()['enforce_lowercase']; + } + + public function getSeparatorReplacement(): string + { + return $this->getConfig()['separator_replacement']; + } + + /** + * @return array{enforce_lowercase: bool, separator_replacement: string, parameters: array>} + */ + private function getConfig(): array + { + $raw = $this->coreParametersHelper->get(self::CONFIG_PARAMETER, []); + + // Upgrades from < 0.5.0 keep their settings in local.php under the legacy key; serve them + // until the Configuration page is saved again (which writes the new key). + if (null === $raw || [] === $raw) { + $legacy = $this->coreParametersHelper->get(self::LEGACY_CONFIG_PARAMETER, []); + if (null !== $legacy && [] !== $legacy) { + $raw = $legacy; + } + } + + return $this->normalizer->normalize($raw); + } + + /** + * @param array $parameter + * + * @return array + */ + private function decorate(string $key, array $parameter): array + { + $definition = $this->catalog->get($key); + + if ('' === $parameter['label']) { + $parameter['label'] = null !== $definition ? $this->translator->trans($definition->getLabelKey()) : $key; + } + + return ['key' => $key] + $parameter + [ + 'group' => $definition?->group ?? UtmParameterCatalog::GROUP_CUSTOM, + 'custom' => null === $definition, + 'auto_generated' => $definition?->autoGenerated ?? false, + ]; + } +} diff --git a/Tests/Unit/Catalog/UtmParameterCatalogTest.php b/Tests/Unit/Catalog/UtmParameterCatalogTest.php new file mode 100644 index 0000000..ffa7772 --- /dev/null +++ b/Tests/Unit/Catalog/UtmParameterCatalogTest.php @@ -0,0 +1,147 @@ + UtmParameterMode::DROPDOWN, + 'utm_medium' => UtmParameterMode::DROPDOWN, + 'utm_campaign' => UtmParameterMode::FREE, + 'utm_term' => UtmParameterMode::FREE, + 'utm_content' => UtmParameterMode::FREE, + 'utm_id' => UtmParameterMode::FREE, + 'utm_source_platform' => UtmParameterMode::DROPDOWN, + 'utm_creative_format' => UtmParameterMode::DROPDOWN, + 'utm_marketing_tactic' => UtmParameterMode::DROPDOWN, + ]; + + private const PLATFORM_KEYS = ['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid', 'epik']; + + private UtmParameterCatalog $catalog; + + protected function setUp(): void + { + $this->catalog = new UtmParameterCatalog(); + } + + public function testCatalogContainsExactlyTheExpectedKeysInOrder(): void + { + $this->assertSame( + array_merge(array_keys(self::STANDARD_MODES), self::PLATFORM_KEYS), + array_keys($this->catalog->all()) + ); + } + + public function testStandardParameters(): void + { + $standard = $this->catalog->getByGroup(UtmParameterCatalog::GROUP_STANDARD); + $this->assertSame(array_keys(self::STANDARD_MODES), array_keys($standard)); + + foreach (self::STANDARD_MODES as $key => $mode) { + $definition = $standard[$key]; + $this->assertSame($mode, $definition->defaultMode, $key); + $this->assertFalse($definition->autoGenerated, $key); + $this->assertSame(UtmParameterMode::ALL, $definition->getAllowedModes(), $key); + $this->assertSame('mautic.smartlinks.config.parameter.'.$key.'.label', $definition->getLabelKey()); + $this->assertSame('mautic.smartlinks.config.parameter.'.$key.'.description', $definition->getDescriptionKey()); + } + } + + public function testPlatformParametersAreAutoGeneratedDisabledAndCannotBeDropdowns(): void + { + $platform = $this->catalog->getByGroup(UtmParameterCatalog::GROUP_PLATFORM); + $this->assertSame(self::PLATFORM_KEYS, array_keys($platform)); + + foreach ($platform as $key => $definition) { + $this->assertTrue($definition->autoGenerated, $key); + $this->assertSame(UtmParameterMode::DISABLED, $definition->defaultMode, $key); + $this->assertSame([UtmParameterMode::FREE, UtmParameterMode::DISABLED], $definition->getAllowedModes(), $key); + $this->assertFalse($definition->isModeAllowed(UtmParameterMode::DROPDOWN), $key); + $this->assertSame([], $definition->suggestions, $key); + } + } + + public function testSuggestionsOnlyForDropdownParameters(): void + { + $this->assertSame( + ['newsletter', 'linkedin', 'facebook', 'instagram', 'google', 'youtube', 'x', 'tiktok', 'partner', 'direct'], + $this->catalog->get('utm_source')?->suggestions + ); + $this->assertSame( + ['email', 'cpc', 'social', 'social_paid', 'display', 'affiliate', 'referral', 'qr', 'sms', 'print', 'event'], + $this->catalog->get('utm_medium')?->suggestions + ); + $this->assertSame(['google_ads', 'meta_ads', 'linkedin_ads', 'microsoft_ads', 'tiktok_ads'], $this->catalog->get('utm_source_platform')?->suggestions); + $this->assertSame(['banner', 'video', 'carousel', 'text', 'native'], $this->catalog->get('utm_creative_format')?->suggestions); + $this->assertSame(['prospecting', 'remarketing', 'retargeting', 'brand', 'nurturing'], $this->catalog->get('utm_marketing_tactic')?->suggestions); + + foreach ($this->catalog->all() as $key => $definition) { + if (UtmParameterMode::DROPDOWN !== $definition->defaultMode) { + $this->assertSame([], $definition->suggestions, $key); + } + } + + $this->assertSame('mautic.smartlinks.config.suggestion.google_ads', UtmParameterDefinition::getSuggestionLabelKey('google_ads')); + } + + public function testGetAndHas(): void + { + $this->assertTrue($this->catalog->has('utm_source')); + $this->assertInstanceOf(UtmParameterDefinition::class, $this->catalog->get('gclid')); + $this->assertFalse($this->catalog->has('my_param')); + $this->assertNull($this->catalog->get('my_param')); + } + + #[DataProvider('reservedKeys')] + public function testReservedKeys(string $key): void + { + $this->assertTrue($this->catalog->isReservedKey($key)); + $this->assertFalse($this->catalog->isValidCustomKey($key)); + } + + /** + * @return iterable + */ + public static function reservedKeys(): iterable + { + yield 'catalog key' => ['utm_source']; + yield 'click id' => ['gclid']; + yield 'mautic click tracking' => ['ct']; + yield 'utm prefix' => ['utm_custom']; + yield 'utm prefix without underscore' => ['utmx']; + yield 'mtc prefix' => ['mtc_id']; + } + + #[DataProvider('customKeys')] + public function testCustomKeyFormat(string $key, bool $valid): void + { + $this->assertSame($valid, $this->catalog->isValidCustomKey($key)); + } + + /** + * @return iterable + */ + public static function customKeys(): iterable + { + yield 'simple' => ['ref', true]; + yield 'with digits and underscore' => ['partner_id2', true]; + yield 'two characters' => ['ab', true]; + yield 'max 41 characters' => ['a'.str_repeat('b', 40), true]; + yield 'one character' => ['a', false]; + yield 'too long' => ['a'.str_repeat('b', 41), false]; + yield 'starts with digit' => ['1abc', false]; + yield 'starts with underscore' => ['_abc', false]; + yield 'uppercase' => ['Abc', false]; + yield 'hyphen' => ['my-param', false]; + yield 'empty' => ['', false]; + } +} diff --git a/Tests/Unit/Entity/SmartLinkHitTest.php b/Tests/Unit/Entity/SmartLinkHitTest.php new file mode 100644 index 0000000..0db7a3e --- /dev/null +++ b/Tests/Unit/Entity/SmartLinkHitTest.php @@ -0,0 +1,29 @@ +setSmartLink($link); + $hit->setIpAddress('2001:db8::1'); + $hit->setReferer('https://newsletter.example.com/'); + $hit->setUserAgent('curl/8.18.0'); + + $this->assertSame($link, $hit->getSmartLink()); + $this->assertSame('2001:db8::1', $hit->getIpAddress()); + $this->assertSame('https://newsletter.example.com/', $hit->getReferer()); + $this->assertSame('curl/8.18.0', $hit->getUserAgent()); + $this->assertNull($hit->getId()); + } +} diff --git a/Tests/Unit/Entity/SmartLinkTest.php b/Tests/Unit/Entity/SmartLinkTest.php new file mode 100644 index 0000000..ca93042 --- /dev/null +++ b/Tests/Unit/Entity/SmartLinkTest.php @@ -0,0 +1,82 @@ +setSlug('abc'); + + // Not saved yet: the slug can still be set. + $link->setSlug('xyz'); + $this->assertSame('xyz', $link->getSlug()); + + $reflection = new \ReflectionClass(SmartLink::class); + $property = $reflection->getProperty('id'); + $property->setValue($link, 1); + + // Saved: the same slug is accepted (no-op), a different one is refused. + $link->setSlug('xyz'); + $this->assertSame('xyz', $link->getSlug()); + + $this->expectException(\LogicException::class); + $link->setSlug('other'); + } + + public function testMauticRedirectHasNoDestination(): void + { + $link = new SmartLink(); + $link->setRedirectType(SmartLinkRedirectType::External); + $link->setDestinationUrl('https://www.example.com'); + $this->assertSame('https://www.example.com', $link->getDestinationUrl()); + + $link->setRedirectType(SmartLinkRedirectType::Mautic); + $this->assertNull($link->getDestinationUrl()); + } + + public function testBlankDestinationIsNormalizedToNull(): void + { + $link = new SmartLink(); + $link->setDestinationUrl(' '); + $this->assertNull($link->getDestinationUrl()); + } + + public function testUtmParametersAreStoredAsGiven(): void + { + // The model (normalizeUtmValues) cleans the values before they reach the entity. + $link = new SmartLink(); + $link->setUtmParameters(['utm_source' => 'newsletter']); + $this->assertSame(['utm_source' => 'newsletter'], $link->getUtmParameters()); + + $link->setUtmParameters(null); + $this->assertSame([], $link->getUtmParameters()); + } + + public function testShortLinkIsBuiltFromDomainAndSlug(): void + { + $link = new SmartLink(); + $link->setSlug('ab3x'); + + $this->assertSame('https://lnk.example.com/l/ab3x', $link->getShortLink('lnk.example.com')); + $this->assertSame('https://lnk.example.com/l/ab3x', $link->getShortLink('lnk.example.com/')); + $this->assertSame('', $link->getShortLink('')); + } + + public function testRedirectEnums(): void + { + $this->assertTrue(SmartLinkRedirectType::External->isExternal()); + $this->assertTrue(SmartLinkRedirectType::Mautic->isMautic()); + $this->assertSame(SmartLinkRedirectCode::MovedPermanently, SmartLinkRedirectCode::tryFrom(301)); + $this->assertSame(SmartLinkRedirectCode::PermanentRedirect, SmartLinkRedirectCode::tryFrom(308)); + $this->assertNull(SmartLinkRedirectCode::tryFrom(418)); + } +} diff --git a/Tests/Unit/Form/SmartlinksSettingsTypeTest.php b/Tests/Unit/Form/SmartlinksSettingsTypeTest.php new file mode 100644 index 0000000..e60c5cf --- /dev/null +++ b/Tests/Unit/Form/SmartlinksSettingsTypeTest.php @@ -0,0 +1,275 @@ +submit($this->defaultSubmission()); + + $this->assertTrue($form->isSynchronized()); + $this->assertSame([], $this->errorMessages($form)); + + $data = $form->getData(); + $this->assertTrue($data['enforce_lowercase']); + $this->assertSame('-', $data['separator_replacement']); + $this->assertSame(['enabled' => true, 'label' => 'mautic.smartlinks.config.parameter.utm_campaign.label', 'mode' => 'free'], $data['parameters']['utm_campaign']); + $this->assertSame(['enabled' => false, 'label' => 'mautic.smartlinks.config.parameter.gclid.label', 'mode' => 'disabled'], $data['parameters']['gclid']); + $this->assertSame(['enabled', 'label', 'mode', 'values', 'default'], array_keys($data['parameters']['utm_source'])); + } + + public function testValuesSubmittedForAFreeParameterAreIgnored(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['utm_source']['mode'] = 'free'; + $submission['parameters']['utm_source']['values'] = [ + ['value' => 'NOT VALID', 'label' => ''], + ['value' => 'NOT VALID', 'label' => ''], + ]; + + $form = $this->submit($submission); + + $this->assertSame([], $this->errorMessages($form)); + $this->assertSame(['enabled' => false, 'label' => 'mautic.smartlinks.config.parameter.utm_source.label', 'mode' => 'free'], $form->getData()['parameters']['utm_source']); + } + + public function testEnabledDropdownWithoutValuesIsRejected(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['utm_source']['enabled'] = '1'; + + $form = $this->submit($submission); + + $this->assertSame( + [UtmSettingsValidator::ERROR_VALUES_REQUIRED], + $this->messages($form->get('parameters')->get('utm_source')->get('values')) + ); + } + + public function testDropdownValuesAreStoredInOrderWithTheirDefault(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['utm_source']['enabled'] = '1'; + $submission['parameters']['utm_source']['values'] = [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn', 'is_default' => '1'], + ]; + + $form = $this->submit($submission); + + $this->assertSame([], $this->errorMessages($form)); + $this->assertSame([ + 'enabled' => true, + 'label' => 'mautic.smartlinks.config.parameter.utm_source.label', + 'mode' => 'dropdown', + 'values' => [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn'], + ], + 'default' => 'linkedin', + ], $form->getData()['parameters']['utm_source']); + } + + public function testDuplicateAndInvalidValuesAreRejected(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['utm_medium']['enabled'] = '1'; + $submission['parameters']['utm_medium']['values'] = [ + ['value' => 'email', 'label' => 'Email', 'is_default' => '1'], + ['value' => 'email', 'label' => 'Email again', 'is_default' => '1'], + ['value' => 'Paid Social', 'label' => 'Paid social'], + ['value' => str_repeat('a', 101), 'label' => ''], + ]; + + $form = $this->submit($submission); + $values = $form->get('parameters')->get('utm_medium')->get('values'); + + $this->assertSame([UtmSettingsValidator::ERROR_VALUE_DUPLICATE, UtmSettingsValidator::ERROR_DEFAULT_MULTIPLE], $this->messages($values)); + $this->assertSame(['mautic.smartlinks.config.error.value_invalid'], $this->messages($values->get('2')->get('value'))); + $this->assertSame(['mautic.smartlinks.config.error.value_length'], $this->messages($values->get('3')->get('value'))); + $this->assertSame(['mautic.smartlinks.config.error.label_required'], $this->messages($values->get('3')->get('label'))); + } + + public function testDropdownModeIsRefusedForClickIds(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['gclid']['mode'] = 'dropdown'; + + $form = $this->submit($submission); + + $this->assertSame(['mautic.smartlinks.config.error.mode_invalid'], $this->messages($form->get('parameters')->get('gclid')->get('mode'))); + } + + public function testCustomParameterIsStoredUnderItsKey(): void + { + $submission = $this->defaultSubmission(); + $submission['custom_parameters'][] = $this->customParameter('partner', 'free'); + + $form = $this->submit($submission); + + $this->assertSame([], $this->errorMessages($form)); + $this->assertSame(['enabled' => true, 'label' => 'Partner', 'mode' => 'free'], $form->getData()['parameters']['partner']); + } + + public function testCustomKeyRules(): void + { + $submission = $this->defaultSubmission(); + $submission['custom_parameters'] = [ + $this->customParameter('Bad-Key'), + $this->customParameter('utm_partner'), + $this->customParameter('mtc_x'), + $this->customParameter('ct'), + $this->customParameter('gclid'), + $this->customParameter('ref'), + $this->customParameter('ref'), + $this->customParameter(''), + ]; + + $custom = $this->submit($submission)->get('custom_parameters'); + + $this->assertSame([UtmSettingsValidator::ERROR_KEY_INVALID], $this->messages($custom->get('0')->get('key'))); + foreach (['1', '2', '3', '4'] as $index) { + $this->assertSame([UtmSettingsValidator::ERROR_KEY_RESERVED], $this->messages($custom->get($index)->get('key')), $index); + } + $this->assertSame([UtmSettingsValidator::ERROR_KEY_DUPLICATE], $this->messages($custom->get('5')->get('key'))); + $this->assertSame([UtmSettingsValidator::ERROR_KEY_DUPLICATE], $this->messages($custom->get('6')->get('key'))); + $this->assertSame(['mautic.smartlinks.config.error.key_required'], $this->messages($custom->get('7')->get('key'))); + } + + public function testLabelCannotContainPercent(): void + { + $submission = $this->defaultSubmission(); + $submission['parameters']['utm_campaign']['label'] = '50% off'; + + $form = $this->submit($submission); + + $this->assertSame(['mautic.smartlinks.config.error.label_invalid'], $this->messages($form->get('parameters')->get('utm_campaign')->get('label'))); + } + + public function testStoredConfigurationIsLoadedIntoTheForm(): void + { + $form = $this->factory->create(SmartlinksSettingsType::class, [ + 'enforce_lowercase' => '', + 'parameters' => [ + 'utm_source' => ['enabled' => '1', 'label' => 'Src', 'mode' => 'dropdown', 'values' => [['value' => 'a', 'label' => 'A']], 'default' => 'a'], + 'partner' => ['enabled' => '1', 'label' => 'Partner', 'mode' => 'free'], + ], + ]); + + $this->assertFalse($form->get('enforce_lowercase')->getData()); + $this->assertSame('Src', $form->get('parameters')->get('utm_source')->get('label')->getData()); + $this->assertSame([['value' => 'a', 'label' => 'A', 'is_default' => true]], $form->get('parameters')->get('utm_source')->get('values')->getData()); + $this->assertSame('partner', $form->get('custom_parameters')->get('0')->get('key')->getData()); + } + + /** + * @param array $submission + * + * @return FormInterface + */ + private function submit(array $submission): FormInterface + { + $form = $this->factory->create(SmartlinksSettingsType::class, []); + $form->submit($submission); + + return $form; + } + + /** + * What the browser posts for an untouched form. + * + * @return array + */ + private function defaultSubmission(): array + { + $view = $this->factory->create(SmartlinksSettingsType::class, [])->getViewData(); + + $parameters = []; + foreach ($view['parameters'] as $key => $parameter) { + $parameters[$key] = [ + 'enabled' => $parameter['enabled'] ? '1' : '0', + 'label' => $parameter['label'], + 'mode' => $parameter['mode'], + 'values' => [], + ]; + } + + return [ + 'enforce_lowercase' => '1', + 'separator_replacement' => '-', + 'parameters' => $parameters, + 'custom_parameters' => [], + ]; + } + + /** + * @return array + */ + private function customParameter(string $key, string $mode = 'free'): array + { + return ['key' => $key, 'enabled' => '1', 'label' => ucfirst($key) ?: 'Label', 'mode' => $mode, 'values' => []]; + } + + /** + * @param FormInterface $form + * + * @return string[] + */ + private function messages(FormInterface $form): array + { + return array_map( + fn (FormError $error): string => $error->getMessageTemplate(), + iterator_to_array($form->getErrors()) + ); + } + + /** + * @param FormInterface $form + * + * @return string[] + */ + private function errorMessages(FormInterface $form): array + { + return array_map( + fn (FormError $error): string => $error->getOrigin()?->getName().': '.$error->getMessageTemplate(), + iterator_to_array($form->getErrors(true)) + ); + } +} diff --git a/Tests/Unit/Form/UtmFieldsApplicatorTest.php b/Tests/Unit/Form/UtmFieldsApplicatorTest.php new file mode 100644 index 0000000..285b53a --- /dev/null +++ b/Tests/Unit/Form/UtmFieldsApplicatorTest.php @@ -0,0 +1,267 @@ + 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn'], + ['value' => 'google', 'label' => 'Google'], + ]; + + public function testDropdownModeRendersConfiguredValuesInOrder(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]); + + $field = $form->get('utmSource'); + $this->assertInstanceOf(ChoiceType::class, $field->getConfig()->getType()->getInnerType()); + $this->assertSame(['newsletter', 'linkedin', 'google'], $field->getConfig()->getOption('choices')); + $this->assertSame('mautic.email.campaign_source', $field->getConfig()->getOption('label'), 'Native label kept'); + $this->assertSame('trans:mautic.smartlinks.form.choose', $field->getConfig()->getOption('placeholder')); + $this->assertNull($field->getConfig()->getOption('help')); + + $view = $form->createView()['utmSource']; + $labels = array_map(static fn ($choice): string => $choice->label, $view->vars['choices']); + $this->assertSame(['Newsletter', 'LinkedIn', 'Google'], array_values($labels)); + } + + public function testDropdownModeAcceptsConfiguredOrEmptyValue(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]); + $form->submit(['utmSource' => 'linkedin', 'utmMedium' => 'email']); + + $this->assertTrue($form->isValid()); + $this->assertSame('linkedin', $form->getData()['utmSource']); + + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]); + $form->submit(['utmSource' => '']); + + $this->assertTrue($form->isValid()); + $this->assertNull($form->getData()['utmSource']); + } + + public function testDropdownModeRejectsValueOutsideTaxonomy(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)]); + $form->submit(['utmSource' => 'hacked']); + + $this->assertFalse($form->isValid()); + $errors = $form->get('utmSource')->getErrors(); + $this->assertCount(1, $errors); + $this->assertSame('mautic.smartlinks.form.error.not_in_taxonomy', $errors[0]->getMessageTemplate()); + } + + public function testFreeModeKeepsNativeTextField(): void + { + $form = $this->createForm(['utm_campaign' => ['enabled' => '1', 'label' => '', 'mode' => 'free']]); + + $field = $form->get('utmCampaign'); + $this->assertInstanceOf(TextType::class, $field->getConfig()->getType()->getInnerType()); + $this->assertSame('mautic.email.campaign_name', $field->getConfig()->getOption('label')); + + $form->submit(['utmCampaign' => 'Spring Sale_2026/FR']); + + $this->assertTrue($form->isValid()); + $this->assertSame('Spring Sale_2026/FR', $form->getData()['utmCampaign'], 'Value stored as typed'); + } + + public function testDisabledModeRemovesFieldAndClearsStoredValue(): void + { + $form = $this->createForm( + [ + 'utm_medium' => ['enabled' => '1', 'label' => '', 'mode' => 'disabled'], + 'utm_source' => ['enabled' => '1', 'label' => '', 'mode' => 'free'], + ], + ['utmMedium' => 'old-medium', 'utmSource' => 'kept'], + ); + + $this->assertFalse($form->has('utmMedium')); + $this->assertArrayNotHasKey('utmMedium', $form->createView()->children); + + // A value posted anyway (stale page, crafted request) is ignored without an "extra fields" error. + $form->submit(['utmMedium' => 'posted', 'utmSource' => 'kept']); + + $this->assertTrue($form->isValid()); + $this->assertNull($form->getData()['utmMedium']); + $this->assertSame('kept', $form->getData()['utmSource']); + } + + public function testNotEnabledParameterIsTreatedAsDisabled(): void + { + $form = $this->createForm( + ['utm_source' => $this->dropdown(self::SOURCE_VALUES, enabled: '')], + ['utmSource' => 'linkedin'], + ); + + $this->assertFalse($form->has('utmSource')); + + $form->submit([]); + + $this->assertTrue($form->isValid()); + $this->assertNull($form->getData()['utmSource']); + } + + public function testLegacyValueIsOfferedAndCanBeKept(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)], ['utmSource' => 'Old Source']); + + $field = $form->get('utmSource'); + $this->assertSame(['newsletter', 'linkedin', 'google', 'Old Source'], $field->getConfig()->getOption('choices')); + $this->assertSame('mautic.smartlinks.form.legacy_warning', $field->getConfig()->getOption('help')); + + $view = $form->createView()['utmSource']; + $this->assertSame('Old Source', $view->vars['value'], 'Legacy value selected'); + $this->assertSame('trans:mautic.smartlinks.form.legacy_choice|Old Source', end($view->vars['choices'])->label); + + $form->submit(['utmSource' => 'Old Source']); + + $this->assertTrue($form->isValid()); + $this->assertSame('Old Source', $form->getData()['utmSource'], 'Legacy value not rewritten'); + } + + public function testLegacyValueCanBeReplacedButNotByAnotherUnknownValue(): void + { + $config = ['utm_source' => $this->dropdown(self::SOURCE_VALUES)]; + + $form = $this->createForm($config, ['utmSource' => 'Old Source']); + $form->submit(['utmSource' => 'google']); + $this->assertTrue($form->isValid()); + $this->assertSame('google', $form->getData()['utmSource']); + + $form = $this->createForm($config, ['utmSource' => 'Old Source']); + $form->submit(['utmSource' => 'another-unknown']); + $this->assertFalse($form->isValid()); + } + + public function testNumericLegacyValueWrittenByApi(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown(self::SOURCE_VALUES)], ['utmSource' => 42]); + $form->submit(['utmSource' => '42']); + + $this->assertTrue($form->isValid()); + $this->assertSame('42', $form->getData()['utmSource']); + } + + public function testEmptyDropdownListShowsOnlyEmptyChoiceAndNotice(): void + { + $form = $this->createForm(['utm_source' => $this->dropdown([])]); + + $field = $form->get('utmSource'); + $this->assertSame([], $field->getConfig()->getOption('choices')); + $this->assertSame('mautic.smartlinks.form.no_values', $field->getConfig()->getOption('help')); + + $form->submit(['utmSource' => '']); + $this->assertTrue($form->isValid()); + } + + public function testCustomLabelReplacesNativeLabel(): void + { + $form = $this->createForm([ + 'utm_source' => $this->dropdown(self::SOURCE_VALUES, label: 'Traffic source'), + 'utm_campaign' => ['enabled' => '1', 'label' => 'Campaign code', 'mode' => 'free'], + ]); + + $this->assertSame('Traffic source', $form->get('utmSource')->getConfig()->getOption('label')); + $this->assertSame('Campaign code', $form->get('utmCampaign')->getConfig()->getOption('label')); + $this->assertInstanceOf(TextType::class, $form->get('utmCampaign')->getConfig()->getType()->getInnerType()); + } + + public function testDropdownOnContentKeepsNativeLengthConstraint(): void + { + $form = $this->createForm(['utm_content' => $this->dropdown([['value' => 'hero', 'label' => 'Hero']])]); + + $constraints = $form->get('utmContent')->getConfig()->getOption('constraints'); + $this->assertNotEmpty($constraints); + $this->assertInstanceOf(Length::class, is_array($constraints) ? $constraints[0] : $constraints); + } + + public function testNativeFieldOrderIsKept(): void + { + $form = $this->createForm([ + 'utm_source' => $this->dropdown(self::SOURCE_VALUES), + 'utm_medium' => $this->dropdown([['value' => 'email', 'label' => 'Email']]), + 'utm_campaign' => ['enabled' => '1', 'label' => '', 'mode' => 'free'], + 'utm_content' => ['enabled' => '1', 'label' => 'Variant', 'mode' => 'free'], + ]); + + $this->assertSame(['utmSource', 'utmMedium', 'utmCampaign', 'utmContent'], array_keys($form->createView()->children)); + } + + public function testKeysWithoutNativeFieldArePreserved(): void + { + $form = $this->createForm( + ['utm_source' => $this->dropdown(self::SOURCE_VALUES)], + ['utmSource' => 'google', 'utmTerm' => 'from-api'], + ); + $form->submit(['utmSource' => 'google']); + + $this->assertTrue($form->isValid()); + $this->assertSame('from-api', $form->getData()['utmTerm']); + } + + /** + * @param list $values + * + * @return array + */ + private function dropdown(array $values, string $enabled = '1', string $label = ''): array + { + return ['enabled' => $enabled, 'label' => $label, 'mode' => 'dropdown', 'values' => $values, 'default' => '']; + } + + /** + * @param array> $parameters Stored configuration (local.php shape), other parameters keep their defaults + * @param array $storedTags The entity's current utmTags + * + * @return FormInterface + */ + private function createForm(array $parameters, array $storedTags = []): FormInterface + { + $coreParameters = $this->createMock(CoreParametersHelper::class); + $coreParameters->method('get') + ->with(UtmConfigurationProvider::CONFIG_PARAMETER) + ->willReturn(['enforce_lowercase' => '', 'separator_replacement' => '_', 'parameters' => $parameters]); + + // Catalog labels translate to themselves, so an empty configured label resolves to the catalog key. + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback( + static fn (string $id, array $parameters = []): string => str_starts_with($id, 'mautic.smartlinks.config.parameter.') + ? $id + : 'trans:'.$id.([] === $parameters ? '' : '|'.implode(',', $parameters)) + ); + + $catalog = new UtmParameterCatalog(); + $provider = new UtmConfigurationProvider($coreParameters, new UtmConfigurationNormalizer($catalog), $catalog, $translator); + $applicator = new UtmFieldsApplicator($provider, $catalog, $translator); + + $factory = Forms::createFormFactoryBuilder() + ->addExtension(new ValidatorExtension(Validation::createValidator())) + ->addTypeExtension(new UtmTagsTypeExtension($applicator)) + ->getFormFactory(); + + return $factory->create(EmailUtmTagsType::class, $storedTags); + } +} diff --git a/Tests/Unit/Form/UtmSettingsValidatorTest.php b/Tests/Unit/Form/UtmSettingsValidatorTest.php new file mode 100644 index 0000000..e70a46f --- /dev/null +++ b/Tests/Unit/Form/UtmSettingsValidatorTest.php @@ -0,0 +1,82 @@ +validator = new UtmSettingsValidator(new UtmParameterCatalog()); + } + + public function testCustomKeyRegex(): void + { + $this->assertSame([], $this->validator->validateCustomKey('partner_id')); + $this->assertSame([[UtmSettingsValidator::ERROR_KEY_INVALID, ['%key%' => 'Partner']]], $this->validator->validateCustomKey('Partner')); + $this->assertSame(UtmSettingsValidator::ERROR_KEY_INVALID, $this->validator->validateCustomKey('9lives')[0][0]); + $this->assertSame(UtmSettingsValidator::ERROR_KEY_INVALID, $this->validator->validateCustomKey('x')[0][0]); + } + + public function testCustomKeyCollisions(): void + { + foreach (['utm_source', 'gclid', 'ct', 'utm_partner', 'mtc_id'] as $key) { + $this->assertSame([[UtmSettingsValidator::ERROR_KEY_RESERVED, ['%key%' => $key]]], $this->validator->validateCustomKey($key), $key); + } + } + + public function testCustomKeyUniqueness(): void + { + $this->assertSame([], $this->validator->validateKeyIsUnique('ref', ['ref', 'partner'])); + $this->assertSame( + [[UtmSettingsValidator::ERROR_KEY_DUPLICATE, ['%key%' => 'ref']]], + $this->validator->validateKeyIsUnique('ref', ['ref', 'partner', 'ref']) + ); + } + + public function testEnabledDropdownNeedsValues(): void + { + $this->assertSame( + [[UtmSettingsValidator::ERROR_VALUES_REQUIRED, []]], + $this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, []) + ); + $this->assertSame([], $this->validator->validateValueList(UtmParameterMode::DROPDOWN, false, [])); + } + + public function testDuplicateValuesAreReportedOnce(): void + { + $rows = [['value' => 'email'], ['value' => 'email'], ['value' => 'email'], ['value' => 'sms']]; + + $this->assertSame( + [[UtmSettingsValidator::ERROR_VALUE_DUPLICATE, ['%value%' => 'email']]], + $this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, $rows) + ); + } + + public function testOnlyOneDefault(): void + { + $rows = [['value' => 'a', 'is_default' => true], ['value' => 'b', 'is_default' => true]]; + + $this->assertSame( + [[UtmSettingsValidator::ERROR_DEFAULT_MULTIPLE, []]], + $this->validator->validateValueList(UtmParameterMode::DROPDOWN, true, $rows) + ); + } + + public function testNothingIsCheckedOutsideDropdownMode(): void + { + $rows = [['value' => 'a', 'is_default' => true], ['value' => 'a', 'is_default' => true]]; + + $this->assertSame([], $this->validator->validateValueList(UtmParameterMode::FREE, true, $rows)); + $this->assertSame([], $this->validator->validateValueList(UtmParameterMode::DISABLED, true, $rows)); + $this->assertSame([], $this->validator->validateValueList(UtmParameterMode::FREE, true, [])); + } +} diff --git a/Tests/Unit/Form/Validator/SmartLinkValidatorTest.php b/Tests/Unit/Form/Validator/SmartLinkValidatorTest.php new file mode 100644 index 0000000..2fbcc3a --- /dev/null +++ b/Tests/Unit/Form/Validator/SmartLinkValidatorTest.php @@ -0,0 +1,155 @@ + '1', + 'separator_replacement' => '-', + 'parameters' => [ + 'utm_source' => [ + 'enabled' => '1', 'label' => 'Source', 'mode' => 'dropdown', + 'values' => [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn'], + ], + ], + 'utm_campaign' => ['enabled' => '1', 'label' => 'Campaign', 'mode' => 'free'], + ], + ]; + + private function createValidator(array $raw = self::RAW_CONFIG): SmartLinkValidator + { + $parameters = $this->createMock(CoreParametersHelper::class); + $parameters->method('get')->willReturnMap([ + [UtmConfigurationProvider::CONFIG_PARAMETER, [], $raw], + ]); + + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(fn (string $id): string => $id); + + $provider = new UtmConfigurationProvider( + $parameters, + new UtmConfigurationNormalizer(new UtmParameterCatalog()), + new UtmParameterCatalog(), + $translator + ); + + return new SmartLinkValidator($this->createMock(SmartLinkModel::class), $provider); + } + + private function createTaxonomy(array $parameters): UtmTaxonomy + { + $taxonomy = new UtmTaxonomy(); + $taxonomy->setName('Spring campaigns'); + $taxonomy->setParameters($parameters); + + return $taxonomy; + } + + public function testTaxonomyValuesAreAccepted(): void + { + $taxonomy = $this->createTaxonomy([ + 'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']], + 'utm_campaign' => [['value' => 'spring', 'label' => 'Spring']], + ]); + + $this->assertSame([], $this->createValidator()->validateUtmParameters([ + 'utm_source' => 'newsletter', + 'utm_campaign' => 'spring', + ], $taxonomy)); + } + + public function testValuesOutsideTheTaxonomyAreRejected(): void + { + $taxonomy = $this->createTaxonomy([ + 'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']], + ]); + + $errors = $this->createValidator()->validateUtmParameters([ + 'utm_source' => 'linkedin', + ], $taxonomy); + + $this->assertSame([[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_source', '%value%' => 'linkedin']]], $errors); + } + + public function testAStoredValueSurvivesAPlainReSave(): void + { + $taxonomy = $this->createTaxonomy([ + 'utm_source' => [['value' => 'newsletter', 'label' => 'Newsletter']], + ]); + + $this->assertSame([], $this->createValidator()->validateUtmParameters( + ['utm_source' => 'legacy_banner'], + $taxonomy, + ['utm_source' => 'legacy_banner'] + )); + } + + public function testFreeParametersTakeTheirValuesFromTheTaxonomyList(): void + { + // The admin left utm_campaign free, but the taxonomy carries its own value list: the + // link picks a value from it, nothing is free-typed. + $taxonomy = $this->createTaxonomy([ + 'utm_campaign' => [ + ['value' => 'spring', 'label' => 'Spring'], + ['value' => 'summer', 'label' => 'Summer'], + ], + ]); + + $this->assertSame([], $this->createValidator()->validateUtmParameters([ + 'utm_campaign' => 'spring', + ], $taxonomy)); + + $this->assertSame( + [[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_campaign', '%value%' => 'autumn']]], + $this->createValidator()->validateUtmParameters(['utm_campaign' => 'autumn'], $taxonomy) + ); + } + + public function testParametersTheTaxonomyDoesntDefineAreRejected(): void + { + // The taxonomy defines neither the configured dropdown utm_source nor the free + // utm_campaign: both are unknown to it. + $taxonomy = $this->createTaxonomy([]); + + $this->assertSame( + [[SmartLinkValidator::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => 'utm_source', '%name%' => 'Spring campaigns']]], + $this->createValidator()->validateUtmParameters(['utm_source' => 'newsletter'], $taxonomy) + ); + $this->assertSame( + [[SmartLinkValidator::ERROR_TAXONOMY_PARAMETER_UNKNOWN, ['%key%' => 'utm_campaign', '%name%' => 'Spring campaigns']]], + $this->createValidator()->validateUtmParameters(['utm_campaign' => 'spring'], $taxonomy) + ); + } + + public function testWithoutATaxonomyTheGlobalConfigurationApplies(): void + { + $validator = $this->createValidator(); + + // Free parameter: any well-formed value; dropdown: only the configured list. + $this->assertSame([], $validator->validateUtmParameters(['utm_campaign' => 'spring', 'utm_source' => 'newsletter'])); + $this->assertSame([], $validator->validateUtmParameters(['utm_campaign' => 'spring'], null, ['utm_campaign' => 'spring'])); + $this->assertSame( + [[SmartLinkValidator::ERROR_UTM_VALUE_NOT_ALLOWED, ['%key%' => 'utm_source', '%value%' => 'facebook']]], + $validator->validateUtmParameters(['utm_source' => 'facebook']) + ); + } +} \ No newline at end of file diff --git a/Tests/Unit/Model/SmartLinkModelTest.php b/Tests/Unit/Model/SmartLinkModelTest.php new file mode 100644 index 0000000..69af8ee --- /dev/null +++ b/Tests/Unit/Model/SmartLinkModelTest.php @@ -0,0 +1,250 @@ +createMock(CoreParametersHelper::class); + $parameters->method('get')->willReturnMap([ + [UtmConfigurationProvider::CONFIG_PARAMETER, [], $raw], + ]); + + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(fn (string $id): string => $id); + + return new UtmConfigurationProvider( + $parameters, + new UtmConfigurationNormalizer(new UtmParameterCatalog()), + new UtmParameterCatalog(), + $translator + ); + } + + /** + * The model with mocked core dependencies; the UTM configuration is real. + */ + private function createModel(array $raw, ?PageModel $pageModel = null, ?UrlGeneratorInterface $router = null): SmartLinkModel + { + return new SmartLinkModel( + $this->createMock(EntityManagerInterface::class), + $this->createMock(CorePermissions::class), + $this->createMock(EventDispatcherInterface::class), + $router ?? $this->createMock(UrlGeneratorInterface::class), + $this->createMock(TranslatorInterface::class), + $this->createMock(UserHelper::class), + $this->createMock(LoggerInterface::class), + $this->createMock(CoreParametersHelper::class), + $this->createProvider($raw), + $pageModel ?? $this->createMock(PageModel::class) + ); + } + + public function testSlugRulesApplyOnNewLink(): void + { + $model = $this->createModel(['separator_replacement' => '_', 'enforce_lowercase' => '1']); + $link = $model->getEntity(); + + $model->applySlugRules($link, 'Big Camp'); + $this->assertSame('big_camp', $link->getSlug()); + } + + public function testSlugRulesWithLowercaseDisabled(): void + { + $model = $this->createModel(['separator_replacement' => '-', 'enforce_lowercase' => '']); + $link = $model->getEntity(); + + $model->applySlugRules($link, 'Big Camp'); + $this->assertSame('Big-Camp', $link->getSlug()); + } + + public function testSlugRulesKeepStoredSlugOnEdit(): void + { + $model = $this->createModel([]); + + $reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class); + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + $reflection->getProperty('id')->setValue($link, 1); + $link->setSlug('stored'); + + // The user never edits the slug of a saved link: the submitted value is ignored... + $model->applySlugRules($link); + $this->assertSame('stored', $link->getSlug()); + + // ...and passing a different slug explicitly is refused. + $this->expectException(\LogicException::class); + $model->applySlugRules($link, 'other'); + } + + public function testNormalizeUtmValues(): void + { + $model = $this->createModel(['enforce_lowercase' => '1']); + + $this->assertSame( + // The model sorts the keys, so the stored array is deterministic. + ['utm_medium' => 'email', 'utm_source' => 'acme'], + $model->normalizeUtmValues(['utm_source' => 'ACME ', 'utm_medium' => 'Email', 'utm_term' => '']) + ); + + $modelNoLower = $this->createModel(['enforce_lowercase' => '']); + $this->assertSame( + ['utm_source' => 'ACME'], + $modelNoLower->normalizeUtmValues(['utm_source' => 'ACME']) + ); + } + + public function testNormalizeUtmValuesUsesValuePatternToo(): void + { + $model = $this->createModel(['enforce_lowercase' => '1']); + // Values of disabled parameters and empty values are dropped by the form; the model + // only applies the case and separator rules. + $this->assertSame(['a' => 'b'], $model->normalizeUtmValues(['a' => 'b', 'x' => null])); + } + + public function testEnabledParameterDefaultModeIsRespected(): void + { + // An empty configuration leaves the utm_source dropdown switched off: an enabled + // dropdown needs values, and they are configured on the Configuration page. + $provider = $this->createProvider([]); + $source = $provider->getParameter('utm_source'); + + $this->assertNotNull($source); + $this->assertFalse($source['enabled']); + $this->assertSame(UtmParameterMode::DROPDOWN, $source['mode']); + $this->assertSame([], $provider->getDropdownValues('utm_source')); + + // Enabled with stored values it stays a dropdown and serves them. + $enabled = $this->createProvider(['parameters' => [ + 'utm_source' => [ + 'enabled' => '1', + 'label' => 'Source', + 'mode' => 'dropdown', + 'values' => [['value' => 'newsletter', 'label' => 'Newsletter']], + ], + ]]); + $source = $enabled->getParameter('utm_source'); + $this->assertTrue($source['enabled']); + $this->assertSame(UtmParameterMode::DROPDOWN, $source['mode']); + $this->assertNotSame([], $enabled->getDropdownValues('utm_source')); + } + + /** + * @param array $utms + */ + #[DataProvider('redirectUrlProvider')] + public function testBuildRedirectUrl(string $destination, array $utms, string $expected): void + { + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + $link->setDestinationUrl($destination); + $link->setUtmParameters($utms); + + $this->assertSame($expected, $this->createModel([])->buildRedirectUrl($link)); + } + + /** + * @return iterable, 2: string}> + */ + public static function redirectUrlProvider(): iterable + { + yield 'no utm parameters keeps destination as-is' => [ + 'https://www.example.com/spring', + [], + 'https://www.example.com/spring', + ]; + + yield 'parameters are appended to a bare destination' => [ + 'https://www.example.com/spring', + ['utm_source' => 'newsletter', 'utm_medium' => 'email'], + 'https://www.example.com/spring?utm_source=newsletter&utm_medium=email', + ]; + + yield 'existing query is kept, link parameters override same-named ones' => [ + 'https://www.example.com/spring?foo=bar&utm_medium=paid', + ['utm_medium' => 'email', 'utm_source' => 'newsletter'], + 'https://www.example.com/spring?foo=bar&utm_medium=email&utm_source=newsletter', + ]; + + yield 'fragment and parts of the destination survive' => [ + 'https://user.example.com:8443/path/page#section', + ['utm_source' => 'x'], + 'https://user.example.com:8443/path/page?utm_source=x#section', + ]; + } + + public function testBuildMauticDestinationUrlWithoutDestinationIsEmpty(): void + { + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + + $this->assertSame('', $this->createModel([])->buildMauticDestinationUrl($link)); + } + + public function testBuildMauticDestinationUrlUsesThePageModel(): void + { + $pageModel = $this->createMock(PageModel::class); + $pageModel->method('generateUrl')->willReturn('https://mautic.example.com/landing'); + + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + $reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class); + $reflection->getProperty('page')->setValue($link, $this->createMock(\Mautic\PageBundle\Entity\Page::class)); + + $this->assertSame('https://mautic.example.com/landing', $this->createModel([], $pageModel)->buildMauticDestinationUrl($link)); + } + + public function testBuildMauticDestinationUrlUsesTheFormPreviewRoute(): void + { + $router = $this->createMock(UrlGeneratorInterface::class); + $router->method('generate') + ->with('mautic_form_preview', ['id' => 7], UrlGeneratorInterface::ABSOLUTE_URL) + ->willReturn('https://mautic.example.com/form/7'); + + $form = $this->createMock(\Mautic\FormBundle\Entity\Form::class); + $form->method('getId')->willReturn(7); + + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + $reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class); + $reflection->getProperty('form')->setValue($link, $form); + + $this->assertSame('https://mautic.example.com/form/7', $this->createModel([], null, $router)->buildMauticDestinationUrl($link)); + } + + public function testBuildRedirectUrlAppendsUtmToMauticDestinations(): void + { + $pageModel = $this->createMock(PageModel::class); + $pageModel->method('generateUrl')->willReturn('https://mautic.example.com/landing'); + + $link = new \MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink(); + $link->setRedirectType(\MauticPlugin\MT3SMarketingProgramBundle\Catalog\SmartLinkRedirectType::Mautic); + $link->setUtmParameters(['utm_source' => 'newsletter']); + $reflection = new \ReflectionClass(\MauticPlugin\MT3SMarketingProgramBundle\Entity\SmartLink::class); + $reflection->getProperty('page')->setValue($link, $this->createMock(\Mautic\PageBundle\Entity\Page::class)); + + $this->assertSame( + 'https://mautic.example.com/landing?utm_source=newsletter', + $this->createModel([], $pageModel)->buildRedirectUrl($link) + ); + } +} diff --git a/Tests/Unit/Model/UtmTaxonomyModelTest.php b/Tests/Unit/Model/UtmTaxonomyModelTest.php new file mode 100644 index 0000000..89838cd --- /dev/null +++ b/Tests/Unit/Model/UtmTaxonomyModelTest.php @@ -0,0 +1,67 @@ +createMock(EntityManagerInterface::class), + $this->createMock(CorePermissions::class), + $this->createMock(EventDispatcherInterface::class), + $this->createMock(UrlGeneratorInterface::class), + $this->createMock(TranslatorInterface::class), + $this->createMock(UserHelper::class), + $this->createMock(LoggerInterface::class), + $this->createMock(CoreParametersHelper::class) + ); + } + + public function testNormalizeParametersTrimsDeduplicatesSortsAndFallsBackToTheValueAsLabel(): void + { + $clean = $this->createModel()->normalizeParameters([ + 'utm_source' => [ + ['value' => ' newsletter ', 'label' => 'Newsletter'], + ['value' => 'newsletter', 'label' => 'Duplicate value, dropped'], + ['value' => '', 'label' => 'Empty value, dropped'], + 'not-an-array', + ], + 'utm_campaign' => [ + ['value' => 'spring', 'label' => ''], + ], + ' ' => [['value' => 'x', 'label' => 'X']], + 'not-an-array' => 'nope', + ]); + + $this->assertSame([ + 'utm_campaign' => [ + ['value' => 'spring', 'label' => 'spring'], + ], + 'utm_source' => [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ], + ], $clean); + } + + public function testNormalizeParametersDropsParametersWithoutValues(): void + { + $this->assertSame([], $this->createModel()->normalizeParameters([ + 'utm_source' => [['value' => '', 'label' => 'Empty']], + 'gclid' => [], + ])); + } +} \ No newline at end of file diff --git a/Tests/Unit/Service/UtmConfigurationProviderTest.php b/Tests/Unit/Service/UtmConfigurationProviderTest.php new file mode 100644 index 0000000..938c29b --- /dev/null +++ b/Tests/Unit/Service/UtmConfigurationProviderTest.php @@ -0,0 +1,193 @@ + '', + 'separator_replacement' => '_', + 'parameters' => [ + 'utm_source' => [ + 'enabled' => '1', + 'label' => 'Source', + 'mode' => 'dropdown', + 'values' => [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn'], + ], + 'default' => 'linkedin', + ], + 'utm_medium' => [ + 'enabled' => '', + 'label' => 'Medium', + 'mode' => 'dropdown', + 'values' => [['value' => 'email', 'label' => 'Email']], + 'default' => '', + ], + // Values left in storage for a free parameter must never be exposed. + 'utm_campaign' => [ + 'enabled' => '1', + 'label' => '', + 'mode' => 'free', + 'values' => [['value' => 'should_not_appear', 'label' => 'x']], + 'default' => 'should_not_appear', + ], + 'utm_term' => ['enabled' => '1', 'label' => 'Term', 'mode' => 'disabled'], + 'gclid' => ['enabled' => '1', 'label' => 'GCLID', 'mode' => 'free'], + // Dropdown isn't allowed for click IDs: falls back to the default mode (disabled). + 'fbclid' => ['enabled' => '1', 'label' => 'FB', 'mode' => 'dropdown', 'values' => [['value' => 'a', 'label' => 'a']]], + 'partner' => ['enabled' => '1', 'label' => 'Partner', 'mode' => 'dropdown', 'values' => [['value' => 'acme', 'label' => 'ACME']], 'default' => ''], + 'utm_hack' => ['enabled' => '1', 'label' => 'Invalid custom key', 'mode' => 'free'], + ], + ]; + + public function testGetEnabledParameters(): void + { + $enabled = $this->createProvider(self::STORED)->getEnabledParameters(); + + // Enabled and not in disabled mode, catalog order first, then custom parameters. + $this->assertSame(['utm_source', 'utm_campaign', 'utm_content', 'utm_id', 'gclid', 'partner'], array_keys($enabled)); + + $this->assertSame([ + 'key' => 'utm_source', + 'enabled' => true, + 'label' => 'Source', + 'mode' => UtmParameterMode::DROPDOWN, + 'values' => [ + ['value' => 'newsletter', 'label' => 'Newsletter'], + ['value' => 'linkedin', 'label' => 'LinkedIn'], + ], + 'default' => 'linkedin', + 'group' => UtmParameterCatalog::GROUP_STANDARD, + 'custom' => false, + 'auto_generated' => false, + ], $enabled['utm_source']); + + $this->assertTrue($enabled['partner']['custom']); + $this->assertSame(UtmParameterCatalog::GROUP_CUSTOM, $enabled['partner']['group']); + $this->assertTrue($enabled['gclid']['auto_generated']); + } + + public function testFreeParameterExposesNoValues(): void + { + $provider = $this->createProvider(self::STORED); + $campaign = $provider->getParameter('utm_campaign'); + + $this->assertSame([ + 'key' => 'utm_campaign', + 'enabled' => true, + 'label' => 'translated:mautic.smartlinks.config.parameter.utm_campaign.label', + 'mode' => UtmParameterMode::FREE, + 'group' => UtmParameterCatalog::GROUP_STANDARD, + 'custom' => false, + 'auto_generated' => false, + ], $campaign); + $this->assertSame([], $provider->getDropdownValues('utm_campaign')); + } + + public function testGetParameter(): void + { + $provider = $this->createProvider(self::STORED); + + $this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('utm_term')['mode'] ?? null); + $this->assertArrayNotHasKey('values', $provider->getParameter('utm_term') ?? []); + $this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('fbclid')['mode'] ?? null); + $this->assertFalse($provider->getParameter('utm_medium')['enabled'] ?? null); + $this->assertArrayHasKey('default', $provider->getParameter('utm_medium')); + $this->assertNull($provider->getParameter('utm_medium')['default']); + $this->assertSame('Partner', $provider->getParameter('partner')['label'] ?? null); + $this->assertNull($provider->getParameter('unknown')); + $this->assertNull($provider->getParameter('utm_hack'), 'Custom keys with a reserved prefix are ignored.'); + } + + public function testGetDropdownValues(): void + { + $provider = $this->createProvider(self::STORED); + + $this->assertSame( + [['value' => 'newsletter', 'label' => 'Newsletter'], ['value' => 'linkedin', 'label' => 'LinkedIn']], + $provider->getDropdownValues('utm_source') + ); + $this->assertSame([['value' => 'acme', 'label' => 'ACME']], $provider->getDropdownValues('partner')); + $this->assertSame([['value' => 'email', 'label' => 'Email']], $provider->getDropdownValues('utm_medium')); + $this->assertSame([], $provider->getDropdownValues('utm_term')); + $this->assertSame([], $provider->getDropdownValues('gclid')); + $this->assertSame([], $provider->getDropdownValues('fbclid')); + $this->assertSame([], $provider->getDropdownValues('unknown')); + } + + public function testGeneralSettings(): void + { + $provider = $this->createProvider(self::STORED); + + $this->assertFalse($provider->isLowercaseEnforced()); + $this->assertSame('_', $provider->getSeparatorReplacement()); + } + + public function testDefaultsWhenNothingIsStored(): void + { + $provider = $this->createProvider(null); + + $this->assertTrue($provider->isLowercaseEnforced()); + $this->assertSame('-', $provider->getSeparatorReplacement()); + + // Free catalog parameters are enabled by default, dropdown parameters wait for values, click IDs are disabled. + $this->assertSame(['utm_campaign', 'utm_term', 'utm_content', 'utm_id'], array_keys($provider->getEnabledParameters())); + $this->assertSame(UtmParameterMode::DROPDOWN, $provider->getParameter('utm_source')['mode'] ?? null); + $this->assertFalse($provider->getParameter('utm_source')['enabled'] ?? null); + $this->assertSame([], $provider->getDropdownValues('utm_source')); + $this->assertSame(UtmParameterMode::DISABLED, $provider->getParameter('gclid')['mode'] ?? null); + } + + public function testInvalidSeparatorFallsBackToHyphen(): void + { + $this->assertSame('-', $this->createProvider(['separator_replacement' => ' '])->getSeparatorReplacement()); + } + + public function testLegacyParameterIsServedUntilTheNewOneIsSaved(): void + { + // Upgrades from < 0.5.0: the new key is empty, the settings live under the legacy key. + $provider = $this->createProvider([], self::STORED); + + $this->assertFalse($provider->isLowercaseEnforced()); + $this->assertSame('_', $provider->getSeparatorReplacement()); + $this->assertSame( + ['utm_source', 'utm_campaign', 'utm_content', 'utm_id', 'gclid', 'partner'], + array_keys($provider->getEnabledParameters()) + ); + } + + private function createProvider(mixed $stored, ?array $legacy = null): UtmConfigurationProvider + { + $parameters = $this->createMock(CoreParametersHelper::class); + $parameters->method('get') + ->willReturnCallback( + fn (string $name, mixed $default = null): mixed => match (true) { + UtmConfigurationProvider::CONFIG_PARAMETER === $name => $stored, + UtmConfigurationProvider::LEGACY_CONFIG_PARAMETER === $name && null !== $legacy => $legacy, + default => $default, + } + ); + + $translator = $this->createMock(TranslatorInterface::class); + $translator->method('trans')->willReturnCallback(fn (string $key): string => 'translated:'.$key); + + $catalog = new UtmParameterCatalog(); + + return new UtmConfigurationProvider($parameters, new UtmConfigurationNormalizer($catalog), $catalog, $translator); + } +} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php new file mode 100644 index 0000000..449569c --- /dev/null +++ b/Tests/bootstrap.php @@ -0,0 +1,19 @@ + Configuration tab title. Core builds this key from the form alias (mautic.config.tab.). +mautic.config.tab.smartlinksconfig="Smart Links Settings" +; Settings > Configuration > Smart Links Settings. +mautic.smartlinks.settings.description="Settings for Smart Links: the UTM parameters they carry, the general rules and the domain of their short links." +mautic.smartlinks.settings.short_link_domain="Short Link Domain" +mautic.smartlinks.settings.short_link_domain.tooltip="Domain used to create future short links, for example lnk.example.com. Do not include https://." +mautic.smartlinks.settings.placeholder="Smart Links will appear here." +; Smart Links (main menu > Smart Links). Translation base mautic.smartlinks.smart_links. +mautic.smartlinks.smart_links.header.index="Smart Links" +mautic.smartlinks.smart_links.header.new="New Smart Link" +mautic.smartlinks.smart_links.header.edit="Smart Link - %slug%" +mautic.smartlinks.smart_links.slug="Slug" +mautic.smartlinks.smart_links.slug.tooltip="Short text (max 9 characters). Spaces are replaced by the configured character, uppercase is turned into lowercase when the link is saved. The slug can't be changed after the link is created." +mautic.smartlinks.smart_links.slug.generate="Generate" +mautic.smartlinks.smart_links.slug.generate.tooltip="Use a random slug of 4 letters and digits." +mautic.smartlinks.smart_links.short_link="Short link" +mautic.smartlinks.smart_links.domain.reminder="Short links domain:" +mautic.smartlinks.smart_links.domain.reminder.empty="No short links domain configured. Set it in Settings > Configuration > Smart Links Settings." +mautic.smartlinks.smart_links.redirect_type="Redirect type" +mautic.smartlinks.smart_links.redirect_type.mautic="Mautic" +mautic.smartlinks.smart_links.redirect_type.external="External" +mautic.smartlinks.smart_links.redirect_code="Redirect HTTP code" +mautic.smartlinks.smart_links.redirect_code.301="301 - Moved permanently — permanent" +mautic.smartlinks.smart_links.redirect_code.302="302 - Found — temporary" +mautic.smartlinks.smart_links.redirect_code.307="307 - Temporary redirect — temporary" +mautic.smartlinks.smart_links.redirect_code.308="308 - Permanent redirect — permanent" +mautic.smartlinks.smart_links.destination_url="Destination URL" +mautic.smartlinks.smart_links.destination_url.tooltip="Where the visitor lands, for example https://www.example.com/page. Only used for external redirects." +mautic.smartlinks.smart_links.destination="Destination" +mautic.smartlinks.smart_links.destination.tooltip="The landing page or the standalone form the visitor is redirected to. Only used for Mautic redirects." +mautic.smartlinks.smart_links.destination.pages="Landing pages" +mautic.smartlinks.smart_links.destination.forms="Standalone forms" +mautic.smartlinks.smart_links.destination.unpublished="No longer published" +mautic.smartlinks.smart_links.utm_parameters="UTM parameters" +mautic.smartlinks.smart_links.utm_parameters.help="Choose the UTM Taxonomy first: each value below is picked among the values it allows." +mautic.smartlinks.smart_links.onboarding.heading="No Smart Links yet" +mautic.smartlinks.smart_links.onboarding.subheading="Smart Links are short links that carry your UTM parameters." +mautic.smartlinks.smart_links.onboarding.copy="Use the New button above to create one. Its slug can't be changed after creation; delete it and create a new one instead." +mautic.smartlinks.smart_links.menu.new="New Smart Link" +mautic.smartlinks.smart_links.menu.edit="Edit %name%" +mautic.smartlinks.smart_links.menu.delete="Delete %name%" +mautic.smartlinks.smart_links.form.confirmdelete="Delete the Smart Link %name%? It can't be restored." +mautic.smartlinks.smart_links.form.confirmbatchdelete="Delete the selected Smart Links? They can't be restored." +mautic.smartlinks.smart_links.error.notfound="No Smart Link with the ID %id% was found." +mautic.smartlinks.smart_links.permissions.header="Smart Links - User has access to" +mautic.smartlinks.smart_links.hits="Hits" +mautic.smartlinks.smart_links.hits.tooltip="Number of times the short link redirected a visitor." +mautic.smartlinks.config.description="Define the UTM parameters offered by the link builder and how each one is presented." +mautic.smartlinks.config.section.utm_settings="UTM Settings" +mautic.smartlinks.config.section.parameters="Parameters" +mautic.smartlinks.config.group.standard="Standard UTM" +mautic.smartlinks.config.group.platform="Platform identifiers" +mautic.smartlinks.config.group.custom="Custom parameters" +mautic.smartlinks.config.enforce_lowercase="Enforce lowercase on all values" +mautic.smartlinks.config.enforce_lowercase.tooltip="The link builder converts every parameter value to lowercase." +mautic.smartlinks.config.separator_replacement="Value separator replacement" +mautic.smartlinks.config.separator_replacement.tooltip="Character that replaces spaces in parameter values." +mautic.smartlinks.config.separator.hyphen="Hyphen ( - )" +mautic.smartlinks.config.separator.underscore="Underscore ( _ )" +mautic.smartlinks.config.separator.dot="Dot ( . )" +mautic.smartlinks.config.parameter.enabled="Enabled" +mautic.smartlinks.config.parameter.label="Label" +mautic.smartlinks.config.parameter.mode="Mode" +mautic.smartlinks.config.parameter.key="Key" +mautic.smartlinks.config.parameter.key.tooltip="Name of the URL parameter: lowercase letters, digits and underscores, starting with a letter (2 to 41 characters)." +mautic.smartlinks.config.mode.dropdown="Dropdown (list of values)" +mautic.smartlinks.config.mode.free="Free text" +mautic.smartlinks.config.mode.disabled="Disabled" +mautic.smartlinks.config.auto_generated.badge="Auto" +mautic.smartlinks.config.auto_generated.tooltip="Usually added automatically by the ad platform. Only enable if you need to handle it manually." +mautic.smartlinks.config.values="Allowed values" +mautic.smartlinks.config.values.value="Value" +mautic.smartlinks.config.values.label="Label" +mautic.smartlinks.config.values.default="Default" +mautic.smartlinks.config.values.add="Add value" +mautic.smartlinks.config.values.remove="Remove value" +mautic.smartlinks.config.values.drag="Drag to reorder" +mautic.smartlinks.config.values.empty="No values yet." +mautic.smartlinks.config.values.suggestions="Load suggested values" +mautic.smartlinks.config.values.import="Paste values (one per line, or value;label)" +mautic.smartlinks.config.values.import.placeholder="newsletter;Newsletter" +mautic.smartlinks.config.values.import.button="Import" +mautic.smartlinks.config.custom.add="Add custom parameter" +mautic.smartlinks.config.custom.remove="Delete" +mautic.smartlinks.config.custom.new="new parameter" +mautic.smartlinks.config.custom.empty="No custom parameters." +mautic.smartlinks.config.parameter.utm_source.label="Source" +mautic.smartlinks.config.parameter.utm_source.description="Traffic origin, for example newsletter, linkedin or google." +mautic.smartlinks.config.parameter.utm_medium.label="Medium" +mautic.smartlinks.config.parameter.utm_medium.description="Channel type, for example email, cpc, social or referral." +mautic.smartlinks.config.parameter.utm_campaign.label="Campaign" +mautic.smartlinks.config.parameter.utm_campaign.description="Campaign name." +mautic.smartlinks.config.parameter.utm_term.label="Term" +mautic.smartlinks.config.parameter.utm_term.description="Paid search keyword." +mautic.smartlinks.config.parameter.utm_content.label="Content" +mautic.smartlinks.config.parameter.utm_content.description="Differentiates variants or links that point to the same URL." +mautic.smartlinks.config.parameter.utm_id.label="Campaign ID" +mautic.smartlinks.config.parameter.utm_id.description="Campaign ID, used by GA4 data import." +mautic.smartlinks.config.parameter.utm_source_platform.label="Source platform" +mautic.smartlinks.config.parameter.utm_source_platform.description="Platform that manages the campaign, for example Google Ads." +mautic.smartlinks.config.parameter.utm_creative_format.label="Creative format" +mautic.smartlinks.config.parameter.utm_creative_format.description="Creative type, for example display, video or native." +mautic.smartlinks.config.parameter.utm_marketing_tactic.label="Marketing tactic" +mautic.smartlinks.config.parameter.utm_marketing_tactic.description="Targeting tactic, for example prospecting or remarketing." +mautic.smartlinks.config.parameter.gclid.label="Google Ads click ID" +mautic.smartlinks.config.parameter.gclid.description="Click ID added by Google Ads." +mautic.smartlinks.config.parameter.gbraid.label="Google Ads iOS web-to-app ID" +mautic.smartlinks.config.parameter.gbraid.description="Click ID added by Google Ads for iOS web-to-app measurement." +mautic.smartlinks.config.parameter.wbraid.label="Google Ads iOS app-to-web ID" +mautic.smartlinks.config.parameter.wbraid.description="Click ID added by Google Ads for iOS app-to-web measurement." +mautic.smartlinks.config.parameter.dclid.label="Display & Video 360 click ID" +mautic.smartlinks.config.parameter.dclid.description="Click ID added by Google Display & Video 360." +mautic.smartlinks.config.parameter.fbclid.label="Meta click ID" +mautic.smartlinks.config.parameter.fbclid.description="Click ID added by Meta (Facebook, Instagram)." +mautic.smartlinks.config.parameter.msclkid.label="Microsoft Advertising click ID" +mautic.smartlinks.config.parameter.msclkid.description="Click ID added by Microsoft Advertising." +mautic.smartlinks.config.parameter.ttclid.label="TikTok click ID" +mautic.smartlinks.config.parameter.ttclid.description="Click ID added by TikTok." +mautic.smartlinks.config.parameter.li_fat_id.label="LinkedIn click ID" +mautic.smartlinks.config.parameter.li_fat_id.description="Click ID added by LinkedIn." +mautic.smartlinks.config.parameter.twclid.label="X click ID" +mautic.smartlinks.config.parameter.twclid.description="Click ID added by X (Twitter)." +mautic.smartlinks.config.parameter.epik.label="Pinterest click ID" +mautic.smartlinks.config.parameter.epik.description="Click ID added by Pinterest." +mautic.smartlinks.config.suggestion.newsletter="Newsletter" +mautic.smartlinks.config.suggestion.linkedin="LinkedIn" +mautic.smartlinks.config.suggestion.facebook="Facebook" +mautic.smartlinks.config.suggestion.instagram="Instagram" +mautic.smartlinks.config.suggestion.google="Google" +mautic.smartlinks.config.suggestion.youtube="YouTube" +mautic.smartlinks.config.suggestion.x="X" +mautic.smartlinks.config.suggestion.tiktok="TikTok" +mautic.smartlinks.config.suggestion.partner="Partner" +mautic.smartlinks.config.suggestion.direct="Direct" +mautic.smartlinks.config.suggestion.email="Email" +mautic.smartlinks.config.suggestion.cpc="Cost per click" +mautic.smartlinks.config.suggestion.social="Social" +mautic.smartlinks.config.suggestion.social_paid="Paid social" +mautic.smartlinks.config.suggestion.display="Display" +mautic.smartlinks.config.suggestion.affiliate="Affiliate" +mautic.smartlinks.config.suggestion.referral="Referral" +mautic.smartlinks.config.suggestion.qr="QR code" +mautic.smartlinks.config.suggestion.sms="SMS" +mautic.smartlinks.config.suggestion.print="Print" +mautic.smartlinks.config.suggestion.event="Event" +mautic.smartlinks.config.suggestion.google_ads="Google Ads" +mautic.smartlinks.config.suggestion.meta_ads="Meta Ads" +mautic.smartlinks.config.suggestion.linkedin_ads="LinkedIn Ads" +mautic.smartlinks.config.suggestion.microsoft_ads="Microsoft Ads" +mautic.smartlinks.config.suggestion.tiktok_ads="TikTok Ads" +mautic.smartlinks.config.suggestion.banner="Banner" +mautic.smartlinks.config.suggestion.video="Video" +mautic.smartlinks.config.suggestion.carousel="Carousel" +mautic.smartlinks.config.suggestion.text="Text" +mautic.smartlinks.config.suggestion.native="Native" +mautic.smartlinks.config.suggestion.prospecting="Prospecting" +mautic.smartlinks.config.suggestion.remarketing="Remarketing" +mautic.smartlinks.config.suggestion.retargeting="Retargeting" +mautic.smartlinks.config.suggestion.brand="Brand" +mautic.smartlinks.config.suggestion.nurturing="Nurturing" +; "UTM tags" section of the Email and Focus Item forms. +mautic.smartlinks.form.choose="Choose..." +mautic.smartlinks.form.legacy_choice="%value% (not in taxonomy)" +mautic.smartlinks.form.legacy_warning="This value is not part of the UTM taxonomy." +mautic.smartlinks.form.no_values="No values configured for this parameter. Ask an administrator." +; Smart Link form and UTM Taxonomies (Smart Links > UTM Taxonomies). Translation base mautic.smartlinks.taxonomies. +mautic.smartlinks.smart_links.taxonomy="UTM Taxonomy" +mautic.smartlinks.smart_links.taxonomy.tooltip="The set of allowed values for the UTM parameters of this link. Every value of the link is picked among the values the taxonomy allows." +mautic.smartlinks.taxonomies.header.index="UTM Taxonomies" +mautic.smartlinks.taxonomies.header.new="New UTM Taxonomy" +mautic.smartlinks.taxonomies.header.edit="UTM Taxonomy - %name%" +mautic.smartlinks.taxonomies.name="Name" +mautic.smartlinks.taxonomies.name.tooltip="A unique, short name identifying this set of allowed UTM values." +mautic.smartlinks.taxonomies.description="Description" +mautic.smartlinks.taxonomies.parameters="UTM parameters" +mautic.smartlinks.taxonomies.parameters.help="Every parameter enabled in Smart Links Settings appears. Dropdown parameters offer the values the admin configured: check the ones a Smart Link may carry. Free-text parameters get their own value list here: a link then picks a value from it instead of typing freely." +mautic.smartlinks.taxonomies.parameter_count="Parameters" +mautic.smartlinks.taxonomies.parameter_count.tooltip="The number of parameters this taxonomy defines values for." +mautic.smartlinks.taxonomies.menu.new="New UTM Taxonomy" +mautic.smartlinks.taxonomies.menu.edit="Edit %name%" +mautic.smartlinks.taxonomies.menu.delete="Delete %name%" +mautic.smartlinks.taxonomies.form.confirmdelete="Delete the UTM Taxonomy %name%? It cannot be restored. The Smart Links that use it keep the values they already carry and ask for a new taxonomy on their next edit." +mautic.smartlinks.taxonomies.form.confirmbatchdelete="Delete the selected UTM Taxonomies? They cannot be restored." +mautic.smartlinks.taxonomies.error.notfound="No UTM Taxonomy with the id %id%." +mautic.smartlinks.taxonomies.permissions.header="UTM Taxonomies - The user has access to" +mautic.smartlinks.taxonomies.onboarding.heading="No UTM Taxonomies yet" +mautic.smartlinks.taxonomies.onboarding.subheading="UTM Taxonomies are sets of allowed values for the UTM parameters of your Smart Links." +mautic.smartlinks.taxonomies.onboarding.copy="Use the New button above to create one. A Smart Link carries one taxonomy; every UTM value it carries is picked among the values the taxonomy allows." +mautic.smartlinks.taxonomies.unpublished_choice="%name% (no longer published)" +mautic.smartlinks.taxonomies.free_values.tooltip="The allowed values of this parameter for the links using this taxonomy. One value per line, optionally value;Label for a display label." +mautic.smartlinks.taxonomies.free_values.placeholder="one value per line" +mautic.smartlinks.taxonomies.no_values.tooltip="No values are configured for this parameter in Smart Links Settings yet: ask the admin to configure some." diff --git a/Translations/en_US/validators.ini b/Translations/en_US/validators.ini index 7142bb4..1c23433 100644 --- a/Translations/en_US/validators.ini +++ b/Translations/en_US/validators.ini @@ -21,3 +21,41 @@ mt3s.marketing_program.description_item.type.required="Choose a type." mt3s.marketing_program.config.type.name.required="A type needs a name in the default language." mt3s.marketing_program.config.type.in_use="These types are in use and can't be removed: %types%. Change the items or tasks that use them to another type first." mt3s.marketing_program.allocation_item.type.required="Choose a type." + +; Form validation messages of Settings > Configuration > UTM Settings (Symfony translates them in the validators domain). +mautic.smartlinks.config.error.key_required="Enter a key for the custom parameter." +mautic.smartlinks.config.error.key_invalid="The key \"%key%\" is invalid. Use 2 to 41 lowercase letters, digits or underscores, starting with a letter." +mautic.smartlinks.config.error.key_reserved="The key \"%key%\" is reserved. Keys of the catalog, \"ct\", keys starting with \"utm\" and keys starting with \"mtc_\" can't be used." +mautic.smartlinks.config.error.key_duplicate="The key \"%key%\" is used by more than one custom parameter." +mautic.smartlinks.config.error.mode_invalid="This mode isn't available for this parameter." +mautic.smartlinks.config.error.separator_invalid="Choose a hyphen, an underscore or a dot." +mautic.smartlinks.config.error.label_required="Enter a label." +mautic.smartlinks.config.error.label_length="The label can't be longer than {{ limit }} characters." +mautic.smartlinks.config.error.label_invalid="The label can't contain the % character." +mautic.smartlinks.config.error.value_required="Enter a value." +mautic.smartlinks.config.error.value_length="The value can't be longer than {{ limit }} characters." +mautic.smartlinks.config.error.value_invalid="Use only lowercase letters, digits, hyphens, underscores and dots in values." +mautic.smartlinks.config.error.value_duplicate="The value \"%value%\" appears more than once." +mautic.smartlinks.config.error.values_required="An enabled parameter in dropdown mode needs at least one value." +mautic.smartlinks.config.error.default_multiple="Only one value can be the default." +; "UTM tags" section of the Email and Focus Item forms. +mautic.smartlinks.form.error.not_in_taxonomy="This value is not part of the UTM taxonomy. Choose a value from the list." +; Smart Link form (main menu > Smart Links). +mautic.smartlinks.smart_links.error.slug_required="Enter a slug." +mautic.smartlinks.smart_links.error.slug_length="The slug can't be longer than {{ limit }} characters." +mautic.smartlinks.smart_links.error.slug_characters="Use only letters, digits, hyphens, underscores and dots in the slug." +mautic.smartlinks.smart_links.error.slug_taken="Another Smart Link already uses the slug \"%slug%\". Choose a different one." +mautic.smartlinks.smart_links.error.slug_immutable="The slug of a Smart Link can't be changed. Delete it and create a new one." +mautic.smartlinks.smart_links.error.destination_required="Enter the destination URL of the external redirect." +mautic.smartlinks.smart_links.error.destination_required_mautic="Choose a landing page or a standalone form as the destination of the Mautic redirect." +mautic.smartlinks.smart_links.error.destination_invalid="The destination URL must be a valid http(s) URL." +mautic.smartlinks.smart_links.error.utm_value_invalid="The parameter \"%key%\" is not enabled, or its value is invalid. Use only lowercase letters, digits, hyphens, underscores and dots." +mautic.smartlinks.smart_links.error.utm_value_not_allowed="The value \"%value%\" of the parameter \"%key%\" is not part of its allowed values." +; UTM Taxonomy form and taxonomy-driven Smart Link values. +mautic.smartlinks.taxonomies.error.name_required="Enter a name." +mautic.smartlinks.taxonomies.error.name_length="The name cannot be longer than {{ limit }} characters." +mautic.smartlinks.taxonomies.error.name_taken="Another UTM Taxonomy already uses the name %name%." +mautic.smartlinks.taxonomies.error.name_characters="The name cannot contain the characters %, { or }." +mautic.smartlinks.taxonomies.error.value_invalid="The value %value% is invalid. Use only lowercase letters, digits, hyphens, underscores and dots." +mautic.smartlinks.smart_links.error.taxonomy_required="Choose a UTM Taxonomy." +mautic.smartlinks.smart_links.error.taxonomy_parameter_unknown="The parameter %key% is not part of the taxonomy %name%." diff --git a/Translations/fr_FR/messages.ini b/Translations/fr_FR/messages.ini new file mode 100644 index 0000000..747ebba --- /dev/null +++ b/Translations/fr_FR/messages.ini @@ -0,0 +1,210 @@ +mautic.plugin.smartlinks.name="Smartlinks" +mautic.smartlinks.menu.root="Smart Links" +mautic.smartlinks.menu.smartlinks="Smart Links" +mautic.smartlinks.menu.taxonomies="Taxonomies UTM" + + +; Titre de l'onglet dans Paramètres > Configuration. Le cœur construit cette clé à partir de l'alias du formulaire. +mautic.config.tab.smartlinksconfig="Paramètres Smart Links" + +; Paramètres > Configuration > Smart Links Settings. +mautic.smartlinks.settings.description="Réglages des Smart Links : les paramètres UTM qu'ils transportent, les règles générales et le domaine de leurs liens courts." +mautic.smartlinks.settings.short_link_domain="Domaine de liens courts" +mautic.smartlinks.settings.short_link_domain.tooltip="Domaine utilisé pour créer les futurs liens courts, par exemple lnk.exemple.com. N'incluez pas https://." +mautic.smartlinks.settings.placeholder="Les Smart Links apparaîtront ici." + +; Smart Links (menu principal > Smart Links). Base de traduction mautic.smartlinks.smart_links. +mautic.smartlinks.smart_links.header.index="Smart Links" +mautic.smartlinks.smart_links.header.new="Nouveau Smart Link" +mautic.smartlinks.smart_links.header.edit="Smart Link - %slug%" +mautic.smartlinks.smart_links.slug="Slug" +mautic.smartlinks.smart_links.slug.tooltip="Texte court (9 caractères maximum). Les espaces sont remplacés par le caractère configuré, les majuscules sont converties en minuscules à l'enregistrement. Le slug ne peut plus être modifié après la création du lien." +mautic.smartlinks.smart_links.slug.generate="Générer" +mautic.smartlinks.smart_links.slug.generate.tooltip="Utiliser un slug aléatoire de 4 lettres et chiffres." +mautic.smartlinks.smart_links.short_link="Lien court" +mautic.smartlinks.smart_links.domain.reminder="Domaine des liens courts :" +mautic.smartlinks.smart_links.domain.reminder.empty="Aucun domaine de liens courts configuré. Définissez-le dans Paramètres > Configuration > Paramètres Smart Links." +mautic.smartlinks.smart_links.redirect_type="Type de redirection" +mautic.smartlinks.smart_links.redirect_type.mautic="Mautic" +mautic.smartlinks.smart_links.redirect_type.external="Externe" +mautic.smartlinks.smart_links.redirect_code="Code HTTP de redirection" +mautic.smartlinks.smart_links.redirect_code.301="301 - Déplacé de façon permanente — permanent" +mautic.smartlinks.smart_links.redirect_code.302="302 - Trouvé — temporaire" +mautic.smartlinks.smart_links.redirect_code.307="307 - Redirection temporaire — temporaire" +mautic.smartlinks.smart_links.redirect_code.308="308 - Redirection permanente — permanent" +mautic.smartlinks.smart_links.destination_url="URL de destination" +mautic.smartlinks.smart_links.destination_url.tooltip="Page d'arrivée du visiteur, par exemple https://www.exemple.com/page. Utilisée uniquement pour les redirections externes." +mautic.smartlinks.smart_links.destination="Destination" +mautic.smartlinks.smart_links.destination.tooltip="La landing page ou le formulaire autonome vers lequel le visiteur est redirigé. Utilisé uniquement pour les redirections Mautic." +mautic.smartlinks.smart_links.destination.pages="Landing pages" +mautic.smartlinks.smart_links.destination.forms="Formulaires autonomes" +mautic.smartlinks.smart_links.destination.unpublished="Plus publié" +mautic.smartlinks.smart_links.utm_parameters="Paramètres UTM" +mautic.smartlinks.smart_links.utm_parameters.help="Choisissez d’abord la taxonomie UTM : chaque valeur ci-dessous est choisie parmi celles qu’elle autorise." + +mautic.smartlinks.smart_links.onboarding.heading="Aucun Smart Link" +mautic.smartlinks.smart_links.onboarding.subheading="Les Smart Links sont des liens courts qui transportent vos paramètres UTM." +mautic.smartlinks.smart_links.onboarding.copy="Utilisez le bouton Nouveau ci-dessus pour en créer un. Son slug ne peut pas être modifié après la création ; supprimez-le et créez-en un nouveau." +mautic.smartlinks.smart_links.menu.new="Nouveau Smart Link" +mautic.smartlinks.smart_links.menu.edit="Modifier %name%" +mautic.smartlinks.smart_links.menu.delete="Supprimer %name%" +mautic.smartlinks.smart_links.form.confirmdelete="Supprimer le Smart Link %name% ? Il ne pourra pas être restauré." +mautic.smartlinks.smart_links.form.confirmbatchdelete="Supprimer les Smart Links sélectionnés ? Ils ne pourront pas être restaurés." +mautic.smartlinks.smart_links.error.notfound="Aucun Smart Link avec l'identifiant %id%." +mautic.smartlinks.smart_links.permissions.header="Smart Links - L'utilisateur a accès à" +mautic.smartlinks.smart_links.hits="Clics" +mautic.smartlinks.smart_links.hits.tooltip="Nombre de fois où le lien court a redirigé un visiteur." + +mautic.smartlinks.config.description="Définissez les paramètres UTM proposés par le générateur de liens et leur mode de saisie." +mautic.smartlinks.config.section.utm_settings="Paramètres UTM" +mautic.smartlinks.config.section.parameters="Paramètres" +mautic.smartlinks.config.group.standard="UTM standards" +mautic.smartlinks.config.group.platform="Identifiants de plateformes" +mautic.smartlinks.config.group.custom="Paramètres personnalisés" + +mautic.smartlinks.config.enforce_lowercase="Forcer les minuscules sur toutes les valeurs" +mautic.smartlinks.config.enforce_lowercase.tooltip="Le générateur de liens convertit toutes les valeurs des paramètres en minuscules." +mautic.smartlinks.config.separator_replacement="Caractère de remplacement des espaces" +mautic.smartlinks.config.separator_replacement.tooltip="Caractère qui remplace les espaces dans les valeurs des paramètres." +mautic.smartlinks.config.separator.hyphen="Tiret ( - )" +mautic.smartlinks.config.separator.underscore="Tiret bas ( _ )" +mautic.smartlinks.config.separator.dot="Point ( . )" + +mautic.smartlinks.config.parameter.enabled="Activé" +mautic.smartlinks.config.parameter.label="Libellé" +mautic.smartlinks.config.parameter.mode="Mode" +mautic.smartlinks.config.parameter.key="Clé" +mautic.smartlinks.config.parameter.key.tooltip="Nom du paramètre dans l'URL : lettres minuscules, chiffres et tirets bas, commençant par une lettre (2 à 41 caractères)." +mautic.smartlinks.config.mode.dropdown="Liste déroulante (liste de valeurs)" +mautic.smartlinks.config.mode.free="Texte libre" +mautic.smartlinks.config.mode.disabled="Désactivé" +mautic.smartlinks.config.auto_generated.badge="Auto" +mautic.smartlinks.config.auto_generated.tooltip="Généralement ajouté automatiquement par la plateforme publicitaire. Activez-le uniquement si vous devez le gérer manuellement." + +mautic.smartlinks.config.values="Valeurs autorisées" +mautic.smartlinks.config.values.value="Valeur" +mautic.smartlinks.config.values.label="Libellé" +mautic.smartlinks.config.values.default="Par défaut" +mautic.smartlinks.config.values.add="Ajouter une valeur" +mautic.smartlinks.config.values.remove="Supprimer la valeur" +mautic.smartlinks.config.values.drag="Glisser pour réordonner" +mautic.smartlinks.config.values.empty="Aucune valeur pour le moment." +mautic.smartlinks.config.values.suggestions="Charger les valeurs suggérées" +mautic.smartlinks.config.values.import="Coller des valeurs (une par ligne, ou valeur;libellé)" +mautic.smartlinks.config.values.import.placeholder="newsletter;Newsletter" +mautic.smartlinks.config.values.import.button="Importer" + +mautic.smartlinks.config.custom.add="Ajouter un paramètre personnalisé" +mautic.smartlinks.config.custom.remove="Supprimer" +mautic.smartlinks.config.custom.new="nouveau paramètre" +mautic.smartlinks.config.custom.empty="Aucun paramètre personnalisé." + +mautic.smartlinks.config.parameter.utm_source.label="Source" +mautic.smartlinks.config.parameter.utm_source.description="Origine du trafic, par exemple newsletter, linkedin ou google." +mautic.smartlinks.config.parameter.utm_medium.label="Support" +mautic.smartlinks.config.parameter.utm_medium.description="Type de canal, par exemple email, cpc, social ou referral." +mautic.smartlinks.config.parameter.utm_campaign.label="Campagne" +mautic.smartlinks.config.parameter.utm_campaign.description="Nom de la campagne." +mautic.smartlinks.config.parameter.utm_term.label="Terme" +mautic.smartlinks.config.parameter.utm_term.description="Mot-clé de la recherche payante." +mautic.smartlinks.config.parameter.utm_content.label="Contenu" +mautic.smartlinks.config.parameter.utm_content.description="Distingue les variantes ou les liens qui pointent vers la même URL." +mautic.smartlinks.config.parameter.utm_id.label="ID de campagne" +mautic.smartlinks.config.parameter.utm_id.description="Identifiant de campagne, utilisé par l'import de données GA4." +mautic.smartlinks.config.parameter.utm_source_platform.label="Plateforme source" +mautic.smartlinks.config.parameter.utm_source_platform.description="Plateforme qui gère la campagne, par exemple Google Ads." +mautic.smartlinks.config.parameter.utm_creative_format.label="Format créatif" +mautic.smartlinks.config.parameter.utm_creative_format.description="Type de création, par exemple display, vidéo ou native." +mautic.smartlinks.config.parameter.utm_marketing_tactic.label="Tactique marketing" +mautic.smartlinks.config.parameter.utm_marketing_tactic.description="Tactique de ciblage, par exemple prospection ou remarketing." +mautic.smartlinks.config.parameter.gclid.label="ID de clic Google Ads" +mautic.smartlinks.config.parameter.gclid.description="Identifiant de clic ajouté par Google Ads." +mautic.smartlinks.config.parameter.gbraid.label="ID Google Ads iOS web vers app" +mautic.smartlinks.config.parameter.gbraid.description="Identifiant de clic ajouté par Google Ads pour la mesure iOS du web vers l'application." +mautic.smartlinks.config.parameter.wbraid.label="ID Google Ads iOS app vers web" +mautic.smartlinks.config.parameter.wbraid.description="Identifiant de clic ajouté par Google Ads pour la mesure iOS de l'application vers le web." +mautic.smartlinks.config.parameter.dclid.label="ID de clic Display & Video 360" +mautic.smartlinks.config.parameter.dclid.description="Identifiant de clic ajouté par Google Display & Video 360." +mautic.smartlinks.config.parameter.fbclid.label="ID de clic Meta" +mautic.smartlinks.config.parameter.fbclid.description="Identifiant de clic ajouté par Meta (Facebook, Instagram)." +mautic.smartlinks.config.parameter.msclkid.label="ID de clic Microsoft Advertising" +mautic.smartlinks.config.parameter.msclkid.description="Identifiant de clic ajouté par Microsoft Advertising." +mautic.smartlinks.config.parameter.ttclid.label="ID de clic TikTok" +mautic.smartlinks.config.parameter.ttclid.description="Identifiant de clic ajouté par TikTok." +mautic.smartlinks.config.parameter.li_fat_id.label="ID de clic LinkedIn" +mautic.smartlinks.config.parameter.li_fat_id.description="Identifiant de clic ajouté par LinkedIn." +mautic.smartlinks.config.parameter.twclid.label="ID de clic X" +mautic.smartlinks.config.parameter.twclid.description="Identifiant de clic ajouté par X (Twitter)." +mautic.smartlinks.config.parameter.epik.label="ID de clic Pinterest" +mautic.smartlinks.config.parameter.epik.description="Identifiant de clic ajouté par Pinterest." + +mautic.smartlinks.config.suggestion.newsletter="Newsletter" +mautic.smartlinks.config.suggestion.linkedin="LinkedIn" +mautic.smartlinks.config.suggestion.facebook="Facebook" +mautic.smartlinks.config.suggestion.instagram="Instagram" +mautic.smartlinks.config.suggestion.google="Google" +mautic.smartlinks.config.suggestion.youtube="YouTube" +mautic.smartlinks.config.suggestion.x="X" +mautic.smartlinks.config.suggestion.tiktok="TikTok" +mautic.smartlinks.config.suggestion.partner="Partenaire" +mautic.smartlinks.config.suggestion.direct="Direct" +mautic.smartlinks.config.suggestion.email="E-mail" +mautic.smartlinks.config.suggestion.cpc="Coût par clic" +mautic.smartlinks.config.suggestion.social="Réseaux sociaux" +mautic.smartlinks.config.suggestion.social_paid="Réseaux sociaux payants" +mautic.smartlinks.config.suggestion.display="Display" +mautic.smartlinks.config.suggestion.affiliate="Affiliation" +mautic.smartlinks.config.suggestion.referral="Site référent" +mautic.smartlinks.config.suggestion.qr="QR code" +mautic.smartlinks.config.suggestion.sms="SMS" +mautic.smartlinks.config.suggestion.print="Imprimé" +mautic.smartlinks.config.suggestion.event="Événement" +mautic.smartlinks.config.suggestion.google_ads="Google Ads" +mautic.smartlinks.config.suggestion.meta_ads="Meta Ads" +mautic.smartlinks.config.suggestion.linkedin_ads="LinkedIn Ads" +mautic.smartlinks.config.suggestion.microsoft_ads="Microsoft Ads" +mautic.smartlinks.config.suggestion.tiktok_ads="TikTok Ads" +mautic.smartlinks.config.suggestion.banner="Bannière" +mautic.smartlinks.config.suggestion.video="Vidéo" +mautic.smartlinks.config.suggestion.carousel="Carrousel" +mautic.smartlinks.config.suggestion.text="Texte" +mautic.smartlinks.config.suggestion.native="Native" +mautic.smartlinks.config.suggestion.prospecting="Prospection" +mautic.smartlinks.config.suggestion.remarketing="Remarketing" +mautic.smartlinks.config.suggestion.retargeting="Retargeting" +mautic.smartlinks.config.suggestion.brand="Marque" +mautic.smartlinks.config.suggestion.nurturing="Nurturing" + +; Section « UTM tags » des formulaires Email et Focus. +mautic.smartlinks.form.choose="Choisir..." +mautic.smartlinks.form.legacy_choice="%value% (hors taxonomie)" +mautic.smartlinks.form.legacy_warning="Cette valeur ne fait pas partie de la taxonomie UTM." +mautic.smartlinks.form.no_values="Aucune valeur configurée pour ce paramètre. Contactez un administrateur." + +; Formulaire Smart Link et taxonomies UTM (Smart Links > Taxonomies UTM). Base de traduction mautic.smartlinks.taxonomies. +mautic.smartlinks.smart_links.taxonomy="Taxonomie UTM" +mautic.smartlinks.smart_links.taxonomy.tooltip="L’ensemble des valeurs autorisées pour les paramètres UTM de ce lien. Chaque valeur du lien est choisie parmi celles qu’autorise la taxonomie." +mautic.smartlinks.taxonomies.header.index="Taxonomies UTM" +mautic.smartlinks.taxonomies.header.new="Nouvelle taxonomie UTM" +mautic.smartlinks.taxonomies.header.edit="Taxonomie UTM - %name%" +mautic.smartlinks.taxonomies.name="Nom" +mautic.smartlinks.taxonomies.name.tooltip="Un nom court et unique identifiant cet ensemble de valeurs UTM autorisées." +mautic.smartlinks.taxonomies.description="Description" +mautic.smartlinks.taxonomies.parameters="Paramètres UTM" +mautic.smartlinks.taxonomies.parameters.help="Chaque paramètre activé dans Paramètres Smart Links apparaît. Les paramètres en liste déroulante offrent les valeurs définies par l’administrateur : cochez celles qu’un Smart Link peut porter. Les paramètres en texte libre reçoivent ici leur propre liste de valeurs : le lien y choisira une valeur au lieu de saisir librement." +mautic.smartlinks.taxonomies.parameter_count="Paramètres" +mautic.smartlinks.taxonomies.parameter_count.tooltip="Le nombre de paramètres pour lesquels cette taxonomie définit des valeurs." +mautic.smartlinks.taxonomies.menu.new="Nouvelle taxonomie UTM" +mautic.smartlinks.taxonomies.menu.edit="Modifier %name%" +mautic.smartlinks.taxonomies.menu.delete="Supprimer %name%" +mautic.smartlinks.taxonomies.form.confirmdelete="Supprimer la taxonomie UTM %name% ? Elle ne pourra pas être restaurée. Les Smart Links qui l’utilisent conservent les valeurs qu’ils portent déjà et demanderont une nouvelle taxonomie à leur prochaine modification." +mautic.smartlinks.taxonomies.form.confirmbatchdelete="Supprimer les taxonomies UTM sélectionnées ? Elles ne pourront pas être restaurées." +mautic.smartlinks.taxonomies.error.notfound="Aucune taxonomie UTM avec l’identifiant %id%." +mautic.smartlinks.taxonomies.permissions.header="Taxonomies UTM - L’utilisateur a accès à" +mautic.smartlinks.taxonomies.onboarding.heading="Aucune taxonomie UTM" +mautic.smartlinks.taxonomies.onboarding.subheading="Les taxonomies UTM sont des ensembles de valeurs autorisées pour les paramètres UTM de vos Smart Links." +mautic.smartlinks.taxonomies.onboarding.copy="Utilisez le bouton Nouveau ci-dessus pour en créer une. Un Smart Link porte une taxonomie ; chaque valeur UTM qu’il porte est choisie parmi celles que la taxonomie autorise." +mautic.smartlinks.taxonomies.unpublished_choice="%name% (plus publiée)" +mautic.smartlinks.taxonomies.free_values.tooltip="Les valeurs autorisées de ce paramètre pour les liens utilisant cette taxonomie. Une valeur par ligne, éventuellement valeur;Libellé." +mautic.smartlinks.taxonomies.free_values.placeholder="une valeur par ligne" +mautic.smartlinks.taxonomies.no_values.tooltip="Aucune valeur n’est encore configurée pour ce paramètre dans Paramètres Smart Links : demandez à l’administrateur d’en configurer." diff --git a/Translations/fr_FR/validators.ini b/Translations/fr_FR/validators.ini new file mode 100644 index 0000000..b91b996 --- /dev/null +++ b/Translations/fr_FR/validators.ini @@ -0,0 +1,40 @@ +; Messages de validation de Paramètres > Configuration > Paramètres UTM (domaine validators de Symfony). +mautic.smartlinks.config.error.key_required="Saisissez une clé pour le paramètre personnalisé." +mautic.smartlinks.config.error.key_invalid="La clé « %key% » n'est pas valide. Utilisez de 2 à 41 lettres minuscules, chiffres ou tirets bas, en commençant par une lettre." +mautic.smartlinks.config.error.key_reserved="La clé « %key% » est réservée. Les clés du catalogue, « ct », les clés commençant par « utm » et celles commençant par « mtc_ » ne peuvent pas être utilisées." +mautic.smartlinks.config.error.key_duplicate="La clé « %key% » est utilisée par plusieurs paramètres personnalisés." +mautic.smartlinks.config.error.mode_invalid="Ce mode n'est pas disponible pour ce paramètre." +mautic.smartlinks.config.error.separator_invalid="Choisissez un tiret, un tiret bas ou un point." +mautic.smartlinks.config.error.label_required="Saisissez un libellé." +mautic.smartlinks.config.error.label_length="Le libellé ne peut pas dépasser {{ limit }} caractères." +mautic.smartlinks.config.error.label_invalid="Le libellé ne peut pas contenir le caractère %." +mautic.smartlinks.config.error.value_required="Saisissez une valeur." +mautic.smartlinks.config.error.value_length="La valeur ne peut pas dépasser {{ limit }} caractères." +mautic.smartlinks.config.error.value_invalid="Les valeurs ne peuvent contenir que des lettres minuscules, des chiffres, des tirets, des tirets bas et des points." +mautic.smartlinks.config.error.value_duplicate="La valeur « %value% » apparaît plusieurs fois." +mautic.smartlinks.config.error.values_required="Un paramètre activé en mode liste déroulante doit avoir au moins une valeur." +mautic.smartlinks.config.error.default_multiple="Une seule valeur peut être la valeur par défaut." + +; Section « UTM tags » des formulaires Email et Focus. +mautic.smartlinks.form.error.not_in_taxonomy="Cette valeur ne fait pas partie de la taxonomie UTM. Choisissez une valeur de la liste." + +; Formulaire Smart Link (menu principal > Smart Links). +mautic.smartlinks.smart_links.error.slug_required="Saisissez un slug." +mautic.smartlinks.smart_links.error.slug_length="Le slug ne peut pas dépasser {{ limit }} caractères." +mautic.smartlinks.smart_links.error.slug_characters="Le slug ne peut contenir que des lettres, des chiffres, des tirets, des tirets bas et des points." +mautic.smartlinks.smart_links.error.slug_taken="Un autre Smart Link utilise déjà le slug « %slug% ». Choisissez-en un autre." +mautic.smartlinks.smart_links.error.slug_immutable="Le slug d'un Smart Link ne peut pas être modifié. Supprimez-le et créez-en un nouveau." +mautic.smartlinks.smart_links.error.destination_required="Saisissez l'URL de destination de la redirection externe." +mautic.smartlinks.smart_links.error.destination_required_mautic="Choisissez une landing page ou un formulaire autonome comme destination de la redirection Mautic." +mautic.smartlinks.smart_links.error.destination_invalid="L'URL de destination doit être une URL http(s) valide." +mautic.smartlinks.smart_links.error.utm_value_invalid="Le paramètre « %key% » n'est pas activé, ou sa valeur n'est pas valide. Utilisez uniquement des lettres minuscules, des chiffres, des tirets, des tirets bas et des points." +mautic.smartlinks.smart_links.error.utm_value_not_allowed="La valeur « %value% » du paramètre « %key% » ne fait pas partie des valeurs autorisées." + +; Formulaire de taxonomie UTM et valeurs des Smart Links pilotées par taxonomie. +mautic.smartlinks.taxonomies.error.name_required="Saisissez un nom." +mautic.smartlinks.taxonomies.error.name_length="Le nom ne peut pas dépasser {{ limit }} caractères." +mautic.smartlinks.taxonomies.error.name_taken="Une autre taxonomie UTM utilise déjà le nom %name%." +mautic.smartlinks.taxonomies.error.name_characters="Le nom ne peut pas contenir les caractères %, { ou }." +mautic.smartlinks.taxonomies.error.value_invalid="La valeur %value% est invalide. Utilisez uniquement des lettres minuscules, des chiffres, des tirets, des tirets bas et des points." +mautic.smartlinks.smart_links.error.taxonomy_required="Choisissez une taxonomie UTM." +mautic.smartlinks.smart_links.error.taxonomy_parameter_unknown="Le paramètre %key% ne fait pas partie de la taxonomie %name%." diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..53a70ad --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,13 @@ + + + + + + Tests + + + diff --git a/readme.md b/readme.md index 09fa9ab..aec99ec 100644 --- a/readme.md +++ b/readme.md @@ -1,8 +1,8 @@ -# Mautic Marketing Program plugin +# Mautic MT3S Marketing plugin -A custom Mautic 7 plugin (`MT3SMarketingProgramBundle`) for managing marketing programs: a name, status, owner, dates, budget and category, with their mt3s_mp_programs. +A custom Mautic 7 plugin (`MT3SMarketingProgramBundle`) by MT3 Solutions with two separate domains: **Marketing Programs** — programs with a name, status, owner, dates, budget and category, with their mt3s_mp_programs — and **Smart Links** — short links (`/l/{slug}`) that tag the click with the UTM parameters of a UTM taxonomy before redirecting. The two domains share one bundle, one permission base (`mt3smarketingprogram:*`), one Plugins page entry and one config page, but keep separate menus, tables and code. -This repository holds only the plugin source. The bundle files are at the repository root, and Mautic loads them from `docroot/plugins/MT3SMarketingProgramBundle`. The plugin was called `PlanBundle` before 0.16.0 and `ProgramBundle` (with programs) before 0.17.0: see *Rename history* below. +This repository holds only the plugin source. The bundle files are at the repository root, and Mautic loads them from `docroot/plugins/MT3SMarketingProgramBundle`. The plugin was called `PlanBundle` before 0.16.0 and `ProgramBundle` (with programs) before 0.17.0, and the Smart Links used to be a separate `SmartlinksBundle` plugin before 0.18.0: see *Rename history* below. ## Installation @@ -16,7 +16,15 @@ This repository holds only the plugin source. The bundle files are at the reposi 3. In Mautic, go to **Settings > Plugins**, open **MT3S Marketing Program** and publish it. -Programs are listed under **Marketing Programs** in the main menu (URL `/s/marketing-programs`), tasks under **Marketing Programs > Tasks** (URL `/s/marketing-program-tasks`), the stakeholder directory under **Marketing Programs > Stakeholders** (URL `/s/marketing-program-stakeholders`), and the audience directory under **Marketing Programs > Audiences** (URL `/s/marketing-program-audiences`). The item type lists are edited under **Marketing Programs > Item types** (URL `/s/marketing-program-item-types`). The UTM Taxonomies page (URL `/s/marketing-program-utm-taxonomies`) is a placeholder for a coming feature and is kept out of the menu. Users who aren't administrators need a role with the **Marketing Program Permissions** set in **Settings > Roles**. +Programs are listed under **Marketing Programs** in the main menu (URL `/s/marketing-programs`), tasks under **Marketing Programs > Tasks** (URL `/s/marketing-program-tasks`), the stakeholder directory under **Marketing Programs > Stakeholders** (URL `/s/marketing-program-stakeholders`), and the audience directory under **Marketing Programs > Audiences** (URL `/s/marketing-program-audiences`). The item type lists are edited under **Marketing Programs > Item types** (URL `/s/marketing-program-item-types`). The Smart Links of the second domain are listed under **Smart Links > Smart Links** (URL `/s/smart-links`) and their UTM taxonomies under **Smart Links > UTM Taxonomies** (URL `/s/utm-taxonomies`). Users who aren't administrators need a role with the **Marketing Program Permissions** set in **Settings > Roles** (the Smart Links domain adds `mt3smarketingprogram:smart_links:*` and `mt3smarketingprogram:taxonomies:*`; the marketing program domain uses `mt3smarketingprogram:programs:*` and its other keys). + +### Smart Links + +- A **smart link** is a short link: a slug (like `https://m.shrl.be/l/y32b`), a destination URL, and an optional **UTM taxonomy**. When it is hit, the visitor is redirected to the destination with the taxonomy's UTM parameters appended, and the hit is recorded (`smart_link_hits`). +- The **UTM taxonomies** (`/s/utm-taxonomies`) define, per UTM parameter (`utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term`), whether and how the taxonomy's values apply: as a fixed value, as a pick list on the link, or as a free text field. The Smart Link form then shows exactly the fields the taxonomy allows, and rejects values outside a pick list. +- The **short link domain** is set under **Settings > Configuration > Smart Links Settings**, together with which UTM parameters to use and their modes. The public `/l/{slug}` route only answers on the configured domain (404 elsewhere), doesn't require authentication, and records one hit for the statistics; a statistics failure never blocks the redirect. The redirect status code (301, 302, …) is per link. +- A link redirects to its external **destination URL**, or — redirect type `mautic` — to its Mautic **landing page or standalone form**. The redirect never happens for an unknown slug, an unpublished link, or a link without destination: 404. +- The Smart Links domain was merged from the standalone `SmartlinksBundle` plugin (versions 0.1.0 to 0.6.0) in 0.18.0: routes, tables, URL format and translation keys are unchanged, so existing short links keep working. Roles must be re-granted (`smartlinks:smart_links:*` → `mt3smarketingprogram:smart_links:*`, `smartlinks:taxonomies:*` → `mt3smarketingprogram:taxonomies:*`). Before using the items of a program's **Insights**, **Objectives**, **Allocations** and **Tasks** tabs, set up their types under **Marketing Programs > Item types** (`mt3smarketingprogram:itemtypes:view` to see the page, `mt3smarketingprogram:itemtypes:edit` to save it). @@ -69,7 +77,11 @@ The plugin uses the IntegrationsBundle conventions: - `Resources/views/Program/form.html.twig` and `details.html.twig`: the create/edit form and the detail page. Both have the same seven tabs, from `_tabs.html.twig`: **Details**, **Insights** (description items), **Objectives**, **Allocations** (planned budget, currency and allocation items), **Audiences**, **Stakeholders** and **Tasks**. - `Resources/views/Program/_task_table.html.twig`: the program's tasks in the Tasks tab. It has the harmonized tab columns (pictogram, Type, Name with kind badge for milestones and phases, Description, Start date, End date, Status — no ID), one row per task, no tree: a phase's or milestone's badge marks it in the name column. On the detail page it has an **Add task** button, links to each task and the filter/sort of the other tabs. On the program form it is read-only (no links, no filter), so that following a link doesn't drop unsaved changes. - `Controller/TaskController.php` and `Resources/views/Task/`: the task list, and the create/edit form (**Marketing Programs > Tasks**). `new?program=ID` preselects the program. After Save or Cancel, the user goes back to where the form was opened from. Opened from **Marketing Programs > Tasks**, that's the task list. Opened from a program's Tasks tab, whose links carry `returnTo=program`, that's the program (its new program, if the task was moved). The origin is stored in the session when the form is opened, because the form posts without the query string. -- `Controller/UtmTaxonomyController.php` and `Resources/views/UtmTaxonomy/`: the placeholder page for the coming UTM Taxonomies feature, kept out of the menu (reachable at `/s/marketing-program-utm-taxonomies`). +- `Controller/SmartLinkController.php` and `Resources/views/SmartLink/`: the Smart Links list and form (**Smart Links > Smart Links**, `/s/smart-links`), built on core's `AbstractStandardFormController`. +- `Controller/UtmTaxonomyController.php` and `Resources/views/UtmTaxonomy/`: the UTM taxonomies list and form (**Smart Links > UTM Taxonomies**, `/s/utm-taxonomies`). Replaced the placeholder page of 0.17.0 in 0.18.0. `Model/UtmTaxonomyModel.php`, `Model/SmartLinkModel.php`, `Entity/SmartLink.php`, `Entity/SmartLinkHit.php`, `Entity/UtmTaxonomy.php` (tables `smart_links`, `smart_link_hits`, `utm_taxonomies` — unchanged from the standalone plugin), `Catalog/` (redirect codes 301/302/307/308, redirect types `external`/`mautic`, the UTM parameter catalog and its modes), `Form/` (the link and taxonomy forms, the per-taxonomy UTM fields via `Form/UtmFieldsApplicator.php`, the validators) and `Controller/PublicController.php` (the public `/l/{slug}`) make up the Smart Links domain. +- `EventListener/SmartLinksConfigSubscriber.php`: adds the **Smart Links Settings** tab to Settings > Configuration (`Form/Type/SmartLinksConfigType.php`, `Form/Type/SmartlinksSettingsType.php`, `Integration/Support/ConfigSupport.php`), next to the plugin's **Program Settings** tab; `Service/UtmConfigurationProvider.php` and `Service/UtmConfigurationNormalizer.php` read those parameters, `Service/SmartLinkShortUrlBuilder.php` builds the redirect URLs. +- `Assets/js/mt3s-mp-smartlinks.js`: the Smart Links form script (started by `Mautic.smartlinksSmartLinkOnLoad()` when a page's `mauticContent` is `smartlinksSmartLink`). +- `Tests/Unit/` and `phpunit.xml.dist`: the plugin's unit test suite (mostly covering the Smart Links domain: the catalog, the entities, the form type, the fields applicator, the validators, the models and the configuration provider). - `Controller/ItemTypesController.php` and `Resources/views/ItemTypes/form.html.twig`: the Item types page (**Marketing Programs > Item types**). The type lists that used to be sections of **Settings > Configuration > Marketing Program Settings** (insights, allocation, objective, task, stakeholder types and the audience decision roles and tones) are edited here. `Form/Type/ItemTypesType.php` builds the lists, `Service/ItemTypeInUseGuard.php` refuses to remove a type that items still use, and the page saves through core's `Configurator` exactly like the Settings pages do: merge into `config/local.php`, write, refresh the config cache. **Settings > Configuration > Marketing Program Settings** keeps only the plugin's general settings: the currency, the stakeholder phone region and the audience attribute toggles. - `Assets/js/mt3s-mp-program.js`: on the form, the objectives editor (add, remove, drag-and-drop ordering), and after a failed save, marking the tabs that contain errors with an icon and opening the first one. Started by `Mautic.mt3sMpProgramOnLoad()`. @@ -218,6 +230,7 @@ The plugin was born as `PlanBundle` with a `Plan` entity (table `plans`) and men - Before 0.15.0: "targets" were renamed to "audiences" (entity `Audience`, table `plan_targets` → `plan_audiences`), with Mautic segments attached to each audience. - 0.16.0: the full rename to `ProgramBundle` / `Program` (and a "plan" became an "initiative"). The bundle namespace, class names, the `plugins` DB row (`ProgramBundle`), all tables (`plan_*` → `initiative_*`), all columns (`plan_id` → `initiative_id`, `role_in_plan` → `role_in_initiative`), all permission keys (`plan:*` → `program:*`), the config parameters and the menu (root **Programs**, entry **Initiatives**, plus the placeholder **UTM Taxonomies**) took the new names. The data was kept: the migration renames the tables, it doesn't rebuild them. - 0.17.0: the rename to `MT3SMarketingProgramBundle` / "MT3S Marketing Program", and an initiative became a marketing program. The bundle namespace, class names, the `plugins` DB row (`MT3SMarketingProgramBundle`, name "MT3S Marketing Program"), all tables (`initiative_*` → `mt3s_mp_program_*`), all columns (`initiative_id` → `program_id`, `role_in_initiative` → `role_in_program`), all permission keys (`program:*` → `mt3smarketingprogram:*`), the routes, the service IDs, the config parameters, the URLs (`/s/marketing-programs`, …) and the menu (root **Marketing Programs**, entry **Marketing Programs**) took the new names, and the plugin's events (`mt3s.marketing_program.*`) and the `mt3s:marketing-program:refresh-stats` command were added. The data was kept again: `Version_0_17_0.php` renames the tables and carries over the rows the rename orphans — the plugins row, the roles' permission rows (which the 0.16.0 rename had missed), the categories (`plan`- and `initiative`-era rows) and the audit log. +- 0.18.0: the merge of the standalone **Smartlinks** plugin (`SmartlinksBundle`, versions 0.1.0–0.6.0) into this bundle. The Smart Links and UTM Taxonomies code, tables (`smart_links`, `smart_link_hits`, `utm_taxonomies`), routes (`/s/smart-links`, `/s/utm-taxonomies`, the public `/l/{slug}`), translation keys (`mautic.smartlinks.*`) and settings keys (`smartlinks_*`, with the legacy `utm_manager_*` keys still readable) are unchanged; only the PHP namespace (`MauticPlugin\SmartlinksBundle\` → `MauticPlugin\MT3SMarketingProgramBundle\`), the service IDs, the template namespace (`@Smartlinks/` → `@MT3SMarketingProgram/`), the **Plugins page entry** (one row: "MT3S Marketing Program") and the **permission base** changed (`smartlinks:smart_links:*` → `mt3smarketingprogram:smart_links:*`, `smartlinks:taxonomies:*` → `mt3smarketingprogram:taxonomies:*` — roles must be re-granted). The incoming migrations were renamed `Version_0_X_0_SmartLinks.php` to avoid the class-name collision with this bundle's own migrations. The old placeholder page `/s/marketing-program-utm-taxonomies` is gone (the real feature is at `/s/utm-taxonomies`), and the dev environment mounts only this repository. The source repository is archived at its `post-merge-v1` tag. - The old URLs (`/s/plans`, `/s/plan-tasks`, `/s/programs`, `/s/program-tasks`, …) are gone: the routes were renamed and the old names return 404. A rename like this needs care: