*/ 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; } }