repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/RespektUrlParserGenerator.php
Mailer/app/Models/Generators/RespektUrlParserGenerator.php
<?php namespace Remp\Mailer\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Remp\Mailer\Components\GeneratorWidgets\Widgets\RespektUrlParserWidget\RespektUrlParserWidget; use Remp\Mailer\Models\PageMeta\Content\RespektContent; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\IGenerator; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; use Tracy\Debugger; use Tracy\ILogger; class RespektUrlParserGenerator implements IGenerator { public $onSubmit; public function __construct( private readonly ContentInterface $content, private readonly SourceTemplatesRepository $sourceTemplatesRepository, private readonly EngineFactory $engineFactory ) { } public function generateForm(Form $form): void { $form->addTextArea('articles', 'Article') ->setHtmlAttribute('rows', 7) ->setOption('description', 'Paste article URLs. Each on separate line.') ->setRequired(true) ->getControlPrototype() ->setHtmlAttribute('class', 'form-control html-editor'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function formSucceeded(Form $form, ArrayHash $values): void { if (!$this->content instanceof RespektContent) { Debugger::log(self::class . ' depends on ' . RespektContent::class . '.', ILogger::ERROR); $sourceTemplate = null; if (isset($values['source_template_id'])) { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); } $form->addError(sprintf( "Mail generator [%s] is not configured correctly. Contact developers.", $sourceTemplate->title ?? '', )); return; } try { $output = $this->process((array) $values); $addonParams = [ 'render' => true, 'errors' => $output['errors'], ]; $this->onSubmit->__invoke($output['htmlContent'], $output['textContent'], $addonParams); } catch (InvalidUrlException $e) { $form->addError($e->getMessage()); } } public function apiParams(): array { return [ (new PostInputParam('articles'))->setRequired(), (new PostInputParam('utm_campaign'))->setRequired(), ]; } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); $items = []; $errors = []; $urls = explode("\n", trim($values['articles'])); foreach ($urls as $url) { $url = trim($url); if (empty($url)) { // people sometimes enter blank lines continue; } try { $meta = $this->content->fetchUrlMeta($url); if ($meta) { $items[$url] = $meta; } else { $errors[] = $url; } } catch (InvalidUrlException $e) { $errors[] = $url; } } $params = [ 'items' => $items, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), 'errors' => $errors, ]; } public function getWidgets(): array { return [RespektUrlParserWidget::class]; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/MediaBriefingGenerator.php
Mailer/app/Models/Generators/MediaBriefingGenerator.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Remp\Mailer\Components\GeneratorWidgets\Widgets\MediaBriefingWidget\MediaBriefingWidget; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\HtmlArticleLocker; use Remp\MailerModule\Models\Generators\EmbedParser; use Remp\MailerModule\Models\Generators\IGenerator; use Remp\MailerModule\Models\Generators\PreprocessException; use Remp\MailerModule\Models\Generators\WordpressHelpers; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use GuzzleHttp\Client; use Tomaj\NetteApi\Params\PostInputParam; class MediaBriefingGenerator implements IGenerator { use RulesTrait, TemplatesTrait; public $onSubmit; private $mailSourceTemplateRepository; private $helpers; private $content; private $linksColor = "#1F3F83"; private $embedParser; private $articleLocker; private $engineFactory; public function __construct( SourceTemplatesRepository $mailSourceTemplateRepository, WordpressHelpers $helpers, ContentInterface $content, EmbedParser $embedParser, HtmlArticleLocker $articleLocker, EngineFactory $engineFactory ) { $this->mailSourceTemplateRepository = $mailSourceTemplateRepository; $this->helpers = $helpers; $this->content = $content; $this->embedParser = $embedParser; $this->articleLocker = $articleLocker; $this->engineFactory = $engineFactory; } public function apiParams(): array { return [ (new PostInputParam('mediabriefing_html'))->setRequired(), (new PostInputParam('url'))->setRequired(), (new PostInputParam('title'))->setRequired(), (new PostInputParam('sub_title')), (new PostInputParam('image_url')), (new PostInputParam('image_title')), (new PostInputParam('from'))->setRequired(), ]; } public function getWidgets(): array { return [MediaBriefingWidget::class]; } public function process(array $values): array { $sourceTemplate = $this->mailSourceTemplateRepository->find($values['source_template_id']); $post = $values['mediabriefing_html']; $lockedPost = $this->articleLocker->getLockedPost($post); $generatorRules = [ '/<p.*?>(.*?)<\/p>/is' => "<p style=\"color:#181818;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:normal;padding:0;margin:0 0 26px 0;text-align:left;font-size:18px;line-height:160%;\">$1</p>", ]; $rules = $this->getRules($generatorRules); foreach ($rules as $rule => $replace) { if (is_array($replace) || is_callable($replace)) { $post = preg_replace_callback($rule, $replace, $post); $lockedPost = preg_replace_callback($rule, $replace, $lockedPost); } else { $post = preg_replace($rule, $replace, $post); $lockedPost = preg_replace($rule, $replace, $lockedPost); } } // wrap text in paragraphs $post = $this->helpers->wpautop($post); $lockedPost = $this->helpers->wpautop($lockedPost); // parse article links $post = $this->helpers->wpParseArticleLinks($post, 'https://dennikn.sk/', $this->getArticleLinkTemplateFunction()); $lockedPost = $this->helpers->wpParseArticleLinks($lockedPost, 'https://dennikn.sk/', $this->getArticleLinkTemplateFunction()); // fix pees [$post, $lockedPost] = preg_replace('/<p>/is', "<p style=\"color:#181818;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:normal;padding:0;margin:0 0 26px 0;text-align:left;font-size:18px;line-height:160%;\">", [$post, $lockedPost]); [$captionTemplate,,,,,$imageTemplate] = $this->getTemplates(); $imageHtml = ''; if (isset($values['image_title']) && isset($values['image_url'])) { $imageHtml = str_replace('$1', $values['image_url'], $captionTemplate); $imageHtml = str_replace('$2', $values['image_title'], $imageHtml); } elseif (isset($values['image_url'])) { $imageHtml = str_replace('$1', $values['image_url'], $imageTemplate); } $post = $imageHtml . $post; $lockedPost = $imageHtml . $lockedPost; $text = str_replace("<br />", "\r\n", $post); $lockedText = str_replace("<br />", "\r\n", $lockedPost); $lockedPost = $this->articleLocker->injectLockedMessage($lockedPost); $text = strip_tags($text); $lockedText = strip_tags($lockedText); $text = preg_replace('/(\r\n|\r|\n)+/', "\n", $text); $lockedText = preg_replace('/(\r\n|\r|\n)+/', "\n", $lockedText); $params = [ 'title' => $values['title'], 'sub_title' => $values['sub_title'], 'url' => $values['url'], 'html' => $post, 'text' => $text, ]; $lockedParams = [ 'title' => $values['title'], 'sub_title' => $values['sub_title'], 'url' => $values['url'], 'html' => $lockedPost, 'text' => strip_tags($lockedText), ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), 'lockedHtmlContent' => $engine->render($sourceTemplate->content_html, $lockedParams), 'lockedTextContent' => strip_tags($engine->render($sourceTemplate->content_text, $lockedParams)), ]; } public function formSucceeded(Form $form, ArrayHash $values): void { $output = $this->process((array) $values); $addonParams = [ 'lockedHtmlContent' => $output['lockedHtmlContent'], 'lockedTextContent' => $output['lockedTextContent'], 'mediaBriefingTitle' => $values->title, 'from' => $values->from, 'render' => true, 'articleId' => $values->article_id, ]; $this->onSubmit->__invoke($output['htmlContent'], $output['textContent'], $addonParams); } public function generateForm(Form $form): void { // disable CSRF protection as external sources could post the params here $form->offsetUnset(Form::PROTECTOR_ID); $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->offsetUnset(Form::PROTECTOR_ID); $form->addText('sub_title', 'Sub title'); $form->addText('from', 'Sender'); $form->addText('url', 'Media Briefing URL') ->addRule(Form::URL) ->setRequired("Field 'Media Briefing URL' is required."); $form->addTextArea('mediabriefing_html', 'HTML') ->setHtmlAttribute('rows', 20) ->setHtmlAttribute('class', 'form-control html-editor') ->getControlPrototype(); $form->addHidden('article_id'); $form->addSubmit('send') ->getControlPrototype() ->setName('button') ->setHtml('<i class="fa fa-magic"></i> ' . 'Generate'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } /** * @param \stdClass $data containing WP article data * @return ArrayHash with data to fill the form with */ public function preprocessParameters($data): ?ArrayHash { $output = new ArrayHash(); if (!isset($data->post_authors[0]->display_name)) { throw new PreprocessException("WP json object does not contain required attribute 'post_authors.0.display_name'"); } if (isset($data->sender_email) && $data->sender_email) { $output->from = $data->sender_email; } else { $output->from = "Denník N <info@dennikn.sk>"; foreach ($data->post_authors as $author) { if ($author->user_email === "editori@dennikn.sk") { continue; } $output->from = $author->display_name . ' Denník N <' . $author->user_email . '>'; break; } } if (!isset($data->post_title)) { throw new PreprocessException("WP json object does not contain required attribute 'post_title'"); } $output->title = $data->post_title; if (!isset($data->post_url)) { throw new PreprocessException("WP json object does not contain required attribute 'post_url'"); } $output->url = $data->post_url; if (!isset($data->post_excerpt)) { throw new PreprocessException("WP json object does not contain required attribute 'post_excerpt'"); } $output->sub_title = $data->post_excerpt; if (isset($data->post_image->image_sizes->medium->file)) { $output->image_url = $data->post_image->image_sizes->medium->file; } if (isset($data->post_image->image_title)) { $output->image_title = $data->post_image->image_title; } if (!isset($data->post_content)) { throw new PreprocessException("WP json object does not contain required attribute 'post_content'"); } $output->mediabriefing_html = $data->post_content; $output->article_id = $data->ID; return $output; } public function parseEmbed($matches) { $link = trim($matches[0]); if (preg_match('/youtu/', $link)) { $result = (new Client())->get('https://www.youtube.com/oembed?url=' . $link . '&format=json')->getBody()->getContents(); $result = json_decode($result); $thumbLink = $result->thumbnail_url; return "<br><a href=\"{$link}\" target=\"_blank\" style=\"color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;color:#1F3F83;text-decoration:underline;\"><img src=\"{$thumbLink}\" alt=\"\" style=\"outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;\"></a><br><br>" . PHP_EOL; } return "<a href=\"{$link}\" target=\"_blank\" style=\"color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;color:#1F3F83;text-decoration:underline;\">$link</a><br><br>"; } public function getTemplates() { $captionTemplate = <<< HTML <img src="$1" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;"> <p style="margin:0 0 0 26px;Margin:0 0 0 26px;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-size:18px;line-height:1.6;margin-bottom:26px;Margin-bottom:26px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;"> <small class="text-gray" style="font-size:13px;line-height:18px;display:block;color:#9B9B9B;">$2</small> </p> HTML; $captionWithLinkTemplate = <<< HTML <a href="$1" style="color:#181818;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:normal;padding:0;margin:0;Margin:0;text-align:left;line-height:1.3;color:#1F3F83;text-decoration:none;"> <img src="$2" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;border:none;"> </a> <p style="margin:0 0 0 26px;Margin:0 0 0 26px;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-size:18px;line-height:1.6;margin-bottom:26px;Margin-bottom:26px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;"> <small class="text-gray" style="font-size:13px;line-height:18px;display:block;color:#9B9B9B;">$3</small> </p> HTML; $liTemplate = <<< HTML <tr style="padding:0;vertical-align:top;text-align:left;"> <td class="bullet" style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;width:30px;border-collapse:collapse !important;">&#8226;</td> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;border-collapse:collapse !important;"> <p style="color:#181818;padding:0;margin:0 0 5px 0;font-size:18px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;">$1</p> </td> </tr> HTML; $hrTemplate = <<< HTML <table cellspacing="0" cellpadding="0" border="0" width="100%" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:100%;min-width:100%;"> <tr style="padding:0;vertical-align:top;text-align:left;width:100%;min-width:100%;"> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;border-collapse:collapse !important; padding: 30px 0 0 0; border-top:1px solid #E2E2E2;height:0;line-height: 0;width:100%;min-width:100%;">&#xA0;</td> </tr> </table> HTML; $spacerTemplate = <<< HTML <table class="spacer" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:100%;"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left;"> <td height="20px" style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;mso-line-height-rule:exactly;border-collapse:collapse !important;font-size:20px;line-height:20px;">&#xA0;</td> </tr> </tbody> </table> HTML; $imageTemplate = <<< HTML <img src="$1" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;"> HTML; return [ $captionTemplate, $captionWithLinkTemplate, $liTemplate, $hrTemplate, $spacerTemplate, $imageTemplate, ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/MinutaDigestGenerator.php
Mailer/app/Models/Generators/MinutaDigestGenerator.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Nette\Utils\Validators; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\IGenerator; use Remp\MailerModule\Models\Generators\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; class MinutaDigestGenerator implements IGenerator { protected $sourceTemplatesRepository; protected $content; public $onSubmit; private $engineFactory; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, ContentInterface $content, EngineFactory $engineFactory ) { $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->content = $content; $this->engineFactory = $engineFactory; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function formSucceeded(Form $form, ArrayHash $values): void { try { $output = $this->process((array) $values); $this->onSubmit->__invoke($output['htmlContent'], $output['textContent']); } catch (InvalidUrlException $e) { $form->addError($e->getMessage()); } } public function apiParams(): array { return [ (new PostInputParam('posts'))->setRequired(), ]; } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); $posts = []; $urls = explode("\n", $values['posts']); foreach ($urls as $url) { $url = trim($url); if (Validators::isUrl($url)) { $posts[$url] = $this->content->fetchUrlMeta($url); } } $params = [ 'posts' => $posts, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), ]; } public function generateForm(Form $form): void { $form->addTextArea('posts', 'List of posts') ->setHtmlAttribute('rows', 4) ->setOption('description', 'Insert URLs for Minutky - each on separate line') ->getControlPrototype() ->setHtmlAttribute('class', 'form-control html-editor'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function getWidgets(): array { return []; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/DailyNewsletterGenerator.php
Mailer/app/Models/Generators/DailyNewsletterGenerator.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\Generators; use Nette\Application\UI\Form; use Nette\Utils\ArrayHash; use Nette\Utils\Validators; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\IGenerator; use Remp\MailerModule\Models\Generators\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; class DailyNewsletterGenerator implements IGenerator { protected $sourceTemplatesRepository; protected $content; private $engineFactory; public $onSubmit; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, ContentInterface $content, EngineFactory $engineFactory ) { $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->content = $content; $this->engineFactory = $engineFactory; } public function generateForm(Form $form): void { $form->addTextArea('posts', 'List of posts') ->setHtmlAttribute('rows', 4) ->setHtmlAttribute('class', 'form-control html-editor') ->setOption('description', 'Insert Urls for every Minuta - each on separate line'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function formSucceeded(Form $form, ArrayHash $values): void { try { $output = $this->process((array)$values); $this->onSubmit->__invoke($output['htmlContent'], $output['textContent']); } catch (InvalidUrlException $e) { $form->addError($e->getMessage()); } } public function process(array $values): array { $sourceTemplate = $this->sourceTemplatesRepository->find($values['source_template_id']); $posts = []; $urls = explode("\n", $values['posts']); foreach ($urls as $url) { $url = trim($url); if (Validators::isUrl($url)) { $posts[$url] = $this->content->fetchUrlMeta($url); } } $params = [ 'contents' => $posts, ]; $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), ]; } public function getWidgets(): array { return []; } public function apiParams(): array { return [ (new PostInputParam('posts'))->setRequired(), ]; } public function preprocessParameters($data): ?ArrayHash { return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/GrafdnaGenerator.php
Mailer/app/Models/Generators/GrafdnaGenerator.php
<?php namespace Remp\Mailer\Models\Generators; use Nette\Application\UI\Form; use Nette\Http\Url; use Nette\Utils\ArrayHash; use Nette\Utils\Strings; use Remp\Mailer\Components\GeneratorWidgets\Widgets\GrafdnaWidget\GrafdnaWidget; use Remp\Mailer\Models\WebClient; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\HtmlArticleLocker; use Remp\MailerModule\Models\Generators\EmbedParser; use Remp\MailerModule\Models\Generators\IGenerator; use Remp\MailerModule\Models\Generators\PreprocessException; use Remp\MailerModule\Models\Generators\WordpressHelpers; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Tomaj\NetteApi\Params\PostInputParam; class GrafdnaGenerator implements IGenerator { use RulesTrait, TemplatesTrait; public $onSubmit; public function __construct( private SourceTemplatesRepository $mailSourceTemplateRepository, private WordpressHelpers $helpers, private ContentInterface $content, private EmbedParser $embedParser, private HtmlArticleLocker $articleLocker, private EngineFactory $engineFactory, private WebClient $webClient, private SnippetsRepository $snippetsRepository, private TransportInterface $transport, ) { } public function apiParams(): array { return [ (new PostInputParam('grafdna_html'))->setRequired(), (new PostInputParam('url'))->setRequired(), (new PostInputParam('image_url')), (new PostInputParam('title'))->setRequired(), (new PostInputParam('from'))->setRequired(), ]; } public function generateForm(Form $form): void { // disable CSRF protection as external sources could post the params here $form->offsetUnset(Form::PROTECTOR_ID); $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->addText('url', 'Newsfilter URL') ->addRule(Form::URL) ->setRequired("Field 'Newsfilter URL' is required."); $form->addText('image_url', 'Image URL') ->setNullable() ->addRule(Form::URL); $form->addText('from', 'Sender'); $form->addTextArea('grafdna_html', 'HTML') ->setHtmlAttribute('rows', 20) ->setHtmlAttribute('class', 'form-control html-editor') ->getControlPrototype(); $form->addHidden('article_id')->setNullable(); $form->addSubmit('send') ->getControlPrototype() ->setName('button') ->setHtml('<i class="fa fa-magic"></i> ' . 'Generate'); $form->onSuccess[] = [$this, 'formSucceeded']; } public function onSubmit(callable $onSubmit): void { $this->onSubmit = $onSubmit; } public function getWidgets(): array { return [GrafdnaWidget::class]; } public function process(array $values): array { $this->articleLocker->setLockText('Predplaťte si Denník E a tento newsletter dostanete celý.'); $this->articleLocker->setupLockLink('Pridajte sa k predplatiteľom', 'https://predplatne.dennikn.sk/ecko'); $errors = []; $post = $values['grafdna_html']; $post = $this->parseOls($post); $lockedPost = $this->articleLocker->getLockedPost($post); if (!empty($values['image_url'])) { // match first embed or graph URL in text and replace with provided image $specialRule = [ "/(\[embed\](.*?)\[\/embed\]|^(http|https)\:\/\/[a-zA-Z0-9\-\.]*(flourish|datawrapper)+[a-zA-Z0-9\-\.]*\.[a-zA-Z]+(\/\S*)?\s*$)/im" => function ($matches) use ($values) { $link = null; foreach ($matches as $match) { if (Strings::startsWith($match, 'http')) { $link = $match; break; } } if (isset($link)) { return <<< HTML <img src={$values['image_url']} alt="" style="width: 100%"/> <p>Graf nájdete aj na <a href="$link">$link</a>.</p> HTML; } return ''; } ]; $post = preg_replace_callback(key($specialRule), current($specialRule), $post, 1); $lockedPost = preg_replace_callback(key($specialRule), current($specialRule), $lockedPost, 1); } $generatorRules = [ "/\[embed\](.*?)\[\/embed\]/is" => function ($matches) { return '<p>Graf nájdete aj na <a href="' . $matches[1] . '" style="padding:0;margin:0;line-height:1.3;color:' . $this->linksColor . ';text-decoration:underline;">' . $matches[1] . ' </a>.</p>'; }, "/^(http|https)\:\/\/[a-zA-Z0-9\-\.]*(flourish|datawrapper)+[a-zA-Z0-9\-\.]*\.[a-zA-Z]+(\/\S*)?\s*$/im" => function ($matches) { return '<p>Graf nájdete aj na <a href="' . $matches[0] . '" style="padding:0;margin:0;line-height:1.3;color:' . $this->linksColor . ';text-decoration:underline;">' . $matches[0] . ' </a>.</p>'; }, ]; $rules = $this->getRules($generatorRules); foreach ($rules as $rule => $replace) { if (is_array($replace) || is_callable($replace)) { $post = preg_replace_callback($rule, $replace, $post); $lockedPost = preg_replace_callback($rule, $replace, $lockedPost); } else { $post = preg_replace($rule, $replace, $post); $lockedPost = preg_replace($rule, $replace, $lockedPost); } } // wrap text in paragraphs $post = $this->helpers->wpautop($post); $lockedPost = $this->helpers->wpautop($lockedPost); // parse article links $post = $this->helpers->wpParseArticleLinks($post, 'https://dennikn.sk/', $this->getArticleLinkTemplateFunction(), $errors); $lockedPost = $this->helpers->wpParseArticleLinks($lockedPost, 'https://dennikn.sk/', $this->getArticleLinkTemplateFunction(), $errors); [$post, $lockedPost] = preg_replace('/<p>/is', "<p style=\"color:#181818;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:normal;padding:0;text-align:left;font-size:18px;line-height:160%;margin: 16px 0 16px 0\">", [$post, $lockedPost]); $lockedPost = $this->articleLocker->injectLockedMessage($lockedPost); $economyPostsResponse = $this->webClient->getEconomyPostsLast24Hours(); $excerpt = $economyPostsResponse['meta']['excerpt']; $economyPosts = $this->filterPosts($economyPostsResponse['posts']); $economyPosts = array_slice($economyPosts, 0, 5); foreach ($economyPosts as &$economyPost) { $economyPost['image_url'] = $this->getImageUrlForPost($economyPost); } $adSnippet = $this->snippetsRepository->all()->where([ 'code' => 'ad-grafdna', 'html <> ?' => '', 'mail_type_id' => null, ])->fetch(); $params = [ 'title' => $values['title'], 'url' => $values['url'], 'image_url' => $values['image_url'], 'html' => $post, 'text' => strip_tags($post), 'excerpt' => $excerpt, 'excerptText' => strip_tags($excerpt), 'economyPosts' => $economyPosts, 'adSnippetHtml' => $adSnippet?->html, 'adSnippetText' => $adSnippet?->text, ]; $lockedParams = [ 'title' => $values['title'], 'url' => $values['url'], 'image_url' => $values['image_url'], 'html' => $lockedPost, 'text' => strip_tags($lockedPost), 'excerpt' => $excerpt, 'economyPosts' => $economyPosts, 'adSnippetHtml' => $adSnippet?->html, 'adSnippetText' => $adSnippet?->text, ]; $sourceTemplate = $this->mailSourceTemplateRepository->find($values['source_template_id']); $engine = $this->engineFactory->engine(); return [ 'htmlContent' => $engine->render($sourceTemplate->content_html, $params), 'textContent' => strip_tags($engine->render($sourceTemplate->content_text, $params)), 'lockedHtmlContent' => $engine->render($sourceTemplate->content_html, $lockedParams), 'lockedTextContent' => strip_tags($engine->render($sourceTemplate->content_text, $lockedParams)), 'errors' => $errors, ]; } public function formSucceeded(Form $form, ArrayHash $values): void { $output = $this->process((array) $values); $addonParams = [ 'lockedHtmlContent' => $output['lockedHtmlContent'], 'lockedTextContent' => $output['lockedTextContent'], 'grafdnaTitle' => $values->title, 'from' => $values->from, 'render' => true, 'articleId' => $values->article_id, 'errors' => $output['errors'], ]; $this->onSubmit->__invoke($output['htmlContent'], $output['textContent'], $addonParams); } /** * @param \stdClass $data containing WP article data * @return ArrayHash with data to fill the form with */ public function preprocessParameters($data): ?ArrayHash { $output = new ArrayHash(); $output->from = "Denník E <e@dennikn.sk>"; if (!isset($data->post_title)) { throw new PreprocessException("WP json object does not contain required attribute 'post_title'"); } $output->title = $data->post_title; if (!isset($data->post_url)) { throw new PreprocessException("WP json object does not contain required attribute 'post_url'"); } $output->url = $data->post_url; if (!isset($data->post_content)) { throw new PreprocessException("WP json object does not contain required attribute 'post_content'"); } $output->grafdna_html = $data->post_content; // remp/remp#1174 // og:image is used as graph image instead of complex graph element in generated newsletter // this image contains labels and logo $imageUrl = $this->getSocialImageUrl($data->post_url); if (!$imageUrl) { $meta = $this->content->fetchUrlMeta($data->post_url); $imageUrl = $meta->getImage(); } $output->image_url = (new Url($imageUrl))->setQuery([])->getAbsoluteUrl(); $output->article_id = $data->ID; return $output; } public function getTemplates(): array { $captionTemplate = <<< HTML <img src="$1" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;"> <p style="margin:0 0 0 26px;Margin:0 0 0 26px;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-size:18px;line-height:1.6;margin-bottom:26px;Margin-bottom:26px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;"> <small class="text-gray" style="font-size:13px;line-height:18px;display:block;color:#9B9B9B;">$2</small> </p> HTML; $captionWithLinkTemplate = <<< HTML <a href="$1" style="color:#181818;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:normal;padding:0;margin:0;Margin:0;text-align:left;line-height:1.3;color:{$this->linksColor};text-decoration:none;"> <img src="$2" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;border:none;"> </a> <p style="margin:0 0 0 26px;Margin:0 0 0 26px;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-size:18px;line-height:1.6;margin-bottom:26px;Margin-bottom:26px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;"> <small class="text-gray" style="font-size:13px;line-height:18px;display:block;color:#9B9B9B;">$3</small> </p> HTML; $liTemplate = <<< HTML <tr style="padding:0;vertical-align:top;text-align:left;"> <td class="bullet" style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;width:30px;border-collapse:collapse !important;">&#8226;</td> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;border-collapse:collapse !important;"> <p style="color:#181818;padding:0;margin:0 0 5px 0;font-size:18px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;">$1</p> </td> </tr> HTML; $hrTemplate = <<< HTML <table cellspacing="0" cellpadding="0" border="0" width="100%" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:100%;min-width:100%;"> <tr style="padding:0;vertical-align:top;text-align:left;width:100%;min-width:100%;"> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;border-collapse:collapse !important; padding: 30px 0 0 0; border-top:1px solid #E2E2E2;height:0;line-height: 0;width:100%;min-width:100%;">&#xA0;</td> </tr> </table> HTML; $spacerTemplate = <<< HTML <table class="spacer" style="border-spacing:0;border-collapse:collapse;vertical-align:top;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;text-align:left;font-family:'Helvetica Neue', Helvetica, Arial;width:100%;"> <tbody> <tr style="padding:0;vertical-align:top;text-align:left;"> <td height="20px" style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;mso-line-height-rule:exactly;border-collapse:collapse !important;font-size:20px;line-height:20px;">&#xA0;</td> </tr> </tbody> </table> HTML; $imageTemplate = <<< HTML <img src="$1" alt="" style="outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:auto;max-width:100%;clear:both;display:block;margin-bottom:20px;"> HTML; return [ $captionTemplate, $captionWithLinkTemplate, $liTemplate, $hrTemplate, $spacerTemplate, $imageTemplate, ]; } public function parseOls($post) { $ols = []; preg_match_all('/<ol.*?>(.*?)<\/ol>/is', $post, $ols); foreach ($ols[1] as $olContent) { $olsLis = []; $liNum = 1; $newOlContent = ''; preg_match_all('/<li>(.*?)<\/li>/is', $olContent, $olsLis); foreach ($olsLis[1] as $liContent) { $newOlContent .= ' <tr style="padding:0;vertical-align:top;text-align:left;"> <td class="bullet" style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;width:30px;border-collapse:collapse !important;">' . $liNum . '</td> <td style="padding:0;vertical-align:top;text-align:left;font-size:18px;line-height:1.6;border-collapse:collapse !important;"> <p style="margin:0 0 0 26px;Margin:0 0 0 26px;color:#181818;padding:0;margin:0;Margin:0;line-height:1.3;font-size:18px;line-height:1.6;margin-bottom:26px;Margin-bottom:26px;line-height:160%;text-align:left;font-weight:normal;word-wrap:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;border-collapse:collapse !important;">' . $liContent . '</p> </td> </tr>'; $liNum++; } $post = str_replace($olContent, $newOlContent, $post); } return $post; } private function filterPosts($posts): array { $tagsToFilter = ['graf-dna', 'ekonomicky-newsfilter']; return array_filter($posts, function ($post) use ($tagsToFilter) { foreach ($post['tags'] as $tag) { if (in_array($tag['slug'], $tagsToFilter, true)) { return false; } } return true; }, ARRAY_FILTER_USE_BOTH); } private function getImageUrlForPost($post) { $desiredWidth = 500; $currentDiff = null; $currentUrl = null; foreach ($post['image']['sizes'] as $image) { $diff = abs($image['width'] - $desiredWidth); if (!isset($currentDiff) || $diff < $currentDiff) { $currentDiff = $diff; $currentUrl = $image['url']; } } return $currentUrl; } private function getSocialImageUrl($postUrl) { $content = $this->transport->getContent($postUrl); $matches = []; preg_match('/<meta property=\"og:image\" content=\"(.+)\">/U', $content, $matches); if ($matches) { return $matches[1]; } return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/NapunkNewsfilterGenerator.php
Mailer/app/Models/Generators/NapunkNewsfilterGenerator.php
<?php namespace Remp\Mailer\Models\Generators; class NapunkNewsfilterGenerator extends NewsfilterGenerator { public function process(array $values): array { $this->articleLocker->setLockText('Ezt a cikket csak a Napunk előfizetői olvashatják végig.'); $this->articleLocker->setupLockLink('Csatlakozz hozzánk', 'https://predplatne.dennikn.sk/napunk-start'); return parent::process($values); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/Generators/WordpressBlockParser.php
Mailer/app/Models/Generators/WordpressBlockParser.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\Generators; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\ContentGenerator\Engine\IEngine; use Remp\MailerModule\Models\ContentGenerator\Engine\TwigEngine; class WordpressBlockParser { public const BLOCK_CORE_GROUP = 'core/group'; public const BLOCK_CORE_HEADING = 'core/heading'; public const BLOCK_CORE_PARAGRAPH = 'core/paragraph'; public const BLOCK_CORE_LIST = 'core/list'; public const BLOCK_CORE_COLUMN = 'core/column'; public const BLOCK_CORE_COLUMNS = 'core/columns'; public const BLOCK_CORE_IMAGE = 'core/image'; public const BLOCK_CORE_LIST_ITEM = 'core/list-item'; public const BLOCK_CORE_EMBED = 'core/embed'; public const BLOCK_DN_MINUTE = 'dn-newsletter/r5m-minute'; public const BLOCK_DN_GROUP = 'dn-newsletter/r5m-group'; public const BLOCK_DN_HEADER = 'dn-newsletter/r5m-header'; public const BLOCK_DN_ADVERTISEMENT = 'dn-newsletter/r5m-ad'; /** @var TwigEngine $twig */ private IEngine $twig; private int $minuteOrderCounter = 1; private bool $isFirstDNMinuteInGroup = true; private bool $isFirstDnHeaderInMinuteGroup = true; public function __construct( EngineFactory $engineFactory, private EmbedParser $embedParser ) { $this->twig = $engineFactory->engine('twig'); } public function parseJson(string $json) { $data = preg_replace('/[[:cntrl:]]/', '', $json); $data = json_decode($data); $isFirstBlock = true; $htmlResult = ''; $textResult = ''; foreach ($data as $block) { $parsedBlock = $this->parseBlock($block); $htmlResult .= $parsedBlock; $textBlock = html_entity_decode(strip_tags($parsedBlock)); $textBlock = preg_replace('/\n(\s*)\n(\s*)\n/', "\n\n", $textBlock); $textBlock = preg_replace('/^\s/', "", $textBlock); $textBlock = str_replace(' ', " ", $textBlock); $textResult .= $textBlock; // put advertisement snippet into template after first main block if ($isFirstBlock) { $htmlResult .= "{{ include('r5m-advertisement') }}"; $textResult .= "\n\n{{ include('r5m-advertisement') }}\n\n"; } $isFirstBlock = false; } return [$htmlResult, $textResult]; } public function getBlockTemplateData(object $block, array $innerBlockParams = []): array { $data = [ 'originalContent' => $block->originalContent ?? null, 'content' => $block->attributes->content ?? null, 'verticalAlignment' => $block->attributes->verticalAlignment ?? null, 'fontSize' => $block->attributes->style->typography->fontSize ?? null, 'width' => $block->attributes->width ?? null, 'url' => $block->attributes->url ?? null, 'alt' => $block->attributes->alt ?? null, 'caption' => $block->attributes->caption ?? null, 'href' => $block->attributes->href ?? null, 'isInMinute' => $innerBlockParams['isInMinute'] ?? false, 'minuteListItem' => $innerBlockParams['minuteListItem'] ?? false, ]; if ($block->name === self::BLOCK_CORE_GROUP && isset($block->attributes->className) && str_contains($block->attributes->className, 'wp-block-dn-newsletter-group-grey') ) { $data['group_grey'] = true; } if ($block->name === self::BLOCK_CORE_LIST) { $data['list_type'] = $block->attributes->ordered ? 'ol' : 'ul'; } if ($block->name === self::BLOCK_CORE_GROUP && isset($block->attributes->className) && str_contains($block->attributes->className, 'wp-block-dn-newsletter-group-ordered') ) { $data['group_ordered'] = true; } if ($block->name === self::BLOCK_CORE_EMBED) { $data['embed_html'] = $this->embedParser->parse($block->attributes->url); } if ($block->name === self::BLOCK_DN_MINUTE) { $data['isFirstDNMinuteInGroup'] = $this->isFirstDNMinuteInGroup; if (isset($block->attributes->bullet) && !empty($block->attributes->bullet)) { $data['bullet'] = $block->attributes->bullet; } } if ($block->name === self::BLOCK_CORE_HEADING) { $data['level'] = $block->attributes->level; // Override content - get the width of image from style and add as html attribute to fix Outlook $data['content'] = preg_replace('/(\N*width:\\s?)(\d*)(px\N*")(\N*)/', '$1$2$3 width=$2 $4', $block->attributes->content); } if (isset($innerBlockParams['groupOrdered']) && $innerBlockParams['groupOrdered'] && $block->name === self::BLOCK_DN_MINUTE) { if ($this->minuteOrderCounter < 6) { $data['minuteOrderCounter'] = $this->minuteOrderCounter; } $this->minuteOrderCounter++; } if ($block->name === self::BLOCK_CORE_PARAGRAPH && isset($block->attributes->className) && str_contains($block->attributes->className, 'wp-block-dn-newsletter-paragraph-hr') ) { $data['paragraph_hr'] = true; } if ($block->name === self::BLOCK_DN_HEADER) { $data['isFirstDnHeaderInMinuteGroup'] = $this->isFirstDnHeaderInMinuteGroup; } if ($block->name === self::BLOCK_CORE_IMAGE) { $imageSize = getimagesize($block->attributes->url)[0]; $data['imageWidth'] = min($imageSize, 660); } return $data; } public function parseBlock(object $block, array $innerBlockParams = []): string { $params = [ 'contents' => '' ]; $params += $this->getBlockTemplateData($block, $innerBlockParams); if ($block->name === self::BLOCK_CORE_GROUP) { $this->minuteOrderCounter = 1; $this->isFirstDNMinuteInGroup = true; } elseif ($block->name === self::BLOCK_CORE_HEADING) { $this->isFirstDNMinuteInGroup = true; } elseif ($block->name === self::BLOCK_DN_MINUTE) { $this->isFirstDNMinuteInGroup = false; $this->isFirstDnHeaderInMinuteGroup = false; } elseif ($block->name === self::BLOCK_DN_GROUP) { $this->isFirstDNMinuteInGroup = true; $this->isFirstDnHeaderInMinuteGroup = true; } elseif ($block->name === self::BLOCK_DN_HEADER) { $this->isFirstDnHeaderInMinuteGroup = false; } $template = $this->getTemplate($block->name); if (isset($block->innerBlocks) && !empty($block->innerBlocks)) { foreach ($block->innerBlocks as $innerBlock) { $params['contents'] .= $this->parseBlock($innerBlock, [ 'isInMinute' => $block->name === self::BLOCK_DN_MINUTE, 'groupOrdered' => $params['group_ordered'] ?? false, 'minuteListItem' => isset($innerBlockParams['groupOrdered']) && $innerBlockParams['groupOrdered'] && $block->name === self::BLOCK_DN_MINUTE && $this->minuteOrderCounter > 6 ]); } } return $this->twig->render($template, $params); } public function getTemplate(string $blockName): string { $templateFile = match ($blockName) { self::BLOCK_CORE_GROUP => __DIR__ . '/resources/templates/WordpressBlockParser/core-group.twig', self::BLOCK_CORE_PARAGRAPH => __DIR__ . '/resources/templates/WordpressBlockParser/core-paragraph.twig', self::BLOCK_CORE_HEADING => __DIR__ . '/resources/templates/WordpressBlockParser/core-heading.twig', self::BLOCK_CORE_IMAGE => __DIR__ . '/resources/templates/WordpressBlockParser/core-image.twig', self::BLOCK_CORE_COLUMN => __DIR__ . '/resources/templates/WordpressBlockParser/core-column.twig', self::BLOCK_CORE_COLUMNS => __DIR__ . '/resources/templates/WordpressBlockParser/core-columns.twig', self::BLOCK_CORE_LIST => __DIR__ . '/resources/templates/WordpressBlockParser/core-list.twig', self::BLOCK_CORE_LIST_ITEM => __DIR__ . '/resources/templates/WordpressBlockParser/core-list-item.twig', self::BLOCK_CORE_EMBED => __DIR__ . '/resources/templates/WordpressBlockParser/core-embed.twig', self::BLOCK_DN_MINUTE => __DIR__ . '/resources/templates/WordpressBlockParser/dn-minute.twig', self::BLOCK_DN_GROUP => __DIR__ . '/resources/templates/WordpressBlockParser/dn-group.twig', self::BLOCK_DN_HEADER => __DIR__ . '/resources/templates/WordpressBlockParser/dn-header.twig', self::BLOCK_DN_ADVERTISEMENT => __DIR__ . '/resources/templates/WordpressBlockParser/dn-advertisement.twig', default => throw new \Exception("not existing block template: '{$blockName}'"), }; return file_get_contents($templateFile); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/RespektMeta.php
Mailer/app/Models/PageMeta/RespektMeta.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta; use Remp\MailerModule\Models\PageMeta\Meta; class RespektMeta extends Meta { public function __construct( ?string $title = null, ?string $image = null, array $authors = [], public readonly ?string $type = null, public readonly ?string $subtitle = null, public readonly ?string $firstParagraph = null, public readonly ?string $firstContentPartType = null, public readonly ?string $fullContent = null, public readonly ?string $unlockedContent = null, public readonly ?string $imageTitle = null, public readonly ?string $subject = null, ) { parent::__construct( title: $title, image: $image, authors: $authors, ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Transport/RespektApiTransport.php
Mailer/app/Models/PageMeta/Transport/RespektApiTransport.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Transport; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Uri; use Nette\Utils\Json; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Tracy\Debugger; use Tracy\ILogger; class RespektApiTransport implements TransportInterface { public function __construct( private readonly string $respektContentUrl, private readonly string $respektContentToken, ) { } public function getContent(string $url): ?string { $uri = new Uri($url); $contentPath = trim($uri->getPath(), '/'); $client = new Client(); try { $query = <<<'GRAPHQL' query GetArticleForMailer($articleUrl: String) { getArticle(by: { url: { url: $articleUrl } }) { title authors {author {name}} coverPhoto {image {url width height title author {name}} title} categories {category {id name}} publishAt subtitle {parts {json order}} newsletterSubject content { parts { json order references {id type target {type externalTarget internalTarget {url article {title}}} image { title image { url title author {name} } }} } } } } GRAPHQL; $response = $client->post($this->respektContentUrl, [ 'headers' => ['Authorization' => 'Bearer ' . $this->respektContentToken], 'json' => [ 'query' => $query, 'variables' => [ 'articleUrl' => $contentPath ] ] ]); } catch (ClientException $e) { Debugger::log($e->getMessage() . ': ' . $e->getResponse()->getBody()->getContents(), ILogger::ERROR); return null; } catch (GuzzleException $e) { Debugger::log($e->getMessage(), ILogger::ERROR); return null; } return $response->getBody()->getContents(); } public function resolveRedirects(string $url): ?string { $uri = new Uri($url); $contentPath = trim($uri->getPath(), '/'); $client = new Client(); try { $query = <<<'GRAPHQL' query GetRedirectUrlForMailer($articleUrl: String) { getUrl(by: { url: $articleUrl}) { redirectType target { internalTarget { url } } } } GRAPHQL; $response = $client->post($this->respektContentUrl, [ 'headers' => ['Authorization' => 'Bearer ' . $this->respektContentToken], 'json' => [ 'query' => $query, 'variables' => [ 'articleUrl' => $contentPath ] ] ]); } catch (GuzzleException $e) { Debugger::log($e->getMessage(), ILogger::ERROR); return null; } $response = $response->getBody()->getContents(); $json = Json::decode($response); $path = $json->data->getUrl->target->internalTarget->url ?? null; if (!$path) { return null; } $resolvedUrl = new Uri($url); $resolvedUrl = $resolvedUrl->withPath($path); return (string) $resolvedUrl; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/DenniknShopContent.php
Mailer/app/Models/PageMeta/Content/DenniknShopContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Nette\Utils\Json; use Nette\Utils\JsonException; use Nette\Utils\Strings; use Remp\MailerModule\Models\PageMeta\Content\ShopContentInterface; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; class DenniknShopContent implements ShopContentInterface { private $transport; public function __construct(TransportInterface $transport) { $this->transport = $transport; } public function fetchUrlMeta(string $url): ?Meta { $url = preg_replace('/\\?ref=(.*)/', '', $url); try { $content = $this->transport->getContent($url); if ($content === null) { return null; } $meta = $this->parseMeta($content); if (!$meta) { return null; } } catch (RequestException $e) { throw new InvalidUrlException("Invalid URL: {$url}", 0, $e); } return $meta; } public function parseMeta(string $content): ?Meta { preg_match_all('/<script type="application\/ld\+json">(.*?)<\/script>/s', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][0]); } catch (JsonException $e) { return null; } // authors $authors = []; if (isset($schema->dataFeedElement[0]->author)) { $authors = explode(',', $schema->dataFeedElement[0]->author->name); } // title $title = $schema->dataFeedElement[0]->name ?? null; // description $description = null; if (isset($schema->dataFeedElement[0]->workExample[0]->abstract)) { $description = str_replace('\n', '', Strings::truncate($schema->dataFeedElement[0]->workExample[0]->abstract, 200)); } // image $image = $schema->dataFeedElement[0]->workExample[0]->image ?? null; return new Meta($title, $description, $image, $authors); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/TyzdenContent.php
Mailer/app/Models/PageMeta/Content/TyzdenContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; class TyzdenContent implements ContentInterface { private $transport; public function __construct(TransportInterface $transport) { $this->transport = $transport; } public function fetchUrlMeta(string $url): ?Meta { $url = preg_replace('/\\?ref=(.*)/', '', $url); try { $content = $this->transport->getContent($url); if ($content === null) { return null; } $meta = $this->parseMeta($content); if (!$meta) { return null; } } catch (RequestException $e) { throw new InvalidUrlException("Invalid URL: {$url}", 0, $e); } return $meta; } public function parseMeta(string $content): Meta { // author $authors = []; $matches = []; preg_match_all('/<meta name=\"author\" content=\"(.+)\">/U', $content, $matches); if ($matches) { foreach ($matches[1] as $author) { $authors[] = $author; } } // title $title = null; $matches = []; preg_match('/<meta property=\"og:title\" content=\"(.+)\">/U', $content, $matches); if ($matches) { $title = $matches[1]; } // description $description = null; $matches = []; preg_match('/<meta property=\"og:description\" content=\"(.+)\">/Us', $content, $matches); if ($matches) { $description = $matches[1]; } // image $image = null; $matches = []; preg_match('/<meta property=\"og:image\" content=\"(.+)\">/U', $content, $matches); if ($matches) { $image = $matches[1]; } return new Meta($title, $description, $image, $authors); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/NytContent.php
Mailer/app/Models/PageMeta/Content/NytContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\ServerException; use Nette\Utils\Json; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Meta; use Tracy\Debugger; use Tracy\ILogger; class NytContent implements ContentInterface { public function __construct( private readonly string $apiKey, ) { } public function fetchUrlMeta(string $url): ?Meta { $client = new Client(); try { $responseRaw = $client->get('http://api.nytimes.com/svc/news/v3/content.json', [ 'query' => [ 'url' => $url, 'api-key' => $this->apiKey, ], ]); $responseJson = $responseRaw->getBody()->getContents(); $response = Json::decode($responseJson, forceArrays: true); if ($response['num_results'] !== 1) { throw new \RuntimeException('Unable to fetch NYT article: ' . $responseJson); } } catch (ClientException $e) { throw new InvalidUrlException("Invalid URL: {$url}", $e->getCode(), $e); } catch (ServerException|ConnectException|RequestException $e) { Debugger::log('Unable to request NYT API: ' . $e->getMessage(), ILogger::EXCEPTION); return null; } return $this->parseMeta($response['results'][0]); } public function parseMeta(array $article): ?Meta { $imageUrl = null; foreach ($article['multimedia'] as $imageDef) { if ($imageDef['format'] === 'mediumThreeByTwo440') { $imageUrl = $imageDef['url']; break; } } return new Meta( title: $article['title'], description: $article['abstract'], image: $imageUrl, authors: [$article['byline']], // e.g. "By Devlin Barrett" ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/NovydenikContent.php
Mailer/app/Models/PageMeta/Content/NovydenikContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Nette\Http\Url; use Nette\Utils\Json; use Nette\Utils\JsonException; use Nette\Utils\Strings; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Tracy\Debugger; use Tracy\ILogger; class NovydenikContent implements ContentInterface { private $transport; public function __construct( TransportInterface $transport ) { $this->transport = $transport; } public function fetchUrlMeta(string $url): ?Meta { $url = preg_replace('/\\?ref=(.*)/', '', $url); try { $content = $this->transport->getContent($url); if ($content === null) { return null; } if (strpos($url, 'obchod.denikn.cz') !== false) { $meta = $this->parseShopMeta($content); } else { $meta = $this->parseMeta($content); } if (!$meta) { return null; } } catch (RequestException $e) { Debugger::log("Invalid URL: {$url}", ILogger::EXCEPTION); return null; } return $meta; } public function parseMeta(string $content): ?Meta { preg_match_all('/<script id="schema" type="application\/ld\+json">(.*?)<\/script>/', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][0]); } catch (JsonException $e) { return null; } // author $denniknAuthors = []; if (isset($schema->author) && !is_array($schema->author)) { $schema->author = [$schema->author]; } foreach ($schema->author as $author) { $denniknAuthors[] = Strings::upper($author->name); } $title = $schema->headline ?? null; $description = $schema->description ?? null; $image = $this->processImage($schema->image->url ?? null); return new Meta($title, $description, $image, $denniknAuthors); } public function parseShopMeta(string $content): ?Meta { preg_match_all('/<script type="application\/ld\+json">(.*?)<\/script>/s', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][1]); } catch (JsonException $e) { return null; } // authors $authors = []; if (isset($schema->dataFeedElement[0]->author)) { $authors = explode(',', $schema->dataFeedElement[0]->author->name); } // title $title = $schema->dataFeedElement[0]->name ?? null; // description $description = null; if (isset($schema->dataFeedElement[0]->workExample[0]->abstract)) { $description = str_replace('\n', '', Strings::truncate($schema->dataFeedElement[0]->workExample[0]->abstract, 200)); } // image $image = $schema->dataFeedElement[0]->workExample[0]->image ?? null; return new Meta($title, $description, $image, $authors); } private function processImage(?string $imageUrl): string { if (!$imageUrl) { return 'https://static.novydenik.com/2018/11/placeholder_2@2x.png'; } $url = new Url($imageUrl); $url = (string) $url->appendQuery(['w' => 558, 'h' => 270, 'fit' =>'crop']); // return placeholder if image doesn't exist $response = get_headers($url); if (strpos($response[0], '404')) { return 'https://static.novydenik.com/2018/11/placeholder_2@2x.png'; } return $url; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/NovydenikShopContent.php
Mailer/app/Models/PageMeta/Content/NovydenikShopContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Nette\Utils\Json; use Nette\Utils\JsonException; use Nette\Utils\Strings; use Remp\MailerModule\Models\PageMeta\Content\ShopContentInterface; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; class NovydenikShopContent implements ShopContentInterface { private $transport; public function __construct(TransportInterface $transport) { $this->transport = $transport; } public function fetchUrlMeta(string $url): ?Meta { $url = preg_replace('/\\?ref=(.*)/', '', $url); try { $content = $this->transport->getContent($url); if ($content === null) { return null; } $meta = $this->parseMeta($content); if (!$meta) { return null; } } catch (RequestException $e) { throw new InvalidUrlException("Invalid URL: {$url}", 0, $e); } return $meta; } public function parseMeta(string $content): ?Meta { preg_match_all('/<script type="application\/ld\+json">(.*?)<\/script>/s', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][1]); } catch (JsonException $e) { return null; } // authors $authors = []; if (isset($schema->dataFeedElement[0]->author)) { $authors = explode(',', $schema->dataFeedElement[0]->author->name); } // title $title = $schema->dataFeedElement[0]->name ?? null; // description $description = null; if (isset($schema->dataFeedElement[0]->workExample[0]->abstract)) { $description = str_replace('\n', '', Strings::truncate($schema->dataFeedElement[0]->workExample[0]->abstract, 200)); } // image $image = $schema->dataFeedElement[0]->workExample[0]->image ?? null; return new Meta($title, $description, $image, $authors); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/DenniknContent.php
Mailer/app/Models/PageMeta/Content/DenniknContent.php
<?php declare(strict_types=1); namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Nette\Http\Url; use Nette\Utils\Json; use Nette\Utils\JsonException; use Nette\Utils\Strings; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; class DenniknContent implements ContentInterface { private $transport; public function __construct( TransportInterface $transport ) { $this->transport = $transport; } public function fetchUrlMeta(string $url): ?Meta { $url = preg_replace('/\\?ref=(.*)/', '', $url); try { $content = $this->transport->getContent($url); if ($content === null) { return null; } if (strpos($url, 'obchod.dennikn.sk') !== false) { $meta = $this->parseShopMeta($content); } else { $meta = $this->parseMeta($content); } } catch (RequestException $e) { throw new InvalidUrlException("Invalid URL: {$url}", 0, $e); } return $meta; } public function parseMeta(string $content): ?Meta { preg_match_all('/<script id="schema" type="application\/ld\+json">(.*?)<\/script>/', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][0]); } catch (JsonException $e) { return null; } // author $denniknAuthors = []; if (isset($schema->author) && !is_array($schema->author)) { $schema->author = [$schema->author]; } foreach ($schema->author as $author) { $denniknAuthors[] = Strings::upper($author->name); } $title = $schema->headline ?? null; $description = $schema->description ?? null; $image = $this->processImage($schema->image->url ?? null); return new Meta($title, $description, $image, $denniknAuthors); } public function parseShopMeta(string $content): ?Meta { preg_match_all('/<script type="application\/ld\+json">(.*?)<\/script>/s', $content, $matches); if (!$matches || empty($matches[1])) { return null; } try { $schema = Json::decode($matches[1][0]); } catch (JsonException $e) { return null; } // authors $authors = []; if (isset($schema->dataFeedElement[0]->author)) { $authors = explode(',', $schema->dataFeedElement[0]->author->name); } // title $title = $schema->dataFeedElement[0]->name ?? null; // description $description = null; if (isset($schema->dataFeedElement[0]->workExample[0]->abstract)) { $description = str_replace('\n', '', Strings::truncate($schema->dataFeedElement[0]->workExample[0]->abstract, 200)); } // image $image = $schema->dataFeedElement[0]->workExample[0]->image ?? null; return new Meta($title, $description, $image, $authors); } private function processImage(?string $imageUrl): string { if (!$imageUrl) { return 'https://static.novydenik.com/2018/11/placeholder_2@2x.png'; } $url = new Url($imageUrl); $url = (string) $url->appendQuery(['w' => 558, 'h' => 270, 'fit' =>'crop']); // return placeholder if image doesn't exist $response = get_headers($url); if (strpos($response[0], '404')) { return 'https://img.projektn.sk/wp-static/2018/10/placeholder_2@2x.png'; } return $url; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Models/PageMeta/Content/RespektContent.php
Mailer/app/Models/PageMeta/Content/RespektContent.php
<?php namespace Remp\Mailer\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Nette\Utils\Json; use Nette\Utils\JsonException; use Remp\Mailer\Models\PageMeta\RespektMeta; use Remp\Mailer\Models\PageMeta\Transport\RespektApiTransport; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; use Tracy\Debugger; use Tracy\ILogger; class RespektContent implements ContentInterface { private const RESPEKT_IMAGE_URL = 'https://i.respekt.cz/'; private const RESPEKT_PAGE_URL = 'https://respekt.cz/'; private array $categoryArticleTypeMap = [ '63d5958a-cb51-4aee-b6a2-81f560ce4f6d' => 'podcast', '65357154-6820-441d-ae1d-a7a9b456e68f' => 'commentary', 'd8c0a494-2241-4a27-ab75-d64cdbae8007' => 'interview', ]; public function __construct(private TransportInterface $transport) { } public function fetchUrlMeta(string $url): ?Meta { if (!$this->transport instanceof RespektApiTransport) { Debugger::log(self::class . ' depends on ' . RespektApiTransport::class . '.', ILogger::ERROR); return null; } try { $data = $this->transport->getContent($url); if ($data === null) { return null; } try { $data = Json::decode($data, true); } catch (JsonException $e) { Debugger::log($e->getMessage(), ILogger::ERROR); return null; } $article = $data['data']['getArticle']; if ($article === null) { // URL has changed, we need to follow redirects and determine new URL $resolvedUrl = $this->transport->resolveRedirects($url); if (!$resolvedUrl) { // The article wasn't published yet. return null; } if ($url && $resolvedUrl !== $url) { return $this->fetchUrlMeta($resolvedUrl); } return null; } } catch (RequestException $e) { throw new InvalidUrlException("Invalid URL: {$url}", 0, $e); } // get article title $title = $article['title']; // get article subtitle $subtitle = $this->getContentFromParts( parts: $article['subtitle']['parts'] ?? [], countOfParagraphs: 1, ); // get first paragraph $firstContentParagraph = $this->getContentFromParts( parts: $article['content']['parts'], countOfParagraphs: 1, ); // get first content part type $firstPart = Json::decode($article['content']['parts'][0]['json'], true); $firstContentPartType = $firstPart['children'][0]['type']; $fullContent = $this->getContentFromParts($article['content']['parts']); $unLockedContent = $this->getContentFromParts($article['content']['parts'], 3); // get article cover image $image = null; if (isset($article['coverPhoto']['image']['url'])) { $image = $this->getImageUrl($article['coverPhoto']['image']['url']); } $imageTitle = $article['coverPhoto']['title'] ?? $article['coverPhoto']['image']['title']; $imageAuthor = $article['coverPhoto']['image']['author']['name'] ?? null; if ($imageAuthor) { $imageTitle .= " &bull; Autor: {$imageAuthor}"; } // get article authors $authors = []; foreach ($article['authors'] as $author) { $authors[] = $author['author']['name']; } // get article type $articleType = null; foreach ($article['categories'] as $articleCategory) { $category = $articleCategory['category']; if (array_key_exists($category['id'], $this->categoryArticleTypeMap)) { $articleType = $this->categoryArticleTypeMap[$category['id']]; break; } } // get newsletter subject $subject = null; if (isset($article['newsletterSubject'])) { $subject = $article['newsletterSubject']; } return new RespektMeta( title: $title, image: $image, authors: $authors, type: $articleType, subtitle: $subtitle, firstParagraph: $firstContentParagraph, firstContentPartType: $firstContentPartType, fullContent: $fullContent, unlockedContent: $unLockedContent, imageTitle: $imageTitle, subject: $subject, ); } private function getContentFromParts(array $parts, int $countOfParagraphs = null): ?string { $paragraphCount = 0; $processedContent = null; $references = []; $textChildTypes = [ 'paragraph' => true, 'interTitle' => true, ]; foreach ($parts as $contentPart) { try { // decode content $contentPartData = Json::decode($contentPart['json'], true); } catch (JsonException $e) { Debugger::log($e->getMessage(), ILogger::ERROR); return null; } // remap links so we can look by key (reference id) if (isset($contentPart['references'])) { foreach ($contentPart['references'] as $reference) { $references[$reference['id']] = $reference; } } foreach ($contentPartData['children'] as $contentPartChild) { if ($textChildTypes[$contentPartChild['type']] ?? false) { $processedPart = '<p>'; if ($contentPartChild['type'] === 'interTitle') { $processedPart = '<strong>'; } $processedChildren = ''; foreach ($contentPartChild['children'] as $child) { $node = ''; if (isset($child['text'])) { $node = $child['text']; if (isset($child['isBold']) && $child['isBold'] === true) { $node = "<strong>{$node}</strong>"; } if (isset($child['isUnderlined']) && $child['isUnderlined'] === true) { $node = "<u>{$node}</u>"; } if (isset($child['isItalic']) && $child['isItalic'] === true) { $node = "<em>{$node}</em>"; } if (isset($child['isStruckThrough']) && $child['isStruckThrough'] === true) { $node = "<s>{$node}</s>"; } } elseif (isset($child['type']) && $child['type'] === 'link') { $linkTarget = $references[$child['referenceId']]['target']; $link = ($linkTarget['externalTarget'] ?? $linkTarget['internalTarget']) ?? null; if ($link !== null) { $node = $child['children'][0]['text']; // TODO[respekt#192]: this can contain multiple children with formatting $node = is_array($link) ? "<a href='{$this->getAbsoluteUrl($link['url'])}'>{$node}</a>" : "<a href='{$this->getAbsoluteUrl($link)}'>{$node}</a>"; } } elseif (isset($child['type']) && $child['type'] === 'anchor') { $node = $child['children'][0]['text']; $node = "<a href='{$child['href']}'>{$node}</a>"; } $processedChildren .= $node; } if ($processedChildren) { $processedPart .= $processedChildren; if ($contentPartChild['type'] === 'interTitle') { $processedPart .= '</strong>'; } $processedContent .= $processedPart . '</p>'; $paragraphCount++; } if ($countOfParagraphs && $countOfParagraphs === $paragraphCount) { break 2; } } if ($contentPartChild['type'] === 'reference' && isset($references[$contentPartChild['referenceId']])) { $reference = $references[$contentPartChild['referenceId']]; if ($reference['type'] === 'image' && $reference['image']['image']['url']) { $title = $reference['image']['image']['title']; if (isset($reference['image']['title'])) { $title = $reference['image']['title']; } $author = null; if (isset($reference['image']['image']['author']['name'])) { $author = 'Autor: ' . $reference['image']['image']['author']['name']; } $processedContent .= sprintf( '<figure><img src="%s" alt="%s"><figcaption style="font-size: 0.8rem; color: #6b6b6b; font-style: italic;">%s</figcaption></figure><p></p>', $this->getImageUrl($reference['image']['image']['url']), $author, isset($title, $author) ? "{$title} &bull; {$author}" : "", ); } if ($reference['type'] === 'block_link' && isset($reference['target']['internalTarget']['article']['title'])) { $processedContent .= "<p><strong>Mohlo by vás zaujmout:</strong> <a href='{$this->getAbsoluteUrl($reference['target']['internalTarget']['url'])}'>{$reference['target']['internalTarget']['article']['title']}</a></p>"; } if ($reference['type'] === 'horizontal_divider') { $processedContent .= '<hr>'; } } if ($contentPartChild['type'] === 'question' && isset($contentPartChild['children'][0]['text'])) { $processedContent .= "<p><strong>{$contentPartChild['children'][0]['text']}</strong></p>"; } if ($contentPartChild['type'] === 'heading') { $level = $contentPartChild['level']; $fontSize = match ($level) { 1 => 32, 2 => 24, 3 => 18, default => 20 }; $processedContent .= "<h{$level} style='font-size: {$fontSize}px;'>{$contentPartChild['children'][0]['text']}</h{$level}>"; } if ($contentPartChild['type'] === 'unorderedList') { $processedContent .= "<ul>"; foreach ($contentPartChild['children'] as $listItem) { $processedContent .= "<li>{$listItem['children'][0]['text']}</li>"; } $processedContent .= "</ul>"; } if ($contentPartChild['type'] === 'orderedList') { $processedContent .= "<ol>"; foreach ($contentPartChild['children'] as $listItem) { $processedContent .= "<li>{$listItem['children'][0]['text']}</li>"; } $processedContent .= "</ol>"; } } } return $processedContent; } private function getImageUrl(string $sourceUrl): string { $image = preg_replace('#^https://#', '', $sourceUrl); return self::RESPEKT_IMAGE_URL . $image . '?width=500&fit=crop'; } private function getAbsoluteUrl(string $sourceUrl): string { if (str_starts_with($sourceUrl, 'https://')) { return $sourceUrl; } return self::RESPEKT_PAGE_URL . $sourceUrl; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/NovydenikNewsfilterTemplateFormFactory.php
Mailer/app/Forms/NovydenikNewsfilterTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class NovydenikNewsfilterTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private $activeUsersSegment; private $inactiveUsersSegment; private $templatesRepository; private $layoutsRepository; private $jobsRepository; private $batchesRepository; private $listsRepository; private $permissionManager; private $user; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, JobsRepository $jobsRepository, BatchesRepository $batchesRepository, PermissionManager $permissionManager, User $user ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->permissionManager = $permissionManager; $this->user = $user; } public function create(): Form { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->where(['public_listing' => true])->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); if (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 27) { $defaults = [ 'name' => 'Děcka, práce ' . date('j.n.Y'), 'code' => 'nwsf_detska_prace_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 21, // live! 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 26) { $defaults = [ 'name' => 'live! ' . date('j.n.Y'), 'code' => 'nwsf_live_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 20, // live! 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 25) { $defaults = [ 'name' => 'Česká inteligence 20. století ' . date('j.n.Y'), 'code' => 'nwsf_ceska_inteligence_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 19, // Česká inteligence 20. století 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 24) { $defaults = [ 'name' => 'Přepište dějiny ' . date('j.n.Y'), 'code' => 'nwsf_prepiste_dejiny_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 18, // Přepište dějiny 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 23) { $defaults = [ 'name' => 'Čínská depeše ' . date('j.n.Y'), 'code' => 'nwsf_cinska_depese_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 17, // Čínská depeše 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 21) { $defaults = [ 'name' => 'Brněnský orloj ' . date('j.n.Y'), 'code' => 'nwsf_brnensky_orloj_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 15, // Brnensky orloj 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 17) { $defaults = [ 'name' => 'PolitikoN ' . date('j.n.Y'), 'code' => 'nwsf_politikon_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 14, // Politikon 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 16) { $defaults = [ 'name' => 'Americký týdeník ' . date('j.n.Y'), 'code' => 'nwsf_amer_tydenik_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 13, // Americký týdeník 'from' => 'Jana Ciglerová Deník N <jana.ciglerova@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 15) { $defaults = [ 'name' => 'Částečný součet ' . date('j.n.Y'), 'code' => 'nwsf_cs_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 12, // Částečný součet Petra Koubského, 'from' => 'Petr Koubský <petr.koubsky@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 14) { $defaults = [ 'name' => 'Newsfilter Německo ' . date('j.n.Y'), 'code' => 'nwsf_de_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 11, // nemecko, 'from' => 'Deník N <info@denikn.cz>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 28) { $defaults = [ 'name' => 'Vývoj bojů ' . date('j.n.Y'), 'code' => 'vyvoj_boju_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 22, // Vývoj bojů, 'from' => 'Deník N <info@denikn.cz>', ]; } else { $defaults = [ 'name' => 'Newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_' . date('dmY'), 'mail_layout_id' => 2, // empty layout 'locked_mail_layout_id' => 2, // empty layout 'mail_type_id' => 6, // newsfilter, 'from' => 'Deník N <info@denikn.cz>', ]; } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/NewsfilterTemplateFormFactory.php
Mailer/app/Forms/NewsfilterTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\LinkGenerator; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Http\Request; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class NewsfilterTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private $activeUsersSegment; private $inactiveUsersSegment; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, private TemplatesRepository $templatesRepository, private LayoutsRepository $layoutsRepository, private ListsRepository $listsRepository, private ListVariantsRepository $listVariantsRepository, private SourceTemplatesRepository $sourceTemplatesRepository, private JobsRepository $jobsRepository, private BatchesRepository $batchesRepository, private PermissionManager $permissionManager, private User $user, private LinkGenerator $linkGenerator, private Request $request, ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; } public function create(): Form { $defaults = array_filter($this->getDefaults((int) $this->request->getPost('source_template_id'))); $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_code', 'Template', $this->layoutsRepository->all()->fetchPairs('code', 'name')); $form->addSelect('locked_mail_layout_code', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('code', 'name')); $mailTypes = $this->listsRepository->all()->where(['public_listing' => true])->fetchPairs('code', 'title'); $mailTypeField = $form->addSelect('mail_type_code', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $variantsList = $selectedMailType = null; if ($this->request->getPost('mail_type_code')) { $selectedMailType = $this->listsRepository->findByCode($this->request->getPost('mail_type_code'))->fetch(); } elseif (isset($defaults['mail_type_code'])) { $selectedMailType = $this->listsRepository->findByCode($defaults['mail_type_code'])->fetch(); } if ($selectedMailType) { $variantsList = $this->listVariantsRepository->getVariantsForType($selectedMailType)->fetchPairs('code', 'title'); } $form->addSelect('mail_type_variant_code', 'Type variant', $variantsList) ->setPrompt('Select variant') ->setDisabled(!$variantsList || count($variantsList) === 0) ->setHtmlAttribute('data-depends', $mailTypeField->getHtmlName()) // %value% will be replaced by selected ID from 'data-depends' input ->setHtmlAttribute('data-url', $this->linkGenerator->link('Mailer:Job:MailTypeCodeVariants', ['id'=>'%value%'])); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } private function getDefaults(?int $sourceTemplateId): array { $defaults = [ 'name' => 'Newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_' . date('dmY'), 'mail_layout_code' => '33_empty-layout', // layout for subscribers 'locked_mail_layout_code' => '33_empty-layout', // layout for non-subscribers 'mail_type_code' => 'newsfilter', 'mail_type_variant_code' => null, 'from' => 'Denník N <info@dennikn.sk>', ]; if (!$sourceTemplateId) { return $defaults; } $sourceTemplate = $this->sourceTemplatesRepository->find($sourceTemplateId); if (!$sourceTemplate) { return $defaults; } $override = match ($sourceTemplate->code) { 'rano-nhl' => [ 'name' => 'Ráno s NHL ' . date('j.n.Y'), 'code' => 'nwsf_rano-nhl_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.rano-nhl' ], 'pod-slankom' => [ 'name' => 'Pod slnkom Jany Shemesh ' . date('Y. n. j.'), 'code' => 'pod_slnkom_' . date('dmY'), 'mail_type_code' => 'pod-slnkom', ], 'napunk-newsfilter' => [ 'name' => 'Napunk newsfilter ' . date('Y. n. j.'), 'code' => 'napunk_nwsf_' . date('dmY'), 'mail_type_code' => 'napunk-newsfilter', 'from' => 'Napunk <napunk@napunk.sk>', ], 'vyvoj-bojov' => [ 'name' => 'Vývoj bojov ' . date('j.n.Y'), 'code' => 'nwsf_vyvoj_bojov_' . date('dmY'), 'mail_type_code' => 'vyvoj-bojov', ], 'boxova-ulicka' => [ 'name' => 'Boxová ulička ' . date('j.n.Y'), 'code' => 'nwsf_boxova_ulicka_' . date('dmY'), 'mail_type_code' => 'boxova-ulicka', ], 'tyzden-v-zdravi' => [ 'name' => 'Týždeň v zdraví ' . date('j.n.Y'), 'code' => 'nwsf_tyzdenvzdravi_' . date('dmY'), 'mail_type_code' => 'tyzden-v-zdravi', ], 'tyzden-v-prave' => [ 'name' => 'Týždeň v práve Rada Procházku ' . date('j.n.Y'), 'code' => 'nwsf_pravoprochazka_' . date('dmY'), 'mail_type_code' => 'tyzden-v-prave', ], 'greenfilter' => [ 'name' => 'Greenfilter ' . date('j.n.Y'), 'code' => 'nwsf_greenfilter_' . date('dmY'), 'mail_type_code' => 'greenfilter', ], 'vlhova-newsletter' => [ 'name' => 'Vlhová newsletter ' . date('j.n.Y'), 'code' => 'nwsf_vlhova_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.vlhova-newsletter' ], 'skolsky-newsfilter' => [ 'name' => 'Školský newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_skolsky_' . date('dmY'), 'mail_type_code' => 'skolsky-newsfilter', ], 'suhrn-letna-olympiada' => [ 'name' => 'Súhrn dňa letnej olympiády ' . date('j.n.Y'), 'code' => 'nwsf_let_olympiada_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.suhrn-letna-olympiada' ], 'suhrn-futbalove-euro' => [ 'name' => 'Súhrn dňa futbalového Eura ' . date('j.n.Y'), 'code' => 'nwsf_fut_euro_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.suhrn-futbalove-euro' ], 'ako-cita-ivan-miklo' => [ 'name' => 'Ako to číta Ivan Mikloš ' . date('j.n.Y'), 'code' => 'nwsf_miklos_' . date('dmY'), 'mail_type_code' => 'ako-cita-ivan-miklo', ], 'cesky-tyzden' => [ 'name' => 'Český týždeň ' . date('j.n.Y'), 'code' => 'nwsf_cz_tyzden_' . date('dmY'), 'mail_type_code' => 'cesky-tyzden', ], 'suhrn-ms-hokej' => [ 'name' => 'Súhrn MS v hokeji ' . date('j.n.Y'), 'code' => 'nwsf_ms_hokej_2021_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.suhrn-ms-hokej' ], 'porazeni' => [ 'name' => 'Porazení ' . date('j.n.Y'), 'code' => 'nwsf_porazeni_' . date('dmY'), 'mail_type_code' => 'porazeni', ], 'kosicky-newsfilter' => [ 'name' => 'Košický newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_kosice_' . date('dmY'), 'mail_type_code' => 'kosicky-newsfilter', ], 'tyzden-v-behu' => [ 'name' => 'Týždeň v behu ' . date('j.n.Y'), 'code' => 'nwsf_beh_' . date('dmY'), 'mail_type_code' => 'tyzden-v-behu', ], 'grandslamove-turnaje' => [ 'name' => 'Grandslamové turnaje ' . date('j.n.Y'), 'code' => 'nwsf_grandslam_' . date('dmY'), 'mail_type_code' => 'grandslamove-turnaje', ], 'euroligy' => [ 'name' => 'Euroligy ' . date('j.n.Y'), 'code' => 'nwsf_euroligy_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.euroligy' ], 'tour-de-france' => [ 'name' => 'Súhrn Tour de France ' . date('j.n.Y'), 'code' => 'nwsf_tourdefrance_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.suhrn-tour-defrance' ], 'suhrn-ligy-majstrov' => [ 'name' => 'Súhrn Ligy majstrov ' . date('j.n.Y'), 'code' => 'nwsf_ligamajstrov_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'mail_type_variant_code' => 'newsfilter_sport.liga-majstrov' ], 'tyzden-v-nhl' => [ 'name' => 'Týždeň v NHL ' . date('j.n.Y'), 'code' => 'nwsf_nhl_' . date('dmY'), 'mail_type_code' => 'tyzden-nhl', ], 'ofsajd' => [ 'name' => 'Ofsajd ' . date('j.n.Y'), 'code' => 'nwsf_ofsajd_' . date('dmY'), 'mail_type_code' => 'ofsajd', 'from' => 'Lukáš Vráblik Denník N <lukas.vrablik@dennikn.sk>', ], 'svetovy-newsfilter-v2' => [ 'name' => 'Svetový newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_world_' . date('dmY'), 'mail_type_code' => 'svetovy_newsfilter', 'from' => 'Rastislav Kačmár Denník N <rastislav.kacmar@dennikn.sk>', ], 'newsfilter-sport-v2' => [ 'name' => 'Športový newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_sport_' . date('dmY'), 'mail_type_code' => 'newsfilter_sport', 'from' => 'Michal Červený Denník N <michal.cerveny@dennikn.sk>', ], 'high-five-v2' => [ 'name' => 'High Five ' . date('j.n.Y'), 'code' => 'high_five_' . date('dmY'), 'mail_type_code' => 'high_five', 'from' => 'Kultúra Denník N <kultura@dennikn.sk>', ], 'newsfilter-v3' => [ 'name' => 'Newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_' . date('dmY'), 'mail_type_code' => 'newsfilter', 'from' => 'Denník N <info@dennikn.sk>', ], 'psychologicka-poradna' => [ 'name' => 'Psychologická poradňa ' . date('j.n.Y'), 'code' => 'psypod_' . date('dmY'), 'mail_type_code' => 'psychologicka-poradna', 'from' => 'Poradňa Denníka N <poradna@dennikn.sk>', ], 'pat-knih' => [ 'name' => 'Päť kníh ' . date('j.n.Y'), 'code' => 'patknih_' . date('dmY'), 'mail_type_code' => 'pat-knih', 'from' => 'Denník N <info@dennikn.sk>', ], 'do-hlbky' => [ 'name' => 'Do hĺbky s Jánom Markošom ' . date('j.n.Y'), 'code' => 'dohlbky_' . date('dmY'), 'mail_type_code' => 'do-hlbky', 'from' => 'Denník N <info@dennikn.sk>', ], 'trumpov-svet' => [ 'name' => 'Trumpov svet ' . date('j.n.Y'), 'code' => 'trumpov_svet_' . date('dmY'), 'mail_type_code' => 'trumpov-svet', 'from' => 'Denník N <info@dennikn.sk>', ], 'poradna-o-tele' => [ 'name' => 'Poradňa o tele ' . date('j.n.Y'), 'code' => 'poradna_o_tele_' . date('dmY'), 'mail_type_code' => 'poradna-o-tele', 'from' => 'Denník N <info@dennikn.sk>', ], 'vikend-bez-politiky' => [ 'name' => 'Víkend bez politiky ' . date('j.n.Y'), 'code' => 'vikend_bez_politiky_' . date('dmY'), 'mail_type_code' => 'bez-politiky', 'from' => 'Denník N <info@dennikn.sk>', ], 'predvolebne-madarsko' => [ 'name' => 'Predvolebné Maďarsko ' . date('j.n.Y'), 'code' => 'predvolebne_madarsko_' . date('dmY'), 'mail_type_code' => 'predvolebne-madarsko', 'from' => 'Denník N <posta@dennikn.sk>', ], 'valaszt-a-magyar' => [ 'name' => 'Választ a magyar ' . date('Y. n. j.'), 'code' => 'valaszt_a_magyar_' . date('dmY'), 'mail_type_code' => 'valaszt-a-magyar', 'from' => 'Napunk <napunk@dennikn.sk>', ], default => throw new \Exception("No default values found for source template code='{$sourceTemplate->code}'"), }; return array_merge($defaults, $override); } public function formSucceeded(Form $form, $values): void { $startSending = true; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $startSending = false; } $this->createJob( values: $values, htmlBody: $values['locked_html_content'], textBody: $values['locked_text_content'], mailLayoutCode: $values['locked_mail_layout_code'], segmentCode: $this->inactiveUsersSegment, startSending: $startSending, ); $this->createJob( values: $values, htmlBody: $values['html_content'], textBody: $values['text_content'], mailLayoutCode: $values['mail_layout_code'], segmentCode: $this->activeUsersSegment, startSending: $startSending, ); $this->onSave->__invoke(); } private function createJob(iterable $values, $htmlBody, $textBody, $mailLayoutCode, $segmentCode, bool $startSending): void { $mailLayout = $this->layoutsRepository->findBy('code', $mailLayoutCode); if (!$mailLayout) { throw new \Exception("Unable to find mail_layout with code '{$mailLayoutCode}'"); } $mailType = $this->listsRepository->findByCode($values['mail_type_code'])->fetch(); if (!$mailType) { throw new \Exception("Unable to find mail_type with code '{$values['mail_type_code']}'"); } $mailTemplate = $this->templatesRepository->add( name: $values['name'], code: $this->templatesRepository->getUniqueTemplateCode($values['code']), description: '', from: $values['from'], subject: $values['subject'], templateText: $textBody, templateHtml: $htmlBody, layoutId: $mailLayout->id, typeId: $mailType->id, ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailTypeVariant = null; if (isset($values['mail_type_variant_code'])) { $mailTypeVariant = $this->listVariantsRepository->findByCode($values['mail_type_variant_code']); } $mailJob = $this->jobsRepository->add( (new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext, $mailTypeVariant, ); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = $startSending ? BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND : BatchesRepository::STATUS_CREATED; $this->batchesRepository->updateStatus($batch, $batchStatus); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/GrafdnaTemplateFormFactory.php
Mailer/app/Forms/GrafdnaTemplateFormFactory.php
<?php namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class GrafdnaTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; public $onUpdate; public $onSave; public function __construct( private $activeUsersSegment, private $inactiveUsersSegment, private TemplatesRepository $templatesRepository, private LayoutsRepository $layoutsRepository, private ListsRepository $listsRepository, private JobsRepository $jobsRepository, private BatchesRepository $batchesRepository, private PermissionManager $permissionManager, private User $user ) { } public function create() { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->where(['public_listing' => true])->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); $defaults = [ 'name' => 'Graf dňa ' . date('j.n.Y'), 'code' => 'graf_dna_' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 60, // Graf dna 'from' => 'Denník E <e@dennikn.sk>', ]; $mailType = $this->listsRepository->find($defaults['mail_type_id']); if (!$mailType) { unset($defaults['mail_type_id']); } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/DailyMinuteTemplateFormFactory.php
Mailer/app/Forms/DailyMinuteTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class DailyMinuteTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; public $onUpdate; public $onSave; private string $layoutCode; private string $typeCode; private string $from; public function __construct( private string $segment, private TemplatesRepository $templatesRepository, private LayoutsRepository $layoutsRepository, private ListsRepository $listsRepository, private JobsRepository $jobsRepository, private BatchesRepository $batchesRepository, private PermissionManager $permissionManager, private User $user ) { } public function setLayoutCode(string $layoutCode): void { $this->layoutCode = $layoutCode; } public function setTypeCode(string $typeCode): void { $this->typeCode = $typeCode; } public function setFrom(string $from): void { $this->from = $from; } public function overrideSegment(string $segment): void { $this->segment = $segment; } public function create() { $mailLayout = $this->layoutsRepository->findBy('code', $this->layoutCode); if (!$mailLayout) { throw new \Exception("No mail layout found with code: '{$this->layoutCode}'"); } $mailType = $this->listsRepository->findByCode($this->typeCode)->fetch(); if (!$mailType) { throw new \Exception("No mail type found with code: '{$this->typeCode}'"); } $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->where(['public_listing' => true])->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->setDefaults([ 'name' => 'Daily minute ' . date('j.n.Y'), 'code' => 'daily_minute_' . date('dmY'), 'mail_layout_id' => $mailLayout->id, 'mail_type_id' => $mailType->id, 'from' => $this->from, ]); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); // Temporary disable contenxt for CZ testing purposes // $jobContext = 'daily_minute.' . date('Ymd'); $jobContext = null; $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->segment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/MMSTemplateFormFactory.php
Mailer/app/Forms/MMSTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class MMSTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private $activeUsersSegment; private $inactiveUsersSegment; private $templatesRepository; private $layoutsRepository; private $jobsRepository; private $batchesRepository; private $listsRepository; private $permissionManager; private $user; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, JobsRepository $jobsRepository, BatchesRepository $batchesRepository, PermissionManager $permissionManager, User $user ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->permissionManager = $permissionManager; $this->user = $user; } public function create(): Form { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required.") ->setDefaultValue("Odkaz MMŠ: O poznaní ľudskej povahy, ktoré sa dá získať iba v takých extrémnych podmienkach, aké panovali v sovietskom gulagu"); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); $defaults = [ 'name' => 'Odkaz MMS ' . date('j.n.Y'), 'code' => 'mms_' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 17, // Follow tem, 'from' => 'Denník N <info@dennikn.sk>', ]; $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/DennikeTemplateFormFactory.php
Mailer/app/Forms/DennikeTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class DennikeTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private $activeUsersSegment; private $inactiveUsersSegment; private $templatesRepository; private $layoutsRepository; private $jobsRepository; private $batchesRepository; private $listsRepository; private $permissionManager; private $user; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, JobsRepository $jobsRepository, BatchesRepository $batchesRepository, PermissionManager $permissionManager, User $user ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->permissionManager = $permissionManager; $this->user = $user; } public function create() { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); if (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 84) { $defaults = [ 'name' => 'Týždeň v európskej ekonomike ' . date('j.n.Y'), 'code' => 'nwsf_eu_economy' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 65, // Týždeň v európskej ekonomike 'from' => 'Denník E <e@dennikn.sk>', ]; } elseif (isset($_POST['source_template_id']) && $_POST['source_template_id'] == 63) { $defaults = [ 'name' => 'Firemný newsfilter ' . date('j.n.Y'), 'code' => 'nwsf_firemny' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 45, // firemny newsfilter 'from' => 'Denník E <e@dennikn.sk>', ]; } else { $defaults = [ 'name' => 'Denník E ' . date('j.n.Y'), 'code' => 'dennike_' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 23, // dennike 'from' => 'Denník E <e@dennikn.sk>', ]; } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/ArticleUrlParserTemplateFormFactory.php
Mailer/app/Forms/ArticleUrlParserTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Models\Segment\Mailer; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class ArticleUrlParserTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private string $segmentCode; private string $segmentProvider = Mailer::PROVIDER_ALIAS; private string $layoutCode; public $onUpdate; public $onSave; public function __construct( private readonly TemplatesRepository $templatesRepository, private readonly LayoutsRepository $layoutsRepository, private readonly ListsRepository $listsRepository, private readonly JobsRepository $jobsRepository, private readonly BatchesRepository $batchesRepository, private readonly SourceTemplatesRepository $sourceTemplatesRepository, private readonly PermissionManager $permissionManager, private readonly User $user ) { } public function setSegmentCode(string $segmentCode, string $segmentProvider = Mailer::PROVIDER_ALIAS): void { $this->segmentCode = $segmentCode; $this->segmentProvider = $segmentProvider; } public function setLayoutCode(string $layoutCode): void { $this->layoutCode = $layoutCode; } public function create() { $form = new Form; $form->addProtection(); if (!$this->layoutCode) { $form->addError("Default value 'layout code' is missing."); } $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $mailTypes = $this->listsRepository->all() ->where(['public_listing' => true]) ->fetchPairs('id', 'title'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setPrompt('Select type') ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addText('subject_b', 'Subject (B version)') ->setNullable(); $form->addText('email_count', 'Batch size') ->setNullable(); $form->addText('start_at', 'Start date') ->setNullable(); $form->addHidden('mail_layout_id'); $form->addHidden('source_template_id'); $form->addHidden('html_content'); $form->addHidden('text_content'); $sourceTemplate = $this->sourceTemplatesRepository->find($_POST['source_template_id']); $defaults = [ 'source_template_id' => $sourceTemplate->id, 'name' => "{$sourceTemplate->title} " . date('d. m. Y'), 'code' => "{$sourceTemplate->code}_" . date('Y-m-d'), ]; if ($this->layoutCode) { $defaults['mail_layout_id'] = (int)$this->layoutsRepository->findBy('code', $this->layoutCode)->id; } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, (int)$mailLayoutId, $values['mail_type_id'] ); if (isset($this->segmentCode)) { $segmentCode = $this->segmentCode; $segmentProvider = $this->segmentProvider; } else { $segmentCode = Mailer::mailTypeSegment($mailTemplate->mail_type->code); $segmentProvider = Mailer::PROVIDER_ALIAS; } $jobContext = null; $jobSegmentsManager = (new JobSegmentsManager())->includeSegment($segmentCode, $segmentProvider); $mailJob = $this->jobsRepository->add($jobSegmentsManager, $jobContext); $batch = $this->batchesRepository->add( $mailJob->id, (int)$values['email_count'], $values['start_at'], BatchesRepository::METHOD_RANDOM ); $this->batchesRepository->addTemplate($batch, $mailTemplate); if (isset($values['subject_b'])) { $mailTemplateB = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject_b'], $textBody, $htmlBody, (int)$mailLayoutId, $values['mail_type_id'] ); $this->batchesRepository->addTemplate($batch, $mailTemplateB); } $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/RespektUrlParserTemplateFormFactory.php
Mailer/app/Forms/RespektUrlParserTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Mailer; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\MailTypesRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class RespektUrlParserTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private string $layoutCode; private string $segmentCode; private string $segmentProvider = Mailer::PROVIDER_ALIAS; private string $defaultMailTypeCode; public $onUpdate; public $onSave; public function __construct( private readonly TemplatesRepository $templatesRepository, private readonly LayoutsRepository $layoutsRepository, private readonly ListsRepository $listsRepository, private readonly JobsRepository $jobsRepository, private readonly BatchesRepository $batchesRepository, private readonly SourceTemplatesRepository $sourceTemplatesRepository, private readonly PermissionManager $permissionManager, private readonly MailTypesRepository $mailTypesRepository, private readonly User $user ) { } public function setLayoutCode(string $layoutCode): void { $this->layoutCode = $layoutCode; } public function setSegmentCode(string $segmentCode, string $segmentProvider = Mailer::PROVIDER_ALIAS): void { $this->segmentCode = $segmentCode; $this->segmentProvider = $segmentProvider; } public function setDefaultMailTypeCode(string $defaultMailTypeCode): void { $this->defaultMailTypeCode = $defaultMailTypeCode; } public function create() { $form = new Form; $form->addProtection(); if (!$this->layoutCode) { $form->addError("Default value 'layout code' is missing."); } $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $mailTypes = $this->listsRepository->all() ->where(['public_listing' => true]) ->fetchPairs('id', 'title'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setPrompt('Select type') ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addText('subject_b', 'Subject (B version)') ->setNullable(); $form->addText('email_count', 'Batch size') ->setNullable(); $form->addText('start_at', 'Start date') ->setNullable(); $form->addHidden('mail_layout_id'); $form->addHidden('source_template_id'); $form->addHidden('html_content'); $form->addHidden('text_content'); $sourceTemplate = $this->sourceTemplatesRepository->find($_POST['source_template_id']); $mailType = $this->mailTypesRepository->findBy('code', $this->defaultMailTypeCode); $defaults = [ 'source_template_id' => $sourceTemplate->id, 'name' => "{$sourceTemplate->title} " . date('d. m. Y'), 'code' => "{$sourceTemplate->code}_" . date('Y-m-d'), 'mail_type_id' => $mailType->id, 'from' => $mailType->mail_from, ]; if ($this->layoutCode) { $defaults['mail_layout_id'] = (int)$this->layoutsRepository->findBy('code', $this->layoutCode)->id; } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, (int) $mailLayoutId, $values['mail_type_id'] ); if (isset($this->segmentCode)) { $segmentCode = $this->segmentCode; $segmentProvider = $this->segmentProvider; } else { $segmentCode = Mailer::mailTypeSegment($mailTemplate->mail_type->code); $segmentProvider = Mailer::PROVIDER_ALIAS; } $jobContext = null; $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, $segmentProvider), $jobContext); $batch = $this->batchesRepository->add( $mailJob->id, (int)$values['email_count'], $values['start_at'], BatchesRepository::METHOD_RANDOM ); $this->batchesRepository->addTemplate($batch, $mailTemplate); if (isset($values['subject_b'])) { $mailTemplateB = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject_b'], $textBody, $htmlBody, (int)$mailLayoutId, $values['mail_type_id'] ); $this->batchesRepository->addTemplate($batch, $mailTemplateB); } $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/RespektArticleParserTemplateFormFactory.php
Mailer/app/Forms/RespektArticleParserTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Http\Request; use Nette\Security\User; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Models\Segment\Mailer; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\MailTypesRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class RespektArticleParserTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private string $layoutCode; private string $activeUsersSegmentCode; private string $inactiveUsersSegmentCode; private string $defaultMailTypeCode; public $onUpdate; public $onSave; public function __construct( private readonly TemplatesRepository $templatesRepository, private readonly LayoutsRepository $layoutsRepository, private readonly ListsRepository $listsRepository, private readonly JobsRepository $jobsRepository, private readonly BatchesRepository $batchesRepository, private readonly SourceTemplatesRepository $sourceTemplatesRepository, private readonly PermissionManager $permissionManager, private readonly MailTypesRepository $mailTypesRepository, private readonly User $user, private readonly Request $request, ) { } public function setLayoutCode(string $layoutCode): void { $this->layoutCode = $layoutCode; } public function setActiveUserSegmentCode(string $activeUsersSegmentCode): void { $this->activeUsersSegmentCode = $activeUsersSegmentCode; } public function setInactiveUserSegmentCode(string $inactiveUsersSegmentCode): void { $this->inactiveUsersSegmentCode = $inactiveUsersSegmentCode; } public function setDefaultMailTypeCode(string $defaultMailTypeCode): void { $this->defaultMailTypeCode = $defaultMailTypeCode; } public function create() { $form = new Form; $form->addProtection(); if (!$this->layoutCode) { $form->addError("Default value 'layout code' is missing."); } if (!$this->activeUsersSegmentCode) { $form->addError("Default value 'active users segment code' is missing."); } if (!$this->inactiveUsersSegmentCode) { $form->addError("Default value 'inactive users segment code' is missing."); } $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $mailTypes = $this->listsRepository->all() ->where(['public_listing' => true]) ->fetchPairs('id', 'title'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setPrompt('Select type') ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addText('start_at', 'Start date') ->setNullable(); $form->addHidden('mail_layout_id'); $form->addHidden('locked_mail_layout_id'); $form->addHidden('source_template_id'); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $sourceTemplate = $this->sourceTemplatesRepository->find($this->request->getPost('source_template_id')); $mailType = $this->mailTypesRepository->findBy('code', $this->defaultMailTypeCode); $defaults = [ 'source_template_id' => $sourceTemplate->id, 'name' => "{$sourceTemplate->title} " . date('d. m. Y'), 'code' => "{$sourceTemplate->code}_" . date('Y-m-d'), 'mail_type_id' => $mailType->id, 'from' => $mailType->mail_from, ]; if ($this->layoutCode) { $mailLayout = $this->layoutsRepository->findBy('code', $this->layoutCode); $defaults['mail_layout_id'] = (int)$mailLayout->id; $defaults['locked_mail_layout_id'] = (int)$mailLayout->id; } $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, $values) { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, (int) $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; $mailJob = $this->jobsRepository->add((new JobSegmentsManager()) ->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add( $mailJob->id, null, $values['start_at'], BatchesRepository::METHOD_RANDOM ); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegmentCode, ); $generate( $values['locked_html_content'], $values['locked_text_content'], $values['mail_layout_id'], $this->inactiveUsersSegmentCode, ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/TldrTemplateFormFactory.php
Mailer/app/Forms/TldrTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Security\User; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Models\Segment\Crm; class TldrTemplateFormFactory { private $activeUsersSegment; private $inactiveUsersSegment; private $templatesRepository; private $layoutsRepository; private $jobsRepository; private $batchesRepository; private $listsRepository; private $permissionManager; private $user; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, JobsRepository $jobsRepository, BatchesRepository $batchesRepository, PermissionManager $permissionManager, User $user ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->permissionManager = $permissionManager; $this->user = $user; } public function create(): Form { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); $defaults = [ 'name' => 'Tl;dr ' . date('j.n.Y'), 'code' => 'tldr_' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 19, // tldr 'from' => 'Denník N <info@dennikn.sk>', ]; $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit('generate_emails_jobs'); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit('generate_emails_jobs_created'); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; if ($form->getComponent('generate_emails_jobs_created')->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/app/Forms/MediaBriefingTemplateFormFactory.php
Mailer/app/Forms/MediaBriefingTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\Mailer\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class MediaBriefingTemplateFormFactory { private const FORM_ACTION_WITH_JOBS_CREATED = 'generate_emails_jobs_created'; private const FORM_ACTION_WITH_JOBS_STARTED = 'generate_emails_jobs'; private $activeUsersSegment; private $inactiveUsersSegment; private $templatesRepository; private $layoutsRepository; private $jobsRepository; private $batchesRepository; private $listsRepository; private $permissionManager; private $user; public $onUpdate; public $onSave; public function __construct( $activeUsersSegment, $inactiveUsersSegment, TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, JobsRepository $jobsRepository, BatchesRepository $batchesRepository, PermissionManager $permissionManager, User $user ) { $this->activeUsersSegment = $activeUsersSegment; $this->inactiveUsersSegment = $inactiveUsersSegment; $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->permissionManager = $permissionManager; $this->user = $user; } public function create(): Form { $form = new Form; $form->addProtection(); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'Identifier') ->setRequired("Field 'Identifier' is required."); $form->addSelect('mail_layout_id', 'Template', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $form->addSelect('locked_mail_layout_id', 'Template for non-subscribers', $this->layoutsRepository->all()->fetchPairs('id', 'name')); $mailTypes = $this->listsRepository->all()->fetchPairs('id', 'code'); $form->addSelect('mail_type_id', 'Type', $mailTypes) ->setRequired("Field 'Type' is required."); $form->addText('from', 'Sender') ->setHtmlAttribute('placeholder', 'e.g. info@domain.com') ->setRequired("Field 'Sender' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addHidden('html_content'); $form->addHidden('text_content'); $form->addHidden('locked_html_content'); $form->addHidden('locked_text_content'); $form->addHidden('article_id'); $defaults = [ 'name' => 'MediaBrifing ' . date('j.n.Y'), 'code' => 'mbrf_' . date('dmY'), 'mail_layout_id' => 33, // layout for subscribers 'locked_mail_layout_id' => 33, // layout for non-subscribers 'mail_type_id' => 16, // mediabrifing 'from' => 'Denník N <info@dennikn.sk>', ]; $form->setDefaults($defaults); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $withJobs = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_STARTED); $withJobs->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch and start sending'); } $withJobsCreated = $form->addSubmit(self::FORM_ACTION_WITH_JOBS_CREATED); $withJobsCreated->getControlPrototype() ->setName('button') ->setHtml('Generate newsletter batch'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $generate = function ($htmlBody, $textBody, $mailLayoutId, $segmentCode = null) use ($values, $form) { $mailTemplate = $this->templatesRepository->add( $values['name'], $this->templatesRepository->getUniqueTemplateCode($values['code']), '', $values['from'], $values['subject'], $textBody, $htmlBody, $mailLayoutId, $values['mail_type_id'] ); $jobContext = null; if ($values['article_id']) { $jobContext = 'newsletter.' . $values['article_id']; } $mailJob = $this->jobsRepository->add((new JobSegmentsManager())->includeSegment($segmentCode, Crm::PROVIDER_ALIAS), $jobContext); $batch = $this->batchesRepository->add($mailJob->id, null, null, BatchesRepository::METHOD_RANDOM); $this->batchesRepository->addTemplate($batch, $mailTemplate); $batchStatus = BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND; /** @var SubmitButton $withJobsCreatedSubmit */ $withJobsCreatedSubmit = $form[self::FORM_ACTION_WITH_JOBS_CREATED]; if ($withJobsCreatedSubmit->isSubmittedBy()) { $batchStatus = BatchesRepository::STATUS_CREATED; } $this->batchesRepository->updateStatus($batch, $batchStatus); }; $generate( $values['locked_html_content'], $values['locked_text_content'], $values['locked_mail_layout_id'], $this->inactiveUsersSegment ); $generate( $values['html_content'], $values['text_content'], $values['mail_layout_id'], $this->activeUsersSegment ); $this->onSave->__invoke(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Latte/MailerModuleExtension.php
Mailer/extensions/mailer-module/src/Latte/MailerModuleExtension.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Latte; use Latte\Extension; use Remp\MailerModule\Models\Auth\PermissionManager; class MailerModuleExtension extends Extension { public function __construct(private PermissionManager $permissionManager) { } public function getTags(): array { return [ 'ifAllowed' => [IfAllowedNode::class, 'create'], ]; } public function getProviders(): array { return [ 'permissionManager' => $this->permissionManager, ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Latte/IfAllowedNode.php
Mailer/extensions/mailer-module/src/Latte/IfAllowedNode.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Latte; use Latte\Compiler\Nodes\AreaNode; use Latte\Compiler\Nodes\Php\Expression\ArrayNode; use Latte\Compiler\Nodes\StatementNode; use Latte\Compiler\PrintContext; use Latte\Compiler\Tag; class IfAllowedNode extends StatementNode { public AreaNode $content; public ArrayNode $args; public static function create(Tag $tag): \Generator { $tag->expectArguments(); $node = new self; $node->args = $tag->parser->parseArguments(); [$node->content, $endTag] = yield; return $node; } public function print(PrintContext $context): string { return $context->format( 'if ($this->global->permissionManager->isAllowed(%node, %node, %node)) { %node }', $this->args->items[0]->value, $this->args->items[1]->value, $this->args->items[2]->value, $this->content, ); } public function &getIterator(): \Generator { yield $this->args; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/BaseControl.php
Mailer/extensions/mailer-module/src/Components/BaseControl.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components; use Nette\Application\UI\Control; abstract class BaseControl extends Control { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/ApplicationStatus/IApplicationStatusFactory.php
Mailer/extensions/mailer-module/src/Components/ApplicationStatus/IApplicationStatusFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\ApplicationStatus; interface IApplicationStatusFactory { /** @return ApplicationStatus */ public function create(): ApplicationStatus; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/ApplicationStatus/ApplicationStatus.php
Mailer/extensions/mailer-module/src/Components/ApplicationStatus/ApplicationStatus.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\ApplicationStatus; use Nette\Application\UI\Control; use Remp\MailerModule\Commands\HermesWorkerCommand; use Remp\MailerModule\Commands\MailWorkerCommand; use Remp\MailerModule\Commands\ProcessJobCommand; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\HealthChecker; use Remp\MailerModule\Models\Sender\MailerFactory; use Remp\MailerModule\Repositories\ListsRepository; class ApplicationStatus extends Control { private HealthChecker $healthChecker; private Config $config; private ListsRepository $listsRepository; private MailerFactory $mailerFactory; public function __construct( Config $config, HealthChecker $healthChecker, MailerFactory $mailerFactory, ListsRepository $listsRepository ) { $this->healthChecker = $healthChecker; $this->config = $config; $this->listsRepository = $listsRepository; $this->mailerFactory = $mailerFactory; } public function render(): void { // Missing configuration $this->template->unconfiguredMailer = $this->getUnconfiguredMailer(); $this->template->settingsLink = $this->getPresenter()->link('Settings:default'); // Application status $apps = [ ProcessJobCommand::COMMAND_NAME, HermesWorkerCommand::COMMAND_NAME, MailWorkerCommand::COMMAND_NAME, ]; $onlineStatuses = []; $online = true; foreach ($apps as $app) { $onlineStatuses[$app] = $this->healthChecker->isHealthy($app); $online = $online && $onlineStatuses[$app]; } $this->template->onlineStatuses = $onlineStatuses; $this->template->online = $online; $this->template->setFile(__DIR__ . '/application_status.latte'); $this->template->render(); } private function getUnconfiguredMailer(): ?string { $defaultMailerSetting = $this->config->get('default_mailer'); if ($defaultMailerSetting !== null) { $activeMailer = $this->mailerFactory->getMailer($defaultMailerSetting); if (!$activeMailer->isConfigured()) { return $activeMailer->getIdentifier(); } } $usedMailersAliases = $this->listsRepository->getUsedMailersAliases(); foreach ($usedMailersAliases as $mailerAlias) { $mailer = $this->mailerFactory->getMailer($mailerAlias); if (!$mailer->isConfigured()) { return $mailer->getIdentifier(); } } return null; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/GeneratorWidgetsManager.php
Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/GeneratorWidgetsManager.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\GeneratorWidgets; class GeneratorWidgetsManager { private $widgets = []; public function registerWidget($generator, $widget) { $this->widgets[$generator][] = $widget; } public function getWidgets($generator) { return $this->widgets[$generator]; } public function getAllWidgets(): array { return $this->widgets; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/IGeneratorWidgetsFactory.php
Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/IGeneratorWidgetsFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\GeneratorWidgets; interface IGeneratorWidgetsFactory { /** * @param int $sourceTemplateId * * @return GeneratorWidgets */ public function create(int $sourceTemplateId): GeneratorWidgets; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/GeneratorWidgets.php
Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/GeneratorWidgets.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\GeneratorWidgets; use Nette\Application\IPresenter; use Remp\MailerModule\Components\BaseControl; use Remp\MailerModule\Repositories\SourceTemplatesRepository; class GeneratorWidgets extends BaseControl { private $templateName = 'generator_widgets.latte'; private $sourceTemplateId; private $sourceTemplatesRepository; private $widgetsManager; public function __construct( int $sourceTemplateId, GeneratorWidgetsManager $widgetsManager, SourceTemplatesRepository $sourceTemplatesRepository ) { $this->sourceTemplateId = $sourceTemplateId; $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->widgetsManager = $widgetsManager; $this->monitor(IPresenter::class, function (IPresenter $presenter): void { $allWidgets = $this->widgetsManager->getAllWidgets(); foreach ($allWidgets as $generator => $widgets) { foreach ($widgets as $widget) { if (!$this->getComponent($widget->identifier(), false)) { $this->addComponent($widget, $widget->identifier()); } } } }); } public function render(array $params): void { $template = $this->sourceTemplatesRepository->find($this->sourceTemplateId); $widgets = $this->widgetsManager->getWidgets($template->generator); $this->template->widgets = $widgets; $this->template->params = $params; $this->template->setFile(__DIR__ . '/' . $this->templateName); $this->template->render(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/Widgets/IGeneratorWidget.php
Mailer/extensions/mailer-module/src/Components/GeneratorWidgets/Widgets/IGeneratorWidget.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\GeneratorWidgets\Widgets; interface IGeneratorWidget { public function identifier(): string; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/BatchExperimentEvaluation/IBatchExperimentEvaluationFactory.php
Mailer/extensions/mailer-module/src/Components/BatchExperimentEvaluation/IBatchExperimentEvaluationFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\BatchExperimentEvaluation; interface IBatchExperimentEvaluationFactory { /** @return BatchExperimentEvaluation */ public function create(): BatchExperimentEvaluation; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/BatchExperimentEvaluation/BatchExperimentEvaluation.php
Mailer/extensions/mailer-module/src/Components/BatchExperimentEvaluation/BatchExperimentEvaluation.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\BatchExperimentEvaluation; use Nette\Application\UI\Control; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MultiArmedBandit\Lever; use Remp\MultiArmedBandit\Machine; class BatchExperimentEvaluation extends Control { private $batchesRepository; public function __construct(BatchesRepository $batchesRepository) { $this->batchesRepository = $batchesRepository; } public function render($batchId): void { $batch = $this->batchesRepository->find($batchId); $jobBatchTemplates = $batch->related('mail_job_batch_templates'); $openProbabilities = $this->run($jobBatchTemplates, 'opened'); $clickProbabilities = $this->run($jobBatchTemplates, 'clicked'); $this->template->jobBatchTemplates = $jobBatchTemplates; $this->template->openProbabilities = $openProbabilities; $this->template->clickProbabilities = $clickProbabilities; $this->template->setFile(__DIR__ . '/batch_experiment_evaluation.latte'); $this->template->render(); } private function run($jobBatchTemplates, string $conversionField): array { $machine = new Machine(10000); $zeroStat = []; foreach ($jobBatchTemplates as $jobBatchTemplate) { if (!$jobBatchTemplate->$conversionField) { $zeroStat[$jobBatchTemplate->mail_template->code] = 0; continue; } $machine->addLever(new Lever($jobBatchTemplate->mail_template->code, $jobBatchTemplate->$conversionField, $jobBatchTemplate->sent)); } return $machine->run() + $zeroStat; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/SendingStats/ISendingStatsFactory.php
Mailer/extensions/mailer-module/src/Components/SendingStats/ISendingStatsFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\SendingStats; interface ISendingStatsFactory { public function create(): SendingStats; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/SendingStats/SendingStats.php
Mailer/extensions/mailer-module/src/Components/SendingStats/SendingStats.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\SendingStats; use Nette\Application\UI\Control; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; class SendingStats extends Control { private $logsRepository; private $templatesRepository; private $userSubscriptionsRepository; private $templateIds = []; private $jobBatchTemplates = []; private $showTotal = false; private $showConversions = false; public function __construct( LogsRepository $mailLogsRepository, TemplatesRepository $templatesRepository, UserSubscriptionsRepository $userSubscriptionsRepository ) { $this->logsRepository = $mailLogsRepository; $this->templatesRepository = $templatesRepository; $this->userSubscriptionsRepository = $userSubscriptionsRepository; } public function addTemplate(ActiveRow $mailTemplate): self { /** @var ActiveRow $jobBatchTemplate */ foreach ($mailTemplate->related('mail_job_batch_templates') as $jobBatchTemplate) { $this->jobBatchTemplates[] = $jobBatchTemplate; } $this->templateIds[] = $mailTemplate->id; return $this; } public function addBatch(ActiveRow $batch): self { /** @var ActiveRow $jobBatchTemplate */ foreach ($batch->related('mail_job_batch_templates') as $jobBatchTemplate) { $this->jobBatchTemplates[] = $jobBatchTemplate; $this->templateIds[] = $jobBatchTemplate->mail_template_id; } return $this; } public function addJobBatchTemplate(ActiveRow $jobBatchTemplate): void { $this->jobBatchTemplates[] = $jobBatchTemplate; $this->templateIds[] = $jobBatchTemplate->mail_template_id; } public function showTotal(): void { $this->showTotal = true; } public function showConversions(): void { $this->showConversions = true; } public function render(): void { $total = 0; $stats = [ 'delivered' => ['value' => 0, 'per' => 0], 'opened' => ['value' => 0, 'per' => 0], 'clicked' => ['value' => 0, 'per' => 0], 'converted' => ['value' => 0, 'per' => 0], 'dropped' => ['value' => 0, 'per' => 0], 'spam_complained' => ['value' => 0, 'per' => 0], 'unsubscribed' => ['value' => 0, 'per' => 0], ]; foreach ($this->jobBatchTemplates as $jobBatchTemplate) { $total += $jobBatchTemplate->sent; $stats['delivered']['value'] += $jobBatchTemplate->delivered; $stats['opened']['value'] += $jobBatchTemplate->opened; $stats['clicked']['value'] += $jobBatchTemplate->clicked; $stats['converted']['value'] += $jobBatchTemplate->converted; $stats['dropped']['value'] += $jobBatchTemplate->dropped; $stats['spam_complained']['value'] += $jobBatchTemplate->spam_complained; $stats['unsubscribed']['value'] += $jobBatchTemplate->mail_template->mail_type ->related('mail_user_subscriptions') ->where([ 'rtm_campaign' => $jobBatchTemplate->mail_template->code, 'rtm_content' => $jobBatchTemplate->mail_job_batch_id, 'subscribed' => false, ]) ->count('*'); } $nonBatchTemplateStat = $this->logsRepository->getNonBatchTemplateStats($this->templateIds); if ($nonBatchTemplateStat) { $total += $nonBatchTemplateStat->sent; $stats['delivered']['value'] += $nonBatchTemplateStat->delivered; $stats['opened']['value'] += $nonBatchTemplateStat->opened; $stats['clicked']['value'] += $nonBatchTemplateStat->clicked; $stats['converted']['value'] += $nonBatchTemplateStat->converted; $stats['dropped']['value'] += $nonBatchTemplateStat->dropped; $stats['spam_complained']['value'] += $nonBatchTemplateStat->spam_complained; $templateCodes = $this->templatesRepository->getTable() ->where(['id' => $this->templateIds]) ->fetchPairs('code', 'code'); $stats['unsubscribed']['value'] += $this->userSubscriptionsRepository->getTable() ->where([ 'rtm_campaign' => array_values($templateCodes), 'rtm_content' => null, 'subscribed' => false, ]) ->count('*'); } foreach ($stats as $key => $stat) { $stats[$key]['per'] = $total ? ($stat['value'] / $total * 100) : 0; } $this->template->delivered_stat = $stats['delivered']; $this->template->opened_stat = $stats['opened']; $this->template->clicked_stat = $stats['clicked']; $this->template->converted_stat = $stats['converted']; $this->template->dropped_stat = $stats['dropped']; $this->template->spam_stat = $stats['spam_complained']; $this->template->unsubscribed_stat = $stats['unsubscribed']; $this->template->total_stat = $total; if ($this->showConversions) { $this->template->conversions = ['value' => 0, 'per' => 0]; } $this->template->setFile(__DIR__ . '/sending_stats.latte'); $this->template->render(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/DataTable/DataTableFactory.php
Mailer/extensions/mailer-module/src/Components/DataTable/DataTableFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\DataTable; class DataTableFactory { public function create(): DataTable { return new DataTable(); } public function getOrderFromRequest(array $params): array { if (!isset($params['order'])) { return [null, null]; } return [ $params['columns'][$params['order'][0]['column']]['name'], $params['order'][0]['dir'], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/DataTable/DataTable.php
Mailer/extensions/mailer-module/src/Components/DataTable/DataTable.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\DataTable; use Nette\Application\UI\Control; use Nette\Utils\Json; class DataTable extends Control { private $sourceUrl; private $colSettings = []; private $tableSettings = []; private $rowActions = []; public function setSourceUrl(string $sourceUrl): self { $this->sourceUrl = $sourceUrl; return $this; } public function getSourceUrl(): string { if ($this->sourceUrl === null) { $presenter = $this->getPresenter(); return $presenter->link($presenter->getAction() . 'JsonData'); } return $this->sourceUrl; } public function setColSetting(string $colName, array $colSetting): self { if (!array_key_exists('priority', $colSetting)) { throw new DataTableException('Missing "priority" item in DataTable configuration array for column: "' . $colName . '"'); } $this->colSettings[$colName] = $colSetting; return $this; } public function setAllColSetting(string $colSettingName, bool $colSettingValue = true): self { foreach ($this->colSettings as $colName => $colSetting) { $this->colSettings[$colName][$colSettingName] = $colSettingValue; } return $this; } public function setTableSetting(string $tableSettingName, $tableSetting = null): self { $this->tableSettings[$tableSettingName] = $tableSetting; return $this; } public function setRowAction(string $actionName, string $actionClass, string $actionTitle, array $htmlAttributes = []): self { $action = [ 'name' => $actionName, 'class' => $actionClass, 'title' => $actionTitle ]; $action = array_merge($action, $htmlAttributes); $this->rowActions[] = $action; return $this; } public function render(): void { $this->template->sourceUrl = $this->getSourceUrl(); $this->template->colSettings = $this->colSettings; $this->template->tableSettings = $this->tableSettings; $this->template->rowActions = $this->rowActions; foreach ($this->template->colSettings as $colName => $colSetting) { $this->template->colSettings[$colName] = array_merge([ 'colIndex' => array_search( $colName, array_keys($this->template->colSettings) ) ], $this->template->colSettings[$colName]); } $this->template->tableId = 'dt-' . hash("crc32c", Json::encode([ $this->template->sourceUrl, $this->template->colSettings, $this->template->tableSettings, $this->template->rowActions, ])); $this->template->setFile(__DIR__ . '/data_table.latte'); $this->template->render(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/DataTable/DataTableException.php
Mailer/extensions/mailer-module/src/Components/DataTable/DataTableException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Components\DataTable; class DataTableException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Components/MailLinkStats/MailLinkStats.php
Mailer/extensions/mailer-module/src/Components/MailLinkStats/MailLinkStats.php
<?php namespace Remp\MailerModule\Components\MailLinkStats; use Nette\Application\UI\Control; use Nette\Utils\Json; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Models\ContentGenerator\ContentGenerator; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Models\ContentGenerator\Replace\RtmClickReplace; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Repositories\MailTemplateLinksRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class MailLinkStats extends Control { private string $templateCode; public function __construct( private DataTableFactory $dataTableFactory, private TemplatesRepository $templatesRepository, private ContentGenerator $contentGenerator, private GeneratorInputFactory $generatorInputFactory, private MailTemplateLinksRepository $mailTemplateLinksRepository ) { } public function create(ActiveRow $mailTemplate): self { $this->templateCode = $mailTemplate->code; return $this; } public function createComponentDataTableMailLinkStats(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('mailLinkStatsJsonData')) ->setColSetting('url', [ 'header' => 'url', 'render' => 'link', 'priority' => 1, 'orderable' => false, 'width' => '70%', 'class' => 'all table-url', ]) ->setColSetting('text', [ 'header' => 'content', 'render' => 'raw', 'priority' => 1, 'orderable' => false, 'class' => 'all', ]) ->setColSetting('click_count', [ 'header' => 'clicked', 'priority' => 1, 'render' => 'number', 'class' => 'text-right all', 'orderable' => false, ]) ->setTableSetting('order', Json::encode([])) // removes sorting arrow from first column ->setTableSetting('allowSearch', false) ->setTableSetting('scrollX', false); return $dataTable; } public function handleMailLinkStatsJsonData(): void { $request = $this->getPresenter()->getRequest()->getParameters(); $length = (int)$request['length']; $offset = (int)$request['start']; $template = $this->templatesRepository->findBy('code', $this->templateCode); $mailContent = $this->contentGenerator->render($this->generatorInputFactory->create($template)); $parsedLinks = $this->extractUrlContent($mailContent->html()); $dbLinks = $this->mailTemplateLinksRepository->getLinksForTemplate($template); $mailLinks = array_replace_recursive($dbLinks, $parsedLinks); $linksCount = count($mailLinks); $resultData = []; foreach ($mailLinks as $mailLink) { $text = isset($mailLink['content']) ? $this->processContent($mailLink['content']) : ''; $resultData[] = [ [ 'url' => $mailLink['url'], 'text' => $mailLink['url'], ], $text, $mailLink['clickCount'] ?? 0 ]; } usort($resultData, static function ($a, $b) { return $b[2] <=> $a[2]; }); $resultData = array_slice($resultData, $offset, $length); $result = [ 'recordsTotal' => $linksCount, 'recordsFiltered' => $linksCount, 'data' => $resultData ]; $this->presenter->sendJson($result); } /** * @param string $mailContent * @return array{hash: string, array{text: string, url: string}} */ public function extractUrlContent(string $mailContent): array { $matches = []; $rtmClickQueryParam = RtmClickReplace::HASH_PARAM . '='; $matched = preg_match_all('/<a(\s[^>]*)href\s*=\s*([\"\']??)(http[^\"\' >]*?' . $rtmClickQueryParam . '.*)\2[^>]*>(.*)<\/a>/isU', $mailContent, $matches); if (!$matched) { return []; } $result = []; foreach ($matches[3] as $index => $url) { $hash = RtmClickReplace::getRtmClickHashFromUrl($url); $result[$hash] = [ 'content' => $matches[4][$index], 'url'=> RtmClickReplace::removeRtmClickHash($url), ]; } return $result; } private function processContent(string $content): string { $text = trim(html_entity_decode(strip_tags($content))); if (empty($text)) { $matches = []; preg_match('/<img\s[^>]*src\s*=\s*([\"\']??)([^\"\' >]*?)\1[^>]*>/iU', $content, $matches); $title = htmlspecialchars($matches[0], ENT_QUOTES); return "<i class='table-image-tooltip' title='$title'><a href='$matches[2]' target='_blank'>(image)</a></i>"; } return $text; } public function render(): void { $this->template->setFile(__DIR__ . '/mail_link_stats.latte'); $this->template->render(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/JobPresenter.php
Mailer/extensions/mailer-module/src/Presenters/JobPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Latte\Essential\CoreExtension; use Nette\Application\ForbiddenRequestException; use Nette\Application\LinkGenerator; use Nette\Application\UI\Multiplier; use Nette\Bridges\ApplicationLatte\LatteFactory; use Nette\Bridges\ApplicationLatte\UIExtension; use Nette\Http\IResponse; use Nette\Utils\Json; use Remp\MailerModule\Components\BatchExperimentEvaluation\IBatchExperimentEvaluationFactory; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Components\SendingStats\ISendingStatsFactory; use Remp\MailerModule\Forms\EditBatchFormFactory; use Remp\MailerModule\Forms\IFormFactory; use Remp\MailerModule\Forms\JobFormFactory; use Remp\MailerModule\Forms\NewBatchFormFactory; use Remp\MailerModule\Forms\NewTemplateFormFactory; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Job\MailCache; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\JobQueueRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Tracy\Debugger; final class JobPresenter extends BasePresenter { public function __construct( private JobsRepository $jobsRepository, private JobFormFactory $jobFormFactory, private BatchesRepository $batchesRepository, private BatchTemplatesRepository $batchTemplatesRepository, private TemplatesRepository $templatesRepository, private LogsRepository $logsRepository, private NewBatchFormFactory $newBatchFormFactory, private EditBatchFormFactory $editBatchFormFactory, private NewTemplateFormFactory $newTemplateFormFactory, private Aggregator $segmentAggregator, private MailCache $mailCache, private JobQueueRepository $jobQueueRepository, private LatteFactory $latteFactory, private LinkGenerator $linkGenerator, private ListsRepository $listsRepository, private DataTableFactory $dataTableFactory, private ISendingStatsFactory $sendingStatsFactory, private IBatchExperimentEvaluationFactory $batchExperimentEvaluationFactory, private ListVariantsRepository $listVariantsRepository, ) { parent::__construct(); } public function createComponentDataTableDefault() { $mailTypePairs = $this->listsRepository->all()->fetchPairs('id', 'title'); $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('defaultJsonData')) ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 1, ]) ->setColSetting('segments', [ 'orderable' => false, 'priority' => 1, 'render' => 'raw', ]) ->setColSetting('batches', [ 'orderable' => false, 'filter' => $mailTypePairs, 'priority' => 2, 'render' => 'raw', ]) ->setColSetting('sent_count', [ 'header' => 'sent', 'orderable' => false, 'priority' => 1, 'class' => 'text-right', 'render' => 'raw', ]) ->setColSetting('opened_count', [ 'header' => 'opened', 'orderable' => false, 'priority' => 3, 'class' => 'text-right', 'render' => 'raw', ]) ->setColSetting('clicked_count', [ 'header' => 'clicked', 'orderable' => false, 'priority' => 3, 'class' => 'text-right', 'render' => 'raw', ]) ->setColSetting('unsubscribed_count', [ 'header' => 'unsubscribed', 'orderable' => false, 'priority' => 3, 'class' => 'text-right', 'render' => 'raw', ]) ->setRowAction('show', 'palette-Cyan zmdi-eye', 'Show job') ->setTableSetting('order', Json::encode([[0, 'DESC']])) ->setTableSetting('exportColumns', [0,1,2,3,4,5,6]); return $dataTable; } public function renderDefaultJsonData() { $request = $this->request->getParameters(); $listIds = []; foreach ($request['columns'] as $column) { if ($column['name'] !== 'batches') { continue; } if (!empty($column['search']['value'])) { $listIds = explode(',', $column['search']['value']); } break; } $jobsCount = $this->jobsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], $listIds) ->count('*'); $jobs = $this->jobsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], $listIds, (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->jobsRepository->totalCount(), 'recordsFiltered' => $jobsCount, 'data' => [] ]; $segments = []; $segmentList = $this->segmentAggregator->list(); array_walk($segmentList, function ($segment) use (&$segments) { $segments[$segment['provider']][$segment['code']] = $segment['name']; }); if ($this->segmentAggregator->hasErrors()) { $result['error'] = 'Unable to fetch list of segments, please check the application configuration.'; Debugger::log($this->segmentAggregator->getErrors()[0], Debugger::WARNING); } $latte = $this->latteFactory->create(); $latte->addExtension(new CoreExtension()); $latte->addExtension(new UIExtension($this)); $latte->addProvider('uiControl', $this->linkGenerator); /** @var ActiveRow $job */ foreach ($jobs as $job) { $status = $latte->renderToString(__DIR__ . '/templates/Job/_job_status.latte', ['job' => $job]); $sentCount = $latte->renderToString(__DIR__ . '/templates/Job/_sent_count.latte', ['job' => $job]); $openedCount = $latte->renderToString(__DIR__ . '/templates/Job/_opened_count.latte', ['job' => $job]); $clickedCount = $latte->renderToString(__DIR__ . '/templates/Job/_clicked_count.latte', ['job' => $job]); $unsubscribedCount = $latte->renderToString(__DIR__ . '/templates/Job/_unsubscribed_count.latte', ['job' => $job]); $jobSegmentsManager = new JobSegmentsManager($job); $includeSegments = []; foreach ($jobSegmentsManager->getIncludeSegments() as $segment) { $includeSegments[] = $segments[$segment['provider']][$segment['code']] ?? 'Missing segment'; } $excludeSegments = []; foreach ($jobSegmentsManager->getExcludeSegments() as $segment) { $excludeSegments[] = $segments[$segment['provider']][$segment['code']] ?? 'Missing segment'; } $segmentsRaw = $latte->renderToString( __DIR__ . '/templates/Job/_job_segments.latte', ['includeSegments' => $includeSegments, 'excludeSegments' => $excludeSegments] ); $result['data'][] = [ 'actions' => [ 'show' => $this->link('Show', $job->id), ], $job->created_at, $segmentsRaw, $status, $sentCount, $openedCount, $clickedCount, $unsubscribedCount, ]; } $this->presenter->sendJson($result); } public function renderShow($id) { $job = $this->jobsRepository->find($id); $segmentList = $this->segmentAggregator->list(); $jobSegmentsManager = new JobSegmentsManager($job); $this->template->includeSegments = $this->pairSegments($jobSegmentsManager->getIncludeSegments(), $segmentList); $this->template->excludeSegments = $this->pairSegments($jobSegmentsManager->getExcludeSegments(), $segmentList); if ($this->segmentAggregator->hasErrors()) { $this->flashMessage('Unable to fetch list of segments, please check the application configuration.', 'danger'); Debugger::log($this->segmentAggregator->getErrors(), Debugger::WARNING); } $batchUnsubscribeStats = []; $batchPreparedEmailsStats = []; foreach ($job->related('mail_job_batch') as $batch) { $batchUnsubscribeStats[$batch->id] = 0; foreach ($batch->related('mail_job_batch_templates') as $mjbt) { $batchUnsubscribeStats[$batch->id] += $mjbt->mail_template->mail_type ->related('mail_user_subscriptions') ->where([ 'rtm_campaign' => $mjbt->mail_template->code, 'rtm_content' => (string) $mjbt->mail_job_batch_id, 'subscribed' => false, ]) ->count('*'); } $batchPreparedEmailsStats[$batch->id] = $this->mailCache->countJobs($batch->id); } $this->template->job = $job; $this->template->total_sent = $this->logsRepository->getJobLogs($job->id)->count('*'); $this->template->jobIsEditable = $this->jobsRepository->isEditable($job->id); $this->template->batchUnsubscribeStats = $batchUnsubscribeStats; $this->template->batchPreparedEmailsStats = $batchPreparedEmailsStats; } private function pairSegments($jobSegments, $aggSegments): array { $result = []; foreach ($jobSegments as $jobSegment) { foreach ($aggSegments as $aggSegment) { if ($aggSegment['provider'] === $jobSegment['provider'] && $aggSegment['code'] === $jobSegment['code']) { $result[] = $aggSegment['name']; continue 2; } } $result[] = $jobSegment['provider'] . ':' . $jobSegment['code'] . ' - Missing segment'; } return $result; } public function renderEditJob($id) { $this->template->job = $this->jobsRepository->find($id); } public function createComponentEditJobForm() { $form = $this->jobFormFactory->create((int) $this->params['id']); $this->jobFormFactory->onSuccess = function ($job) { $this->flashMessage('Job was updated'); $this->redirect('Show', $job->id); }; $this->jobFormFactory->onError = function ($job, $message) { $this->flashMessage($message, 'danger'); $this->redirect('Show', $job->id); }; return $form; } public function renderEditBatch($id) { $batch = $this->batchesRepository->find($id); $this->template->batch = $batch; } public function handleRemoveTemplate($id) { $batchTemplate = $this->batchTemplatesRepository->find($id); $this->batchTemplatesRepository->delete($batchTemplate); $this->flashMessage('Email was removed'); $this->redirect('Show', $batchTemplate->mail_job_id); } public function handleSetBatchReadyToSend($id) { if (!$this->permissionManager->isAllowed($this->getUser(), 'batch', 'start')) { throw new ForbiddenRequestException( "You don't have permission to run this action. (batch/start)", IResponse::S403_Forbidden ); } $batch = $this->batchesRepository->find($id); $priority = $this->batchesRepository->getBatchPriority($batch); if (!$priority) { $this->flashMessage("You can't send batch which mail type have priority set to 0."); $this->redirect('Show', $batch->mail_job_id); } if ($batch->status === BatchesRepository::STATUS_PROCESSED) { $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_QUEUED); } else { $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND); } $this->flashMessage('Status of batch was changed.'); $this->redirect('Show', $batch->mail_job_id); } public function handleSetBatchSend($id) { if (!$this->permissionManager->isAllowed($this->getUser(), 'batch', 'start')) { throw new ForbiddenRequestException( "You don't have permission to run this action. (batch/start)", IResponse::S403_Forbidden ); } $batch = $this->batchesRepository->find($id); $priority = $this->batchesRepository->getBatchPriority($batch); if (!$priority) { $this->flashMessage("You can't send batch which mail type have priority set to 0."); $this->redirect('Show', $batch->mail_job_id); } $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_SENDING); $this->flashMessage('Status of batch was changed.'); $this->redirect('Show', $batch->mail_job_id); } public function handleSetBatchUserStop($id) { if (!$this->permissionManager->isAllowed($this->getUser(), 'batch', 'stop')) { throw new ForbiddenRequestException( "You don't have permission to run this action. (batch/stop)", IResponse::S403_Forbidden ); } $batch = $this->batchesRepository->find($id); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_USER_STOP); $this->flashMessage('Status of batch was changed.'); $this->redirect('Show', $batch->mail_job_id); } public function handleSetBatchCreated($id) { $batch = $this->batchesRepository->find($id); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_CREATED); $this->flashMessage('Status of batch was changed.'); $this->redirect('Show', $batch->mail_job_id); } public function handleRemoveBatch($id) { $batch = $this->batchesRepository->find($id); $sentCount = $this->logsRepository->getTable()->where([ 'mail_job_batch_id' => $batch->id, ])->count('*'); if ($sentCount > 0) { $this->flashMessage('Batch was not removed, some emails were already sent'); $this->redirect('Show', $batch->mail_job_id); } $this->batchTemplatesRepository->deleteByBatchId($batch->id); $this->mailCache->removeQueue($batch->id); $this->jobQueueRepository->deleteJobsByBatch($batch->id, true); $this->batchesRepository->delete($batch); $this->flashMessage('Batch was removed.'); $this->redirect('Show', $batch->mail_job_id); } public function handleSetBatchReadyToProcess($id) { if (!$this->permissionManager->isAllowed($this->getUser(), 'batch', 'process')) { throw new ForbiddenRequestException( "You don't have permission to run this action. (batch/process)", IResponse::S403_Forbidden ); } $batch = $this->batchesRepository->find($id); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_READY_TO_PROCESS); $this->flashMessage('Status of batch was changed.'); $this->redirect('Show', $batch->mail_job_id); } public function actionMailTypeTemplates($id): void { $templates = $this->templatesRepository->pairs((int) $id); $this->sendJson($templates); } public function actionMailTypeVariants($id): void { $mailType = $this->listsRepository->find($id); $variants = []; if ($mailType) { $variants = $this->listVariantsRepository->getVariantsForType($mailType) ->order('sorting') ->fetchPairs('id', 'title'); } $this->sendJson($variants); } public function actionMailTypeCodeVariants($id): void { $mailType = $this->listsRepository->findByCode($id)->fetch(); $variants = []; if ($mailType) { $variants = $this->listVariantsRepository->getVariantsForType($mailType) ->order('sorting') ->fetchPairs('id', 'title'); } $this->sendJson($variants); } public function createComponentNewBatchForm() { $form = $this->newBatchFormFactory->create(isset($this->params['id']) ? (int)$this->params['id'] : null); $this->newBatchFormFactory->onSuccess = function ($job) { $this->flashMessage('Batch was added'); $this->redirect('Show', $job->id); }; return $form; } public function createComponentEditBatchForm() { $batch = $this->batchesRepository->find($this->getParameter('id')); $form = $this->editBatchFormFactory->create($batch); $this->editBatchFormFactory->onSuccess = function ($batch, $buttonSubmitted) { $this->flashMessage(sprintf('Batch #%d was updated', $batch->id)); // redirect based on button clicked by user if ($buttonSubmitted === IFormFactory::FORM_ACTION_SAVE_CLOSE) { $this->redirect('Show', $batch->job->id); } else { $this->redirect('EditBatch', $batch->id); } }; return $form; } public function createComponentNewTemplateForm() { return new Multiplier(function ($batchId) { $form = $this->newTemplateFormFactory->create($batchId); $this->newTemplateFormFactory->onSuccess = function ($job) { $this->flashMessage('Email was added'); $this->redirect('Show', $job->id); }; return $form; }); } protected function createComponentTemplateStats() { return new Multiplier(function ($templateId) { $templateStats = $this->sendingStatsFactory->create(); $template = $this->templatesRepository->find($templateId); $templateStats->addTemplate($template); $templateStats->showConversions(); return $templateStats; }); } protected function createComponentJobBatchTemplateStats() { return new Multiplier(function ($jobBatchTemplateId) { $stats = $this->sendingStatsFactory->create(); $jobBatchTemplate = $this->batchTemplatesRepository->find($jobBatchTemplateId); $stats->addJobBatchTemplate($jobBatchTemplate); $stats->showConversions(); return $stats; }); } protected function createComponentJobStats() { $templateStats = $this->sendingStatsFactory->create(); $batches = $this->batchesRepository ->getTable() ->where([ 'mail_job_id' => $this->params['id'], ]); foreach ($batches as $batch) { $templateStats->addBatch($batch); } $templateStats->showConversions(); return $templateStats; } public function createComponentBatchExperimentEvaluation() { return $this->batchExperimentEvaluationFactory->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/DashboardPresenter.php
Mailer/extensions/mailer-module/src/Presenters/DashboardPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Utils\DateTime; use DateInterval; use Remp\MailerModule\Models\ChartTrait; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\MailTemplateStatsRepository; use Remp\MailerModule\Repositories\MailTypeStatsRepository; final class DashboardPresenter extends BasePresenter { use ChartTrait; private $batchesRepository; private $listsRepository; /** * @var MailTypeStatsRepository */ private $mailTypeStatsRepository; /** @var MailTemplateStatsRepository */ private $mailTemplateStatsRepository; public function __construct( MailTemplateStatsRepository $mailTemplateStatsRepository, MailTypeStatsRepository $mailTypeStatsRepository, BatchesRepository $batchesRepository, ListsRepository $listsRepository ) { parent::__construct(); $this->mailTemplateStatsRepository = $mailTemplateStatsRepository; $this->mailTypeStatsRepository = $mailTypeStatsRepository; $this->batchesRepository = $batchesRepository; $this->listsRepository = $listsRepository; } public function renderDefault(): void { $numOfDays = 30; $graphLabels = []; $typeDataSets = []; $now = new DateTime(); $from = (clone $now)->sub( new DateInterval('P' . $numOfDays . 'D') ); // init graph data set settings $defaultGraphSettings = [ 'data' => array_fill(0, $numOfDays, 0), 'backgroundColor' => '#FDECB7', 'strokeColor' => '#FDECB7', 'borderColor' => '#FDECB7', 'lineColor' => '#FDECB7', 'prevPeriodCount' => 0, 'fill' => true, 'count' => 0, 'lineTension' => 0.1, ]; // fill graph column labels for ($i = $numOfDays; $i >= 0; $i--) { $graphLabels[] = DateTime::from('-' . $i . ' days')->format('Y-m-d'); } $allMailTypes = $this->listsRepository->all(); // fill datasets meta info foreach ($allMailTypes as $mailType) { $typeDataSets[$mailType->id] = [ 'id' => $mailType->id, 'label' => $mailType->title, ] + $defaultGraphSettings; } $typeSubscriberDataSets = $typeDataSets; $allSentMailsData = $this->mailTemplateStatsRepository->getAllMailTemplatesGraphData($from, $now); $allSentEmailsDataSet = [] + $defaultGraphSettings; // parse all sent mails data to chart.js format foreach ($allSentMailsData as $row) { $foundAt = array_search( $row->date->format('Y-m-d'), $graphLabels ); if ($foundAt !== false) { $allSentEmailsDataSet['data'][$foundAt] = $row->sent_mails; $allSentEmailsDataSet['count'] += $row->sent_mails; } } $typesData = $this->mailTemplateStatsRepository->getTemplatesGraphDataGroupedByMailType($from, $now); // parse sent mails by type data to chart.js format foreach ($typesData as $row) { $foundAt = array_search( $row->date->format('Y-m-d'), $graphLabels ); if ($foundAt !== false) { $typeDataSets[$row->mail_type_id]['count'] += $row->sent_mails; $typeDataSets[$row->mail_type_id]['data'][$foundAt] = $row->sent_mails; } } // parse previous period data (counts) $prevPeriodFrom = (clone $from)->sub(new DateInterval('P' . $numOfDays . 'D')); $prevPeriodTypesData = $this->mailTemplateStatsRepository->getTemplatesGraphDataGroupedByMailType($prevPeriodFrom, $from); foreach ($prevPeriodTypesData as $row) { $typeDataSets[$row->mail_type_id]['prevPeriodCount'] += $row->sent_mails; } // remove sets with zero sent count $typeDataSets = array_filter($typeDataSets, function ($a) { return ($a['count'] == 0) ? null : $a; }); // order sets by sent count usort($typeDataSets, function ($a, $b) { return $b['count'] <=> $a['count']; }); $typeSubscribersData = $this->mailTypeStatsRepository->getDashboardDataGroupedByTypes($from, $now); foreach ($typeSubscribersData as $row) { $foundAt = array_search( $row->created_date->format('Y-m-d'), $graphLabels ); if ($foundAt !== false) { $typeSubscriberDataSets[$row->mail_type_id]['data'][$foundAt] = $row->count; $typeSubscriberDataSets[$row->mail_type_id]['count'] = $row->count; } } foreach ($typeSubscriberDataSets as $mailTypeId => $typeSubscriberDataSet) { $typeSubscriberDataSets[$mailTypeId]['suggestedMin'] = $this->getChartSuggestedMin([$typeSubscriberDataSet['data']]); } foreach ($typeDataSets as $mailTypeId => $typeDataSet) { $typeDataSets[$mailTypeId]['suggestedMin'] = $this->getChartSuggestedMin([$typeDataSet['data']]); } $prevPeriodSubscribersTypeData = $this->mailTypeStatsRepository->getDashboardDataGroupedByTypes($prevPeriodFrom, $from); foreach ($prevPeriodSubscribersTypeData as $row) { $typeSubscriberDataSets[$row->mail_type_id]['prevPeriodCount'] = $row->count; } // remove sets with zero sent count $typeSubscriberDataSets = array_filter($typeSubscriberDataSets, function ($a) { return ($a['count'] == 0) ? null : $a; }); // order sets by sent count usort($typeSubscriberDataSets, function ($a, $b) { return $b['count'] <=> $a['count']; }); $inProgressBatches = $this->batchesRepository->getInProgressBatches(10); $lastDoneBatches = $this->batchesRepository->getLastDoneBatches(10); $this->template->typeSubscriberDataSets = array_values($typeSubscriberDataSets); $this->template->allSentEmailsDataSet = $allSentEmailsDataSet; $this->template->typeDataSets = array_values($typeDataSets); $this->template->inProgressBatches = $inProgressBatches; $this->template->lastDoneBatches = $lastDoneBatches; $this->template->labels = $graphLabels; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/GeneratorPresenter.php
Mailer/extensions/mailer-module/src/Presenters/GeneratorPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\BadRequestException; use Nette\Application\UI\Form; use Nette\Forms\Controls\BaseControl; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Forms\SourceTemplateFormFactory; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\SourceTemplatesRepository; final class GeneratorPresenter extends BasePresenter { public function __construct( private SourceTemplatesRepository $sourceTemplatesRepository, private SourceTemplateFormFactory $sourceTemplateFormFactory, private DataTableFactory $dataTableFactory ) { parent::__construct(); } public function createComponentDataTableDefault(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('title', [ 'priority' => 1, 'render' => 'link', ]) ->setColSetting('code', [ 'priority' => 1, 'render' => 'code', ]) ->setColSetting('generator', [ 'priority' => 2, 'render' => 'code', ]) ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 3, ]) ->setColSetting('updated_at', [ 'header' => 'updated at', 'render' => 'date', 'priority' => 3, ]) ->setRowAction('edit', 'palette-Cyan zmdi-edit', 'Edit generator') ->setRowAction('delete', 'palette-Red zmdi-delete', 'Delete generator', [ 'onclick' => 'return confirm(\'Are you sure you want to delete this item?\');' ]) ->setRowAction('generate', 'palette-Cyan zmdi-spellcheck', 'Generate emails') ->setTableSetting('order', '[]'); return $dataTable; } public function renderDefaultJsonData(): void { $request = $this->request->getParameters(); [$orderColumn, $orderDir] = $this->dataTableFactory->getOrderFromRequest($request); $sourceTemplatesCount = $this->sourceTemplatesRepository ->tableFilter($request['search']['value'], $orderColumn, $orderDir) ->count('*'); $sourceTemplates = $this->sourceTemplatesRepository ->tableFilter($request['search']['value'], $orderColumn, $orderDir, (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->sourceTemplatesRepository->totalCount(), 'recordsFiltered' => $sourceTemplatesCount, 'data' => [] ]; /** @var ActiveRow $sourceTemplate */ foreach ($sourceTemplates as $i => $sourceTemplate) { $editUrl = $this->link('Edit', $sourceTemplate->id); $generateUrl = $this->link('Generate', $sourceTemplate->id); $deleteUrl = $this->link('Delete!', $sourceTemplate->id); $result['data'][] = [ 'actions' => [ 'edit' => $editUrl, 'generate' => $generateUrl, 'delete' => $deleteUrl, ], [ 'url' => $editUrl, 'text' => $sourceTemplate->title, ], $sourceTemplate->code, $sourceTemplate->generator, $sourceTemplate->created_at, $sourceTemplate->updated_at, ]; } $this->presenter->sendJson($result); } public function renderEdit($id): void { $generator = $this->sourceTemplatesRepository->find($id); if (!$generator) { throw new BadRequestException(); } $this->template->generator = $generator; } public function renderGenerate($id): void { $this->redirect("MailGenerator:default", ['source_template_id' => $id]); } public function createComponentMailSourceTemplateForm(): Form { $form = $this->sourceTemplateFormFactory->create(isset($this->params['id']) ? (int)$this->params['id'] : null); $this->sourceTemplateFormFactory->onUpdate = function ($form, $mailSourceTemplate, $buttonSubmitted) { $this->flashMessage('Source template was successfully updated'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $mailSourceTemplate->id); }; $this->sourceTemplateFormFactory->onSave = function ($form, $mailSourceTemplate, $buttonSubmitted) { $this->flashMessage('Source template was successfully created'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $mailSourceTemplate->id); }; return $form; } public function handleRenderSorting($sorting): void { /** @var BaseControl $sortingInput */ $sortingInput = $this['mailSourceTemplateForm']['sorting']; $sortingInput->setValue($sorting); $this->redrawControl('wrapper'); $this->redrawControl('sortingAfterSnippet'); } public function handleDelete($id): void { $sourceTemplate = $this->sourceTemplatesRepository->find($id); $this->sourceTemplatesRepository->softDelete($sourceTemplate); $this->flashMessage("Generator {$sourceTemplate->title} was deleted."); $this->redirect('default'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/FrontendPresenter.php
Mailer/extensions/mailer-module/src/Presenters/FrontendPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Presenter; use Nette\DI\Attributes\Inject; use Remp\MailerModule\Components\ApplicationStatus\ApplicationStatus; use Remp\MailerModule\Components\ApplicationStatus\IApplicationStatusFactory; abstract class FrontendPresenter extends Presenter { #[Inject] public IApplicationStatusFactory $applicationStatusFactory; public function createComponentApplicationStatus(): ApplicationStatus { return $this->applicationStatusFactory->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/Error4xxPresenter.php
Mailer/extensions/mailer-module/src/Presenters/Error4xxPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette; use Remp\MailerModule\Models\Config\LinkedServices; use Remp\MailerModule\Models\Config\LocalizationConfig; class Error4xxPresenter extends FrontendPresenter { /** @var LocalizationConfig @inject */ public $localizationConfig; /** @var LinkedServices @inject */ public $linkedServices; public function startup(): void { parent::startup(); if (!$this->getRequest()->isMethod(Nette\Application\Request::FORWARD)) { $this->error(); } } public function renderDefault( Nette\Application\BadRequestException $exception, ?Nette\Application\UI\Presenter $previousPresenter = null, ): void { if ($previousPresenter instanceof FrontendPresenter) { $this->setLayout('layout_public'); } $this->template->currentUser = $this->getUser(); $this->template->linkedServices = $this->linkedServices->getServices(); $this->template->locale = $this->localizationConfig->getDefaultLocale(); // load template 403.latte or 404.latte or ... 4xx.latte $file = __DIR__ . "/templates/Error/{$exception->getCode()}.latte"; $this->template->setFile(is_file($file) ? $file : __DIR__ . '/templates/Error/4xx.latte'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/ErrorPresenter.php
Mailer/extensions/mailer-module/src/Presenters/ErrorPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette; use Nette\Application\Responses; use Remp\MailerModule\Components\ApplicationStatus\ApplicationStatus; use Remp\MailerModule\Components\ApplicationStatus\IApplicationStatusFactory; use Tracy\Debugger; class ErrorPresenter implements Nette\Application\IPresenter { use Nette\SmartObject; private $applicationStatusFactory; public function __construct(IApplicationStatusFactory $applicationStatusFactory) { $this->applicationStatusFactory = $applicationStatusFactory; } public function run(Nette\Application\Request $request): Nette\Application\Response { $exception = $request->getParameter('exception'); if ($exception instanceof Nette\Application\BadRequestException) { [$module, , $sep] = Nette\Application\Helpers::splitName($request->getPresenterName()); return new Responses\ForwardResponse($request->setPresenterName($module . $sep . 'Error4xx')); } Debugger::log($exception, Debugger::EXCEPTION); return new Responses\CallbackResponse(function () { require __DIR__ . '/templates/Error/500.phtml'; }); } public function createComponentApplicationStatus(): ApplicationStatus { return $this->applicationStatusFactory->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/HealthPresenter.php
Mailer/extensions/mailer-module/src/Presenters/HealthPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Presenter; use Nette\Http\IResponse; use Nette\Utils\FileSystem; use Remp\MailerModule\Commands\HermesWorkerCommand; use Remp\MailerModule\Commands\MailWorkerCommand; use Remp\MailerModule\Commands\ProcessJobCommand; use Remp\MailerModule\Models\HealthChecker; use Remp\MailerModule\Models\Job\MailCache; use Remp\MailerModule\Repositories\ConfigsRepository; use Tomaj\NetteApi\Response\JsonApiResponse; use Tracy\Debugger; use Tracy\ILogger; /** * Health check presenter * * Behavior and response should be same or similar to health checks within REMP (package ukfast/laravel-health-check). */ final class HealthPresenter extends Presenter { private const STATUS_OK = 'ok'; private const STATUS_PROBLEM = 'PROBLEM'; private $configsRepository; private $mailCache; private $tempDir; private HealthChecker $healthChecker; public function __construct( string $tempDir, ConfigsRepository $configsRepository, MailCache $mailCache, HealthChecker $healthChecker ) { parent::__construct(); $this->configsRepository = $configsRepository; $this->mailCache = $mailCache; $this->tempDir = $tempDir; $this->healthChecker = $healthChecker; } public function renderDefault(): void { $result = [ 'status' => self::STATUS_OK, ]; $result['database'] = $this->databaseCheck(); $result['redis'] = $this->redisCheck(); $result['log'] = $this->logCheck(); $result['storage'] = $this->storageCheck(); $result['mail_worker'] = $this->mailWorkerCheck(); $result['hermes_worker'] = $this->hermesWorkerCheck(); $result['process_job_command'] = $this->processJobCommandCheck(); foreach ($result as $key => $value) { if ($key !== 'status' && $value['status'] === self::STATUS_PROBLEM) { $result['status'] = self::STATUS_PROBLEM; break; } } // set correct response code and return results if ($result['status'] === self::STATUS_OK) { $resultCode = IResponse::S200_OK; } else { $resultCode = IResponse::S500_InternalServerError; } $this->getHttpResponse()->setCode($resultCode); $this->sendResponse(new JsonApiResponse($resultCode, $result)); } private function databaseCheck(): array { $result['status'] = self::STATUS_OK; try { // fetching default_mailer which is always present in seeded DB $defaultMailerConfigString = 'default_mailer'; $defaultMailer = $this->configsRepository->loadByName($defaultMailerConfigString); if (!$defaultMailer) { throw new \Exception("Unable to find [{$defaultMailerConfigString}] config. Did you migrate & seed database?"); } } catch (\Exception $e) { $result = [ 'status' => self::STATUS_PROBLEM, // https://github.com/ukfast/laravel-health-check/blob/9979cd58831f42fdd284e882eaed4d74362e1641/src/Checks/DatabaseHealthCheck.php#L31 'message' => 'Could not connect to db', 'context' => $e->getMessage() ]; } return $result; } private function redisCheck(): array { $result['status'] = self::STATUS_OK; try { $pingPongResponse = 'PONG'; $redisPing = $this->mailCache->ping($pingPongResponse); if ($redisPing !== $pingPongResponse) { throw new \Exception('Unable to ping redis.'); } } catch (\Exception $e) { $result = [ 'status' => self::STATUS_PROBLEM, // https://github.com/ukfast/laravel-health-check/blob/9979cd58831f42fdd284e882eaed4d74362e1641/src/Checks/RedisHealthCheck.php#L18 'message' => 'Failed to connect to redis', 'context' => $e->getMessage(), ]; } return $result; } private function mailWorkerCheck(): array { $result['status'] = $this->healthChecker->isHealthy(MailWorkerCommand::COMMAND_NAME) ? self::STATUS_OK : self::STATUS_PROBLEM; if ($result['status'] === self::STATUS_PROBLEM) { $result['message'] = 'Mail worker command is not running'; } return $result; } private function hermesWorkerCheck(): array { $result['status'] = $this->healthChecker->isHealthy(HermesWorkerCommand::COMMAND_NAME) ? self::STATUS_OK : self::STATUS_PROBLEM; if ($result['status'] === self::STATUS_PROBLEM) { $result['message'] = 'Hermes worker command is not running'; } return $result; } private function processJobCommandCheck(): array { $result['status'] = $this->healthChecker->isHealthy(ProcessJobCommand::COMMAND_NAME) ? self::STATUS_OK : self::STATUS_PROBLEM; if ($result['status'] === self::STATUS_PROBLEM) { $result['message'] = 'Process Job command is not running'; } return $result; } private function logCheck(): array { $result['status'] = self::STATUS_OK; try { // see \Tracy\Logger::log() for exceptions Debugger::log('Healthcheck ping', ILogger::DEBUG); } catch (\Exception $e) { $result = [ 'status' => self::STATUS_PROBLEM, // https://github.com/ukfast/laravel-health-check/blob/9979cd58831f42fdd284e882eaed4d74362e1641/src/Checks/LogHealthCheck.php#L25 'message' => 'Could not write to log file', 'context' => $e->getMessage(), ]; } return $result; } private function storageCheck(): array { $result['status'] = self::STATUS_OK; try { $filePath = $this->tempDir . DIRECTORY_SEPARATOR . 'healtcheck'; $fileContent = 'healthcheck'; FileSystem::write($filePath, $fileContent); $fileContentRead = FileSystem::read($filePath); FileSystem::delete($filePath); if ($fileContentRead !== $fileContent) { throw new \Exception('Contents of written file are not same.'); } } catch (\Exception $e) { $result = [ 'status' => self::STATUS_PROBLEM, 'message' => 'Could not write to temp dir', 'context' => $e->getMessage(), ]; } return $result; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/LayoutPresenter.php
Mailer/extensions/mailer-module/src/Presenters/LayoutPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\BadRequestException; use Nette\Application\UI\Form; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Forms\LayoutFormFactory; use Remp\MailerModule\Repositories\LayoutsRepository; final class LayoutPresenter extends BasePresenter { private $layoutsRepository; private $layoutFormFactory; private $dataTableFactory; public function __construct( LayoutsRepository $layoutsRepository, LayoutFormFactory $layoutFormFactory, DataTableFactory $dataTableFactory ) { parent::__construct(); $this->layoutsRepository = $layoutsRepository; $this->layoutFormFactory = $layoutFormFactory; $this->dataTableFactory = $dataTableFactory; } public function createComponentDataTableDefault(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('name', [ 'priority' => 1, 'render' => 'link', ]) ->setColSetting('code', [ 'priority' => 1, ]) ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 2, ]) ->setRowAction('edit', 'palette-Cyan zmdi-edit', 'Edit layout') ->setRowAction('delete', 'palette-Red zmdi-delete', 'Delete layout', [ 'onclick' => 'return confirm(\'Are you sure you want to delete this item?\');' ]); return $dataTable; } public function renderDefaultJsonData(): void { $request = $this->request->getParameters(); $layoutsCount = $this->layoutsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir']) ->count('*'); $layouts = $this->layoutsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->layoutsRepository->totalCount(), 'recordsFiltered' => $layoutsCount, 'data' => [] ]; foreach ($layouts as $layout) { $editUrl = $this->link('Edit', $layout->id); $deleteUrl = $this->link('Delete!', $layout->id); $result['data'][] = [ 'actions' => [ 'edit' => $editUrl, 'delete' => $deleteUrl, ], [ 'url' => $editUrl, 'text' => $layout->name, ], $layout->code, $layout->created_at, ]; } $this->presenter->sendJson($result); } public function renderEdit($id): void { $layout = $this->layoutsRepository->find($id); if (!$layout) { throw new BadRequestException(); } $this->template->layout = $layout; } public function createComponentLayoutForm(): Form { $id = null; if (isset($this->params['id'])) { $id = (int)$this->params['id']; } $form = $this->layoutFormFactory->create($id); $presenter = $this; $this->layoutFormFactory->onCreate = function ($layout, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Layout was created'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $layout->id); }; $this->layoutFormFactory->onUpdate = function ($layout, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Layout was updated'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $layout->id); }; return $form; } public function handleDelete($id): void { $layout = $this->layoutsRepository->find($id); if ($this->layoutsRepository->canBeDeleted($layout)) { $this->layoutsRepository->softDelete($layout); $this->flashMessage("Layout {$layout->name} was deleted."); $this->redirect('default'); } else { $this->flashMessage("There are emails using layout {$layout->name}.", 'danger'); $this->redirect('Template:default', ['layout' => $layout->id]); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/SnippetPresenter.php
Mailer/extensions/mailer-module/src/Presenters/SnippetPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\BadRequestException; use Nette\Application\UI\Form; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Forms\SnippetFormFactory; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\SnippetTranslationsRepository; final class SnippetPresenter extends BasePresenter { private SnippetsRepository $snippetsRepository; private SnippetFormFactory $snippetFormFactory; private DataTableFactory $dataTableFactory; private SnippetTranslationsRepository $snippetTranslationsRepository; public function __construct( SnippetsRepository $snippetsRepository, SnippetFormFactory $snippetFormFactory, DataTableFactory $dataTableFactory, SnippetTranslationsRepository $snippetTranslationsRepository ) { parent::__construct(); $this->snippetsRepository = $snippetsRepository; $this->snippetFormFactory = $snippetFormFactory; $this->dataTableFactory = $dataTableFactory; $this->snippetTranslationsRepository = $snippetTranslationsRepository; } public function createComponentDataTableDefault(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('name', [ 'priority' => 1, 'render' => 'link', ]) ->setColSetting('code', [ 'priority' => 1, ]) ->setColSetting('mail_type_id', [ 'header' => 'mail type', 'priority' => 1, ]) ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 2, ]) ->setRowAction('edit', 'palette-Cyan zmdi-edit', 'Edit snippet') ->setRowAction('delete', 'palette-Red zmdi-delete', 'Delete snippet', [ 'onclick' => 'return confirm(\'Are you sure you want to delete this item?\');' ]); return $dataTable; } public function renderDefaultJsonData(): void { $request = $this->request->getParameters(); $query = $request['search']['value']; $order = $request['columns'][$request['order'][0]['column']]['name']; $orderDir = $request['order'][0]['dir']; $snippetsCount = $this->snippetsRepository ->tableFilter($query, $order, $orderDir) ->count('*'); $snippets = $this->snippetsRepository ->tableFilter($query, $order, $orderDir, (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->snippetsRepository->totalCount(), 'recordsFiltered' => $snippetsCount, 'data' => [] ]; foreach ($snippets as $snippet) { $editUrl = $this->link('Edit', $snippet->id); $deleteUrl = $this->link('Delete!', $snippet->id); $result['data'][] = [ 'actions' => [ 'edit' => $editUrl, 'delete' => $deleteUrl ], [ 'url' => $editUrl, 'text' => $snippet->name, ], $snippet->code, $snippet->mail_type->title ?? null, $snippet->created_at, ]; } $this->presenter->sendJson($result); } public function renderEdit($id): void { $snippet = $this->snippetsRepository->find($id); if (!$snippet) { throw new BadRequestException(); } $this->template->snippet = $snippet; } public function handleDelete($id): void { $snippet = $this->snippetsRepository->find($id); $this->snippetTranslationsRepository->getTranslationsForSnippet($snippet)->delete(); $this->snippetsRepository->delete($snippet); $this->flashMessage("Snippet {$snippet->name} was deleted."); $this->redirect('default'); } public function createComponentSnippetForm(): Form { $id = null; if (isset($this->params['id'])) { $id = (int)$this->params['id']; } $form = $this->snippetFormFactory->create($id); $presenter = $this; $this->snippetFormFactory->onCreate = function ($snippet, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Snippet was created'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $snippet->id); }; $this->snippetFormFactory->onUpdate = function ($snippet, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Snippet was updated'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $snippet->id); }; return $form; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/PreviewPresenter.php
Mailer/extensions/mailer-module/src/Presenters/PreviewPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\BadRequestException; use Nette\Application\UI\Presenter; use Remp\MailerModule\Models\ContentGenerator\ContentGenerator; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Repositories\TemplatesRepository; final class PreviewPresenter extends FrontendPresenter { /** @var TemplatesRepository @inject */ public $templatesRepository; /** @var ContentGenerator @inject */ public $contentGenerator; /** @var GeneratorInputFactory @inject */ public $generatorInputFactory; public function renderPublic(string $id, ?string $lang = null): void { $template = $this->templatesRepository->getByPublicCode($id); if (!$template) { throw new BadRequestException(); } $mailContent = $this->contentGenerator->render($this->generatorInputFactory->create($template, [], null, $lang)); $this->template->content = $mailContent->html(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/SearchPresenter.php
Mailer/extensions/mailer-module/src/Presenters/SearchPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Remp\MailerModule\Models\Config\SearchConfig; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; final class SearchPresenter extends BasePresenter { public function __construct( private TemplatesRepository $templatesRepository, private LayoutsRepository $layoutsRepository, private ListsRepository $listsRepository, private JobsRepository $jobsRepository, private SearchConfig $searchConfig, ) { parent::__construct(); } public function actionDefault($term): void { $limit = $this->searchConfig->getMaxResultCount(); $layouts = array_values($this->layoutsRepository->search($term, $limit)); $lists = array_values($this->listsRepository->search($term, $limit)); $emails = []; $templateIds = []; foreach ($this->templatesRepository->search($term, $limit) as $mailTemplate) { $templateIds[$mailTemplate->id] = $mailTemplate->id; $emails[] = [ 'type' => 'email', 'search_result_url' => $this->link('Template:show', ['id' => $mailTemplate->id]), 'name' => $mailTemplate->subject, 'tags' => [$mailTemplate->code], 'mail_types' => [$mailTemplate->mail_type->title], ]; } $jobs = []; $query = $this->jobsRepository->getTable()->where([ ':mail_job_batch_templates.mail_template_id' => array_values($templateIds), ]); foreach ($query as $job) { $templates = []; $mailTypes = []; foreach ($job->related('mail_job_batch_templates') as $mailJobBatchTemplate) { $templates[] = $mailJobBatchTemplate->mail_template->subject; $mailTypes[] = $mailJobBatchTemplate->mail_template->mail_type->title; } $jobs[] = [ 'type' => 'job', 'search_result_url' => $this->link('Job:show', ['id' => $job->id]), 'name' => $templates, 'date' => $job->created_at->format(DATE_RFC3339), 'mail_types' => $mailTypes, ]; } $layouts = $this->addTypeAndLink($layouts, 'layout', 'Layout:edit'); $lists = $this->addTypeAndLink($lists, 'list', 'List:show'); $result = array_merge($emails, $layouts, $lists, $jobs); $this->sendJson($result); } protected function addTypeAndLink(array $items, string $type, string $destination): array { foreach ($items as &$item) { $item['type'] = $type; $item['search_result_url'] = $this->link($destination, ['id' => $item['id']]); } return $items; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/BasePresenter.php
Mailer/extensions/mailer-module/src/Presenters/BasePresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Presenter; use Remp\MailerModule\Components\ApplicationStatus\ApplicationStatus; use Remp\MailerModule\Components\ApplicationStatus\IApplicationStatusFactory; use Remp\MailerModule\Forms\IFormFactory; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Config\LinkedServices; use Remp\MailerModule\Models\Config\LocalizationConfig; use Remp\MailerModule\Models\EnvironmentConfig; abstract class BasePresenter extends Presenter { /** @var EnvironmentConfig @inject */ public $environmentConfig; /** @var IApplicationStatusFactory @inject */ public $applicationStatusFactory; /** @var PermissionManager @inject */ public $permissionManager; /** @var LocalizationConfig @inject */ public $localizationConfig; /** @var LinkedServices @inject */ public $linkedServices; public function startup(): void { parent::startup(); if (!$this->getUser()->isLoggedIn()) { $this->getUser()->login("", ""); } $this->template->currentUser = $this->getUser(); $this->template->linkedServices = $this->linkedServices->getServices(); $this->template->locale = $this->localizationConfig->getDefaultLocale(); $this->template->langs = $this->localizationConfig->getSecondaryLocales(); } /** * Redirect based on button clicked by user. * * @param string $buttonSubmitted * @param int|null $itemID ID of item to which redirect when staying on view * (if null, redirected to Default view ignoring button) * @throws \Nette\Application\AbortException */ protected function redirectBasedOnButtonSubmitted(string $buttonSubmitted, int $itemID = null): void { if ($buttonSubmitted === IFormFactory::FORM_ACTION_SAVE_CLOSE || is_null($itemID)) { $this->redirect('Default'); } else { $this->redirect('Edit', $itemID); } } public function createComponentApplicationStatus(): ApplicationStatus { return $this->applicationStatusFactory->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/ListCategoryPresenter.php
Mailer/extensions/mailer-module/src/Presenters/ListCategoryPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\BadRequestException; use Nette\Application\UI\Form; use Remp\MailerModule\Forms\IFormFactory; use Remp\MailerModule\Forms\ListCategoryFormFactory; use Remp\MailerModule\Repositories\ListCategoriesRepository; final class ListCategoryPresenter extends BasePresenter { public function __construct( private readonly ListCategoriesRepository $listCategoriesRepository, private readonly ListCategoryFormFactory $listCategoryFormFactory ) { parent::__construct(); } public function renderEdit($id): void { $listCategory = $this->listCategoriesRepository->find($id); if (!$listCategory) { throw new BadRequestException(); } $this->template->listCategory = $listCategory; } public function createComponentListCategoryForm(): Form { $id = null; if (isset($this->params['id'])) { $id = (int)$this->params['id']; } $form = $this->listCategoryFormFactory->create($id); $this->listCategoryFormFactory->onUpdate = function ($list, $buttonSubmitted) { $this->flashMessage('Newsletter list category was updated'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $list->id); }; return $form; } protected function redirectBasedOnButtonSubmitted(string $buttonSubmitted, int $itemID = null): void { if ($buttonSubmitted === IFormFactory::FORM_ACTION_SAVE_CLOSE || is_null($itemID)) { $this->redirect('List:Default'); } else { $this->redirect('Edit', $itemID); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/SignPresenter.php
Mailer/extensions/mailer-module/src/Presenters/SignPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Form; use Nette\Application\UI\Presenter; use Remp\MailerModule\Forms\SignInFormFactory; final class SignPresenter extends Presenter { /** @var SignInFormFactory */ private $signInFormFactory; public function __construct(SignInFormFactory $signInFormFactory) { parent::__construct(); $this->signInFormFactory = $signInFormFactory; } public function renderIn(): void { if ($this->getUser()->isLoggedIn()) { $this->redirect('Dashboard:Default'); } } public function actionOut(): void { $this->getUser()->logout(); $this->flashMessage('You have been successfully signed out'); $this->redirect('in'); } public function renderError(): void { $this->template->error = $this->request->getParameter('error'); } protected function createComponentSignInForm(): Form { $form = $this->signInFormFactory->create(); $presenter = $this; $this->signInFormFactory->onSignIn = function ($user) use ($presenter) { $presenter->flashMessage("Welcome {$user->email}"); $presenter->redirect('Dashboard:Default'); }; return $form; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/MailGeneratorPresenter.php
Mailer/extensions/mailer-module/src/Presenters/MailGeneratorPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Form; use Remp\MailerModule\Components\GeneratorWidgets\GeneratorWidgets; use Remp\MailerModule\Components\GeneratorWidgets\IGeneratorWidgetsFactory; use Remp\MailerModule\Forms\MailGeneratorFormFactory; use Remp\MailerModule\Repositories\SourceTemplatesRepository; final class MailGeneratorPresenter extends BasePresenter { const SESSION_SECTION_CONTENT_PREVIEW = "content_preview"; private $sourceTemplatesRepository; private $mailGeneratorFormFactory; private $generatorWidgetsFactory; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, MailGeneratorFormFactory $mailGeneratorFormFactory, IGeneratorWidgetsFactory $generatorWidgetsFactory ) { parent::__construct(); $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->mailGeneratorFormFactory = $mailGeneratorFormFactory; $this->generatorWidgetsFactory = $generatorWidgetsFactory; } public function renderDefault(): void { $this->template->last = $this->sourceTemplatesRepository->findLast()->fetch(); } public function renderPreview($isLocked): void { $section = $this->session->getSection(self::SESSION_SECTION_CONTENT_PREVIEW); $this->template->content = $isLocked ? $section->generatedLockedHtml : $section->generatedHtml; } protected function createComponentMailGeneratorForm(): Form { $sourceTemplateId = $this->getSourceTemplateIdParameter(); $form = $this->mailGeneratorFormFactory->create($sourceTemplateId, function ($htmlContent, $textContent, $controlParams = []) { $this->template->htmlContent = $htmlContent; $this->template->textContent = $textContent; $this->template->addonParams = $controlParams; }, function ($destination) { return $this->link($destination); }); return $form; } protected function createComponentGeneratorWidgets(): GeneratorWidgets { return $this->generatorWidgetsFactory->create($this->getSourceTemplateIdParameter()); } private function getSourceTemplateIdParameter(): int { $sourceTemplateId = $this->request->getParameter('source_template_id'); if (!$sourceTemplateId) { $sourceTemplateId = $this->request->getPost('source_template_id'); } return (int)$sourceTemplateId; } public function handleSourceTemplateChange($sourceTemplateId): void { $this->template->range = $sourceTemplateId; $this->template->redraw = true; $this->redrawControl('mailFormWrapper'); $this->redrawControl('wrapper'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/TemplatePresenter.php
Mailer/extensions/mailer-module/src/Presenters/TemplatePresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Exception; use Http\Discovery\Exception\NotFoundException; use Nette\Application\BadRequestException; use Nette\Application\UI\Control; use Nette\Application\UI\Form; use Remp\MailerModule\Components\MailLinkStats\MailLinkStats; use Remp\MailerModule\Forms\IFormFactory; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Config\EditorConfig; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Models\ContentGenerator\Replace\RtmClickReplace; use Remp\MailerModule\Repositories\ActiveRow; use Nette\Utils\Json; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Components\SendingStats\ISendingStatsFactory; use Remp\MailerModule\Models\ContentGenerator\ContentGenerator; use Remp\MailerModule\Forms\TemplateFormFactory; use Remp\MailerModule\Forms\TemplateTestFormFactory; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\LayoutTranslationsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\TemplateTranslationsRepository; final class TemplatePresenter extends BasePresenter { public function __construct( private TemplatesRepository $templatesRepository, private LogsRepository $logsRepository, private TemplateFormFactory $templateFormFactory, private TemplateTestFormFactory $templateTestFormFactory, private LayoutsRepository $layoutsRepository, private SnippetsRepository $snippetsRepository, private ListsRepository $listsRepository, private ContentGenerator $contentGenerator, private DataTableFactory $dataTableFactory, private ISendingStatsFactory $sendingStatsFactory, private GeneratorInputFactory $generatorInputFactory, private LayoutTranslationsRepository $layoutTranslationsRepository, private TemplateTranslationsRepository $templateTranslationsRepository, private MailLinkStats $mailLinkStats, private Config $config, private EditorConfig $editorConfig, ) { parent::__construct(); } public function createComponentDataTableDefault(): DataTable { $mailTypePairs = $this->listsRepository->all()->fetchPairs('id', 'title'); $mailLayoutPairs = $this->layoutsRepository->all()->fetchPairs('id', 'name'); $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 1, ]) ->setColSetting('code', [ 'priority' => 2, ]) ->setColSetting('subject', [ 'priority' => 1, 'render' => 'link' ]) ->setColSetting('type', [ 'orderable' => false, 'filter' => $mailTypePairs, 'priority' => 1, 'search' => $this->params['type'] ?? null, ]) ->setColSetting('layout', [ 'orderable' => false, 'filter' => $mailLayoutPairs, 'priority' => 1, 'search' => $this->params['layout'] ?? null, ]) ->setColSetting('opened', [ 'orderable' => false, 'priority' => 3, 'render' => 'number', 'class' => 'text-right', ]) ->setColSetting('clicked', [ 'orderable' => false, 'priority' => 3, 'render' => 'number', 'class' => 'text-right', ]) ->setRowAction('show', 'palette-Cyan zmdi-eye', 'Show template') ->setRowAction('edit', 'palette-Cyan zmdi-edit', 'Edit template') ->setRowAction('duplicate', 'palette-Cyan zmdi-copy', 'Duplicate template') ->setRowAction('delete', 'palette-Red zmdi-delete', 'Delete template', [ 'onclick' => 'return confirm(\'Are you sure you want to delete this item?\');' ]) ->setTableSetting('order', Json::encode([[0, 'DESC']])) ->setTableSetting('exportColumns', [0,1,2,3,4,5]); return $dataTable; } public function renderDefaultJsonData(): void { $request = $this->request->getParameters(); $mailTypeIds = $this->getColumnValue('type', $request['columns']); $mailLayoutIds = $this->getColumnValue('layout', $request['columns']); $query = $request['search']['value']; $order = $request['columns'][$request['order'][0]['column']]['name']; $orderDir = $request['order'][0]['dir']; $templatesCount = $this->templatesRepository ->tableFilter($query, $order, $orderDir, $mailTypeIds, $mailLayoutIds) ->count('*'); $templates = $this->templatesRepository ->tableFilter($query, $order, $orderDir, $mailTypeIds, $mailLayoutIds, (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->templatesRepository->totalCount(), 'recordsFiltered' => $templatesCount, 'data' => [] ]; /** @var ActiveRow $template */ foreach ($templates as $template) { $editUrl = $this->link('Edit', $template->id); $result['data'][] = [ 'actions' => [ 'show' => $this->link('Show', $template->id), 'edit' => $this->link('Edit', $template->id), 'duplicate' => $this->link('Duplicate!', $template->id), 'delete' => $this->link('Delete!', $template->id), ], $template->created_at, $template->code, [ 'url' => $editUrl, 'text' => $template->subject ], $template->type->title, $template->mail_layout->name, $template->related('mail_job_batch_template')->sum('opened') + $template->related('mail_logs', 'mail_template_id')->where('mail_job_id IS NULL')->count('opened_at'), $template->related('mail_job_batch_template')->sum('clicked') + $template->related('mail_logs', 'mail_template_id')->where('mail_job_id IS NULL')->count('clicked_at'), ]; } $this->presenter->sendJson($result); } private function getColumnValue($columnName, $columns) { foreach ($columns as $column) { if ($column['name'] !== $columnName) { continue; } if (!empty($column['search']['value'])) { return explode(',', $column['search']['value']); } break; } return null; } public function renderShow($id): void { $template = $this->templatesRepository->find($id); if (!$template) { throw new BadRequestException(); } $this->template->mailTemplate = $template; $this->template->isClickTrackerEnabled = $this->config->get(RtmClickReplace::CONFIG_NAME) && ($template->click_tracking === null || $template->click_tracking); } public function actionShowByCode($id): void { $template = $this->templatesRepository->getByCode($id); if (!$template) { throw new NotFoundException('', 404); } $this->redirect('show', ['id' => $template->id]); } public function createComponentDataTableLogs(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('logJsonData')) ->setColSetting('created_at', [ 'header' => 'sent at', 'render' => 'date', 'priority' => 1, ]) ->setColSetting('email', [ 'orderable' => false, 'priority' => 1, ]) ->setColSetting('subject', [ 'orderable' => false, 'priority' => 1, ]) ->setColSetting('events', [ 'render' => 'badge', 'orderable' => false, 'priority' => 2, ]) ->setTableSetting('remove-search') ->setTableSetting('order', Json::encode([[2, 'DESC']])) ->setTableSetting('add-params', Json::encode(['templateId' => $this->getParameter('id')])); return $dataTable; } public function renderLogJsonData(): void { $request = $this->request->getParameters(); $logsCount = $this->logsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], null, null, (int)$request['templateId']) ->count('*'); $logs = $this->logsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], (int)$request['length'], (int)$request['start'], (int)$request['templateId']) ->fetchAll(); $result = [ 'recordsTotal' => $this->logsRepository->totalCount(), 'recordsFiltered' => $logsCount, 'data' => [] ]; foreach ($logs as $log) { $result['data'][] = [ 'RowId' => $log->id, $log->created_at, $log->email, $log->subject, [ isset($log->delivered_at) ? ['text' => 'Delivered', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->dropped_at) ? ['text' => 'Dropped', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->spam_complained_at) ? ['text' => 'Span', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->hard_bounced_at) ? ['text' => 'Hard Bounce', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->clicked_at) ? ['text' => 'Clicked', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->opened_at) ? ['text' => 'Opened', 'class' => 'palette-Cyan-700 bg'] : '', ], ]; } $this->presenter->sendJson($result); } public function renderNew(): void { $layouts = $this->layoutsRepository->all()->fetchPairs('id', 'layout_html'); $snippets = $this->snippetsRepository->getTable()->select('code')->group('code')->fetchAssoc('code'); $lists = $this->listsRepository->all()->fetchAssoc('id'); $this->template->layouts = $layouts; $this->template->snippets = $snippets; $this->template->lists = $lists; $this->template->templateEditor = $this->editorConfig->getTemplateEditor(); $this->template->editedLocale = null; } public function renderEdit($id, string $editedLocale = null): void { $template = $this->templatesRepository->find($id); if (!$template) { throw new BadRequestException(); } $layouts = $this->layoutsRepository->all()->fetchAssoc('id'); if ($editedLocale && $editedLocale !== $this->localizationConfig->getDefaultLocale()) { $layoutTranslations = $this->layoutTranslationsRepository->getTranslationsForLocale($editedLocale) ->fetchAssoc('mail_layout_id'); foreach ($layouts as $layoutId => $layout) { if (isset($layoutTranslations[$layoutId])) { $layouts[$layoutId] = $layoutTranslations[$layoutId]; } } } $snippets = $this->snippetsRepository->getTable()->select('code')->group('code')->fetchAssoc('code'); $lists = $this->listsRepository->all()->fetchAssoc('id'); $this->template->mailTemplate = $template; $this->template->layouts = $layouts; $this->template->snippets = $snippets; $this->template->lists = $lists; $this->template->templateEditor = $this->editorConfig->getTemplateEditor(); $this->template->editedLocale = $editedLocale; } public function renderPreview($id, $type = 'html', $lang = null): void { $template = $this->templatesRepository->find($id); if (!$template) { throw new BadRequestException(); } try { $mailContent = $this->contentGenerator->render($this->generatorInputFactory->create($template, [], null, $lang)); $this->template->content = ($type === 'html') ? $mailContent->html() : "<pre>{$mailContent->text()}</pre>"; } catch (Exception $exception) { $this->template->content = $exception->getMessage(); } } public function handleDuplicate($id): void { $template = $this->templatesRepository->find($id); $newTemplate = $this->templatesRepository->duplicate($template); $this->templateTranslationsRepository->duplicate($template, $newTemplate); $this->flashMessage('Email was duplicated.'); $this->redirect('edit', $newTemplate->id); } public function createComponentTemplateForm(): Form { $id = isset($this->params['id']) ? (int)$this->params['id'] : null; $lang = $this->getParameter('editedLocale'); if ($lang && $lang === $this->localizationConfig->getDefaultLocale()) { $lang = null; } $form = $this->templateFormFactory->create($id, $lang); $presenter = $this; $this->templateFormFactory->onCreate = function ($template, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Email was created'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $template->id); }; $this->templateFormFactory->onUpdate = function ($template, $buttonSubmitted) use ($presenter) { $presenter->flashMessage('Email was updated'); $this->redirectBasedOnButtonSubmitted($buttonSubmitted, $template->id); }; return $form; } public function createComponentTemplateTestForm(): Form { $form = $this->templateTestFormFactory->create((int)$this->params['id']); $presenter = $this; $this->templateTestFormFactory->onSuccess = function ($template) use ($presenter) { $presenter->flashMessage('Email was sent'); $presenter->redirect('Show', $template->id); }; return $form; } protected function createComponentTemplateStats(): Control { $templateStats = $this->sendingStatsFactory->create(); if (isset($this->params['id'])) { $template = $this->templatesRepository->find($this->params['id']); $templateStats->addTemplate($template); $templateStats->showTotal(); } return $templateStats; } protected function createComponentMailLinkStats(): Control { $template = $this->templatesRepository->find($this->params['id']); return $this->mailLinkStats->create($template); } protected function redirectBasedOnButtonSubmitted(string $buttonSubmitted, int $itemID = null): void { if ($buttonSubmitted === IFormFactory::FORM_ACTION_SAVE_CLOSE || is_null($itemID)) { $this->redirect('Default'); } else { $this->redirect('Edit', ['id' => $itemID, 'editedLocale' => $this->getParameter('editedLocale')]); } } public function handleDelete($id): void { $template = $this->templatesRepository->find($id); $this->templatesRepository->softDelete($template); $this->flashMessage("Template {$template->name} was deleted."); $this->redirect('default'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/LogPresenter.php
Mailer/extensions/mailer-module/src/Presenters/LogPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Crm\ApplicationModule\Repository\AuditLogRepository; use Nette\Application\UI\Form; use Nette\Utils\DateTime; use Nette\Utils\Json; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Tomaj\Form\Renderer\BootstrapInlineRenderer; final class LogPresenter extends BasePresenter { /** @persistent */ public $email; /** @persistent */ public $created_at_from; /** @persistent */ public $created_at_to; /** @persistent */ public $mail_template_code; private $logsRepository; private $dataTableFactory; private $templatesRepository; public function __construct( LogsRepository $logsRepository, DataTableFactory $dataTableFactory, TemplatesRepository $templatesRepository ) { parent::__construct(); $this->logsRepository = $logsRepository; $this->dataTableFactory = $dataTableFactory; $this->templatesRepository = $templatesRepository; } public function startup(): void { parent::startup(); if ($this->created_at_from === null) { $this->created_at_from = (new DateTime())->modify('-1 day')->format('m/d/Y H:i A'); } if ($this->created_at_to === null) { $this->created_at_to = (new DateTime())->format('m/d/Y H:i A'); } } public function createComponentDataTableDefault(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('created_at', [ 'header' => 'sent at', 'render' => 'date', 'priority' => 1, ]) ->setColSetting('email', [ 'priority' => 1, 'render' => 'text', ]) ->setColSetting('subject', [ 'priority' => 1, 'render' => 'text', ]) ->setColSetting('mail_template_id', [ 'header' => 'template code', 'render' => 'link', 'orderable' => false, 'priority' => 2, ]) ->setColSetting('attachment_size', [ 'header' => 'attachment', 'render' => 'bytes', 'class' => 'text-right', 'priority' => 2, ]) ->setColSetting('events', [ 'render' => 'badge', 'orderable' => false, 'priority' => 3, ]) ->setTableSetting('order', Json::encode([[0, 'DESC']])) ->setTableSetting('allowSearch', false); return $dataTable; } private function isFilterActive() { if ($this->email) { return true; } if ($this->mail_template_code) { return true; } if ($this->created_at_from) { return true; } if ($this->created_at_to) { return true; } return false; } public function renderDefaultJsonData(): void { $request = $this->request->getParameters(); $mailTemplateId = null; if ($this->mail_template_code) { $mailTemplate = $this->templatesRepository->getByCode($this->mail_template_code); if ($mailTemplate) { $mailTemplateId = $mailTemplate->id; } else { $this->mail_template_code = null; } } $logsCount = 0; $logs = []; if ($this->isFilterActive()) { $logsCount = $this->logsRepository ->tableFilter( $this->email ?? '', $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], null, null, $mailTemplateId, $this->created_at_from ? DateTime::createFromFormat('m/d/Y H:i A', $this->created_at_from) : null, $this->created_at_to ? DateTime::createFromFormat('m/d/Y H:i A', $this->created_at_to) : null, )->count('*'); $logs = $this->logsRepository ->tableFilter( $this->email ?? '', $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], (int)$request['length'], (int)$request['start'], $mailTemplateId, $this->created_at_from ? DateTime::createFromFormat('m/d/Y H:i A', $this->created_at_from) : null, $this->created_at_to ? DateTime::createFromFormat('m/d/Y H:i A', $this->created_at_to) : null, )->fetchAll(); } $result = [ 'recordsFiltered' => $logsCount, 'data' => [] ]; foreach ($logs as $log) { $result['data'][] = [ 'RowId' => $log->id, $log->created_at, $log->email, $log->subject, [ 'url' => $this->link( 'Template:Show', ['id' => $log->mail_template_id] ), 'text' => $log->mail_template->code ?? null ], $log->attachment_size, [ isset($log->delivered_at) ? ['text' => 'Delivered', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->dropped_at) ? ['text' => 'Dropped', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->spam_complained_at) ? ['text' => 'Span', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->hard_bounced_at) ? ['text' => 'Hard Bounce', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->clicked_at) ? ['text' => 'Clicked', 'class' => 'palette-Cyan-700 bg'] : '', isset($log->opened_at) ? ['text' => 'Opened', 'class' => 'palette-Cyan-700 bg'] : '', ], ]; } $this->presenter->sendJson($result); } public function createComponentFilterLogsForm() { $form = new Form; $form->setRenderer(new BootstrapInlineRenderer()); $form->setHtmlAttribute('class', 'form-logs-filter'); $form->addText('email', 'E-mail'); $form->addText('mail_template_code', 'Mail template code'); $form->addText('created_at_from', 'Sent from')->setRequired('Field `Sent from` is required'); $form->addText('created_at_to', 'Sent to')->setRequired('Field `Sent to` is required'); $form->addSubmit('send') ->getControlPrototype() ->setName('button') ->setHtml('<i class="fa fa-filter"></i> Filter'); $presenter = $this; $form->addSubmit('cancel', 'Cancel')->onClick[] = function () use ($presenter) { $presenter->redirect('Log:Default', [ 'email' => null, 'mail_template_code' => null, 'created_at_from' => null, 'created_at_to' => null, ]); }; $form->onSuccess[] = [$this, 'adminFilterSubmitted']; $form->setDefaults([ 'email' => $this->email, 'created_at_from' => $this->created_at_from, 'created_at_to' => $this->created_at_to, 'mail_template_code' => $this->mail_template_code, ]); return $form; } public function adminFilterSubmitted($form, $values) { $this->redirect($this->action, (array) $values); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/SettingsPresenter.php
Mailer/extensions/mailer-module/src/Presenters/SettingsPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use Nette\Application\UI\Form; use Remp\MailerModule\Forms\ConfigFormFactory; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Mailer\Mailer; use Remp\MailerModule\Models\Sender\MailerFactory; final class SettingsPresenter extends BasePresenter { private $mailerFactory; private $configFormFactory; private $config; public function __construct(MailerFactory $mailerFactory, ConfigFormFactory $configFormFactory, Config $config) { parent::__construct(); $this->mailerFactory = $mailerFactory; $this->configFormFactory = $configFormFactory; $this->config = $config; } public function renderDefault(): void { $availableMailers = $this->mailerFactory->getAvailableMailers(); $requiredFields = []; array_walk($availableMailers, function (Mailer $mailer, $name) use (&$requiredFields) { $requiredFields[$name] = $mailer->getRequiredOptions(); }); $this->template->requiredFields = $requiredFields; } public function createComponentConfigForm(): Form { $form = $this->configFormFactory->create(); $this->configFormFactory->onSuccess = function () { $this->flashMessage('Config was updated.'); $this->redirect('Settings:default'); }; return $form; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Presenters/ListPresenter.php
Mailer/extensions/mailer-module/src/Presenters/ListPresenter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Presenters; use DateInterval; use DateTimeZone; use Nette\Application\BadRequestException; use Nette\Application\UI\Form; use Nette\Utils\DateTime; use Nette\Utils\Json; use Remp\MailerModule\Components\DataTable\DataTable; use Remp\MailerModule\Components\DataTable\DataTableFactory; use Remp\MailerModule\Forms\DuplicateListFormFactory; use Remp\MailerModule\Forms\ListFormFactory; use Remp\MailerModule\Hermes\HermesMessage; use Remp\MailerModule\Hermes\RedisDriver; use Remp\MailerModule\Models\ChartTrait; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; use Remp\MailerModule\Repositories\MailTemplateStatsRepository; use Remp\MailerModule\Repositories\MailTypeStatsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Tomaj\Hermes\Emitter; final class ListPresenter extends BasePresenter { use ChartTrait; public function __construct( private readonly ListsRepository $listsRepository, private readonly TemplatesRepository $templatesRepository, private readonly MailTypeStatsRepository $mailTypeStatsRepository, private readonly MailTemplateStatsRepository $mailTemplateStatsRepository, private readonly UserSubscriptionsRepository $userSubscriptionsRepository, private readonly ListFormFactory $listFormFactory, private readonly DuplicateListFormFactory $duplicateListFormFactory, private readonly ListVariantsRepository $listVariantsRepository, private readonly Emitter $emitter, private readonly DataTableFactory $dataTableFactory, ) { parent::__construct(); } public function createComponentDataTableDefault(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setColSetting('category', [ 'visible' => false, 'priority' => 1, ]) ->setColSetting('title', [ 'priority' => 1, 'render' => 'link' ]) ->setColSetting('code', [ 'priority' => 2, 'render' => 'text', ]) ->setColSetting('subscribed', [ 'render' => 'number', 'priority' => 2, ]) ->setColSetting('auto_subscribe', [ 'header' => 'auto subscribe', 'render' => 'boolean', 'priority' => 3, ]) ->setColSetting('locked', [ 'render' => 'boolean', 'priority' => 2, ]) ->setColSetting('public_listing', [ 'header' => 'publicly listed', 'render' => 'boolean', 'priority' => 3, ]) ->setAllColSetting('orderable', false) ->setRowAction('show', 'palette-Cyan zmdi-eye', 'Show list') ->setRowAction('edit', 'palette-Cyan zmdi-edit', 'Edit list') ->setRowAction('duplicate', 'palette-Cyan zmdi-copy', 'Duplicate list') ->setRowAction('delete', 'palette-Red zmdi-delete', 'Delete list', [ 'onclick' => 'return confirm(\'Are you sure you want to delete this item?\');' ]) ->setRowAction('sentEmailsDetail', 'palette-Cyan zmdi-chart', 'List stats') ->setTableSetting('displayNavigation', false) ->setTableSetting('rowGroup', 0) ->setTableSetting('rowGroupActions', 'groupActions'); return $dataTable; } public function renderDefaultJsonData(): void { $lists = $this->listsRepository->tableFilter(); $listsCount = $lists->count('*'); $result = [ 'recordsTotal' => $listsCount, 'recordsFiltered' => $listsCount, 'data' => [] ]; /** @var ActiveRow $list */ foreach ($lists as $list) { $showUrl = $this->link('Show', $list->id); $editUrl = $this->link('Edit', $list->id); $duplicateUrl = $this->link('Duplicate', $list->id); $deleteUrl = $this->link('Delete!', $list->id); $sentEmailsDetail = $this->link('sentEmailsDetail', $list->id); $editCategory = $this->link('ListCategory:edit', $list->mail_type_category_id); $result['data'][] = [ 'actions' => [ 'show' => $showUrl, 'edit' => $editUrl, 'duplicate' => $duplicateUrl, 'delete' => $deleteUrl, 'sentEmailsDetail' => $sentEmailsDetail, ], $list->type_category->title ?? null, [ 'url' => $showUrl, 'text' => $list->title, ], $list->code, $list->related('mail_user_subscriptions')->where(['subscribed' => true])->count('*'), $list->auto_subscribe, $list->locked, $list->public_listing, 'groupActions' => [ [ 'url' => $editCategory, 'title' => 'Edit category', 'icon' => 'palette-Cyan zmdi-edit', ] ] ]; } $this->presenter->sendJson($result); } public function renderShow($id): void { $list = $this->listsRepository->find($id); if (!$list) { throw new BadRequestException(); } $week = new DateTime('-7 days'); $month = new DateTime('-30 days'); $this->template->stats = [ 'subscribed' => $list->related('mail_user_subscriptions') ->where(['subscribed' => true]) ->count('*'), 'un-subscribed' => $list->related('mail_user_subscriptions') ->where(['subscribed' => false]) ->count('*'), 'opened' => [ '7-days' => $this->mailTemplateStatsRepository->byMailTypeId($list->id) ->where('date > DATE(?)', $week) ->select('SUM(mail_template_stats.opened) AS opened') ->fetch()->opened ?? 0, '30-days' => $this->mailTemplateStatsRepository->byMailTypeId($list->id) ->where('date > DATE(?)', $month) ->select('SUM(mail_template_stats.opened) AS opened') ->fetch()->opened ?? 0, ], 'clicked' => [ '7-days' => $this->mailTemplateStatsRepository->byMailTypeId($list->id) ->where('date > DATE(?)', $week) ->select('SUM(mail_template_stats.clicked) AS opened') ->fetch()->opened ?? 0, '30-days' => $this->mailTemplateStatsRepository->byMailTypeId($list->id) ->where('date > DATE(?)', $month) ->select('SUM(mail_template_stats.clicked) AS opened') ->fetch()->opened ?? 0, ] ]; $this->template->list = $list; $this->prepareDetailSubscribersGraphData($id); } public function prepareDetailSubscribersGraphData($id): void { $labels = []; $numOfDays = 30; $now = new DateTime(); $from = (clone $now)->sub(new DateInterval('P' . $numOfDays . 'D')); // fill graph columns for ($i = $numOfDays; $i >= 0; $i--) { $labels[] = DateTime::from('-' . $i . ' days')->format('Y-m-d'); } $mailType = $this->listsRepository->find($id); $dataSet = [ 'label' => $mailType->title, 'data' => array_fill(0, $numOfDays, 0), 'backgroundColor' => '#008494', ]; $data = $this->mailTypeStatsRepository->getDashboardDetailData($id, $from, $now); $minRow = reset($data); foreach ($data as $row) { $minRow = $row->count < $minRow->count ? $row : $minRow; } // parse sent mails by type data to chart.js format foreach ($data as $row) { $foundAt = array_search( DateTime::from($row->created_date)->format('Y-m-d'), $labels ); if ($foundAt !== false) { $dataSet['data'][$foundAt] = $row->count; } } $this->template->suggestedMin = $this->getChartSuggestedMin([$dataSet['data']]); $this->template->dataSet = $dataSet; $this->template->labels = $labels; } public function renderEdit($id): void { $list = $this->listsRepository->find($id); if (!$list) { throw new BadRequestException(); } $this->template->list = $list; } public function renderDuplicate($id): void { $list = $this->listsRepository->find($id); if (!$list) { throw new BadRequestException(); } $variantsCount = $this->listVariantsRepository->getVariantsForType($list)->count('*'); if ($variantsCount !== 0) { $this->flashMessage('Source list has variants. Duplication is not implemented.', 'danger'); $this->redirect('default'); } $this->template->list = $list; } public function createComponentDataTableTemplates(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('templateJsonData')) ->setColSetting('created_at', [ 'header' => 'created at', 'render' => 'date', 'priority' => 1, ]) ->setColSetting('subject', [ 'priority' => 1, 'render' => 'text' ]) ->setColSetting('opened', [ 'priority' => 2, ]) ->setColSetting('clicked', [ 'priority' => 2, ]) ->setRowAction('show', 'palette-Cyan zmdi-eye', 'Show template') ->setTableSetting('add-params', Json::encode(['listId' => $this->getParameter('id')])) ->setTableSetting('order', Json::encode([[0, 'DESC']])); return $dataTable; } public function renderTemplateJsonData(): void { $request = $this->request->getParameters(); $templatesCount = $this->templatesRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], [$request['listId']]) ->count('*'); $templates = $this->templatesRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], [$request['listId']], null, (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $this->templatesRepository->totalCount(), 'recordsFiltered' => $templatesCount, 'data' => [] ]; /** @var ActiveRow $template */ foreach ($templates as $template) { $opened = 0; $clicked = 0; /** @var ActiveRow $jobBatchTemplate */ foreach ($template->related('mail_job_batch_template') as $jobBatchTemplate) { $opened += $jobBatchTemplate->opened; $clicked += $jobBatchTemplate->clicked; } $result['data'][] = [ 'actions' => [ 'show' => $this->link('Template:Show', $template->id), ], $template->created_at, $template->subject, $opened, $clicked, ]; } $this->presenter->sendJson($result); } public function createComponentDataTableVariants(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('variantsJsonData')) ->setColSetting('title', [ 'header' => 'Title', 'priority' => 1, 'render' => 'text', ]) ->setColSetting('code', [ 'header' => 'Code', 'priority' => 1, 'render' => 'code', ]) ->setColSetting('count', [ 'priority' => 1, ]) ->setTableSetting('add-params', Json::encode(['listId' => $this->getParameter('id')])) ->setTableSetting('order', Json::encode([[2, 'DESC']])); return $dataTable; } public function renderVariantsJsonData(): void { $request = $this->request->getParameters(); $listId = $request['listId'] ? (int)$request['listId'] : null; $length = $request['length'] ? (int)$request['length'] : null; $start = $request['start'] ? (int)$request['start'] : null; $variantsCount = $this->listVariantsRepository ->tableFilter( $request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], [$listId] ) ->count('*'); $variants = $this->listVariantsRepository ->tableFilter( $request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], [$listId], $length, $start ); $result = [ 'recordsTotal' => $this->listVariantsRepository->totalCount(), 'recordsFiltered' => $variantsCount, 'data' => [] ]; /** @var ActiveRow $variant */ foreach ($variants as $variant) { $result['data'][] = [ $variant->title, $variant->code, $variant->count, ]; } $this->presenter->sendJson($result); } public function createComponentListForm(): Form { $id = null; if (isset($this->params['id'])) { $id = (int)$this->params['id']; } $form = $this->listFormFactory->create($id); $presenter = $this; $this->listFormFactory->onCreate = function ($list) use ($presenter) { $this->emitter->emit(new HermesMessage('list-created', [ 'list_id' => $list->id, ]), RedisDriver::PRIORITY_HIGH); $presenter->flashMessage('Newsletter list was created'); $presenter->redirect('Show', $list->id); }; $this->listFormFactory->onUpdate = function ($list) use ($presenter) { $this->emitter->emit(new HermesMessage('list-updated', [ 'list_id' => $list->id, ]), RedisDriver::PRIORITY_HIGH); $presenter->flashMessage('Newsletter list was updated'); $presenter->redirect('Edit', $list->id); }; return $form; } public function createComponentDuplicateListForm(): Form { if (!isset($this->params['id'])) { throw new BadRequestException(); } $sourceListId = (int)$this->params['id']; $form = $this->duplicateListFormFactory->create($sourceListId); $presenter = $this; $this->duplicateListFormFactory->onCreate = function ($newList, $sourceList, $copySubscribers) use ($presenter) { $this->emitter->emit(new HermesMessage('list-created', [ 'list_id' => $newList->id, 'source_list_id' => $sourceList->id, 'duplicate' => true, 'copy_subscribers' => $copySubscribers ]), RedisDriver::PRIORITY_HIGH); $presenter->flashMessage('Newsletter list was duplicated'); $presenter->redirect('Edit', $newList->id); }; return $form; } public function handleRenderSorting($categoryId, $sorting): void { $factory = $this->listFormFactory; // set sorting value $factory->getSortingControl($this['listForm'])->setValue($sorting); // handle newsletter list category change if ($factory->getMailTypeCategoryIdControl($this['listForm'])->getValue() !== $categoryId) { $lists = $this->listsRepository->findByCategory((int)$categoryId); if ($listId = $factory->getListIdControl($this['listForm'])->getValue()) { $lists = $lists->where('id != ?', $listId); } $lists = $lists->order('sorting ASC')->fetchPairs('sorting', 'title'); $factory->getSortingAfterControl($this['listForm'])->setItems($lists); } $this->redrawControl('wrapper'); $this->redrawControl('sortingAfterSnippet'); } public function renderSentEmailsDetail($id): void { $mailType = $this->listsRepository->find($id); $groupBy = $this->getParameter('group_by', 'day'); $this->template->mailTypeId = $mailType->id; $this->template->mailTypeTitle = $mailType->title; $this->template->groupBy = $groupBy; if (!$this->isAjax()) { $from = $this->getParameter('published_from', 'today - 30 days'); $to = $this->getParameter('published_to', 'now'); $tz = $this->getParameter('tz'); $this->template->from = $from; $this->template->to = $to; $data = $this->emailsDetailData($id, $from, $to, $groupBy, $tz); $this->template->labels = $data['labels']; $this->template->parser = $data['parser']; $this->template->tooltipFormat = $data['tooltipFormat']; $this->template->sentDataSet = $data['sentDataSet']; $this->template->openedDataSet = $data['openedDataSet']; $this->template->clickedDataSet = $data['clickedDataSet']; $this->template->openRateDataSet = $data['openRateDataSet']; $this->template->clickRateDataSet = $data['clickRateDataSet']; $this->template->unsubscibedDataSet = $data['unsubscibedDataSet']; } } public function emailsDetailData($id, $from, $to, $groupBy, $tz): array { $labels = []; if ($tz !== null) { $tz = new DateTimeZone($tz); } $from = new DateTime($from, $tz); $to = new DateTime($to, $tz); $dateFormat = 'Y-m-d'; $dateInterval = '+1 day'; $parser = 'YYYY-MM-DD'; $tooltipFormat = 'LL'; if ($groupBy === 'week') { $dateFormat = 'o-W'; $dateInterval = '+1 week'; $parser = 'YYYY-WW'; $tooltipFormat = 'w/YYYY'; } elseif ($groupBy === 'month') { $dateFormat = 'Y-m'; $dateInterval = '+1 month'; $parser = 'YYYY-MM'; $tooltipFormat = 'MMMM YY'; } $fromLimit = clone $from; while ($fromLimit < $to) { $labels[] = $fromLimit->format($dateFormat); $fromLimit = $fromLimit->modify($dateInterval); } $numOfGroups = count($labels); $sentDataSet = [ 'label' => 'Sent', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(0,150,136)', 'lineTension' => 0.2, ]; $openedDataSet = [ 'label' => 'Opened', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(33,150,243)', 'lineTension' => 0.2, ]; $clickedDataSet = [ 'label' => 'Clicked', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(230,57,82)', 'lineTension' => 0.2, ]; $data = $this->mailTemplateStatsRepository->getMailTypeGraphData((int) $id, $from, $to, $groupBy)->fetchAll(); // parse sent mails by type data to chart.js format foreach ($data as $row) { $foundAt = array_search( $row->label_date, $labels ); if ($foundAt !== false) { $sentDataSet['data'][$foundAt] += $row->sent_mails; $openedDataSet['data'][$foundAt] += $row->opened_mails; $clickedDataSet['data'][$foundAt] += $row->clicked_mails; } } $openRateDataSet = [ 'label' => 'Open rate', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(33,150,243)', 'lineTension' => 0.5 ]; $clickRateDataSet = [ 'label' => 'Click rate', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(230,57,82)', 'lineTension' => 0.5 ]; foreach ($sentDataSet['data'] as $key => $sent) { $open = $openedDataSet['data'][$key]; $click = $clickedDataSet['data'][$key]; if ($open > 0) { $openRateDataSet['data'][$key] = round(($open / $sent) * 100, 2); } else { $openRateDataSet['data'][$key] = 0; } if ($click > 0) { $clickRateDataSet['data'][$key] = round(($click / $sent) * 100, 2); } else { $clickRateDataSet['data'][$key] = 0; } } $unsubscibedDataSet = [ 'label' => 'Unsubscribed users', 'data' => array_fill(0, $numOfGroups, 0), 'fill' => false, 'borderColor' => 'rgb(230,57,82)', 'lineTension' => 0.5 ]; $unsubscribedData = $this->userSubscriptionsRepository->getMailTypeGraphData((int) $id, $from, $to, $groupBy) ->fetchAll(); foreach ($unsubscribedData as $unsubscibedDataRow) { $foundAt = array_search( $unsubscibedDataRow->label_date, $labels, true ); if ($foundAt !== false) { $unsubscibedDataSet['data'][$foundAt] += $unsubscibedDataRow->unsubscribed_users; } } return [ 'labels' => $labels, 'parser' => $parser, 'tooltipFormat' => $tooltipFormat, 'sentDataSet' => $sentDataSet, 'openedDataSet' => $openedDataSet, 'clickedDataSet' => $clickedDataSet, 'openRateDataSet' => $openRateDataSet, 'clickRateDataSet' => $clickRateDataSet, 'unsubscibedDataSet' => $unsubscibedDataSet ]; } public function handleFilterChanged($id, $from, $to, $group_by, $tz) { $data = $this->emailsDetailData($id, $from, $to, $group_by, $tz); $this->template->groupBy = $group_by; $this->template->labels = $data['labels']; $this->template->parser = $data['parser']; $this->template->tooltipFormat = $data['tooltipFormat']; $this->template->sentDataSet = $data['sentDataSet']; $this->template->openedDataSet = $data['openedDataSet']; $this->template->clickedDataSet = $data['clickedDataSet']; $this->template->openRateDataSet = $data['openRateDataSet']; $this->template->clickRateDataSet = $data['clickRateDataSet']; $this->template->unsubscibedDataSet = $data['unsubscibedDataSet']; $this->redrawControl('graph'); $this->redrawControl('relativeGraph'); $this->redrawControl('exportData'); } public function createComponentDataTableSubscriberEmails(): DataTable { $dataTable = $this->dataTableFactory->create(); $dataTable ->setSourceUrl($this->link('subscriberEmailsJsonData')) ->setColSetting('user_email', [ 'header' => 'user email', 'priority' => 1, 'render' => 'text', ]) ->setColSetting('updated_at', [ 'header' => 'subscribed at', 'render' => 'date', 'priority' => 1, ]) ->setTableSetting('add-params', Json::encode(['listId' => $this->getParameter('id')])) ->setTableSetting('order', Json::encode([[1, 'DESC']])); return $dataTable; } public function renderSubscriberEmailsJsonData(): void { $request = $this->request->getParameters(); $subscriberEmailsCount = $this->userSubscriptionsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], (int)$request['listId']) ->count('*'); $subscriberEmails = $this->userSubscriptionsRepository ->tableFilter($request['search']['value'], $request['columns'][$request['order'][0]['column']]['name'], $request['order'][0]['dir'], (int)$request['listId'], (int)$request['length'], (int)$request['start']) ->fetchAll(); $result = [ 'recordsTotal' => $subscriberEmailsCount, 'recordsFiltered' => $subscriberEmailsCount, 'data' => [] ]; /** @var ActiveRow $subscriberEmail */ foreach ($subscriberEmails as $subscriberEmail) { $result['data'][] = [ $subscriberEmail->user_email, $subscriberEmail->updated_at, ]; } $this->presenter->sendJson($result); } public function handleDelete($id): void { $list = $this->listsRepository->find($id); if ($this->listsRepository->canBeDeleted($list)) { $this->listsRepository->softDelete($list); $this->flashMessage("List {$list->code} was deleted."); $this->redirect('default'); } else { $this->flashMessage("There are emails using list {$list->code}.", 'danger'); $this->redirect('Template:default', ['type' => $list->id]); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/DI/MailerModuleExtension.php
Mailer/extensions/mailer-module/src/DI/MailerModuleExtension.php
<?php declare(strict_types=1); namespace Remp\MailerModule\DI; use Nette\DI\CompilerExtension; use Nette\DI\Definitions\FactoryDefinition; use Nette\DI\InvalidConfigurationException; use Nette\Schema\Expect; use Nette\Schema\Schema; use Remp\MailerModule\Latte\PermissionMacros; final class MailerModuleExtension extends CompilerExtension { public function getConfigSchema(): Schema { return Expect::structure([ 'redis_client_factory' => Expect::structure([ 'prefix' => Expect::string(), 'replication' => Expect::structure([ 'service' => Expect::string(), 'sentinels' => Expect::arrayOf(Expect::string()) ]) ]), ]); } public function loadConfiguration() { $builder = $this->getContainerBuilder(); // set extension parameters for use in config $config = (object) $this->getConfig(); $builder->parameters['redis_client_factory'] = (array) $config->redis_client_factory; // load services from config and register them to Nette\DI Container $this->compiler->loadDefinitionsFromConfig( $this->loadFromFile(__DIR__ . '/../config/config.neon')['services'] ); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210209133938_add_mailer_alias_column_to_mail_types.php
Mailer/extensions/mailer-module/src/migrations/20210209133938_add_mailer_alias_column_to_mail_types.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddMailerAliasColumnToMailTypes extends AbstractMigration { public function change(): void { $this->table('mail_types') ->addColumn( 'mailer_alias', 'string', [ 'null' => true, 'after' => 'default_variant_id' ] ) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20180305072535_mail_templates_encoding_fix.php
Mailer/extensions/mailer-module/src/migrations/20180305072535_mail_templates_encoding_fix.php
<?php use Phinx\Migration\AbstractMigration; class MailTemplatesEncodingFix extends AbstractMigration { public function up() { $this->table('mail_templates') ->changeColumn('name', 'string', ['null' => false, 'after' => 'id', 'encoding' => 'utf8mb4']) ->changeColumn('description', 'text', ['null' => false, 'after' => 'code', 'encoding' => 'utf8mb4']) ->save(); } public function down() { $this->table('mail_templates') ->changeColumn('description', 'string', ['null' => false, 'after' => 'code', 'encoding' => 'utf8']) ->changeColumn('name', 'string', ['null' => false, 'after' => 'id', 'encoding' => 'utf8']) ->save(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20201106130828_add_missing_subscription_user_id_index.php
Mailer/extensions/mailer-module/src/migrations/20201106130828_add_missing_subscription_user_id_index.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddMissingSubscriptionUserIdIndex extends AbstractMigration { public function change(): void { $this->table('mail_user_subscriptions') ->addIndex('user_id') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20180726110436_add_code_to_mail_source_template.php
Mailer/extensions/mailer-module/src/migrations/20180726110436_add_code_to_mail_source_template.php
<?php use Nette\Utils\Strings; use Phinx\Migration\AbstractMigration; class AddCodeToMailSourceTemplate extends AbstractMigration { public function change() { $this->table('mail_source_template') ->addColumn('code', 'string', ['null' => true, 'after' => 'title']) ->addIndex(['code'], ['unique' => true]) ->update(); foreach ($this->fetchAll('select * from mail_source_template') as $row) { $code = Strings::webalize($row['title']); $this->execute("UPDATE mail_source_template SET code='$code' WHERE id={$row['id']}"); } $this->table('mail_source_template') ->changeColumn('code', 'string', ['null' => false]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210217101856_snippets.php
Mailer/extensions/mailer-module/src/migrations/20210217101856_snippets.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class Snippets extends AbstractMigration { public function change(): void { $this->table('mail_snippets') ->addColumn('name', 'string') ->addColumn('code', 'string') ->addColumn('text', 'text') ->addColumn('html', 'text') ->addTimestamps() ->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20170829092343_initial_migration.php
Mailer/extensions/mailer-module/src/migrations/20170829092343_initial_migration.php
<?php use Phinx\Migration\AbstractMigration; class InitialMigration extends AbstractMigration { public function change() { if (!$this->hasTable('configs')) { $this->table('configs') ->addColumn('name', 'string') ->addColumn('display_name', 'string') ->addColumn('value', 'text', ['null' => true]) ->addColumn('description', 'text', ['null' => true]) ->addColumn('type', 'string', ['default' => 'text']) ->addColumn('sorting', 'integer', ['default' => 10]) ->addColumn('autoload', 'boolean', ['default' => true]) ->addColumn('locked', 'boolean', ['default' => false]) ->addTimestamps() ->create(); } $this->table('mail_type_categories') ->addColumn('title', 'string') ->addColumn('sorting', 'integer') ->addTimestamps() ->create(); $this->table('mail_layouts') ->addColumn('name', 'string') ->addColumn('layout_text', 'text') ->addColumn('layout_html', 'text') ->addTimestamps() ->create(); $this->table('mail_types') ->addColumn('code', 'string') ->addColumn('locked', 'boolean', ['default' => false]) ->addColumn('is_public', 'boolean') ->addColumn('auto_subscribe', 'boolean', ['default' => false]) ->addColumn('title', 'string') ->addColumn('sorting', 'integer', ['default' => 10]) ->addColumn('description', 'text') ->addColumn('priority', 'integer', ['default' => 100]) ->addColumn('mail_type_category_id', 'integer', ['null' => true]) ->addColumn('image_url', 'string', ['null' => true]) ->addColumn('preview_url', 'string', ['null' => true]) ->addColumn('default_variant_id', 'integer', ['null' => true]) ->addForeignKey('mail_type_category_id', 'mail_type_categories', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_type_variants') ->addColumn('mail_type_id', 'integer') ->addColumn('title', 'string') ->addColumn('code', 'string') ->addColumn('sorting', 'integer') ->addForeignKey('mail_type_id', 'mail_types', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_types') ->addForeignKey('default_variant_id', 'mail_type_variants', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->save(); $this->table('mail_templates') ->addColumn('name', 'string') ->addColumn('code', 'string') ->addColumn('description', 'text', ['null' => true]) ->addColumn('from', 'string') ->addColumn('subject', 'string', ['null' => true]) ->addColumn('mail_body_text', 'text') ->addColumn('mail_body_html', 'text') ->addColumn('mail_layout_id', 'integer', ['null' => true]) ->addColumn('copy_from', 'integer', ['null' => true]) ->addColumn('autologin', 'integer') ->addColumn('mail_type_id', 'integer') ->addForeignKey('mail_layout_id', 'mail_layouts', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('mail_type_id', 'mail_types', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('copy_from', 'mail_templates', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addIndex('code') ->addTimestamps() ->create(); $this->table('mail_jobs') ->addColumn('segment_code', 'string') ->addColumn('segment_provider', 'string') ->addColumn('mail_type_variant_id', 'integer', ['null' => true]) ->addColumn('status', 'string') ->addColumn('emails_sent_count', 'integer', ['default' => 0]) ->addForeignKey('mail_type_variant_id', 'mail_type_variants', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_job_batch') ->addColumn('mail_job_id', 'integer') ->addColumn('method', 'string') ->addColumn('max_emails', 'integer', ['null' => true]) ->addColumn('start_at', 'timestamp', ['null' => true]) ->addColumn('sent_emails', 'integer', ['default' => 0]) ->addColumn('status', 'string', ['default' => 'created']) ->addColumn('pid', 'integer', ['null' => true]) ->addColumn('last_ping', 'timestamp', ['null' => true]) ->addColumn('errors_count', 'integer', ['default' => 0]) ->addColumn('first_email_sent_at', 'timestamp', ['null' => true]) ->addColumn('last_email_sent_at', 'timestamp', ['null' => true]) ->addForeignKey('mail_job_id', 'mail_jobs', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_job_batch_templates') ->addColumn('mail_job_id', 'integer') ->addColumn('mail_job_batch_id', 'integer') ->addColumn('mail_template_id', 'integer') ->addColumn('weight', 'integer') ->addForeignKey('mail_job_id', 'mail_jobs', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('mail_template_id', 'mail_templates', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('mail_job_batch_id', 'mail_job_batch', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_job_queue') ->addColumn('email', 'string') ->addColumn('status', 'string', ['default' => 'queued']) ->addColumn('sorting', 'integer', ['default' => 1000]) ->addColumn('mail_batch_id', 'integer') ->addColumn('mail_template_id', 'integer') ->addForeignKey('mail_batch_id', 'mail_job_batch', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('mail_template_id', 'mail_templates', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); $this->table('mail_user_subscriptions') ->addColumn('user_id', 'integer') ->addColumn('user_email', 'string') ->addColumn('mail_type_id', 'integer') ->addColumn('subscribed', 'boolean') ->addColumn('mail_type_variant_id', 'integer', ['null' => true]) ->addForeignKey('mail_type_id', 'mail_types', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addForeignKey('mail_type_variant_id', 'mail_type_variants', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addTimestamps() ->create(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20200226123805_fix_attachment_size_type_in_mail_logs.php
Mailer/extensions/mailer-module/src/migrations/20200226123805_fix_attachment_size_type_in_mail_logs.php
<?php use Phinx\Migration\AbstractMigration; class FixAttachmentSizeTypeInMailLogs extends AbstractMigration { public function change() { $this->table('mail_logs') ->changeColumn('attachment_size', 'integer', ['null' => true, 'default' => null]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210524133046_add_code_column_to_mail_layouts_table.php
Mailer/extensions/mailer-module/src/migrations/20210524133046_add_code_column_to_mail_layouts_table.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddCodeColumnToMailLayoutsTable extends AbstractMigration { public function up(): void { $this->table('mail_layouts') ->addColumn('code', 'string', ['null' => true, 'after' => 'id']) ->update(); $layouts = $this->fetchAll(' SELECT * FROM mail_layouts '); foreach ($layouts as $layout) { $layoutId = $layout['id']; $code = $layoutId . '_' . \Nette\Utils\Strings::webalize($layout['name']); $this->execute(" UPDATE mail_layouts SET code = '{$code}' WHERE id = {$layoutId} "); } $this->table('mail_layouts') ->changeColumn('code', 'string', ['null' => false]) ->addIndex('code', ['unique' => true]) ->update(); } public function down(): void { $this->table('mail_layouts') ->removeColumn('code') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20251017125437_mail_types_deleted_at_index.php
Mailer/extensions/mailer-module/src/migrations/20251017125437_mail_types_deleted_at_index.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailTypesDeletedAtIndex extends AbstractMigration { public function up(): void { $this->table('mail_types') ->addIndex('deleted_at') ->update(); } public function down(): void { $this->table('mail_types') ->removeIndex('deleted_at') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20181121203530_create_mail_type_stats_table.php
Mailer/extensions/mailer-module/src/migrations/20181121203530_create_mail_type_stats_table.php
<?php use Phinx\Migration\AbstractMigration; class CreateMailTypeStatsTable extends AbstractMigration { public function up() { $mailTypeStats = $this->table('mail_type_stats'); $mailTypeStats ->addColumn('mail_type_id', 'integer') ->addColumn('created_at', 'datetime') ->addColumn('subscribers_count', 'integer', [ 'signed' => false ]) ->save(); } public function down() { $this->table('mail_type_stats')->drop()->save(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20220613141157_add_deleted_at_to_tables.php
Mailer/extensions/mailer-module/src/migrations/20220613141157_add_deleted_at_to_tables.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddDeletedAtToTables extends AbstractMigration { public function change(): void { $this->table('mail_source_template') ->addColumn('deleted_at', 'datetime', ['default' => null, 'null' => true, 'after' => 'updated_at']) ->update(); $this->table('mail_layouts') ->addColumn('deleted_at', 'datetime', ['default' => null, 'null' => true, 'after' => 'updated_at']) ->update(); $this->table('mail_types') ->addColumn('deleted_at', 'datetime', ['default' => null, 'null' => true, 'after' => 'updated_at']) ->update(); $this->table('mail_templates') ->addColumn('deleted_at', 'datetime', ['default' => null, 'null' => true, 'after' => 'updated_at']) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20190213082954_mail_templates_change_code_to_unique.php
Mailer/extensions/mailer-module/src/migrations/20190213082954_mail_templates_change_code_to_unique.php
<?php use Phinx\Migration\AbstractMigration; class MailTemplatesChangeCodeToUnique extends AbstractMigration { public function up() { $this->table('mail_templates') ->removeIndex(['code']) ->addIndex('code', array('unique' => true)) ->update(); } public function down() { $this->table('mail_templates') ->removeIndex(['code']) ->addIndex('code') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20220404140056_add_unsubscribe_mail_template_id_to_mail_types.php
Mailer/extensions/mailer-module/src/migrations/20220404140056_add_unsubscribe_mail_template_id_to_mail_types.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddUnsubscribeMailTemplateIdToMailTypes extends AbstractMigration { public function change(): void { $this->table('mail_types') ->addColumn('unsubscribe_mail_template_id', 'integer', ['default' => null, 'null' => true, 'after' => 'subscribe_mail_template_id']) ->addForeignKey('unsubscribe_mail_template_id', 'mail_templates', 'id') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210629105924_add_public_code_to_mail_templates.php
Mailer/extensions/mailer-module/src/migrations/20210629105924_add_public_code_to_mail_templates.php
<?php declare(strict_types=1); use Nette\Utils\Random; use Phinx\Migration\AbstractMigration; final class AddPublicCodeToMailTemplates extends AbstractMigration { public function up(): void { $this->execute('SET foreign_key_checks = 0'); // so we can use inplace algorithm $this->table('mail_templates')->removeIndex('mail_body_html')->update(); $this->execute(" ALTER TABLE mail_templates ADD COLUMN public_code VARCHAR(255) NULL AFTER code, ALGORITHM=INPLACE, LOCK=NONE; CREATE UNIQUE INDEX idx_public_code ON mail_templates(public_code); UPDATE mail_templates SET public_code = (LEFT(MD5(ROUND(RAND(id)*4294967296)), 8)); ALTER TABLE mail_templates MODIFY COLUMN public_code VARCHAR(255) NOT NULL AFTER code, ALGORITHM=INPLACE, LOCK=NONE; "); $this->execute('SET foreign_key_checks = 1'); } public function down(): void { $this->output->writeln("DOWN migration not possible due to complexity of the migration"); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20221107133059_change_mail_job_queue_id_column_to_bigint.php
Mailer/extensions/mailer-module/src/migrations/20221107133059_change_mail_job_queue_id_column_to_bigint.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class ChangeMailJobQueueIdColumnToBigint extends AbstractMigration { public function change(): void { $this->table('mail_job_queue') ->changeColumn('id', 'biginteger', ['identity' => true]) ->save(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20181106082909_add_extras_to_mail_templates.php
Mailer/extensions/mailer-module/src/migrations/20181106082909_add_extras_to_mail_templates.php
<?php use Phinx\Migration\AbstractMigration; class AddExtrasToMailTemplates extends AbstractMigration { public function change() { $this->table('mail_templates') ->addColumn('extras', 'json', ['null' => true]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20230217084810_unique_configs_name.php
Mailer/extensions/mailer-module/src/migrations/20230217084810_unique_configs_name.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class UniqueConfigsName extends AbstractMigration { public function change(): void { $this->table('configs') ->addIndex('name', ['unique' => true]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20251216085341_mail_job_batch_status_index.php
Mailer/extensions/mailer-module/src/migrations/20251216085341_mail_job_batch_status_index.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailJobBatchStatusIndex extends AbstractMigration { public function up(): void { $this->table('mail_job_batch') ->addIndex('status') ->update(); } public function down(): void { $this->table('mail_job_batch') ->removeIndex('status') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20180417124934_autologin_tokens.php
Mailer/extensions/mailer-module/src/migrations/20180417124934_autologin_tokens.php
<?php use Phinx\Migration\AbstractMigration; class AutologinTokens extends AbstractMigration { public function change() { if (!$this->hasTable('autologin_tokens')) { $this->table('autologin_tokens') ->addColumn('token', 'string') ->addColumn('user_id', 'integer', ['null' => true]) ->addColumn('email', 'string') ->addColumn('created_at', 'datetime') ->addColumn('valid_from', 'datetime') ->addColumn('valid_to', 'datetime') ->addColumn('used_count', 'integer', ['default' => 0]) ->addColumn('max_count', 'integer', ['default' => 1]) ->addIndex(['token'], ['unique' => true]) ->addIndex(['valid_to', 'user_id']) ->addIndex(['user_id']) ->create(); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20230123135856_add_deleted_at_into_mail_type_variants.php
Mailer/extensions/mailer-module/src/migrations/20230123135856_add_deleted_at_into_mail_type_variants.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddDeletedAtIntoMailTypeVariants extends AbstractMigration { public function change(): void { $this->table('mail_type_variants') ->addColumn('deleted_at', 'datetime', ['default' => null, 'null' => true, 'after' => 'created_at']) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20180124064156_mail_user_subscription_types.php
Mailer/extensions/mailer-module/src/migrations/20180124064156_mail_user_subscription_types.php
<?php use Phinx\Migration\AbstractMigration; class MailUserSubscriptionTypes extends AbstractMigration { public function change() { $this->table('mail_user_subscription_variants') ->addColumn('mail_user_subscription_id', 'integer', ['null' => false]) ->addColumn('mail_type_variant_id', 'integer', ['null' => false]) ->addColumn('created_at', 'datetime', ['null' => false]) ->addForeignKey('mail_user_subscription_id', 'mail_user_subscriptions') ->addForeignKey('mail_type_variant_id', 'mail_type_variants') ->addIndex(['mail_user_subscription_id', 'mail_type_variant_id'], ['unique' => true]) ->create(); $query = "INSERT INTO mail_user_subscription_variants (mail_user_subscription_id, mail_type_variant_id, created_at) SELECT id,mail_type_variant_id,NOW() FROM mail_user_subscriptions WHERE mail_type_variant_id IS NOT NULL"; $this->query($query); $this->table('mail_user_subscriptions') ->renameColumn('mail_type_variant_id', 'remove_mail_type_variant_id') ->update(); $this->table('mail_types') ->addColumn('is_multi_variant', 'boolean', ['default' => false, 'null' => false, 'after' => 'auto_subscribe']) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210604061746_remove_obsolete_variant_column.php
Mailer/extensions/mailer-module/src/migrations/20210604061746_remove_obsolete_variant_column.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class RemoveObsoleteVariantColumn extends AbstractMigration { public function up(): void { $this->table('mail_user_subscriptions') ->dropForeignKey('remove_mail_type_variant_id') ->save(); $this->table('mail_user_subscriptions') ->removeColumn('remove_mail_type_variant_id') ->save(); } public function down() { $this->output->writeln('Down migration is not available, up migration was destructive.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20190716063513_hermes_retry.php
Mailer/extensions/mailer-module/src/migrations/20190716063513_hermes_retry.php
<?php use Phinx\Migration\AbstractMigration; class HermesRetry extends AbstractMigration { public function up() { // probably the only feasible way how to change this without breaking running instances if (!$this->hasTable('hermes_tasks_old')) { $this->table("hermes_tasks") ->rename("hermes_tasks_old") ->update(); $sql = <<<SQL CREATE TABLE `hermes_tasks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `message_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `retry` int(11) DEFAULT NULL, `created_at` datetime NOT NULL, `type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `payload` text COLLATE utf8mb4_unicode_ci NOT NULL, `processed_at` datetime NOT NULL, `state` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `execute_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `execute_at` (`processed_at`), KEY `created_at` (`created_at`), KEY `state` (`state`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; SQL; $this->execute($sql); } } public function down() { $this->output->writeln('Down migration is not available.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20190424083747_add_mail_type_category_show_title_column.php
Mailer/extensions/mailer-module/src/migrations/20190424083747_add_mail_type_category_show_title_column.php
<?php use Phinx\Migration\AbstractMigration; class AddMailTypeCategoryShowTitleColumn extends AbstractMigration { public function change() { $this->table('mail_type_categories') ->addColumn('show_title', 'boolean', [ 'null' => false, 'default' => true, ]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20220203171758_add_email_index_to_autologin_tokens.php
Mailer/extensions/mailer-module/src/migrations/20220203171758_add_email_index_to_autologin_tokens.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddEmailIndexToAutologinTokens extends AbstractMigration { public function up(): void { if (!$this->table('autologin_tokens')->hasIndex('email')) { $this->table('autologin_tokens') ->addIndex('email') ->update(); } } public function down(): void { $this->table('autologin_tokens') ->removeIndex('email') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210314091651_add_mail_type_to_snippets.php
Mailer/extensions/mailer-module/src/migrations/20210314091651_add_mail_type_to_snippets.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class AddMailTypeToSnippets extends AbstractMigration { public function change(): void { $this->table('mail_snippets') ->addColumn('mail_type_id','integer', ['default' => null, 'null' => true]) ->addForeignKey('mail_type_id', 'mail_types') ->addIndex(['code', 'mail_type_id'], ['unique' => true]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20220308090047_create_mail_snippet_translations_table.php
Mailer/extensions/mailer-module/src/migrations/20220308090047_create_mail_snippet_translations_table.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateMailSnippetTranslationsTable extends AbstractMigration { public function up(): void { $this->table('mail_snippet_translations') ->addColumn('mail_snippet_id', 'integer') ->addColumn('locale', 'string') ->addColumn('text', 'text') ->addColumn('html', 'text') ->addForeignKey('mail_snippet_id', 'mail_snippets', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->addIndex(['mail_snippet_id', 'locale'], ['unique' => true]) ->create(); } public function down(): void { $this->table('mail_snippet_translations') ->drop() ->save(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20171009072801_mail_job_stats.php
Mailer/extensions/mailer-module/src/migrations/20171009072801_mail_job_stats.php
<?php use Phinx\Migration\AbstractMigration; class MailJobStats extends AbstractMigration { public function change() { $this->table('mail_job_batch') ->addColumn('delivered', 'integer', ['null' => false, 'default' => 0]) ->addColumn('opened', 'integer', ['null' => false, 'default' => 0]) ->addColumn('clicked', 'integer', ['null' => false, 'default' => 0]) ->addColumn('dropped', 'integer', ['null' => false, 'default' => 0]) ->addColumn('spam_complained', 'integer', ['null' => false, 'default' => 0]) ->addColumn('hard_bounced', 'integer', ['null' => false, 'default' => 0]) ->save(); $this->table('mail_logs') ->addColumn('mail_job_batch_id', 'integer', ['null' => true, 'after' => 'mail_job_id']) ->save(); // intentional split to two separate queries to lower the blocking time $this->table('mail_logs') ->addForeignKey('mail_job_batch_id', 'mail_job_batch', 'id', ['delete' => 'RESTRICT', 'update' => 'CASCADE']) ->save(); $sql = <<<SQL UPDATE mail_logs SET mail_job_batch_id = ( SELECT id FROM mail_job_batch WHERE mail_job_batch.mail_job_id = mail_logs.mail_job_id ORDER BY mail_job_batch.id DESC LIMIT 1 ) SQL; $this->execute($sql); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20201209084222_mail_template_search_indexes.php
Mailer/extensions/mailer-module/src/migrations/20201209084222_mail_template_search_indexes.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailTemplateSearchIndexes extends AbstractMigration { public function change(): void { $this->table('mail_templates') ->addIndex('name') ->addIndex('subject') ->addIndex('description') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20201208065608_fix_config_names.php
Mailer/extensions/mailer-module/src/migrations/20201208065608_fix_config_names.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class FixConfigNames extends AbstractMigration { public function up(): void { $sql = <<<SQL UPDATE configs SET name = REPLACE(name, 'remp-', 'remp_'); UPDATE configs SET value = REPLACE(value, 'remp-', 'remp_') WHERE name = 'default_mailer'; SQL; $this->execute($sql); } public function down(): void { $sql = <<<SQL UPDATE configs SET value = REPLACE(value, 'remp_', 'remp-') WHERE name = 'default_mailer'; UPDATE configs SET name = REPLACE(name, 'remp_', 'remp-'); SQL; $this->execute($sql); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20221123090507_create_new_mail_user_subscriptions_and_mail_user_subscription_variants_tables.php
Mailer/extensions/mailer-module/src/migrations/20221123090507_create_new_mail_user_subscriptions_and_mail_user_subscription_variants_tables.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class CreateNewMailUserSubscriptionsAndMailUserSubscriptionVariantsTables extends AbstractMigration { public function up(): void { $mailUserSubscriptionsRowCount = $this->query('SELECT 1 FROM mail_user_subscriptions LIMIT 1;')->fetch(); if ($mailUserSubscriptionsRowCount === false) { $this->table('mail_user_subscription_variants') ->dropForeignKey('mail_user_subscription_id') ->save(); $this->table('mail_user_subscription_variants') ->changeColumn('mail_user_subscription_id', 'biginteger') ->save(); $this->table('mail_user_subscriptions') ->changeColumn('id', 'biginteger', ['identity' => true]) ->save(); $this->table('mail_user_subscription_variants') ->addForeignKey('mail_user_subscription_id', 'mail_user_subscriptions') ->save(); } else { $this->query(" CREATE TABLE mail_user_subscriptions_v2 LIKE mail_user_subscriptions; CREATE TABLE mail_user_subscription_variants_v2 LIKE mail_user_subscription_variants; "); $this->table('mail_user_subscription_variants_v2') ->changeColumn('mail_user_subscription_id', 'biginteger') ->save(); $this->table('mail_user_subscriptions_v2') ->changeColumn('id', 'biginteger', ['identity' => true]) ->addForeignKey('mail_type_id', 'mail_types') ->save(); $this->table('mail_user_subscription_variants_v2') ->addForeignKey('mail_user_subscription_id', 'mail_user_subscriptions_v2') ->addForeignKey('mail_type_variant_id', 'mail_type_variants') ->save(); } } public function down() { $this->output->writeln('Down migration is not available.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20201204234345_mailer_config_prefix.php
Mailer/extensions/mailer-module/src/migrations/20201204234345_mailer_config_prefix.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailerConfigPrefix extends AbstractMigration { public function up(): void { $sql = <<<SQL update configs set name = replace(name, "remp_mailermodule_mailer_smtpmailer", "remp-smtp") where name like 'remp_mailermodule_mailer_smtpmailer%'; update configs set name = replace(name, "remp_mailermodule_mailer_mailgunmailer", "remp-mailgun") where name like 'remp_mailermodule_mailer_mailgunmailer%'; SQL; $this->execute($sql); } public function down(): void { $sql = <<<SQL update configs set name = replace(name, "remp-smtp", "remp_mailermodule_mailer_smtpmailer") where name like 'remp-smtp%'; update configs set name = replace(name, "remp-mailgun", "remp_mailermodule_mailer_mailgunmailer") where name like 'remp-mailgun%'; SQL; $this->execute($sql); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20250530084651_mail_type_stats_created_at_index.php
Mailer/extensions/mailer-module/src/migrations/20250530084651_mail_type_stats_created_at_index.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailTypeStatsCreatedAtIndex extends AbstractMigration { public function change(): void { $this->table('mail_type_stats') ->addIndex('created_at') ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20210730112840_mail_logs_subject_encoding.php
Mailer/extensions/mailer-module/src/migrations/20210730112840_mail_logs_subject_encoding.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class MailLogsSubjectEncoding extends AbstractMigration { public function up(): void { $this->execute('SET foreign_key_checks = 0'); // first, create new column; this could take some time, but it's not blocking $this->execute(' ALTER TABLE mail_logs ADD COLUMN subject_new varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL AFTER subject, ALGORITHM=INPLACE, LOCK=NONE '); // rename old column, should be instant $this->execute(' ALTER TABLE mail_logs CHANGE COLUMN subject subject_old varchar(255) DEFAULT NULL, ALGORITHM=INPLACE, LOCK=NONE' ); // rename new column, should be instant $this->execute(' ALTER TABLE mail_logs CHANGE COLUMN subject_new subject varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL, ALGORITHM=INPLACE, LOCK=NONE' ); // restore subjects in the new column; these updates are blocking new writes so we do them in batches $result = $this->fetchRow("SELECT MAX(id), MIN(id) FROM mail_logs"); $maxId = $result[0]; $minId = $result[1]; if ($maxId !== null && $minId !== null) { $current = $maxId; $step = 100000; $this->output->write("Migrating subjects to the new column: "); while ($current >= $minId) { $this->output->write("."); $low = $current - $step; $this->execute(" UPDATE mail_logs SET subject = subject_old WHERE id <= {$current} AND id >= {$low} AND subject IS NULL "); $current -= $step; } $this->output->writeln(' OK!'); } // drop old column (non-blocking) $this->execute(' ALTER TABLE mail_logs DROP COLUMN subject_old, ALGORITHM=INPLACE, LOCK=NONE' ); $this->execute('SET foreign_key_checks = 1'); } public function down(): void { $this->output->writeln("DOWN migration not possible due to complexity of the migration"); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20220127132604_remove_is_public_from_mail_types.php
Mailer/extensions/mailer-module/src/migrations/20220127132604_remove_is_public_from_mail_types.php
<?php declare(strict_types=1); use Phinx\Migration\AbstractMigration; final class RemoveIsPublicFromMailTypes extends AbstractMigration { public function up(): void { $this->table('mail_types') ->removeColumn('is_public') ->update(); } public function down() { $this->output->writeln('Down migration is not available, up migration was destructive.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/migrations/20180206143842_auto_autologin.php
Mailer/extensions/mailer-module/src/migrations/20180206143842_auto_autologin.php
<?php use Phinx\Migration\AbstractMigration; class AutoAutologin extends AbstractMigration { public function change() { $this->table('mail_templates') ->changeColumn('autologin', 'boolean', ['null' => false, 'default' => true]) ->update(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false