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/extensions/mailer-module/src/Models/Mailer/EmailAllowList.php
Mailer/extensions/mailer-module/src/Models/Mailer/EmailAllowList.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Mailer; class EmailAllowList { private array $allowList = []; /** * @param string $allow */ public function allow(string $allow): void { $this->allowList[] = $allow; } /** * @param string $isAllowed * @return bool */ public function isAllowed(string $isAllowed): bool { if (empty($this->allowList)) { return true; } foreach ($this->allowList as $allowItem) { if (str_contains($isAllowed, $allowItem)) { return true; } } return false; } public function reset(): void { $this->allowList = []; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Mailer/SmtpMailer.php
Mailer/extensions/mailer-module/src/Models/Mailer/SmtpMailer.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Mailer; use Nette\Mail\Message; use Nette\Mail\SmtpMailer as NetteSmtpMailer; class SmtpMailer extends Mailer { public const ALIAS = 'remp_smtp'; protected array $options = [ 'host' => [ 'required' => true, 'label' => 'SMTP host', 'description' => 'IP address or hostname of SMTP server (e.g. 127.0.0.1)', ], 'port' => [ 'required' => true, 'label' => 'SMTP Port', 'description' => 'Port on which your SMTP server is exposed (e.g. 1025)', ], 'username' => [ 'required' => false, 'label' => 'SMTP Username', ], 'password' => [ 'required' => false, 'label' => 'SMTP Password', ], 'secure' => [ 'required' => false, 'label' => 'SMTP Secure', 'description' => 'Secure protocol used to connect (e.g. ssl)', ], ]; public function send(Message $mail): void { // Removing this header prevents leaking template parameters that may contain sensitive information. // This header is historically used in MailgunMailer for passing template parameters to Mailgun. // We rather not pass this to SMTP mailer. $mail->clearHeader('X-Mailer-Template-Params'); $mailer = $this->createMailer(); $mailer->send($mail); } private function createMailer(): NetteSmtpMailer { $this->buildConfig(); return new NetteSmtpMailer( host: $this->options['host']['value'] ?? '', username: $this->options['username']['value'] ?? '', password: $this->options['password']['value'] ?? '', port: (int) $this->options['port']['value'] ?? null, encryption: $this->options['secure']['value'] ?? 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/Models/Sender/MailerRuntimeException.php
Mailer/extensions/mailer-module/src/Models/Sender/MailerRuntimeException.php
<?php namespace Remp\MailerModule\Models\Sender; use Exception; class MailerRuntimeException 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/Models/Sender/MailerNotExistsException.php
Mailer/extensions/mailer-module/src/Models/Sender/MailerNotExistsException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sender; use Exception; class MailerNotExistsException 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/Models/Sender/MailerFactory.php
Mailer/extensions/mailer-module/src/Models/Sender/MailerFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sender; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Mailer\Mailer; class MailerFactory { /** @var Config */ private $config; /** @var array */ private $availableMailers; public function __construct(Config $config) { $this->config = $config; } public function addMailer(Mailer $mailer): void { $this->availableMailers[$mailer->getMailerAlias()] = $mailer; } /** * @param null|string $alias - If $alias is null, default mailer is returned. * @return Mailer * @throws MailerNotExistsException|\Remp\MailerModule\Models\Config\ConfigNotExistsException */ public function getMailer(?string $alias = null): Mailer { if ($alias === null) { $alias = $this->config->get('default_mailer'); } if (!isset($this->availableMailers[$alias])) { throw new MailerNotExistsException("Mailer {$alias} not exists"); } return $this->availableMailers[$alias]; } /** * @return Mailer[] */ public function getAvailableMailers(): array { return $this->availableMailers; } public function getMailerByAliasAndCode($alias, $code): Mailer { return $this->getMailer(Mailer::buildAlias($alias, $code)); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Sender/MailerBatchException.php
Mailer/extensions/mailer-module/src/Models/Sender/MailerBatchException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Sender; use Exception; class MailerBatchException 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/Models/PageMeta/Meta.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Meta.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta; class Meta { public function __construct( private readonly ?string $title = null, private readonly ?string $description = null, private readonly ?string $image = null, private readonly array $authors = [], ) { } public function getTitle(): ?string { return $this->title; } public function getDescription(): ?string { return $this->description; } public function getImage(): ?string { return $this->image; } public function getAuthors(): array { return $this->authors; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/PageMeta/Transport/TransportInterface.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Transport/TransportInterface.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Transport; interface TransportInterface { public function getContent(string $url): ?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/Models/PageMeta/Transport/FileTransport.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Transport/FileTransport.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Transport; class FileTransport implements TransportInterface { public function getContent(string $url): ?string { if (!is_file($url)) { return null; } return file_get_contents($url); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/PageMeta/Transport/GuzzleTransport.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Transport/GuzzleTransport.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Transport; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\ServerException; class GuzzleTransport implements TransportInterface { public function getContent(string $url): ?string { $client = new Client(); try { $res = $client->get($url); return (string) $res->getBody(); } catch (ConnectException $e) { return null; } catch (ServerException $e) { 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/Models/PageMeta/Content/GenericPageContent.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Content/GenericPageContent.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; class GenericPageContent 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[] = html_entity_decode($author); } } // title $title = null; $matches = []; preg_match('/<meta property=\"og:title\" content=\"(.+)\">/U', $content, $matches); if ($matches) { $title = html_entity_decode($matches[1]); } // description $description = null; $matches = []; preg_match('/<meta property=\"og:description\" content=\"(.*)\">/Us', $content, $matches); if ($matches) { $description = html_entity_decode($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/extensions/mailer-module/src/Models/PageMeta/Content/InvalidUrlException.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Content/InvalidUrlException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Content; use Exception; class InvalidUrlException 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/Models/PageMeta/Content/GenericShopContent.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Content/GenericShopContent.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Content; use GuzzleHttp\Exception\RequestException; use Remp\MailerModule\Models\PageMeta\Meta; use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface; class GenericShopContent 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 { // author $authors = []; $matches = []; preg_match_all('/<meta name=\"author\" content=\"(.+)\">/U', $content, $matches); if ($matches) { foreach ($matches[1] as $author) { $authors[] = html_entity_decode($author); } } // title $title = null; $matches = []; preg_match('/<meta property=\"og:title\" content=\"(.+)\">/U', $content, $matches); if ($matches) { $title = html_entity_decode($matches[1]); } // description $description = null; $matches = []; preg_match('/<meta property=\"og:description\" content=\"(.*)\">/Us', $content, $matches); if ($matches) { $description = html_entity_decode($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/extensions/mailer-module/src/Models/PageMeta/Content/ShopContentInterface.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Content/ShopContentInterface.php
<?php namespace Remp\MailerModule\Models\PageMeta\Content; use Remp\MailerModule\Models\PageMeta\Meta; interface ShopContentInterface { public function fetchUrlMeta(string $url): ?Meta; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/PageMeta/Content/ContentInterface.php
Mailer/extensions/mailer-module/src/Models/PageMeta/Content/ContentInterface.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\PageMeta\Content; use Remp\MailerModule\Models\PageMeta\Meta; interface ContentInterface { public function fetchUrlMeta(string $url): ?Meta; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/SimpleAuthenticator.php
Mailer/extensions/mailer-module/src/Models/Auth/SimpleAuthenticator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use Nette\Application\LinkGenerator; use Nette\Http\IResponse; use Nette\Security\AuthenticationException; use Nette\Security\IIdentity; use Nette\Security\SimpleIdentity; class SimpleAuthenticator implements \Nette\Security\Authenticator { /** @var IResponse */ private $response; /** @var LinkGenerator */ private $linkGenerator; private $users = []; public function __construct( IResponse $response, LinkGenerator $linkGenerator ) { $this->response = $response; $this->linkGenerator = $linkGenerator; } public function addUser(string $email, string $password) { $this->users[] = [ 'email' => $email, 'password' => $password, ]; } public function authenticate(string $user, string $password): IIdentity { if ($user === "" && $password === "") { $link = $this->linkGenerator->link('Mailer:Sign:In'); $this->response->redirect($link); exit(); } foreach ($this->users as $id => $item) { if ($item['email'] === $user && hash_equals($password, $item['password'])) { $token = bin2hex(random_bytes(16)); return new SimpleIdentity($id, 'admin', [ 'email' => $item['email'], 'token' => $token, 'first_name' => '', 'last_name' => '' ]); } } throw new AuthenticationException('Wrong email or password.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/SsoTokenRepository.php
Mailer/extensions/mailer-module/src/Models/Auth/SsoTokenRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use Remp\MailerModule\Models\Sso\Client; use Tomaj\NetteApi\Misc\TokenRepositoryInterface; class SsoTokenRepository implements TokenRepositoryInterface { private $client; public function __construct(Client $client) { $this->client = $client; } public function validToken(string $token): bool { return $this->client->validToken($token); } public function ipRestrictions(string $token): string { return '*'; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/AutoLogin.php
Mailer/extensions/mailer-module/src/Models/Auth/AutoLogin.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use Remp\MailerModule\Repositories\ActiveRow; use Nette\Utils\DateTime; use Remp\MailerModule\Repositories\AutoLoginTokensRepository; class AutoLogin { /** @var AutoLoginTokensRepository */ private $autoLoginTokensRepository; public function __construct(AutoLoginTokensRepository $autoLoginTokensRepository) { $this->autoLoginTokensRepository = $autoLoginTokensRepository; } public function getToken($token): ?ActiveRow { /** @var ActiveRow $tokenRow */ $tokenRow = $this->autoLoginTokensRepository->findBy('token', $token); if (!$tokenRow) { return null; } return $tokenRow; } public function useToken(ActiveRow $token): bool { return $this->autoLoginTokensRepository->update($token, ['used_count+=' => 1]); } public function createTokens(array $emails): array { if (empty($emails)) { return []; } $autologinInsertData = []; $returnData = []; $validFrom = new DateTime(); $validTo = $validFrom->modifyClone('+1 month'); foreach ($emails as $email) { $token = TokenGenerator::generate(); $autologinInsertData[] = $this->autoLoginTokensRepository->getInsertData( $token, $email, $validFrom, $validTo, 10 ); $returnData[$email] = $token; } $autologinTokensTableName = $this->autoLoginTokensRepository->getTable()->getName(); $this->autoLoginTokensRepository->getDatabase()->query("INSERT INTO $autologinTokensTableName", $autologinInsertData); return $returnData; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/Authenticator.php
Mailer/extensions/mailer-module/src/Models/Auth/Authenticator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use Nette\Application\LinkGenerator; use Nette\Http\IResponse; use Nette\Security\AuthenticationException; use Nette\Security\Authenticator as NetteAuthenticator; use Nette\Security\IIdentity; use Nette\Security\SimpleIdentity; class Authenticator implements NetteAuthenticator { /** @var RemoteUser */ private $remoteUser; /** @var IResponse */ private $response; /** @var LinkGenerator */ private $linkGenerator; public function __construct( RemoteUser $remoteUser, IResponse $response, LinkGenerator $linkGenerator ) { $this->remoteUser = $remoteUser; $this->response = $response; $this->linkGenerator = $linkGenerator; } public function authenticate(string $user, string $password): IIdentity { if ($user === "" && $password === "") { $link = $this->linkGenerator->link('Mailer:Sign:In'); $this->response->redirect($link); exit(); } $result = $this->remoteUser->remoteLogin($user, $password); if ($result['status'] === 'error') { throw new AuthenticationException($result['message']); } $user = $result['data']['user']; return new SimpleIdentity($user['id'], 'admin', [ 'email' => $user['email'], 'token' => $result['data']['access']['token'], 'first_name' => $user['first_name'], 'last_name' => $user['last_name'] ]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/RemoteBearerTokenRepository.php
Mailer/extensions/mailer-module/src/Models/Auth/RemoteBearerTokenRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Nette\Security\AuthenticationException; use Tomaj\NetteApi\Misc\TokenRepositoryInterface; class RemoteBearerTokenRepository implements TokenRepositoryInterface { const ENDPOINT_CHECK_TOKEN = 'api/v1/token/check'; private $client; public function __construct(string $baseUrl) { $this->client = new Client([ 'base_uri' => $baseUrl ]); } public function validToken(string $token): bool { try { $response = $this->client->request('GET', self::ENDPOINT_CHECK_TOKEN, [ 'headers' => [ 'Authorization' => 'Bearer '.$token, ] ]); } catch (ClientException $e) { $response = $e->getResponse(); $contents = $response->getBody()->getContents(); if ($response->getStatusCode() === 403) { return false; } throw new AuthenticationException($contents); } return $response->getStatusCode() === 200; } public function ipRestrictions(string $token): string { return '*'; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/TokenGenerator.php
Mailer/extensions/mailer-module/src/Models/Auth/TokenGenerator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; class TokenGenerator { /** * Function to generate security tokens (for sessions, autologin tokens, etc.) * Minimal recommended length of security tokens is 128 bit (16 bytes) * See OWASP guide for details: * https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md * * @param int $bytes * * @return string of length bytes * 2 (hexadecimally encoded) * @throws \Exception - if not sufficient entropy is available */ public static function generate(int $bytes = 16): string { return bin2hex(random_bytes($bytes)); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/RemoteUser.php
Mailer/extensions/mailer-module/src/Models/Auth/RemoteUser.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\ConnectException; use Nette\Utils\Json; use Nette\Utils\JsonException; class RemoteUser { private $ssoHost; private $timeout; public function __construct(string $ssoHost, float $timeout = 10.0) { $this->ssoHost = $ssoHost; $this->timeout = $timeout; } public function remoteLogin(string $email, string $password): array { $client = new Client([ 'base_uri' => $this->ssoHost, 'timeout' => $this->timeout, ]); try { $response = $client->request('POST', '/api/v1/users/login', [ 'form_params' => [ 'source' => 'remp/Mailer', 'email' => $email, 'password' => $password, ], ]); $responseData = Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); } catch (ClientException $clientException) { try { $data = Json::decode($clientException->getResponse()->getBody()->getContents()); } catch (JsonException $e) { return ['status' => 'error', 'error' => $e->getMessage(), 'message' => 'Invalid response provided by CRM. Is SSO_ADDR configured correctly?']; } return ['status' => 'error', 'error' => $data->error, 'message' => $data->message]; } catch (ConnectException $connectException) { return ['status' => 'error', 'error' => 'unavailable server', 'message' => 'Cannot connect to auth server']; } catch (JsonException $jsonException) { return ['status' => 'error', 'error' => 'wrong response', 'message' => $jsonException->getMessage()]; } if (!isset($responseData['user']['roles'])) { return ['status' => 'error', 'error' => 'not admin', 'message' => 'Your are not admin user']; } if (in_array('superadmin', $responseData['user']['roles'], true) || in_array('remp/mailer', $responseData['user']['roles'], true) ) { $data = ['status' => 'ok', 'data' => $responseData]; } else { return ['status' => 'error', 'error' => 'not admin', 'message' => 'Your are not authorized for this app']; } return $data; } public function userInfo(string $token): array { $client = new Client([ 'base_uri' => $this->ssoHost, 'timeout' => $this->timeout, ]); try { $response = $client->request('GET', '/api/v1/user/info', [ 'headers' => ['Authorization' => 'Bearer ' . $token], ]); } catch (ClientException $clientException) { $data = json_decode($clientException->getResponse()->getBody()->getContents()); return ['status' => 'error', 'error' => 'auth error', 'message' => $data->message]; } catch (ConnectException $connectException) { return ['status' => 'error', 'error' => 'unavailable server', 'message' => 'Cannot connect to auth server']; } $responseData = json_decode($response->getBody()->getContents(), true); return $responseData['user']; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Auth/PermissionManager.php
Mailer/extensions/mailer-module/src/Models/Auth/PermissionManager.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Auth; use Nette\Security\Permission; use Nette\Security\User; class PermissionManager { private Permission $acl; private array $roles = []; private array $privileges = []; public function __construct() { $this->acl = new Permission(); } /** * @param User $user * @param string $resource * @param string $privilege * @return bool */ public function isAllowed(User $user, string $resource, string $privilege): bool { $email = $user->getIdentity()->getData()['email']; // if privilege is not registered for any role we want to allow action for backwards compatibility if (!isset($this->privileges[$resource][$privilege])) { return true; } if (empty($this->roles[$email])) { return false; } $userRoles = $this->roles[$email]; foreach ($userRoles as $userRole) { if ($this->acl->isAllowed($userRole, $resource, $privilege)) { return true; } } return false; } /** * @param string $email * @param string $role */ public function assignRole(string $email, string $role): void { if (!$this->acl->hasRole($role)) { $this->acl->addRole($role); } $this->roles[$email][] = $role; } /** * @param string $role * @param string $resource * @param string|string[] $privileges */ public function allow(string $role, string $resource, $privileges): void { if (!$this->acl->hasRole($role)) { $this->acl->addRole($role); } if (!$this->acl->hasResource($resource)) { $this->acl->addResource($resource); } foreach ((array) $privileges as $privilege) { $this->privileges[$resource][$privilege] = true; } $this->acl->allow($role, $resource, $privileges); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Tracker/Remp.php
Mailer/extensions/mailer-module/src/Models/Tracker/Remp.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Tracker; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Nette\Utils\DateTime; use Nette\Utils\Json; use Ramsey\Uuid\Uuid; use Tracy\Debugger; use Tracy\Logger; class Remp implements ITracker { const TRACK_EVENT = '/track/event'; const TRACK_COMMERCE = '/track/commerce'; private $client; private $token; private $trackerHost; public function __construct(string $trackerHost, string $token) { $this->token = $token; $this->trackerHost = $trackerHost; $this->client = new Client([ 'base_uri' => $trackerHost, ]); } public function trackEvent(DateTime $dateTime, string $category, string $action, EventOptions $options) { $payload = array_filter([ 'system' => [ 'property_token' => $this->token, 'time' => $dateTime->format(DATE_RFC3339), ], 'user' => $options->getUser()->toArray(), 'category' => $category, 'action' => $action, 'fields' => $options->getFields(), 'remp_event_id' => Uuid::uuid4(), ]); try { $this->client->post(self::TRACK_EVENT, [ 'json' => $payload, ]); } catch (ClientException $e) { $jsonPayload = Json::encode($payload); Debugger::log("Host: [{$this->trackerHost}], Payload: [{$jsonPayload}], response: [{$e->getResponse()->getBody()}]", Logger::ERROR); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Tracker/User.php
Mailer/extensions/mailer-module/src/Models/Tracker/User.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Tracker; class User { private $id; private $ip_address; private $url; private $user_agent; public function __construct(array $options = []) { foreach ($options as $key => $val) { $this->{$key} = (string)$val; } } public function toArray(): array { return [ 'id' => $this->id, 'ip_address' => $this->ip_address, 'url' => $this->url, 'user_agent' => $this->user_agent, ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Tracker/EventOptions.php
Mailer/extensions/mailer-module/src/Models/Tracker/EventOptions.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Tracker; class EventOptions { private $user; private $fields = []; private $value; public function getUser(): User { return $this->user; } public function getFields(): array { return $this->fields; } public function getValue(): float { return $this->value; } public function __construct() { $this->user = new User; } public function setUser(User $user): void { $this->user = $user; } public function setFields(array $fields): void { $this->fields = $fields; } public function setValue(float $value): void { $this->value = $value; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Tracker/ITracker.php
Mailer/extensions/mailer-module/src/Models/Tracker/ITracker.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Tracker; use Nette\Utils\DateTime; interface ITracker { /** * trackEvent tracks event with given metadata. * * @param DateTime $dateTime * @param string $category * @param string $action * @param EventOptions $options * @return mixed */ public function trackEvent(DateTime $dateTime, string $category, string $action, EventOptions $options); }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Crm/Client.php
Mailer/extensions/mailer-module/src/Models/Crm/Client.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Crm; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\ServerException; use GuzzleHttp\RequestOptions; use Nette\Utils\Json; use GuzzleHttp\Exception\ClientException; class Client { private $client; public function __construct(string $baseUrl, string $token) { $this->client = new GuzzleClient([ 'base_uri' => $baseUrl, 'headers' => [ 'Authorization' => 'Bearer ' . $token, ] ]); } public function validateEmail(string $email): array { try { $response = $this->client->post('api/v1/users/set-email-validated', [ RequestOptions::FORM_PARAMS => [ 'email' => $email, ], ]); return Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); } catch (ConnectException $connectException) { throw new Exception("could not connect to CRM: {$connectException->getMessage()}"); } catch (ClientException $clientException) { $body = Json::decode($clientException->getResponse()->getBody()->getContents(), Json::FORCE_ARRAY); if (isset($body['code']) && $body['code'] === 'email_not_found') { throw new UserNotFoundException("Unable to find email: {$clientException->getMessage()}"); } throw new Exception("unable to confirm CRM user: {$clientException->getMessage()}"); } catch (ServerException $serverException) { throw new Exception("unable to confirm CRM user: {$serverException->getMessage()}"); } } /** * @param string[] $emails **/ public function validateMultipleEmails(array $emails): mixed { // An empty post request would just waste cpu cycles if (count($emails) === 0) { return []; } try { $response = $this->client->post('api/v2/users/set-email-validated', [ RequestOptions::JSON => ['emails' => $emails] ]); return Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); } catch (ConnectException $connectException) { throw new Exception("could not connect to CRM: {$connectException->getMessage()}"); } catch (ClientException $clientException) { throw new Exception("unable to confirm CRM user: {$clientException->getMessage()}"); } catch (ServerException $serverException) { throw new Exception("unable to confirm CRM user: {$serverException->getMessage()}"); } } public function userTouch(int $userId): bool { try { $response = $this->client->get('api/v1/users/touch', [ RequestOptions::QUERY => [ 'id' => $userId, ] ]); return $response->getStatusCode() === 200; } catch (ClientException|ServerException $exception) { throw new Exception("Unable to touch user: {$exception->getMessage()}"); } catch (ConnectException $exception) { throw new Exception("Could not connect to CRM: {$exception->getMessage()}"); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Crm/UserNotFoundException.php
Mailer/extensions/mailer-module/src/Models/Crm/UserNotFoundException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Crm; class UserNotFoundException 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/Models/Crm/Exception.php
Mailer/extensions/mailer-module/src/Models/Crm/Exception.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Crm; class Exception 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/Models/Config/LocalizationConfig.php
Mailer/extensions/mailer-module/src/Models/Config/LocalizationConfig.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; class LocalizationConfig { private string $defaultLocale; private array $secondaryLocales = []; public function __construct(string $defaultLocale) { $this->defaultLocale = $defaultLocale; } public function getDefaultLocale(): string { return $this->defaultLocale; } public function addSecondaryLocales(array $locales): void { $this->secondaryLocales = $locales; } public function getSecondaryLocales(): array { return $this->secondaryLocales; } public function getAvailableLocales(): array { return array_merge([$this->getDefaultLocale()], $this->getSecondaryLocales()); } public function isTranslatable(string $locale = null): bool { if (!$locale) { return false; } return in_array($locale, $this->getSecondaryLocales(), true) && $locale !== $this->getDefaultLocale(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/LinkedServices.php
Mailer/extensions/mailer-module/src/Models/Config/LinkedServices.php
<?php namespace Remp\MailerModule\Models\Config; class LinkedServices { private array $linkedServices = []; public function linkService(string $code, ?string $url, ?string $icon): void { if (empty($url)) { return; } $this->linkedServices[$code] = [ 'url' => $url, 'icon' => $icon, ]; } public function getServices(): array { return $this->linkedServices; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/EditorConfig.php
Mailer/extensions/mailer-module/src/Models/Config/EditorConfig.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; class EditorConfig { public const EDITOR_CODEMIRROR = 'codemirror'; public const EDITOR_WYSIWYG = 'wysiwyg'; private string $templateEditor = self::EDITOR_CODEMIRROR; public function setTemplateEditor(?string $editor): void { if ($editor === null) { return; } $this->templateEditor = match ($editor) { self::EDITOR_CODEMIRROR => self::EDITOR_CODEMIRROR, self::EDITOR_WYSIWYG => self::EDITOR_WYSIWYG, default => throw new \Exception('Unsupported editor configured: ' . $editor), }; } public function getTemplateEditor(): string { return $this->templateEditor; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/ConfigExtension.php
Mailer/extensions/mailer-module/src/Models/Config/ConfigExtension.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; use Nette\DI\CompilerExtension; class ConfigExtension extends CompilerExtension { public function loadConfiguration(): void { $config = $this->getConfig(); $builder = $this->getContainerBuilder(); $builder->addDefinition($this->prefix('config_overrider')) ->setType(LocalConfig::class) ->setArguments([$config]) ->setAutowired(true); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/Config.php
Mailer/extensions/mailer-module/src/Models/Config/Config.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; use Nette\Caching\Cache; use Nette\Caching\Storage; use Remp\MailerModule\Repositories\ConfigsRepository; class Config { public const TYPE_STRING = 'string'; public const TYPE_INT = 'integer'; public const TYPE_TEXT = 'text'; public const TYPE_PASSWORD = 'password'; public const TYPE_HTML = 'html'; public const TYPE_SELECT = 'select'; public const TYPE_BOOLEAN = 'boolean'; private int $cacheExpirationInSeconds = 60; private int $lastConfigRefreshTimestamp = 0; private bool $allowLocalConfigFallback = false; private ?array $items = null; public function __construct( private readonly ConfigsRepository $configsRepository, private readonly LocalConfig $localConfig, private readonly Storage $cacheStorage, ) { } public function allowLocalConfigFallback(bool $allow = true): void { $this->allowLocalConfigFallback = $allow; } public function get(string $name) { if ($this->needsRefresh()) { $this->refresh(); } if (isset($this->items[$name])) { $item = $this->items[$name]; $value = $this->localConfig->exists($name) ? $this->localConfig->value($name) : $item->value; return $this->formatValue($value, $item->type); } if ($this->allowLocalConfigFallback && $this->localConfig->exists($name)) { return $this->localConfig->value($name); } throw new ConfigNotExistsException("Setting {$name} does not exists."); } public function refresh(bool $force = false): void { $cacheData = $this->cacheStorage->read('application_config_cache'); if (!$force && $cacheData) { $this->items = $cacheData; } else { $items = $this->configsRepository->all(); foreach ($items as $item) { $this->items[$item->name] = (object)$item->toArray(); } $this->cacheStorage->write('application_config_cache', $this->items, [ Cache::Expire => $this->cacheExpirationInSeconds ]); } $this->lastConfigRefreshTimestamp = time(); } private function needsRefresh(): bool { $refreshAt = $this->lastConfigRefreshTimestamp + $this->cacheExpirationInSeconds; return time() > $refreshAt; } private function formatValue($value, $type = 'string') { if ($type == self::TYPE_INT) { return (int)$value; } return $value; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/LocalConfig.php
Mailer/extensions/mailer-module/src/Models/Config/LocalConfig.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; class LocalConfig { private $data; public function __construct(array $data = []) { $this->data = $data; } public function value(string $key) { if ($this->exists($key)) { return $this->data[$key]; } return false; } public function exists(string $key): bool { return isset($this->data[$key]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/SearchConfig.php
Mailer/extensions/mailer-module/src/Models/Config/SearchConfig.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; class SearchConfig { private int $maxResultCount = 5; public function setMaxResultCount(?int $maxResultCount): void { if ($maxResultCount === null) { return; } $this->maxResultCount = $maxResultCount; } public function getMaxResultCount(): int { return $this->maxResultCount; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Config/ConfigNotExistsException.php
Mailer/extensions/mailer-module/src/Models/Config/ConfigNotExistsException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Config; use Exception; class ConfigNotExistsException 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/Models/ServiceParams/DefaultServiceParamsProvider.php
Mailer/extensions/mailer-module/src/Models/ServiceParams/DefaultServiceParamsProvider.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\ServiceParams; use Nette\Caching\Cache; use Nette\Caching\Storage; use Nette\Utils\Json; use Remp\MailerModule\Repositories\BatchesRepository; class DefaultServiceParamsProvider implements ServiceParamsProviderInterface { private const CACHE_PREFIX = 'batch_to_variant_code_'; private const CACHE_PREFIX_VARIANT_DATA = 'batch_to_variant_'; private const NO_ASSIGNED_VARIANT_DATA = '__NO_ASSIGNED_VARIANT_DATA__'; public function __construct( private BatchesRepository $batchesRepository, private Storage $cacheStorage ) { } public function provide($template, string $email, ?int $batchId = null, ?string $autoLogin = null): array { $variantCode = null; if ($batchId) { $variantData = $this->loadVariantData($batchId); if (isset($variantData['code'])) { $variantCode = $variantData['code']; } } $params = []; if (isset($_ENV['UNSUBSCRIBE_URL'])) { $unsubscribe = str_replace('%type%', $template->mail_type->code, $_ENV['UNSUBSCRIBE_URL']) . $autoLogin; if ($variantCode) { $unsubscribe .= '&variantCode=' . $variantCode; } $params['unsubscribe'] = $unsubscribe; } if (isset($_ENV['SETTINGS_URL'])) { $params['settings'] = $_ENV['SETTINGS_URL'] . $autoLogin; } $params['newsletter_id'] = $template->mail_type->id; $params['newsletter_code'] = $template->mail_type->code; $params['newsletter_title'] = $template->mail_type->title; if (!empty($variantData)) { $params['variant_id'] = $variantData['id']; $params['variant_code'] = $variantData['code']; $params['variant_title'] = $variantData['title']; } return $params; } private function loadVariantData(int $batchId): array { $variantData = $this->cacheStorage->read(self::CACHE_PREFIX_VARIANT_DATA . ((string) $batchId)); if (!$variantData) { $batch = $this->batchesRepository->find($batchId); $variant = $batch->mail_job->mail_type_variant; $variantData = []; if ($variant) { $variantData = [ 'id' => $variant->id, 'code' => $variant->code, 'title' => $variant->title, ]; } $this->cacheStorage->write(self::CACHE_PREFIX_VARIANT_DATA . ((string) $batchId), Json::encode($variantData), [ Cache::Expire => 60*20, // 20 minutes ]); return $variantData; } return Json::decode($variantData, true); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/ServiceParams/ServiceParamsProviderInterface.php
Mailer/extensions/mailer-module/src/Models/ServiceParams/ServiceParamsProviderInterface.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\ServiceParams; use Nette\Database\Table\ActiveRow; interface ServiceParamsProviderInterface { public function provide(ActiveRow $template, string $email, ?int $batchId = null, ?string $autoLogin = null): array; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/Aggregator.php
Mailer/extensions/mailer-module/src/Models/Segment/Aggregator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; class Aggregator implements ISegment { /** @var ISegment[] */ private $providers = []; private $errors = []; public function register(ISegment $provider): void { $this->providers = array_merge($this->providers, [$provider->provider() => $provider]); } /** * @return string * @throws SegmentException */ public function provider(): string { throw new SegmentException("Aggregator cannot return provider value"); } public function list(): array { $segments = []; foreach ($this->providers as $provider) { try { $segments = array_merge($segments, $provider->list()); } catch (\Exception $e) { $this->errors[] = sprintf("%s: %s", $provider->provider(), $e->getMessage()); } } return $segments; } public function users(array $segment): array { return $this->providers[$segment['provider']]->users($segment); } public function hasErrors(): bool { return count($this->errors) > 0; } public function getErrors(): array { return $this->errors; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/SegmentException.php
Mailer/extensions/mailer-module/src/Models/Segment/SegmentException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; use Exception; class SegmentException 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/Models/Segment/Mailer.php
Mailer/extensions/mailer-module/src/Models/Segment/Mailer.php
<?php namespace Remp\MailerModule\Models\Segment; use Remp\MailerModule\Repositories\MailTypesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; class Mailer implements ISegment { public const PROVIDER_ALIAS = 'mailer-segment'; private const SEGMENT_EVERYONE = 'everyone'; public function __construct( private MailTypesRepository $mailTypesRepository, private UserSubscriptionsRepository $userSubscriptionsRepository, ) { } public function provider(): string { return static::PROVIDER_ALIAS; } public function list(): array { $segments = [ [ 'name' => 'Everyone', 'provider' => static::PROVIDER_ALIAS, 'code' => self::SEGMENT_EVERYONE, ], ]; $mailTypes = $this->mailTypesRepository->all()->where(['deleted_at' => null]); foreach ($mailTypes as $mailType) { $segments[] = [ 'name' => 'Subscribers of ' . $mailType->title, 'provider' => static::PROVIDER_ALIAS, 'code' => $this->mailTypeSegment($mailType->code), ]; } return $segments; } public function users(array $segment): array { if ($segment['code'] === self::SEGMENT_EVERYONE) { return $this->userSubscriptionsRepository->allSubscribers(); } $code = preg_replace('/^subscribers-/', '', $segment['code']); return $this->userSubscriptionsRepository->findSubscribedUserIdsByMailTypeCode($code); } public static function mailTypeSegment(string $mailTypeCode): string { return 'subscribers-' . $mailTypeCode; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/Dummy.php
Mailer/extensions/mailer-module/src/Models/Segment/Dummy.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; class Dummy implements ISegment { const PROVIDER_ALIAS = 'dummy-segment'; public function provider(): string { return static::PROVIDER_ALIAS; } public function list(): array { return [ [ 'name' => 'Dummy segment', 'provider' => static::PROVIDER_ALIAS, 'code' => 'dummy-segment', 'group' => [ 'id' => 0, 'name' => 'dummy', 'sorting' => 1 ] ], ]; } public function users(array $segment): array { return [1,2]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/Crm.php
Mailer/extensions/mailer-module/src/Models/Segment/Crm.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use JsonMachine\Items; use Psr\Http\Message\StreamInterface; class Crm implements ISegment { const PROVIDER_ALIAS = 'crm-segment'; const ENDPOINT_LIST = 'api/v1/user-segments/list'; const ENDPOINT_USERS = 'api/v1/user-segments/users'; private $baseUrl; private $token; public function __construct(string $baseUrl, string $token) { $this->baseUrl = $baseUrl; $this->token = $token; } public function provider(): string { return static::PROVIDER_ALIAS; } public function list(): array { $response = $this->request(static::ENDPOINT_LIST); $stream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response); try { $segments = []; foreach (Items::fromStream($stream, ['pointer' => '/segments']) as $segment) { $segments[] = [ 'name' => $segment->name, 'provider' => static::PROVIDER_ALIAS, 'code' => $segment->code, 'group' => $segment->group->name, ]; } } finally { fclose($stream); } return $segments; } public function users(array $segment): array { $response = $this->request(static::ENDPOINT_USERS, ['code' => $segment['code']]); $stream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response); try { $userIds = []; foreach (Items::fromStream($stream, ['pointer' => '/users']) as $user) { $userIds[] = $user->id; } } finally { fclose($stream); } return $userIds; } private function request(string $url, array $query = []): StreamInterface { $client = new Client([ 'base_uri' => $this->baseUrl, 'headers' => [ 'Authorization' => 'Bearer ' . $this->token, ] ]); try { $response = $client->get($url, [ 'query' => $query, ]); return $response->getBody(); } catch (ConnectException $connectException) { throw new SegmentException("Could not connect to Segment:{$url} endpoint: {$connectException->getMessage()}"); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/ISegment.php
Mailer/extensions/mailer-module/src/Models/Segment/ISegment.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; use Remp\MailerModule\Repositories\ActiveRow; interface ISegment { /** * Provider returns internal code for identifying the provider implementation. * * @return string */ public function provider(): string; /** * List returns all available segments. * * @return array */ public function list(): array; /** * Users returns array of user IDs matching the provided segment. * * @param array $segment * @return array */ public function users(array $segment): array; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Segment/Beam.php
Mailer/extensions/mailer-module/src/Models/Segment/Beam.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Segment; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use Nette\Utils\Json; class Beam implements ISegment { const PROVIDER_ALIAS = 'remp-segment'; const ENDPOINT_LIST = 'segments'; const ENDPOINT_USERS = 'segments/%s/users'; private $baseUrl; public function __construct($baseUrl) { $this->baseUrl = $baseUrl; } public function provider(): string { return static::PROVIDER_ALIAS; } public function list(): array { $response = $this->request(static::ENDPOINT_LIST); $segments = []; foreach ($response as $segment) { $segments[] = [ 'name' => $segment['name'], 'provider' => static::PROVIDER_ALIAS, 'code' => $segment['code'], 'group' => $segment['group'], ]; } return $segments; } public function users(array $segment): array { $response = $this->request(sprintf(static::ENDPOINT_USERS, $segment['code'])); return $response; } private function request(string $url, array $query = []): array { $client = new Client([ 'base_uri' => $this->baseUrl ]); try { $response = $client->get($url, [ 'query' => $query, ]); return Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY); } catch (ConnectException $connectException) { throw new SegmentException("Could not connect to Segment:{$url} endpoint: {$connectException->getMessage()}"); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/FormRenderer/MaterialRenderer.php
Mailer/extensions/mailer-module/src/Models/FormRenderer/MaterialRenderer.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\FormRenderer; use Nette\Forms\Control; use Nette\Forms\Controls\BaseControl; use Nette\Forms\Controls\Button; use Nette\Forms\Controls\Checkbox; use Nette\Forms\Controls\CheckboxList; use Nette\Forms\Controls\MultiSelectBox; use Nette\Forms\Controls\RadioList; use Nette\Forms\Controls\SelectBox; use Nette\Forms\Controls\TextBase; use Nette\Forms\Controls\TextInput; use Nette\Forms\Form; use Nette\Forms\Rendering\DefaultFormRenderer; use Nette\Utils\Html; class MaterialRenderer extends DefaultFormRenderer { public array $wrappers = [ 'form' => [ 'container' => null, ], 'error' => [ 'container' => 'div class="alert alert-danger"', 'item' => 'p', ], 'group' => [ 'container' => 'fieldset', 'label' => 'legend', 'description' => 'p', ], 'controls' => [ 'container' => 'div class="col-sm-6"', ], 'pair' => [ 'container' => 'div class="form-group fg-float m-b-30"', 'inner-container' => 'div class="fg-line"', '.required' => 'required', '.optional' => null, '.odd' => null, '.error' => 'has-error', ], 'control' => [ 'container' => 'div', '.odd' => null, 'description' => 'span class=help-block', 'requiredsuffix' => '', 'errorcontainer' => 'span class=help-block', 'erroritem' => '', '.required' => 'required', '.text' => 'text', '.password' => 'text', '.file' => 'text', '.submit' => 'button', '.image' => 'imagebutton', '.button' => 'button', ], 'label' => [ 'container' => null, 'suffix' => null, 'requiredsuffix' => '', ], 'hidden' => [ 'container' => 'div', ], ]; /** * Provides complete form rendering. * @param Form $form * @param string|null $mode 'begin', 'errors', 'ownerrors', 'body', 'end' or empty to render all * @return string */ public function render(Form $form, string $mode = null): string { foreach ($form->getControls() as $control) { if ($control instanceof Button) { if ($control->getControlPrototype()->getClass() === null || strpos($control->getControlPrototype()->getClass(), 'btn') === false) { $control->getControlPrototype()->addClass(empty($usedPrimary) ? 'btn btn-info' : 'btn btn-default'); $usedPrimary = true; } } elseif ($control instanceof TextBase || $control instanceof SelectBox || $control instanceof MultiSelectBox) { $control->getControlPrototype()->addClass('form-control fg-input'); } elseif ($control instanceof CheckboxList || $control instanceof RadioList) { $control->getSeparatorPrototype()->setName('div')->addClass($control->getControlPrototype()->type); } } return parent::render($form, $mode); } public function renderControl(Control $control): Html { if ($control instanceof Checkbox) { $el = Html::el("div", [ 'class' => 'toggle-switch', 'data-ts-color' => 'cyan', ]); $el->addHtml($control->getLabelPart()->addClass('ts-label')); $el->addHtml($control->getControlPart()); $el->addHtml('<label for="' . $control->htmlId . '" class="ts-helper"></label>'); return $el; } return parent::renderControl($control); } public function renderPair(Control $control): string { if (!$control instanceof BaseControl) { throw new \Exception('Unable to use MaterialRenderer, control needs to extend Nette\Forms\Controls\BaseControl'); } $outer = $pair = $this->getWrapper('pair container'); $isTextInput = $control instanceof TextInput; if ($isTextInput) { $inner = $this->getWrapper('pair inner-container'); $pair->addHtml($inner); $pair = $inner; } $pair->addHtml($this->renderMaterialLabel($control, $isTextInput)); $pair->addHtml($this->renderControl($control)); $pair->class($this->getValue($control->isRequired() ? 'pair .required' : 'pair .optional'), true); $pair->class($control->hasErrors() ? $this->getValue('pair .error') : null, true); $pair->class($control->getOption('class'), true); if (++$this->counter % 2) { $pair->class($this->getValue('pair .odd'), true); } $pair->id = $control->getOption('id'); return $outer->render(0); } public function renderMaterialLabel(BaseControl $control, bool $animatedLabel): Html { $label = $control->getLabel(); if ($label instanceof Html) { if ($control->isRequired()) { $label->class($this->getValue('control .required'), true); } if ($animatedLabel) { $label->class('fg-label'); } } return $this->getWrapper('label container')->setHtml($label); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Beam/Client.php
Mailer/extensions/mailer-module/src/Models/Beam/Client.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Beam; use Exception; use GuzzleHttp\Exception\ConnectException; use GuzzleHttp\Exception\ServerException; use GuzzleHttp\RequestOptions; use Nette\Utils\Json; class Client { private $client; public function __construct(?string $baseUrl, ?string $token) { if ($baseUrl) { $this->client = new \GuzzleHttp\Client([ 'base_uri' => $baseUrl, 'headers' => [ 'Authorization' => 'Bearer ' . $token, 'Accept' => 'application/json', ] ]); } } public function unreadArticles( $timespan, $articlesCount, array $criteria, array $userIds, array $ignoreAuthors = [], array $ignoreContentTypes = [] ): array { if (!$this->client) { throw new \Exception('Beam Client is not configured'); } try { $response = $this->client->post('api/articles/unread', [ RequestOptions::JSON => [ 'user_ids' => $userIds, 'timespan' => $timespan, 'articles_count' => $articlesCount, 'criteria' => $criteria, 'ignore_authors' => $ignoreAuthors, 'ignore_content_types' => $ignoreContentTypes, ] ]); return Json::decode($response->getBody()->getContents(), Json::FORCE_ARRAY)['data']; } catch (ConnectException $connectException) { throw new Exception("could not connect to Beam: {$connectException->getMessage()}"); } catch (ServerException $serverException) { throw new Exception("Beam service error: {$serverException->getMessage()}"); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Beam/UnreadArticlesResolver.php
Mailer/extensions/mailer-module/src/Models/Beam/UnreadArticlesResolver.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Beam; use Remp\MailerModule\Models\PageMeta\Content\ContentInterface; use Remp\MailerModule\Models\PageMeta\Content\InvalidUrlException; class UnreadArticlesResolver { private $templates = []; private $requiredTemplateArticlesCount = []; private $results = []; private $articlesMeta = []; private $beamClient; private $content; public function __construct( Client $beamClient, ContentInterface $content ) { $this->beamClient = $beamClient; $this->content = $content; } public function addToResolveQueue(string $templateCode, int $userId, array $parameters): void { if (!array_key_exists($templateCode, $this->templates)) { $item = new \stdClass(); $item->timespan = $parameters['timespan']; $item->articlesCount = $parameters['articles_count']; $item->criteria = $parameters['criteria']; $item->ignoreAuthors = $parameters['ignore_authors'] ?? []; $item->ignoreContentTypes = $parameters['ignore_content_types'] ?? []; $item->userIds = []; $this->templates[$templateCode] = $item; } // $this->templates queue is cleaned after each resolve, therefore store number of required articles // in an additional property - so we can check later that enough parameters are resolved for each template if (!array_key_exists($templateCode, $this->requiredTemplateArticlesCount)) { $this->requiredTemplateArticlesCount[$templateCode] = $parameters['articles_count']; } $this->templates[$templateCode]->userIds[] = $userId; } /** * Resolves all parameters added to resolve queue (and subsequently empties the queue) * Resolved parameters can be retrieved using getResolvedMailParameters() method * @throws \Exception */ public function resolve(): void { foreach ($this->templates as $templateCode => $item) { foreach (array_chunk($item->userIds, 1000) as $userIdsChunk) { $results = $this->beamClient->unreadArticles( $item->timespan, $item->articlesCount, $item->criteria, $userIdsChunk, $item->ignoreAuthors, $item->ignoreContentTypes ); foreach ($results as $userId => $urls) { $this->results[$templateCode][$userId] = $urls; } } } $this->templates = []; } public function getResolvedMailParameters(string $templateCode, int $userId): array { $this->checkValidParameters($templateCode, $userId); $params = []; $headlineTitle = null; foreach ($this->results[$templateCode][$userId] as $i => $url) { if (!array_key_exists($url, $this->articlesMeta)) { try { $meta = $this->content->fetchUrlMeta($url); } catch (InvalidUrlException $e) { $meta = null; } if (!$meta) { throw new UserUnreadArticlesResolveException("Unable to fetch meta for url {$url} when resolving article parameters for userId: {$userId}, templateCode: {$templateCode}"); } $this->articlesMeta[$url] = $meta; } $meta = $this->articlesMeta[$url]; $counter = $i + 1; $params["article_{$counter}_title"] = $meta->getTitle(); $params["article_{$counter}_description"] = $meta->getDescription(); $params["article_{$counter}_image"] = $meta->getImage(); $params["article_{$counter}_href_url"] = $url; if (!$headlineTitle) { $headlineTitle = $meta->getTitle(); } } $params['headline_title'] = $headlineTitle; return $params; } private function checkValidParameters(string $templateCode, int $userId): void { // check enough parameters were resolved for template $requiredArticleCount = (int) $this->requiredTemplateArticlesCount[$templateCode]; $userArticleCount = count($this->results[$templateCode][$userId]); if ($userArticleCount < $requiredArticleCount) { throw new UserUnreadArticlesResolveException("Template $templateCode requires $requiredArticleCount unread articles, user #$userId has only $userArticleCount, unable to send personalized email."); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Beam/JournalFactory.php
Mailer/extensions/mailer-module/src/Models/Beam/JournalFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Beam; use GuzzleHttp\Client; use Remp\Journal\Journal; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; class JournalFactory { use RedisClientTrait; private $client; public function __construct(?string $baseUrl, RedisClientFactory $redisClientFactory) { if ($baseUrl) { $client = new Client([ 'base_uri' => $baseUrl, 'headers' => [ 'Accept' => 'application/json', ] ]); $this->client = new Journal($client, $redisClientFactory->getClient()); } } public function getClient(): ?Journal { return $this->client; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Models/Beam/UserUnreadArticlesResolveException.php
Mailer/extensions/mailer-module/src/Models/Beam/UserUnreadArticlesResolveException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Models\Beam; use Exception; class UserUnreadArticlesResolveException 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/Forms/NewBatchFormFactory.php
Mailer/extensions/mailer-module/src/Forms/NewBatchFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\LinkGenerator; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Security\User; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Auth\PermissionManager; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Tracy\Debugger; class NewBatchFormFactory { use SmartObject; private const FORM_ACTION_SAVE_START = 'save_start'; public $onSuccess; public function __construct( private JobsRepository $jobsRepository, private BatchesRepository $batchesRepository, private TemplatesRepository $templatesRepository, private BatchTemplatesRepository $batchTemplatesRepository, private ListsRepository $listsRepository, private Aggregator $segmentAggregator, private PermissionManager $permissionManager, private User $user, private LinkGenerator $linkGenerator, private ListVariantsRepository $listVariantsRepository, ) { } public function create(?int $jobId) { $form = new Form; $form->addProtection(); if ($jobId === null) { $segments = []; $segmentList = $this->segmentAggregator->list(); array_walk($segmentList, function ($segment) use (&$segments) { $segments[$segment['provider']][$segment['provider'] . '::' . $segment['code']] = $segment['name']; }); if ($this->segmentAggregator->hasErrors()) { $form->addError('Unable to fetch list of segments, please check the application configuration.'); Debugger::log($this->segmentAggregator->getErrors()[0], Debugger::WARNING); } $form->addMultiSelect('include_segment_codes', 'Include segments', $segments) ->setRequired("You have to include at least one segment."); $form->addMultiSelect('exclude_segment_codes', 'Exclude segments', $segments); } $methods = [ 'random' => 'Random', 'sequential' => 'Sequential', ]; $form->addSelect('method', 'Method', $methods); $listPairs = $this->listsRepository->all()->fetchPairs('id', 'title'); $mailTypeField = $form->addSelect('mail_type_id', 'Newsletter list', $listPairs) ->setPrompt('Select newsletter list'); if (isset($_POST['mail_type_id'])) { $variantsList = $this->getMailTypeVariants((int) $_POST['mail_type_id']); $templateList = $this->templatesRepository->pairs((int) $_POST['mail_type_id']); } else { $variantsList = $templateList = null; } if ($jobId === null) { $form->addSelect('mail_type_variant_id', 'List 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:MailTypeVariants', ['id'=>'%value%'])); } $templateFieldA = $form->addSelect('template_id', 'Email A alternative', $templateList) ->setPrompt('Select email') ->setRequired('Email for A alternative is required') ->setHtmlAttribute('data-depends', $mailTypeField->getHtmlName()) // %value% will be replaced by selected ID from 'data-depends' input ->setHtmlAttribute('data-url', $this->linkGenerator->link('Mailer:Job:MailTypeTemplates', ['id'=>'%value%'])); $templateFieldB = $form->addSelect('b_template_id', 'Email B alternative', $templateList) ->setPrompt('Select alternative email'); // Mirror dependent data (mail_templates) to template_b, to avoid duplicate ajax call $templateFieldA->setHtmlAttribute('data-mirror-to', $templateFieldB->getHtmlName()); $form->addText('email_count', 'Number of emails'); $form->addText('start_at', 'Start date'); if ($jobId === null) { $form->addText('context', 'Context') ->setNullable(); } $form->addHidden('job_id', $jobId); $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save draft'); if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { $form->addSubmit(self::FORM_ACTION_SAVE_START) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and start sending now'); } $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } private function getMailTypeVariants($mailTypeId): array { $mailType = $this->listsRepository->find($mailTypeId); if (!$mailType) { return []; } return $this->listVariantsRepository->getVariantsForType($mailType) ->order('sorting') ->fetchPairs('id', 'title'); } public function formSucceeded(Form $form, ArrayHash $values): void { if ($values['template_id'] === $values['b_template_id']) { $form->addError("Email A alternative and Email B Alternative cannot be the same."); return; } if (!$values['job_id']) { $jobSegmentsManager = new JobSegmentsManager(); foreach ($values['include_segment_codes'] as $includeSegment) { [$provider, $code] = explode('::', $includeSegment); $jobSegmentsManager->includeSegment($code, $provider); } foreach ($values['exclude_segment_codes'] as $excludeSegment) { [$provider, $code] = explode('::', $excludeSegment); $jobSegmentsManager->excludeSegment($code, $provider); } $variant = null; if (isset($values['mail_type_variant_id'])) { $variant = $this->listVariantsRepository->find($values['mail_type_variant_id']); } $values['job_id'] = $this->jobsRepository->add($jobSegmentsManager, $values->context, $variant)->id; } else { $values['job_id'] = (int)$values['job_id']; } $batch = $this->batchesRepository->add( (int) $values['job_id'], !empty($values['email_count']) ? (int)$values['email_count'] : null, $values['start_at'], $values['method'] ); $this->batchTemplatesRepository->add( (int) $values['job_id'], $batch->id, $values['template_id'] ); if ($values['b_template_id'] !== null) { $this->batchTemplatesRepository->add( (int) $values['job_id'], $batch->id, $values['b_template_id'] ); } if ($this->permissionManager->isAllowed($this->user, 'batch', 'start')) { /** @var SubmitButton $buttonSaveStart */ $buttonSaveStart = $form[self::FORM_ACTION_SAVE_START]; if ($buttonSaveStart->isSubmittedBy()) { $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND); } } ($this->onSuccess)($batch->job); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/IFormFactory.php
Mailer/extensions/mailer-module/src/Forms/IFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; interface IFormFactory { const FORM_ACTION_SAVE = 'save'; const FORM_ACTION_SAVE_CLOSE = 'save_close'; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/NewTemplateFormFactory.php
Mailer/extensions/mailer-module/src/Forms/NewTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\SmartObject; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class NewTemplateFormFactory { use SmartObject; private $templatesRepository; private $batchesRepository; private $batchTemplatesRepository; private $listsRepository; public $onSuccess; public function __construct( TemplatesRepository $templatesRepository, BatchesRepository $batchesRepository, BatchTemplatesRepository $batchTemplatesRepository, ListsRepository $listsRepository ) { $this->templatesRepository = $templatesRepository; $this->batchesRepository = $batchesRepository; $this->batchTemplatesRepository = $batchTemplatesRepository; $this->listsRepository = $listsRepository; } public function create($batchId) { $form = new Form; $form->addProtection(); $batchTemplates = $this->batchTemplatesRepository->findByBatchId((int) $batchId); $mailTypeId = $batchTemplates->fetch()->mail_template->mail_type_id; $templateList = $this->templatesRepository->filteredPairs( listId: $mailTypeId, filterTemplateIds: array_values($batchTemplates->fetchPairs('id', 'mail_template_id')), limit: 10000, // this limit is arbitrary, but things could get ugly without it ); $form->addSelect('template_id', 'Email', $templateList); $form->addHidden('batch_id', $batchId); $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded($form, $values) { $batch = $this->batchesRepository->find((int)$values['batch_id']); $job = $batch->ref('job'); $batchTemplate = $this->batchTemplatesRepository->add( $job->id, $batch->id, $values['template_id'] ); ($this->onSuccess)($job); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/TemplateFormFactory.php
Mailer/extensions/mailer-module/src/Forms/TemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\Database\Explorer; use Nette\Forms\Controls\SubmitButton; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Api\v1\Handlers\Mailers\MailCreateTemplateHandler; use Remp\MailerModule\Forms\Rules\FormRules; use Remp\MailerModule\Models\ContentGenerator\ContentGenerator; use Remp\MailerModule\Models\ContentGenerator\GeneratorInputFactory; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\TemplatesCodeNotUniqueException; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\TemplateTranslationsRepository; class TemplateFormFactory implements IFormFactory { use SmartObject; private TemplatesRepository $templatesRepository; private LayoutsRepository $layoutsRepository; private ListsRepository $listsRepository; private TemplateTranslationsRepository $templateTranslationsRepository; public $onCreate; public $onUpdate; private $contentGenerator; private $database; private $generatorInputFactory; public function __construct( TemplatesRepository $templatesRepository, LayoutsRepository $layoutsRepository, ListsRepository $listsRepository, ContentGenerator $contentGenerator, Explorer $database, GeneratorInputFactory $generatorInputFactory, TemplateTranslationsRepository $templateTranslationsRepository ) { $this->templatesRepository = $templatesRepository; $this->layoutsRepository = $layoutsRepository; $this->listsRepository = $listsRepository; $this->contentGenerator = $contentGenerator; $this->database = $database; $this->generatorInputFactory = $generatorInputFactory; $this->templateTranslationsRepository = $templateTranslationsRepository; } public function create(?int $id = null, ?string $lang = null): Form { $count = 0; $defaults = []; $layouts = $this->layoutsRepository->all()->fetchPairs('id', 'name'); $lists = $this->listsRepository->all()->fetchPairs('id', 'title'); $firstList = $this->listsRepository->find(key($lists)); if (isset($id)) { $template = $this->templatesRepository->find($id); $count = $template->related('mail_logs', 'mail_template_id')->count('*'); $defaults = $template->toArray(); if (isset($lang)) { $templateTranslation = $template->related('mail_template_translations', 'mail_template_id') ->where('locale', $lang) ->fetch(); $defaults['from'] = $templateTranslation->from ?? ''; $defaults['subject'] = $templateTranslation->subject ?? ''; $defaults['mail_body_text'] = $templateTranslation->mail_body_text ?? ''; $defaults['mail_body_html'] = $templateTranslation->mail_body_html ?? ''; } } else { $defaults['mail_layout_id'] = key($layouts); $defaults['from'] = $firstList->mail_from ?? ''; } $form = new Form; $form->addProtection(); $form->addHidden('id', $id); $form->addHidden('lang', $lang); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required.") ->addRule( Form::MaxLength, "The name cannot be longer than %d characters.", MailCreateTemplateHandler::NAME_MAX_LENGTH ); if (isset($id) && $count > 0) { $form->addText('code', 'Code') ->setRequired("Field 'Code' is required.") ->setDisabled(); } else { $form->addText('code', 'Code') ->setRequired("Field 'Code' is required."); } $form->addText('description', 'Description'); $select = $form->addSelect('mail_layout_id', 'Layout', $layouts); if (!$layouts) { $select->addError("No Layouts found, please create some first."); } $field = $form->addSelect('mail_type_id', 'Newsletter list', $lists) ->setRequired("Field 'Newsletter list' is required."); if (!$lists) { $field->addError("No Newsletter lists found, please create some first."); } $form->addText('from', 'From') ->addRule(FormRules::ADVANCED_EMAIL, 'Enter correct email') ->setRequired("Field 'From' is required."); $form->addText('subject', 'Subject') ->setRequired("Field 'Subject' is required."); $form->addSelect('click_tracking', 'Click tracking', [ null => 'Default mailer settings (depends on your provider configuration)', 1 => "Enabled", 0 => "Disabled", ]); $form->addTextArea('mail_body_text', 'Text version') ->setHtmlAttribute('rows', 3); $form->addTextArea('mail_body_html', 'HTML version'); $form->setDefaults($defaults); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml($id ? '<i class="zmdi zmdi-check"></i> Save' : '<i class="zmdi zmdi-caret-right"></i> Continue'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { // decide if user wants to save or save and leave $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } if ($values['click_tracking'] === "") { // handle null (default) selection $values['click_tracking'] = null; } else { $values['click_tracking'] = (bool) $values['click_tracking']; } $this->database->beginTransaction(); try { $row = null; $callback = null; $lang = $values['lang'] ?? null; unset($values['lang']); if (!empty($values['id'])) { $row = $this->templatesRepository->find($values['id']); if ($lang) { $this->templateTranslationsRepository->upsert( $row, $lang, $values['from'], $values['subject'], $values['mail_body_text'], $values['mail_body_html'] ); unset($values['from'], $values['subject'], $values['mail_body_text'], $values['mail_body_html']); } $this->templatesRepository->update($row, (array) $values); $row = $this->templatesRepository->find($values['id']); $callback = $this->onUpdate; } else { $row = $this->templatesRepository->add( $values['name'], $values['code'], $values['description'], $values['from'], $values['subject'], $values['mail_body_text'], $values['mail_body_html'], $values['mail_layout_id'], $values['mail_type_id'], $values['click_tracking'] ); $callback = $this->onCreate; } $this->contentGenerator->render($this->generatorInputFactory->create($row)); } catch (TemplatesCodeNotUniqueException $e) { $this->database->rollback(); $form->getComponent('code')->addError($e->getMessage()); return; } catch (\Exception $exception) { $this->database->rollback(); $form->addError($exception->getMessage()); return; } $this->database->commit(); ($callback)($row, $buttonSubmitted); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/SourceTemplateFormFactory.php
Mailer/extensions/mailer-module/src/Forms/SourceTemplateFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Exception; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory; use Remp\MailerModule\Models\Generators\GeneratorFactory; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; class SourceTemplateFormFactory implements IFormFactory { public $onUpdate; public $onSave; public function __construct( private readonly SourceTemplatesRepository $mailSourceTemplateRepository, private readonly GeneratorFactory $mailGeneratorFactory, private readonly EngineFactory $engineFactory, private readonly SnippetsRepository $snippetsRepository, ) { } public function create(?int $id = null): Form { $mailTemplate = null; $defaults = []; if ($id !== null) { $mailTemplate = $this->mailSourceTemplateRepository->find($id); $defaults = $mailTemplate->toArray(); } $form = new Form; $form->addProtection(); $form->addHidden('id', $id); $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->addText('code', 'Code') ->setRequired("Field 'Code' is required."); $items = $this->mailGeneratorFactory->pairs(); $form->addSelect('generator', 'Generator', $items) ->setRequired("Field 'Generator' is required."); $orderOptions = [ 'begin' => 'At the beginning', 'end' => 'At the end', ]; $sortingPairs = $this->mailSourceTemplateRepository->getSortingPairs(); if (count($sortingPairs) > 0) { $orderOptions['after'] = 'After'; } $form->addRadioList('sorting', 'Order', $orderOptions)->setRequired("Field 'Order' is required."); if ($mailTemplate !== null) { $keys = array_keys($sortingPairs); if (reset($keys) === $mailTemplate->sorting) { $defaults['sorting'] = 'begin'; unset($defaults['sorting_after']); } elseif (end($keys) === $mailTemplate->sorting) { $defaults['sorting'] = 'end'; unset($defaults['sorting_after']); } else { $defaults['sorting'] = 'after'; foreach ($sortingPairs as $sorting => $_) { if ($mailTemplate->sorting <= $sorting) { break; } $defaults['sorting_after'] = $sorting; } } unset($sortingPairs[$mailTemplate->sorting]); } $form->addSelect('sorting_after', null, $sortingPairs) ->setPrompt('Choose newsletter list'); $form->addTextArea('content_text', 'Text') ->setHtmlAttribute('rows', 20) ->getControlPrototype() ->addAttributes(['class' => 'ace', 'data-lang' => 'text']); $form->addTextArea('content_html', 'HTML') ->setHtmlAttribute('rows', 60) ->getControlPrototype() ->addAttributes(['class' => 'ace', 'data-lang' => 'html']); $form->setDefaults($defaults); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-check"></i> Save'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { // decide if user wants to save or save and leave $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } $template = null; if (isset($values['id'])) { $template = $this->mailSourceTemplateRepository->find($values['id']); } $templatesSortingPairs = $this->mailSourceTemplateRepository->getSortingPairs(); try { $this->attemptToRender($values['content_html'], 'html'); $this->attemptToRender($values['content_text'], 'text'); } catch (Exception $e) { $form->addError($e->getMessage()); return; } switch ($values['sorting']) { case 'begin': $first = reset($templatesSortingPairs); $values['sorting'] = $first ? array_key_first($templatesSortingPairs) - 1 : 1; break; case 'after': // fix missing form value because of dynamically loading select options // in ListPresenter->handleRenderSorting if ($values['sorting_after'] === null) { $formHttpData = $form->getHttpData(); // + add validation if (empty($formHttpData['sorting_after'])) { $form->addError("Field 'Order' is required."); return; } $values['sorting_after'] = $formHttpData['sorting_after']; } $values['sorting'] = $values['sorting_after']; if (!$template || ($template && $template->sorting > $values['sorting_after']) ) { $values['sorting'] += 1; } break; default: case 'end': $last = end($templatesSortingPairs); $values['sorting'] = $last ? array_key_last($templatesSortingPairs) + 1 : 1; break; } $this->mailSourceTemplateRepository->updateSorting( $values['sorting'], $template->sorting ?? null ); unset($values['sorting_after']); if ($template) { $this->mailSourceTemplateRepository->update($template, (array) $values); $template = $this->mailSourceTemplateRepository->find($template->id); $this->onUpdate->__invoke($form, $template, $buttonSubmitted); } else { $template = $this->mailSourceTemplateRepository->add( $values['title'], $values['code'], $values['generator'], $values['content_html'], $values['content_text'], $values['sorting'] ); $this->onSave->__invoke($form, $template, $buttonSubmitted); } } /** * @param string $template * @param string $version * @return void * @throws Exception */ private function attemptToRender(string $template, string $version): void { $engine = $this->engineFactory->engine(); $generatedTemplate = $engine->render(preg_replace('/{%[^%]+%}/m', '', $template)); $engine->render($generatedTemplate, ['snippets' => $this->snippetsRepository->all()->fetchPairs('code', $version)]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/JobFormFactory.php
Mailer/extensions/mailer-module/src/Forms/JobFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\FormRenderer\MaterialRenderer; use Remp\MailerModule\Models\Job\JobSegmentsManager; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Tracy\Debugger; class JobFormFactory { use SmartObject; private $jobsRepository; private $batchesRepository; private $segmentAggregator; public $onSuccess; public $onError; public function __construct( JobsRepository $jobsRepository, BatchesRepository $batchesRepository, Aggregator $segmentAggregator ) { $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->segmentAggregator = $segmentAggregator; } public function create(int $jobId): Form { $form = new Form(); $form->addProtection(); $form->setRenderer(new MaterialRenderer()); $form->addHidden('job_id', $jobId); $job = $this->jobsRepository->find($jobId); if (!$job) { $form->addError('Unable to load Mail Job.'); } if ($this->batchesRepository->notEditableBatches($jobId)->count() > 0) { $form->addError("Job can't be updated. One or more Mail Job Batches were already started."); } $segments = []; $segmentList = $this->segmentAggregator->list(); array_walk($segmentList, function ($segment) use (&$segments) { $segments[$segment['provider']][$segment['provider'] . '::' . $segment['code']] = $segment['name']; }); if ($this->segmentAggregator->hasErrors()) { $form->addError('Unable to fetch list of segments, please check the application configuration.'); Debugger::log($this->segmentAggregator->getErrors()[0], Debugger::WARNING); } $jobSegmentsManager = new JobSegmentsManager($job); $includeSegmentsDefault = array_map(static function (array $includeSegment) { return $includeSegment['provider'] . '::' . $includeSegment['code']; }, $jobSegmentsManager->getIncludeSegments()); $form->addMultiSelect('include_segment_codes', 'Include segments', $segments) ->setRequired("You have to include at least one segment.") ->setHtmlAttribute('class', 'selectpicker') ->setHtmlAttribute('data-live-search', 'true') ->setHtmlAttribute('data-live-search-normalize', 'true') ->setDefaultValue($includeSegmentsDefault); $excludeSegmentsDefault = array_map(static function (array $excludeSegment) { return $excludeSegment['provider'] . '::' . $excludeSegment['code']; }, $jobSegmentsManager->getExcludeSegments()); $form->addMultiSelect('exclude_segment_codes', 'Exclude segments', $segments) ->setHtmlAttribute('class', 'selectpicker') ->setHtmlAttribute('data-live-search', 'true') ->setHtmlAttribute('data-live-search-normalize', 'true') ->setDefaultValue($excludeSegmentsDefault); $form->addText('context', 'Context') ->setNullable() ->setDefaultValue($job->context); $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $job = $this->jobsRepository->find($values['job_id']); $jobSegmentsManager = new JobSegmentsManager(); foreach ($values['include_segment_codes'] as $includeSegment) { [$provider, $code] = explode('::', $includeSegment); $jobSegmentsManager->includeSegment($code, $provider); } foreach ($values['exclude_segment_codes'] as $excludeSegment) { [$provider, $code] = explode('::', $excludeSegment); $jobSegmentsManager->excludeSegment($code, $provider); } $jobNewData = [ 'segments' => $jobSegmentsManager->toJson(), 'context' => $values->context, ]; try { $this->jobsRepository->update($job, $jobNewData); $job = $this->jobsRepository->find($job->id); } catch (\Exception $e) { ($this->onError)($job, $e->getMessage()); } ($this->onSuccess)($job); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/ListFormFactory.php
Mailer/extensions/mailer-module/src/Forms/ListFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\LinkGenerator; use Nette\Application\UI\Form; use Nette\Database\Table\ActiveRow; use Nette\Forms\Controls\BaseControl; use Nette\Forms\Controls\SelectBox; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Sender\MailerFactory; use Remp\MailerModule\Repositories\ListCategoriesRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\MailTypesRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class ListFormFactory { use SmartObject; private const SORTING = 'sorting'; private const SORTING_AFTER = 'sorting_after'; private const MAIL_TYPE_CATEGORY = 'mail_type_category_id'; private const LIST_ID = 'id'; public $onCreate; public $onUpdate; public function __construct( private readonly ListsRepository $listsRepository, private readonly ListCategoriesRepository $listCategoriesRepository, private readonly MailerFactory $mailerFactory, private readonly MailTypesRepository $mailTypesRepository, private readonly TemplatesRepository $templatesRepository, private readonly LinkGenerator $linkGenerator ) { } public function create(?int $id = null): Form { $list = null; $defaults = []; $form = new Form; $form->addProtection(); if ($id !== null) { $list = $this->listsRepository->find($id); $defaults = $list->toArray(); $templates = $this->templatesRepository ->findByList($id, 500) ->select('public_code, name') ->order('created_at DESC') ->fetchAll(); $templatePairs = [null => "Select email to prefill email's public preview URL or enter the URL directly."]; foreach ($templates as $template) { $previewUrl = $this->linkGenerator->link('Mailer:Preview:Public', [$template['public_code']]); $templatePairs[$previewUrl] = $template['name']; } $form->addSelect('preview_template', 'Preview email', $templatePairs); } $categoryPairs = $this->listCategoriesRepository->all()->fetchPairs('id', 'title'); if (!isset($defaults['mail_type_category_id'])) { $defaults['mail_type_category_id'] = key($categoryPairs); } $form->addSelect( 'mail_type_category_id', 'Category', $categoryPairs )->setRequired("Field 'Category' is required."); $subscriptionEligibleTemplates = $this->getSubscriptionEligibleTemplates($list); $form->addSelect( 'subscribe_mail_template_id', 'Subscription welcome email', $subscriptionEligibleTemplates )->setPrompt('None'); $form->addSelect( 'unsubscribe_mail_template_id', 'Unsubscribe goodbye email', $subscriptionEligibleTemplates )->setPrompt('None'); $form->addText('priority', 'Priority') ->addRule(Form::INTEGER, "Priority needs to be a number") ->addRule(Form::MIN, "Priority needs to be greater than 0", 1) ->setRequired("Field 'Priority' is required."); $codeInput = $form->addText('code', 'Code') ->setRequired("Field 'Code' is required.") ->addRule(function ($input) { $exists = $this->listsRepository->getTable() ->where('code = ?', $input->value) ->count('*'); return !$exists; }, "Newsletter list code must be unique. Code '%value' is already used."); $mailers = []; $availableMailers = $this->mailerFactory->getAvailableMailers(); array_walk($availableMailers, function ($mailer, $name) use (&$mailers) { $mailers[$name] = $mailer->getIdentifier(); }); $form->addSelect('mailer_alias', 'Sending mailer', $mailers) ->setPrompt('Using default mailer set in configuration'); if ($list !== null) { $codeInput->setDisabled(true); } $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->addTextArea('description', 'Description') ->setHtmlAttribute('rows', 3); $form->addText('mail_from', 'From'); $form->addText('preview_url', 'Preview URL')->setNullable(); $form->addText('page_url', 'Page URL'); $form->addText('image_url', 'Image URL'); $orderOptions = [ 'begin' => 'At the beginning', 'end' => 'At the end', ]; $sortingPairs = $this->listsRepository ->findByCategory($defaults['mail_type_category_id']) ->order('sorting ASC') ->fetchPairs('sorting', 'title'); if (count($sortingPairs) > 0) { $orderOptions['after'] = 'After'; } $form->addRadioList(self::SORTING, 'Order', $orderOptions)->setRequired("Field 'Order' is required."); if ($list !== null) { $keys = array_keys($sortingPairs); if (reset($keys) === $list->sorting) { $defaults[self::SORTING] = 'begin'; unset($defaults[self::SORTING_AFTER]); } elseif (end($keys) === $list->sorting) { $defaults[self::SORTING] = 'end'; unset($defaults[self::SORTING_AFTER]); } else { $defaults[self::SORTING] = 'after'; foreach ($sortingPairs as $sorting => $_) { if ($list->sorting <= $sorting) { break; } $defaults[self::SORTING_AFTER] = $sorting; } } unset($sortingPairs[$list->sorting]); } $form->addSelect(self::SORTING_AFTER, null, $sortingPairs) ->setPrompt('Choose newsletter list'); $form->addCheckbox('auto_subscribe', 'Auto subscribe'); $form->addCheckbox('locked', 'Locked'); $form->addCheckbox('public_listing', 'List publicly'); $form->addHidden('id', $id); $form->setDefaults($defaults); $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } /** * @param Form $form * @param ArrayHash $values * @throws \Exception */ public function formSucceeded(Form $form, ArrayHash $values): void { $list = null; if (isset($values['id'])) { $list = $this->listsRepository->find($values['id']); } $listsInCategory = $this->listsRepository ->findByCategory($values['mail_type_category_id']) ->order('mail_types.sorting') ->fetchAll(); switch ($values[self::SORTING]) { case 'begin': $first = reset($listsInCategory); $values[self::SORTING] = $first ? $first->sorting - 1 : 1; break; case 'after': // fix missing form value because of dynamically loading select options // in ListPresenter->handleRenderSorting if ($values[self::SORTING_AFTER] === null) { $formHttpData = $form->getHttpData(); // + add validation if (empty($formHttpData[self::SORTING_AFTER])) { $form->addError("Field 'Order' is required."); return; } $values[self::SORTING_AFTER] = $formHttpData[self::SORTING_AFTER]; } $values[self::SORTING] = $values[self::SORTING_AFTER]; if (!$list || $values[self::MAIL_TYPE_CATEGORY] != $list->mail_type_category_id || ($list && $list->sorting > $values[self::SORTING_AFTER]) ) { $values[self::SORTING] += 1; } break; default: case 'end': $last = end($listsInCategory); $values[self::SORTING] = $last ? $last->sorting + 1 : 1; break; } $this->listsRepository->updateSorting( $values[self::MAIL_TYPE_CATEGORY], $values[self::SORTING], $list->mail_type_category_id ?? null, $list->sorting ?? null ); unset($values[self::SORTING_AFTER], $values['preview_template']); if ($list) { $this->listsRepository->update($list, (array) $values); $list = $this->listsRepository->find($list->id); ($this->onUpdate)($list); } else { $row = $this->listsRepository->add( $values[self::MAIL_TYPE_CATEGORY], $values['priority'], $values['code'], $values['title'], $values[self::SORTING], $values['auto_subscribe'], $values['locked'], $values['description'], $values['preview_url'], $values['page_url'], $values['image_url'], $values['public_listing'], $values['mail_from'], $values['subscribe_mail_template_id'], $values['unsubscribe_mail_template_id'], ); ($this->onCreate)($row); } } public function getSortingControl(Form $form): BaseControl { return $form[self::SORTING]; } public function getMailTypeCategoryIdControl(Form $form): BaseControl { return $form[self::MAIL_TYPE_CATEGORY]; } public function getListIdControl(Form $form): BaseControl { return $form[self::LIST_ID]; } public function getSortingAfterControl(Form $form): SelectBox { /** @var SelectBox $sortingAfter */ $sortingAfter = $form[self::SORTING_AFTER]; return $sortingAfter; } /** * @return array<string, array<string, string>> */ private function getSubscriptionEligibleTemplates(?ActiveRow $list): array { $items = []; // System mails $systemList = $this->mailTypesRepository->findBy('code', 'system'); if ($systemList !== null) { $systemEmails = $this->templatesRepository ->getByMailTypeIds([$systemList->id]) ->select('mail_templates.id, mail_templates.name') ->fetchPairs('id', 'name'); $items[$systemList->title] = $systemEmails; } if ($list !== null && $list->id !== $systemList->id) { $newsletterEmails = $this->templatesRepository ->findByList($list->id) ->select('mail_templates.id, mail_templates.name') ->order('mail_templates.id DESC') ->limit(1000) ->fetchPairs('id', 'name'); if (count($newsletterEmails) > 0) { $items[$list->title] = $newsletterEmails; } } 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/Forms/ListCategoryFormFactory.php
Mailer/extensions/mailer-module/src/Forms/ListCategoryFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Exception; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Repositories\ListCategoriesRepository; class ListCategoryFormFactory implements IFormFactory { use SmartObject; public $onUpdate; public function __construct( private readonly ListCategoriesRepository $listCategoriesRepository ) { } public function create(int $id): Form { $form = new Form; $form->addProtection(); $listCategory = $this->listCategoriesRepository->find($id); $defaults = $listCategory->toArray(); $form->addText('sorting', 'Sorting') ->addRule(Form::INTEGER, "Sorting needs to be a number") ->addRule(Form::MIN, "Sorting needs to be greater than 0", 1) ->setRequired("Field 'Sorting' is required."); $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->addHidden('id', $id); $form->setDefaults($defaults); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-check"></i> Save'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } /** * @param Form $form * @param ArrayHash $values * @throws Exception */ public function formSucceeded(Form $form, ArrayHash $values): void { $listCategory = null; if (isset($values['id'])) { $listCategory = $this->listCategoriesRepository->find($values['id']); } if ($listCategory) { $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } $this->listCategoriesRepository->update($listCategory, (array)$values); $listCategory = $this->listCategoriesRepository->find($listCategory->id); ($this->onUpdate)($listCategory, $buttonSubmitted); } throw new Exception('List category not found.'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/SignInFormFactory.php
Mailer/extensions/mailer-module/src/Forms/SignInFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\Security\AuthenticationException; use Nette\Security\User; use Nette\SmartObject; class SignInFormFactory { use SmartObject; /** @var User */ private $user; public $onSignIn; public function __construct(User $user) { $this->user = $user; } public function create() { $form = new Form(); $form->addProtection(); $form->addText('username', 'Email Address') ->setHtmlType('email') ->setRequired('Please enter your email'); $form->addPassword('password', 'Password') ->setRequired('Please enter your password.'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded($form, $values) { try { $this->user->login($values->username, $values->password); ($this->onSignIn)($this->user->getIdentity()); } catch (AuthenticationException $exception) { $form->addError($exception->getMessage()); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/DuplicateListFormFactory.php
Mailer/extensions/mailer-module/src/Forms/DuplicateListFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Exception; use InvalidArgumentException; use Nette\Application\UI\Form; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\ListVariantsRepository; class DuplicateListFormFactory { use SmartObject; public $onCreate; public function __construct( private readonly ListsRepository $listsRepository, private readonly ListVariantsRepository $listVariantsRepository, ) { } public function create(int $id): Form { $form = new Form; $form->addProtection(); $sourceList = $this->listsRepository->find($id); if (!$sourceList) { throw new InvalidArgumentException('Source list does not exist'); } $variantsCount = $this->listVariantsRepository->getVariantsForType($sourceList)->count('*'); if ($variantsCount !== 0) { throw new InvalidArgumentException('Source list has variants. Copying is not allowed.'); } $defaults = $sourceList->toArray(); $form->addText('code', 'Code') ->setRequired("Field 'Code' is required.") ->addRule(function ($input) { $exists = $this->listsRepository->getTable() ->where('code = ?', $input->value) ->count('*'); return !$exists; }, "Newsletter list code must be unique. Code '%value' is already used."); $form->addText('title', 'Title') ->setRequired("Field 'Title' is required."); $form->addCheckbox('copy_subscribers', 'Copy subscribers') ->setDefaultValue(true); $form->addCheckbox('auto_subscribe', 'Auto subscribe') ->setDefaultValue(false); $form->addHidden('id', $id); $form->setDefaults($defaults); $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } /** * @param Form $form * @param ArrayHash $values * @throws Exception */ public function formSucceeded(Form $form, ArrayHash $values): void { if (!isset($values['id'])) { throw new InvalidArgumentException('Missing "id" in values'); } $sourceList = $this->listsRepository->find($values['id']); if (!$sourceList) { throw new InvalidArgumentException('Source list does not exist'); } $this->listsRepository->updateSorting( $sourceList->mail_type_category_id, $sourceList->sorting + 1 ); $newList = $this->listsRepository->add( $sourceList->mail_type_category_id, $sourceList->priority, $values['code'], $values['title'], $sourceList->sorting + 1, (bool)$values['auto_subscribe'], (bool)$sourceList->locked, $sourceList->description, $sourceList->preview_url, $sourceList->page_url, $sourceList->image_url, (bool)$sourceList->public_listing, $sourceList->mail_from, $sourceList->subscribe_mail_template_id, $sourceList->unsubscribe_mail_template_id ); ($this->onCreate)($newList, $sourceList, $values['copy_subscribers'] ?? false); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/ConfigFormFactory.php
Mailer/extensions/mailer-module/src/Forms/ConfigFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Exception; use Nette\Application\UI\Form; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Nette\Utils\Html; use Nette\Utils\Json; use Remp\MailerModule\Models\Config\Config; use Remp\MailerModule\Models\Config\LocalConfig; use Remp\MailerModule\Repositories\ConfigsRepository; use Remp\MailerModule\Models\Sender\MailerFactory; class ConfigFormFactory { use SmartObject; public $onSuccess; public function __construct( private ConfigsRepository $configsRepository, private MailerFactory $mailerFactory, private LocalConfig $localConfig ) { } public function create(): Form { $form = new Form; $form->addProtection(); $settings = $form->addContainer('settings'); $mailerContainer = $settings->addContainer('Mailer'); $configs = $this->configsRepository->all()->fetchAssoc('name'); $overriddenConfigs = $this->getOverriddenConfigs($configs); $mailers = []; $availableMailers = $this->mailerFactory->getAvailableMailers(); array_walk($availableMailers, function ($mailer, $name) use (&$mailers) { $mailers[$name] = $mailer->getIdentifier(); }); $defaultMailerKey = 'default_mailer'; $defaultMailer = $mailerContainer ->addSelect($defaultMailerKey, 'Default Mailer', $mailers) ->setDefaultValue($configs[$defaultMailerKey]['value']) ->setOption('configOverridden', isset($overriddenConfigs[$defaultMailerKey]) ? "{$defaultMailerKey}: {$this->localConfig->value($defaultMailerKey)}" : false) ->setOption('description', 'Can be overwriten in newsletter list detail.'); unset($configs[$defaultMailerKey]); // remove to avoid double populating in internal section lower. foreach ($this->mailerFactory->getAvailableMailers() as $mailer) { $mailerContainer = $settings->addContainer($mailer->getIdentifier()); foreach ($mailer->getConfigs() as $name => $option) { $key = $mailer->getMailerAlias() . '_' . $name; $config = $configs[$key]; $configOverridden = isset($overriddenConfigs[$key]) ? "{$key}: {$this->localConfig->value($key)}" : false; $item = null; if ($config['type'] === Config::TYPE_STRING) { $item = $mailerContainer ->addText($config['name'], $config['display_name']) ->setOption('description', $config['description']) ->setOption('configOverridden', $configOverridden) ->setDefaultValue($config['value']); } if ($item != null && $option['required']) { $item->addConditionOn($defaultMailer, Form::EQUAL, $mailer->getMailerAlias()) ->setRequired("Field {$name} is required when mailer {$mailers[$mailer->getMailerAlias()]} is selected"); } unset($configs[$config['name']]); } } if (!empty($configs)) { $othersContainer = $settings->addContainer('Internal'); foreach ($configs as $config) { $item = null; // handle generic types switch ($config['type']) : case Config::TYPE_STRING: case Config::TYPE_PASSWORD: $element = $othersContainer->addText($config['name'], $config['display_name']); break; case Config::TYPE_TEXT: $element = $othersContainer->addTextArea($config['name'], $config['display_name']); $element->getControlPrototype() ->addAttributes(['class' => 'auto-size']); break; case Config::TYPE_HTML: $element = $othersContainer->addTextArea($config['name'], $config['display_name']); $element->setHtmlAttribute('rows', 15) ->getControlPrototype() ->addAttributes(['class' => 'html-editor']); break; case Config::TYPE_BOOLEAN: $element = $othersContainer->addCheckbox($config['name'], $config['display_name']); break; case Config::TYPE_INT: $element = $othersContainer->addText($config['name'], $config['display_name']); $element->addCondition(Form::FILLED) ->addRule(Form::INTEGER); break; case Config::TYPE_SELECT: $selectOptions = $config['options'] ? Json::decode($config['options'], true) : []; $element = $othersContainer->addSelect($config['name'], $config['display_name'] ?? $config['name'], $selectOptions); break; default: throw new Exception('unhandled config type: ' . $config['type']); endswitch; $element->setDefaultValue($config['value']); if (isset($overriddenConfigs[$config['name']])) { $element->setOption('configOverridden', "{$defaultMailerKey}: {$this->localConfig->value($config['name'])}"); } if (isset($config['description'])) { $element->setOption('description', Html::el('span')->setHtml($config['description'])); } } } $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { foreach ($values['settings'] as $category => $configs) { foreach ($configs as $name => $value) { $config = $this->configsRepository->loadByName($name); if ($config->value != $value) { $this->configsRepository->update($config, ['value' => $value]); } } } ($this->onSuccess)(); } protected function getOverriddenConfigs(array $configs): array { return array_filter($configs, function ($key) { return $this->localConfig->exists($key); }, ARRAY_FILTER_USE_KEY); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/TemplateTestFormFactory.php
Mailer/extensions/mailer-module/src/Forms/TemplateTestFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Config\LocalizationConfig; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Models\Sender; class TemplateTestFormFactory { use SmartObject; private TemplatesRepository $templateRepository; private Sender $sender; private LocalizationConfig $localizationConfig; public $onSuccess; public function __construct( TemplatesRepository $templateRepository, Sender $sender, LocalizationConfig $localizationConfig ) { $this->templateRepository = $templateRepository; $this->sender = $sender; $this->localizationConfig = $localizationConfig; } public function create(int $id): Form { $form = new Form; $form->addProtection(); $form->addText('email', 'Email') ->addRule(Form::EMAIL) ->setRequired("Field 'Email' is required."); if ($this->localizationConfig->getSecondaryLocales()) { $options = array_combine($this->localizationConfig->getAvailableLocales(), $this->localizationConfig->getAvailableLocales()); $form->addSelect('locale', 'locale', $options); $form->setDefaults(['locale' => $this->localizationConfig->getDefaultLocale()]); } $form->addSubmit('save') ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Send'); $template = $this->templateRepository->find($id); $form->addHidden('id', $template->id); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $template = $this->templateRepository->find($values['id']); $sender = $this->sender->setTemplate($template) ->addRecipient($values['email']); if (isset($values['locale']) && $values['locale']) { $sender->setLocale($values['locale']); } $sender->send(false); ($this->onSuccess)($template); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/MailGeneratorFormFactory.php
Mailer/extensions/mailer-module/src/Forms/MailGeneratorFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\InvalidStateException; use Nette\SmartObject; use Remp\MailerModule\Models\FormRenderer\MaterialRenderer; use Remp\MailerModule\Models\Generators\GeneratorFactory; use Remp\MailerModule\Repositories\SourceTemplatesRepository; class MailGeneratorFormFactory { use SmartObject; private $sourceTemplatesRepository; private $mailGeneratorFactory; public function __construct( SourceTemplatesRepository $sourceTemplatesRepository, GeneratorFactory $mailGeneratorFactory ) { $this->sourceTemplatesRepository = $sourceTemplatesRepository; $this->mailGeneratorFactory = $mailGeneratorFactory; } public function create($sourceTemplateId, callable $onSubmit, callable $link = null) { $form = new Form; $form->setRenderer(new MaterialRenderer()); $form->addProtection(); $keys = $this->mailGeneratorFactory->keys(); $pairs = $this->sourceTemplatesRepository->all() ->where(['generator' => $keys]) ->fetchPairs('id', 'title'); $form->addSelect('source_template_id', 'Generator', $pairs) ->setRequired("Field 'Generator' is required.") ->setHtmlAttribute('class', 'form-control selectpicker') ->setHtmlAttribute('data-live-search', 'true') ->setHtmlAttribute('data-live-search-normalize', 'true'); $generator = $template = null; if ($sourceTemplateId) { $template = $this->sourceTemplatesRepository->find($sourceTemplateId); $generator = $template->generator; } else { $tmpl = $this->sourceTemplatesRepository->all() ->fetch(); if ($tmpl) { $template = $tmpl; $generator = $tmpl->generator; } } if ($generator && $template) { $formGenerator = $this->mailGeneratorFactory->get($generator); $formGenerator->generateForm($form); $formGenerator->onSubmit($onSubmit); } try { $form->addSubmit('send') ->getControlPrototype() ->setName('button') ->setHtml('<i class="fa fa-cogs"></i> Generate'); } catch (InvalidStateException $e) { // this is fine, submit was added by the generator } $form->setDefaults([ 'source_template_id' => $template->id ?? null, ]); 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/Forms/EditBatchFormFactory.php
Mailer/extensions/mailer-module/src/Forms/EditBatchFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Nette\Utils\DateTime; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\JobsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; class EditBatchFormFactory implements IFormFactory { use SmartObject; /** @var JobsRepository */ private $jobsRepository; /** @var BatchesRepository */ private $batchesRepository; /** @var TemplatesRepository */ private $templatesRepository; /** @var BatchTemplatesRepository */ private $batchTemplatesRepository; public $onSuccess; public $onError; public function __construct( JobsRepository $jobsRepository, BatchesRepository $batchesRepository, TemplatesRepository $templatesRepository, BatchTemplatesRepository $batchTemplatesRepository ) { $this->jobsRepository = $jobsRepository; $this->batchesRepository = $batchesRepository; $this->templatesRepository = $templatesRepository; $this->batchTemplatesRepository = $batchTemplatesRepository; } public function create(ActiveRow $batch): Form { $form = new Form; $form->addProtection(); $methods = [ 'random' => 'Random', 'sequential' => 'Sequential', ]; $form->addSelect('method', 'Method', $methods); $form->addText('max_emails', 'Number of emails')->setHtmlType('number'); $form->addText('start_at', 'Start date'); $form->addHidden('id', $batch->id); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-check"></i> Save'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->setDefaults([ 'method' => $batch->method, 'max_emails' => $batch->max_emails, 'start_at' => $batch->start_at->format(DATE_RFC3339), 'id' => $batch->id, ]); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { $batch = $this->batchesRepository->find($values['id']); if (!in_array($batch->status, BatchesRepository::EDITABLE_STATUSES, true)) { $form->addError("Unable to edit batch, already in non-editable status: {$batch->status}"); return; } $this->batchesRepository->update($batch, array_filter([ 'method' => $values['method'], 'max_emails' => $values['max_emails'], 'start_at' => new DateTime($values['start_at']), ])); $batch = $this->batchesRepository->find($batch->id); // decide if user wants to save or save and leave $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } ($this->onSuccess)($batch, $buttonSubmitted); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/LayoutFormFactory.php
Mailer/extensions/mailer-module/src/Forms/LayoutFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\Forms\Controls\SubmitButton; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Models\Config\LocalizationConfig; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\LayoutTranslationsRepository; class LayoutFormFactory implements IFormFactory { use SmartObject; private LayoutsRepository $layoutsRepository; private LayoutTranslationsRepository $layoutTranslationsRepository; private array $locales; public $onCreate; public $onUpdate; public function __construct( LayoutsRepository $layoutsRepository, LayoutTranslationsRepository $layoutTranslationsRepository, LocalizationConfig $localizationConfig ) { $this->layoutsRepository = $layoutsRepository; $this->layoutTranslationsRepository = $layoutTranslationsRepository; $this->locales = $localizationConfig->getSecondaryLocales(); } public function create(?int $id = null): Form { $layout = null; $defaults = []; if ($id !== null) { $layout = $this->layoutsRepository->find($id); $defaults = $layout->toArray(); $layoutTranslations = $this->layoutTranslationsRepository->getAllTranslationsForLayout($layout) ->fetchAssoc('locale'); } $form = new Form; $form->addProtection(); $form->addHidden('id', $id); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $codeInput = $form->addText('code', 'Code') ->setRequired("Field 'Code' is required.") ->addRule(function ($input) { $exists = $this->layoutsRepository->getTable() ->where('code = ?', $input->value) ->count('*'); return !$exists; }, "Layout code must be unique. Code '%value' is already used."); if ($layout !== null) { $codeInput->setDisabled(true); } $form->addTextArea('layout_text', 'Text version') ->setHtmlAttribute('rows', 3); $form->addTextArea('layout_html', 'HTML version'); $translationFields = []; foreach ($this->locales as $locale) { $translationFields[$locale] = $form->addContainer($locale); $translationFields[$locale]->addTextArea('layout_text', 'Text version') ->setHtmlAttribute('rows', 3) ->setNullable(); $translationFields[$locale]->addTextArea('layout_html', 'HTML version') ->setNullable(); $defaults[$locale]['layout_text'] = $layoutTranslations[$locale]['layout_text'] ?? ''; $defaults[$locale]['layout_html'] = $layoutTranslations[$locale]['layout_html'] ?? ''; } $form->setDefaults($defaults); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-check"></i> Save'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function formSucceeded(Form $form, ArrayHash $values): void { // decide if user wants to save or save and leave $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } $values = (array) $values; $translations = []; foreach ($this->locales as $locale) { $translations[$locale]['layout_text'] = $values[$locale]['layout_text']; $translations[$locale]['layout_html'] = $values[$locale]['layout_html']; unset($values[$locale]); } if (!empty($values['id'])) { $row = $this->layoutsRepository->find($values['id']); $this->layoutsRepository->update($row, $values); $row = $this->layoutsRepository->find($row->id); $this->storeLayoutTranslations($row, $translations); ($this->onUpdate)($row, $buttonSubmitted); } else { $row = $this->layoutsRepository->add( $values['name'], $values['code'], $values['layout_text'], $values['layout_html'] ); $this->storeLayoutTranslations($row, $translations); ($this->onCreate)($row, $buttonSubmitted); } } private function storeLayoutTranslations(ActiveRow $layout, array $values) { foreach ($this->locales as $locale) { if ($values[$locale]['layout_html'] === null && $values[$locale]['layout_text'] === null) { $this->layoutTranslationsRepository->deleteByLayoutLocale($layout, $locale); continue; } $this->layoutTranslationsRepository->upsert( $layout, $locale, $values[$locale]['layout_text'] ?? '', $values[$locale]['layout_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/Forms/SnippetFormFactory.php
Mailer/extensions/mailer-module/src/Forms/SnippetFormFactory.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms; use Nette\Application\UI\Form; use Nette\Database\Table\ActiveRow; use Nette\Forms\Controls\SubmitButton; use Nette\SmartObject; use Nette\Utils\ArrayHash; use Remp\MailerModule\Forms\Rules\StringValidator; use Remp\MailerModule\Models\Config\LocalizationConfig; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\SnippetTranslationsRepository; class SnippetFormFactory implements IFormFactory { use SmartObject; private SnippetsRepository $snippetsRepository; private SnippetTranslationsRepository $snippetTranslationsRepository; private array $locales; public $onCreate; public $onUpdate; private ListsRepository $listsRepository; public function __construct( ListsRepository $listsRepository, SnippetsRepository $snippetsRepository, SnippetTranslationsRepository $snippetTranslationsRepository, LocalizationConfig $localizationConfig ) { $this->snippetsRepository = $snippetsRepository; $this->listsRepository = $listsRepository; $this->snippetTranslationsRepository = $snippetTranslationsRepository; $this->locales = $localizationConfig->getSecondaryLocales(); } public function create(?int $id = null): Form { $defaults = []; if ($id !== null) { $snippet = $this->snippetsRepository->find($id); $defaults = $snippet->toArray(); $snippetTranslations = $this->snippetTranslationsRepository->getTranslationsForSnippet($snippet) ->fetchAssoc('locale'); } $form = new Form; $form->addProtection(); $form->addHidden('id', $id); $form->addText('name', 'Name') ->setRequired("Field 'Name' is required."); $form->addText('code', 'code') ->setRequired("Field 'Code' is required.") ->addRule(StringValidator::SLUG, "Field 'Code' is not a URL friendly slug.") ->setDisabled($id !== null); $mailTypes = $this->listsRepository->all()->fetchPairs('id', 'title'); $form->addSelect('mail_type_id', 'Mail type', $mailTypes) ->setPrompt('None (snippet is global)'); $form->addTextArea('text', 'Text version') ->setHtmlAttribute('rows', 3); $form->addTextArea('html', 'HTML version'); $translationFields = []; foreach ($this->locales as $locale) { $translationFields[$locale] = $form->addContainer($locale); $translationFields[$locale]->addTextArea('text', 'Text version') ->setHtmlAttribute('rows', 3) ->setNullable(); $translationFields[$locale]->addTextArea('html', 'HTML version') ->setNullable(); $defaults[$locale]['text'] = $snippetTranslations[$locale]['text'] ?? null; $defaults[$locale]['html'] = $snippetTranslations[$locale]['html'] ?? null; } $form->setDefaults($defaults); $form->addSubmit(self::FORM_ACTION_SAVE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-check"></i> Save'); $form->addSubmit(self::FORM_ACTION_SAVE_CLOSE) ->getControlPrototype() ->setName('button') ->setHtml('<i class="zmdi zmdi-mail-send"></i> Save and close'); $form->onValidate[] = [$this, 'validateSnippetForm']; $form->onSuccess[] = [$this, 'formSucceeded']; return $form; } public function validateSnippetForm(Form $form, ArrayHash $values): void { if (!empty($values->id)) { $snippet = $this->snippetsRepository->find($values->id); $values->code = $snippet->code; } $snippet = $this->snippetsRepository->findByCodeAndMailType($values->code, $values->mail_type_id); if ($snippet && $snippet->id !== (int) $values->id) { $mailType = $this->listsRepository->find($values->mail_type_id); if ($mailType) { $form->addError("Snippet with code \"{$values->code}\" and mail type \"{$mailType->title}\" already exists."); } else { $form->addError("Snippet with code \"{$values->code}\" and without the mail type already exists."); } } } public function formSucceeded(Form $form, ArrayHash $values): void { // decide if user wants to save or save and leave $buttonSubmitted = self::FORM_ACTION_SAVE; /** @var SubmitButton $buttonSaveClose */ $buttonSaveClose = $form[self::FORM_ACTION_SAVE_CLOSE]; if ($buttonSaveClose->isSubmittedBy()) { $buttonSubmitted = self::FORM_ACTION_SAVE_CLOSE; } $values = (array) $values; $translations = []; foreach ($this->locales as $locale) { $translations[$locale]['html'] = $values[$locale]['html']; $translations[$locale]['text'] = $values[$locale]['text']; unset($values[$locale]); } if (!empty($values['id'])) { $row = $this->snippetsRepository->find($values['id']); $this->snippetsRepository->update($row, $values); $row = $this->snippetsRepository->find($row->id); $this->storeSnippetTranslations($row, $translations); ($this->onUpdate)($row, $buttonSubmitted); } else { $row = $this->snippetsRepository->add($values['name'], $values['code'], $values['text'], $values['html'], $values['mail_type_id']); $this->storeSnippetTranslations($row, $translations); ($this->onCreate)($row, $buttonSubmitted); } } private function storeSnippetTranslations(ActiveRow $snippet, $values) { foreach ($this->locales as $locale) { if ($values[$locale]['html'] === null && $values[$locale]['text'] === null) { $this->snippetTranslationsRepository->deleteBySnippetLocale($snippet, $locale); continue; } $this->snippetTranslationsRepository->upsert( $snippet, $locale, $values[$locale]['text'] ?? '', $values[$locale]['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/Forms/Rules/FormRules.php
Mailer/extensions/mailer-module/src/Forms/Rules/FormRules.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms\Rules; use Nette\Forms\Control; use Nette\SmartObject; class FormRules { use SmartObject; const ADVANCED_EMAIL = 'Remp\MailerModule\Forms\Rules\FormRules::validateAdvancedEmail'; public static function validateAdvancedEmail(Control $control): bool { $value = $control->getValue(); if (preg_match('#^(.+) +<(.*)>\z#', $value, $matches)) { $value = $matches[2]; } $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part $alpha = "a-z\x80-\xFF"; // superset of IDN return (bool)preg_match("(^ (\"([ !#-[\\]-~]*|\\\\[ -~])+\"|$atom+(\\.$atom+)*) # quoted or unquoted @ ([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+ # domain - RFC 1034 [$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain \\z)ix", $value); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Forms/Rules/StringValidator.php
Mailer/extensions/mailer-module/src/Forms/Rules/StringValidator.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Forms\Rules; use Nette\Forms\Controls\BaseControl; use Remp\MailerModule\Models\Traits\SlugTrait; class StringValidator { use SlugTrait; const SLUG = 'Remp\MailerModule\Forms\Rules\StringValidator::validateSlug'; public static function validateSlug(BaseControl $input, $args): bool { return self::isValidSlug($input->getValue()); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/HermesWorkerCommand.php
Mailer/extensions/mailer-module/src/Commands/HermesWorkerCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Tomaj\Hermes\Dispatcher; use Tomaj\Hermes\Handler\HandlerInterface; class HermesWorkerCommand extends Command { public const COMMAND_NAME = "worker:hermes"; private $dispatcher; private $handlers = []; public function __construct(Dispatcher $dispatcher) { parent::__construct(); $this->dispatcher = $dispatcher; } public function add(string $type, HandlerInterface $handler): void { // we store the handlers too so we can print list of them later; dispatcher doesn't provide a list method if (!isset($this->handlers[$type])) { $this->handlers[$type] = []; } $this->handlers[$type][] = $handler; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Start hermes offline worker') ->addOption( 'types', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Filter type of events to handle by this worker.' ); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(''); $output->writeln('<info>***** REMP MAILER HERMES WORKER *****</info>'); $output->writeln(''); $filteredTypes = $input->getOption('types'); $registered = []; foreach ($this->handlers as $type => $handlers) { if (!empty($filteredTypes) && !in_array($type, $filteredTypes, true)) { continue; } foreach ($handlers as $handler) { $this->dispatcher->registerHandler($type, $handler); $registered[] = sprintf(' - <info>%s</info>: %s', $type, get_class($handler)); } } if (count($registered) === 0) { $output->writeln('No handler matched the filtered event types, nothing to do. Bye bye!'); $output->writeln(''); return 0; } $output->writeln('Listening to:'); $output->writeln(implode("\n", $registered)); $output->writeln(''); $this->dispatcher->handle(); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/MigrateMailLogsAndConversionsCommand.php
Mailer/extensions/mailer-module/src/Commands/MigrateMailLogsAndConversionsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Database\Explorer; use Nette\Utils\DateTime; use Remp\MailerModule\Models\EnvironmentConfig; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; use Remp\MailerModule\Repositories\LogConversionsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MigrateMailLogsAndConversionsCommand extends Command { use RedisClientTrait; public const MAIL_LOGS_AND_CONVERSIONS_IS_RUNNING = 'mail_logs_and_conversions_migration_running'; public const COMMAND_NAME = "mail:migrate-mail-logs-and-conversions"; public function __construct( private Explorer $database, private LogsRepository $logsRepository, private LogConversionsRepository $logConversionsRepository, private EnvironmentConfig $environmentConfig, RedisClientFactory $redisClientFactory, ) { parent::__construct(); $this->redisClientFactory = $redisClientFactory; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Migrate mail logs and conversions data to new table.'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('STARTING `mail_logs` AND `mail_log_conversions` TABLE DATA MIGRATION'); $output->writeln(''); $mailLogsTableName = $this->logsRepository->getTable()->getName(); $mailLogsV2TableName = $this->logsRepository->getNewTable()->getName(); $mailLogConversionsTableName = $this->logConversionsRepository->getTable()->getName(); $mailLogConversionsV2TableName = $this->logConversionsRepository->getNewTable()->getName(); // Set migration running/start time flag in redis $migrationStartTime = new DateTime(); if ($this->redis()->exists(self::MAIL_LOGS_AND_CONVERSIONS_IS_RUNNING)) { $migrationStartTime = new DateTime($this->redis()->get(self::MAIL_LOGS_AND_CONVERSIONS_IS_RUNNING)); } else { $this->redis()->set(self::MAIL_LOGS_AND_CONVERSIONS_IS_RUNNING, $migrationStartTime); } $this->database->query(" SET FOREIGN_KEY_CHECKS=0; SET UNIQUE_CHECKS=0; "); // Paging LOOP $pageSize = 10000; while (true) { $lastMigratedId = $this->database ->query("SELECT id FROM `{$mailLogsV2TableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; $maxId = $this->database ->query("SELECT id FROM `{$mailLogsTableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; if ($maxId === 0 || $lastMigratedId === $maxId) { break; } $this->database->query(" INSERT IGNORE INTO `{$mailLogsV2TableName}` (`id`, `email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at`) SELECT `id`, `email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at` FROM `{$mailLogsTableName}` WHERE id > {$lastMigratedId} ORDER BY id ASC LIMIT {$pageSize} "); $this->database->query(" INSERT IGNORE INTO `{$mailLogConversionsV2TableName}` (`id`, `mail_log_id`, `converted_at`) SELECT `{$mailLogConversionsTableName}`.`id`, `mail_log_id`, `converted_at` FROM `{$mailLogConversionsTableName}` WHERE `mail_log_id` IN (SELECT * FROM (SELECT `id` FROM `{$mailLogsTableName}` WHERE id > {$lastMigratedId} ORDER BY id ASC LIMIT {$pageSize}) as t) "); $remaining = $maxId-$lastMigratedId; $output->write("\r\e[0KMIGRATED IDs: {$lastMigratedId} / {$maxId} (REMAINING: {$remaining})"); } $output->writeln(''); $output->writeln('DATA MIGRATED'); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $mailLogsTableName, $mailLogsV2TableName, $mailLogConversionsTableName, $mailLogConversionsV2TableName, $migrationStartTime ); $output->writeln(''); $output->writeln('SETUPING AUTO_INCREMENT'); // Sat AUTO_INCREMENT for new tables to old table values $dbName = $this->environmentConfig->get('DB_NAME'); $this->database->query(" SELECT MAX(id)+10000 INTO @AutoInc FROM {$mailLogsTableName}; SET @s:=CONCAT('ALTER TABLE `{$dbName}`.`{$mailLogsV2TableName}` AUTO_INCREMENT=', @AutoInc); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; SELECT MAX(id)+10000 INTO @AutoInc FROM {$mailLogConversionsTableName}; SET @s:=CONCAT('ALTER TABLE `{$dbName}`.`{$mailLogConversionsV2TableName}` AUTO_INCREMENT=', @AutoInc); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); $output->writeln(''); $output->writeln('RENAMING TABLES'); // Rename tables $this->database->query(" ANALYZE TABLE {$mailLogsV2TableName}; ANALYZE TABLE {$mailLogConversionsV2TableName}; RENAME TABLE {$mailLogsTableName} TO {$mailLogsTableName}_old, {$mailLogsV2TableName} TO {$mailLogsTableName}, {$mailLogConversionsTableName} TO {$mailLogConversionsTableName}_old, {$mailLogConversionsV2TableName} TO {$mailLogConversionsTableName}; "); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $mailLogsTableName . '_old', $mailLogsTableName, $mailLogConversionsTableName . '_old', $mailLogConversionsTableName, $migrationStartTime ); $this->database->query(" SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; "); // Remove migration running flag in redis $this->redis()->del(self::MAIL_LOGS_AND_CONVERSIONS_IS_RUNNING); $output->writeln(''); $output->writeln('DATA MIGRATED SUCCESSFULLY'); return Command::SUCCESS; } public function fixTableDifferences( string $mailLogsFromTable, string $mailLogsToTable, string $mailLogConversionsFromTable, string $mailLogConversionsToTable, DateTime $updatedAfter ) { $this->database->query(" UPDATE {$mailLogsToTable} ml_to JOIN {$mailLogsFromTable} ml_from on ml_to.id = ml_from.id SET ml_to.email = ml_from.email, ml_to.updated_at = ml_from.updated_at, ml_to.subject = ml_from.subject, ml_to.mail_template_id = ml_from.mail_template_id, ml_to.mail_job_id = ml_from.mail_job_id, ml_to.mail_job_batch_id = ml_from.mail_job_batch_id, ml_to.mail_sender_id = ml_from.mail_sender_id, ml_to.context = ml_from.context, ml_to.delivered_at = ml_from.delivered_at, ml_to.dropped_at = ml_from.dropped_at, ml_to.spam_complained_at = ml_from.spam_complained_at, ml_to.hard_bounced_at = ml_from.hard_bounced_at, ml_to.clicked_at = ml_from.clicked_at, ml_to.opened_at = ml_from.opened_at, ml_to.attachment_size = ml_from.attachment_size WHERE ml_from.updated_at > ? AND (ml_to.updated_at IS NULL OR ml_from.updated_at != ml_to.updated_at) ", $updatedAfter); $missingIds = $this->database->query(" SELECT `id` FROM `{$mailLogsFromTable}` WHERE created_at > ? AND `id` NOT IN ( SELECT `id` FROM `{$mailLogsToTable}` WHERE created_at > ? ) ", $updatedAfter, $updatedAfter)->fetchFields(); if ($missingIds) { $this->database->query(" INSERT IGNORE INTO `{$mailLogsToTable}` (`id`, `email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at`) SELECT `id`, `email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at` FROM `{$mailLogsFromTable}` WHERE `id` IN ? ", $missingIds); $this->database->query(" INSERT IGNORE INTO `{$mailLogConversionsToTable}` (`id`, `mail_log_id`, `converted_at`) SELECT `id`, `mail_log_id`, `converted_at` FROM `{$mailLogConversionsFromTable}` WHERE `mail_log_id` IN ? ", $missingIds); } // make sure that any mail_sender_id in the old table is also in the new table $this->database->query(" INSERT INTO `{$mailLogsToTable}` (`email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at`) SELECT `email`, `subject`, `mail_template_id`, `mail_job_id`, `mail_job_batch_id`, `mail_sender_id`, `context`, `delivered_at`, `dropped_at`, `spam_complained_at`, `hard_bounced_at`, `clicked_at`, `opened_at`, `attachment_size`, `created_at`, `updated_at` FROM {$mailLogsFromTable} WHERE `{$mailLogsFromTable}`.created_at >= ? AND mail_sender_id NOT IN ( SELECT `mail_sender_id` FROM `{$mailLogsToTable}` WHERE `{$mailLogsToTable}`.`created_at` >= ? ); ", $updatedAfter, $updatedAfter); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/AggregateMailTemplateStatsCommand.php
Mailer/extensions/mailer-module/src/Commands/AggregateMailTemplateStatsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use DateInterval; use Nette\Utils\DateTime; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\MailTemplateStatsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class AggregateMailTemplateStatsCommand extends Command { private $logsRepository; private $templatesRepository; private $mailTemplateStatsRepository; public function __construct( LogsRepository $logsRepository, TemplatesRepository $templatesRepository, MailTemplateStatsRepository $mailTemplateStatsRepository ) { parent::__construct(); $this->logsRepository = $logsRepository; $this->templatesRepository = $templatesRepository; $this->mailTemplateStatsRepository = $mailTemplateStatsRepository; } protected function configure(): void { $this->setName('mail:aggregate-mail-template-stats') ->addArgument('date', InputArgument::OPTIONAL, 'Date which to aggregate in Y-m-d format.') ->setDescription('Process template stats based on batch stats and mail logs'); } protected function execute(InputInterface $input, OutputInterface $output): int { $date = $input->getArgument('date'); if ($date !== null) { $today = (new DateTime($date))->setTime(0, 0); } else { $today = (new DateTime())->setTime(0, 0); } $yesterday = (clone $today)->sub(new DateInterval('P1D')); $output->writeln("Aggregating mail template stats from logs created from <info>{$yesterday->format(DATE_RFC3339)}</info> to <info>{$today->format(DATE_RFC3339)}</info>"); $data = $this->logsRepository ->getTable() ->select(' mail_template_id, COUNT(created_at) AS sent, COUNT(delivered_at) AS delivered, COUNT(opened_at) AS opened, COUNT(clicked_at) AS clicked, COUNT(dropped_at) AS dropped, COUNT(spam_complained_at) AS spam_complained ') ->where('created_at >= ?', $yesterday->format('Y-m-d')) ->where('created_at < ?', $today->format('Y-m-d')) ->group('mail_template_id') ->fetchAssoc('mail_template_id'); ProgressBar::setFormatDefinition( 'processStats', "%processing% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%" ); if (count($data)) { $progressBar = new ProgressBar($output, count($data)); $progressBar->setFormat('processStats'); $progressBar->start(); foreach ($data as $mailTemplateId => $mailTemplateData) { $progressBar->setMessage('Processing template <info>' . $mailTemplateId . '</info>', 'processing'); $prepData = [ 'sent' => $mailTemplateData['sent'], 'delivered' => $mailTemplateData['delivered'], 'opened' => $mailTemplateData['opened'], 'clicked' => $mailTemplateData['clicked'], 'dropped' => $mailTemplateData['dropped'], 'spam_complained' => $mailTemplateData['spam_complained'], ]; $agg = $this->mailTemplateStatsRepository->byDateAndMailTemplateId($yesterday, $mailTemplateId); if (!$agg) { $this->mailTemplateStatsRepository->insert([ 'mail_template_id' => $mailTemplateId, 'date' => $yesterday->format('Y-m-d'), ] + $prepData); } else { $this->mailTemplateStatsRepository->update($agg, $prepData); } $progressBar->advance(); } $progressBar->setMessage('<info>OK!</info>', 'processing'); $progressBar->finish(); $output->writeln(''); } else { $output->writeln('<info>OK!</info> (no data)'); } return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/DecoratedCommandTrait.php
Mailer/extensions/mailer-module/src/Commands/DecoratedCommandTrait.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Utils\DateTime; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\OutputStyle; use Symfony\Component\Console\Style\SymfonyStyle; /** * Useful shortcuts (inspired by Laravel) to work with Symphony input & output * Can be used in a command extending Symfony\Component\Console\Command\Command; */ trait DecoratedCommandTrait { /** * @var InputInterface */ protected $input; /** * The output interface implementation. * * @var OutputStyle */ protected $output; protected function initialize(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = new SymfonyStyle($input, $output); $this->line('**** ' . self::getCommandName() . ' (date: ' . (new DateTime())->format(DATE_RFC3339) . ') ****', 'info'); } private static function getCommandName(): string { $fullClassName = explode('\\', __CLASS__); $class = end($fullClassName); $words = array_filter(preg_split('/(?=[A-Z])/', $class)); $lastWord = array_pop($words); if ($lastWord !== 'Command') { // put it back $words[] = $lastWord; } return implode(' ', $words); } /** * Write a string as standard output. * * @param string $string * @param string|null $style * @return void */ public function line(string $string, ?string $style = null): void { $styled = $style ? "<$style>$string</$style>" : $string; $this->output->writeln($styled); } /** * Write a string as information output. * * @param string $string * @return void */ public function info(string $string): void { $this->line($string, 'info'); } /** * Write a string as comment output. * * @param string $string * @return void */ public function comment(string $string): void { $this->line($string, 'comment'); } /** * Write a string as question output. * * @param string $string * @return void */ public function question(string $string): void { $this->line($string, 'question'); } /** * Write a string as error output. * * @param string $string * @return void */ public function error(string $string): void { $this->line($string, 'error'); } /** * Write a string as warning output. * * @param string $string * @return void */ public function warn(string $string): void { if (!$this->output->getFormatter()->hasStyle('warning')) { $style = new OutputFormatterStyle('yellow'); $this->output->getFormatter()->setStyle('warning', $style); } $this->line($string, 'warning'); } /** * Write a string in an alert box. * * @param string $string * @return void */ public function alert(string $string): void { $length = strlen(strip_tags($string)) + 12; $this->comment(str_repeat('*', $length)); $this->comment('* '.$string.' *'); $this->comment(str_repeat('*', $length)); $this->output->newLine(); } /** * Confirm a question with the user. * * @param string $question * @param bool $default * @return bool */ public function confirm(string $question, bool $default = false): bool { return $this->output->confirm($question, $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/Commands/MigrateUserSubscriptionsAndVariantsCommand.php
Mailer/extensions/mailer-module/src/Commands/MigrateUserSubscriptionsAndVariantsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Database\Explorer; use Nette\Utils\DateTime; use Remp\MailerModule\Models\EnvironmentConfig; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Remp\MailerModule\Repositories\UserSubscriptionVariantsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MigrateUserSubscriptionsAndVariantsCommand extends Command { use RedisClientTrait; public const USER_SUBSCRIPTIONS_AND_VARIANTS_MIGRATION_IS_RUNNING = 'user_subscriptions_and_variants_migration_running'; public const COMMAND_NAME = "mail:migrate-user-subscriptions-and-variants"; public function __construct( private Explorer $database, private UserSubscriptionsRepository $userSubscriptionsRepository, private UserSubscriptionVariantsRepository $userSubscriptionVariantsRepository, private EnvironmentConfig $environmentConfig, RedisClientFactory $redisClientFactory, ) { parent::__construct(); $this->redisClientFactory = $redisClientFactory; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Migrate user subscriptions and variants data to new table.'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('STARTING `mail_user_subscriptions` AND `mail_user_subscription_variants` TABLE DATA MIGRATION'); $output->writeln(''); $userSubscriptionsTableName = $this->userSubscriptionsRepository->getTable()->getName(); $userSubscriptionsV2TableName = $this->userSubscriptionsRepository->getNewTable()->getName(); $userSubscriptionVariantsTableName = $this->userSubscriptionVariantsRepository->getTable()->getName(); $userSubscriptionVariantsV2TableName = $this->userSubscriptionVariantsRepository->getNewTable()->getName(); // Set migration running/start time flag in redis $migrationStartTime = new DateTime(); if ($this->redis()->exists(self::USER_SUBSCRIPTIONS_AND_VARIANTS_MIGRATION_IS_RUNNING)) { $migrationStartTime = new DateTime($this->redis()->get(self::USER_SUBSCRIPTIONS_AND_VARIANTS_MIGRATION_IS_RUNNING)); } else { $this->redis()->set(self::USER_SUBSCRIPTIONS_AND_VARIANTS_MIGRATION_IS_RUNNING, $migrationStartTime); } $this->database->query(" SET FOREIGN_KEY_CHECKS=0; SET UNIQUE_CHECKS=0; "); // Paging LOOP $pageSize = 10000; while (true) { $lastMigratedId = $this->database ->query("SELECT id FROM `{$userSubscriptionsV2TableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; $maxId = $this->database ->query("SELECT id FROM `{$userSubscriptionsTableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; if ($maxId === 0 || $lastMigratedId === $maxId) { break; } $this->database->query(" INSERT IGNORE INTO `{$userSubscriptionsV2TableName}` (`id`, `user_id`, `user_email`, `mail_type_id`, `created_at`, `updated_at`, `subscribed`, `rtm_source`, `rtm_medium`, `rtm_campaign`, `rtm_content`) SELECT `id`, `user_id`, `user_email`, `mail_type_id`, `created_at`, `updated_at`, `subscribed`, `rtm_source`, `rtm_medium`, `rtm_campaign`, `rtm_content` FROM `{$userSubscriptionsTableName}` WHERE id > {$lastMigratedId} ORDER BY id ASC LIMIT {$pageSize} "); $this->database->query(" INSERT IGNORE INTO `{$userSubscriptionVariantsV2TableName}` (`id`, `mail_user_subscription_id`, `mail_type_variant_id`, `created_at`) SELECT `{$userSubscriptionVariantsTableName}`.`id`, `mail_user_subscription_id`, `mail_type_variant_id`, `created_at` FROM `{$userSubscriptionVariantsTableName}` WHERE `mail_user_subscription_id` IN (SELECT * FROM (SELECT `id` FROM `{$userSubscriptionsTableName}` WHERE id > {$lastMigratedId} ORDER BY id ASC LIMIT {$pageSize}) as t) "); $remaining = $maxId-$lastMigratedId; $output->write("\r\e[0KMIGRATED IDs: {$lastMigratedId} / {$maxId} (REMAINING: {$remaining})"); } $output->writeln(''); $output->writeln('DATA MIGRATED'); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $userSubscriptionsTableName, $userSubscriptionsV2TableName, $userSubscriptionVariantsTableName, $userSubscriptionVariantsV2TableName, $migrationStartTime ); $output->writeln(''); $output->writeln('SETUPING AUTO_INCREMENT'); // Sat AUTO_INCREMENT for new tables to old table values $dbName = $this->environmentConfig->get('DB_NAME'); $this->database->query(" SELECT MAX(id)+10000 INTO @AutoInc FROM {$userSubscriptionsTableName}; SET @s:=CONCAT('ALTER TABLE `{$dbName}`.`{$userSubscriptionsV2TableName}` AUTO_INCREMENT=', @AutoInc); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; SELECT MAX(id)+10000 INTO @AutoInc FROM {$userSubscriptionVariantsTableName}; SET @s:=CONCAT('ALTER TABLE `{$dbName}`.`{$userSubscriptionVariantsV2TableName}` AUTO_INCREMENT=', @AutoInc); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); $output->writeln(''); $output->writeln('RENAMING TABLES'); // Rename tables $this->database->query(" ANALYZE TABLE {$userSubscriptionsV2TableName}; ANALYZE TABLE {$userSubscriptionVariantsV2TableName}; RENAME TABLE {$userSubscriptionsTableName} TO {$userSubscriptionsTableName}_old, {$userSubscriptionsV2TableName} TO {$userSubscriptionsTableName}, {$userSubscriptionVariantsTableName} TO {$userSubscriptionVariantsTableName}_old, {$userSubscriptionVariantsV2TableName} TO {$userSubscriptionVariantsTableName}; "); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $userSubscriptionsTableName . '_old', $userSubscriptionsTableName, $userSubscriptionVariantsTableName . '_old', $userSubscriptionVariantsTableName, $migrationStartTime ); $this->database->query(" SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; "); // Remove migration running flag in redis $this->redis()->del(self::USER_SUBSCRIPTIONS_AND_VARIANTS_MIGRATION_IS_RUNNING); $output->writeln(''); $output->writeln('DATA MIGRATED SUCCESSFULLY'); return Command::SUCCESS; } public function fixTableDifferences( string $userSubscriptionsFromTable, string $userSubscriptionsToTable, string $userSubscriptionVariantsFromTable, string $userSubscriptionVariantsToTable, DateTime $updatedAfter ) { $this->database->query(" UPDATE {$userSubscriptionsToTable} us_to JOIN {$userSubscriptionsFromTable} us_from on us_to.id = us_from.id SET us_to.user_id = us_from.user_id, us_to.user_email = us_from.user_email, us_to.mail_type_id = us_from.mail_type_id, us_to.created_at = us_from.created_at, us_to.updated_at = us_from.updated_at, us_to.subscribed = us_from.subscribed, us_to.rtm_source = us_from.rtm_source, us_to.rtm_medium = us_from.rtm_medium, us_to.rtm_campaign = us_from.rtm_campaign, us_to.rtm_content = us_from.rtm_content WHERE us_from.updated_at > ? AND (us_to.updated_at IS NULL OR us_from.updated_at != us_to.updated_at) ", $updatedAfter); $missingIds = $this->database->query(" SELECT `id` FROM `{$userSubscriptionsFromTable}` WHERE created_at > ? AND `id` NOT IN ( SELECT `id` FROM `{$userSubscriptionsToTable}` WHERE created_at > ? ) ", $updatedAfter, $updatedAfter)->fetchFields(); if ($missingIds) { $this->database->query(" INSERT IGNORE INTO `{$userSubscriptionsToTable}` (`id`, `user_id`, `user_email`, `mail_type_id`, `created_at`, `updated_at`, `subscribed`, `rtm_source`, `rtm_medium`, `rtm_campaign`, `rtm_content`) SELECT `id`, `user_id`, `user_email`, `mail_type_id`, `created_at`, `updated_at`, `subscribed`, `rtm_source`, `rtm_medium`, `rtm_campaign`, `rtm_content` FROM `{$userSubscriptionsFromTable}` WHERE `id` IN ? ", $missingIds); $this->database->query(" INSERT IGNORE INTO `{$userSubscriptionVariantsToTable}` (`id`, `mail_user_subscription_id`, `mail_type_variant_id`, `created_at`) SELECT `id`, `mail_user_subscription_id`, `mail_type_variant_id`, `created_at` FROM `{$userSubscriptionVariantsFromTable}` WHERE `mail_log_id` IN ? ", $missingIds); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/HermesWorkerWaitCallback.php
Mailer/extensions/mailer-module/src/Commands/HermesWorkerWaitCallback.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Hermes\RedisDriverWaitCallbackInterface; use Remp\MailerModule\Models\HealthChecker; class HermesWorkerWaitCallback implements RedisDriverWaitCallbackInterface { private HealthChecker $healthChecker; public function __construct(HealthChecker $healthChecker) { $this->healthChecker = $healthChecker; } public function call(): void { $this->healthChecker->ping(HermesWorkerCommand::COMMAND_NAME); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/CleanupCommand.php
Mailer/extensions/mailer-module/src/Commands/CleanupCommand.php
<?php namespace Remp\MailerModule\Commands; use Nette\DI\Container; use Nette\Utils\DateTime; use Remp\MailerModule\Models\DataRetentionInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class CleanupCommand extends Command { public function __construct(private Container $container) { parent::__construct(); } protected function configure() { $this->setName('application:cleanup') ->setDescription('Cleanup old data based on configured retention rules'); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(sprintf('%s: <info>DATA RETENTION</info>', new DateTime())); $dataRetentionServices = $this->container->findByType(DataRetentionInterface::class); foreach ($dataRetentionServices as $dataRetentionService) { /** @var DataRetentionInterface $dataRetentionHandler */ $dataRetentionHandler = $this->container->getService($dataRetentionService); $output->write(sprintf( '%s: * %s', new DateTime(), get_class($dataRetentionHandler) ),); $deletedRowsCount = $dataRetentionHandler->removeData(); $output->writeln(sprintf(" OK! (%s)", $deletedRowsCount ?? 'keeping data forever')); } return self::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/ProcessJobStatsCommand.php
Mailer/extensions/mailer-module/src/Commands/ProcessJobStatsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\LogsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ProcessJobStatsCommand extends Command { private $logsRepository; private $batchTemplatesRepository; public function __construct( LogsRepository $logsRepository, BatchTemplatesRepository $batchTemplatesRepository ) { parent::__construct(); $this->logsRepository = $logsRepository; $this->batchTemplatesRepository = $batchTemplatesRepository; } protected function configure(): void { $this->setName('mail:job-stats') ->setDescription('Process job stats based on mail logs') ->addOption( 'only-converted', null, InputOption::VALUE_NONE, 'Gets batch template stats only for column converted' ); } protected function execute(InputInterface $input, OutputInterface $output): int { $onlyConverted = (bool) $input->getOption('only-converted'); $output->writeln(''); $output->writeln('<info>***** UPDATE EMAIL JOB STATS *****</info>'); $output->writeln(''); // With only option converted in command, this update executes in every run $output->writeln('<info>Updating column converted.</info>'); $this->batchTemplatesRepository->updateAllConverted(); $output->writeln('<info>Column converted updated.</info>'); if (!$onlyConverted) { $batchTemplatesCount = $this->batchTemplatesRepository->getTable()->count('*'); if ($batchTemplatesCount === 0) { $output->writeln('<info>Nothing to do, exiting.</info>'); return 0; } ProgressBar::setFormatDefinition( 'processStats', "%processing% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%" ); $progressBar = new ProgressBar($output, $batchTemplatesCount); $progressBar->setFormat('processStats'); $progressBar->start(); $page = 1; do { $batchTemplates = $this->batchTemplatesRepository->getTable()->page($page, 1000)->fetchAll(); /** @var ActiveRow $batchTemplate */ foreach ($batchTemplates as $batchTemplate) { $progressBar->setMessage('Processing jobBatchTemplate <info>' . $batchTemplate->id . '</info>', 'processing'); $stats = $this->logsRepository->getBatchTemplateStats($batchTemplate); $this->batchTemplatesRepository->update($batchTemplate, [ 'delivered' => $stats->delivered ?? 0, 'opened' => $stats->opened ?? 0, 'clicked' => $stats->clicked ?? 0, 'dropped' => $stats->dropped ?? 0, 'spam_complained' => $stats->spam_complained ?? 0, 'hard_bounced' => $stats->hard_bounced ?? 0, ]); $progressBar->advance(); } $page++; } while (!empty($batchTemplates)); $progressBar->setMessage('done'); $progressBar->finish(); } $output->writeln(''); $output->writeln('Done'); $output->writeln(''); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/SyncDeletedUsersCommand.php
Mailer/extensions/mailer-module/src/Commands/SyncDeletedUsersCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Models\Users\IUser; use Remp\MailerModule\Models\Users\UserManager; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class SyncDeletedUsersCommand extends Command { private const LIMIT = 1000; private $userProvider; private $userManager; private $userSubscriptionsRepository; public function __construct( IUser $userProvider, UserManager $userManager, UserSubscriptionsRepository $userSubscriptionsRepository ) { parent::__construct(); $this->userProvider = $userProvider; $this->userManager = $userManager; $this->userSubscriptionsRepository = $userSubscriptionsRepository; } protected function configure(): void { $this->setName('mail:sync-deleted-users') ->setDescription("Sync deleted users. Compares Mailer's users with CRM users and deletes user data for anonymized users.") ->addOption( 'delete-deactivated', null, InputOption::VALUE_NONE, "Deletes also deactivated accounts.\nDoesn't affect anonymized accounts - user data for these are always removed." ) ->addOption( 'from-user-id', null, InputOption::VALUE_REQUIRED, "Start sync of deleted users from provided user_id.\nHelpful if you want to run command in batches." ) ->addUsage('--delete-deactivated') ->addUsage('--from-user-id=42') ->addUsage('--from-user-id=42 --delete-deactivated'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(''); $output->writeln('<info>***** DELETE USERS ANONYMIZED IN CRM *****</info>'); // include deactivated in UserProvider::list() in comparison with Mailer users $includeDeactivated = true; if ($input->getOption('delete-deactivated')) { $output->writeln("<info>***** <comment>--delete-deactivated</comment> used. Sync will remove also <comment>deactivated, non-anonymized</comment> users.</info>"); $includeDeactivated = false; } $lastUserId = 0; $fromUserId = $input->getOption('from-user-id'); if ($fromUserId) { $output->writeln("<info>***** <comment>--from-user-id</comment> used. Sync will start from user ID [<comment>{$fromUserId}</comment>].</info>"); $lastUserId = $fromUserId; } $output->writeln(''); // fetch & compare & remove user subscriptions in batches while ($userSubscriptions = $this->userSubscriptionsRepository->getTable() ->where('user_id >= ', $lastUserId) ->limit(self::LIMIT) ->fetchAssoc('user_id=user_email')) { // get CRM users $mailerUserIds = array_keys($userSubscriptions); $maxUserId = max($mailerUserIds); $output->writeln(' * Users [<info>' . $lastUserId . '-' . $maxUserId . '</info>]:'); $lastUserId = $maxUserId; /** @var array<int, array> $crmUsers */ $crmUsers = $this->userProvider->list($mailerUserIds, 1, $includeDeactivated); // compare mailer & crm users; get missing emails /** @var array<int, string> $missingUsers */ $missingUsers = array_diff_key($userSubscriptions, $crmUsers); if (count($missingUsers) === 0) { $output->writeln(' * No users to delete.'); continue; } $output->writeln(' * Deleting user data for emails:'); foreach ($missingUsers as $missingUserId => $missingEmail) { $output->writeln(" - {$missingEmail} ({$missingUserId})"); } try { $this->userManager->deleteUsers($missingUsers); } catch (\Exception $e) { $output->writeln(' * <error>Users were not deleted.</error>'); throw $e; } $output->writeln(' * <info>Users were deleted.</info>'); $output->writeln(''); } $output->writeln(''); $output->writeln('<info>Done.</info>'); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/DemoSeedCommand.php
Mailer/extensions/mailer-module/src/Commands/DemoSeedCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Utils\DateTime; use Remp\MailerModule\Models\Users\Dummy; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\LayoutsRepository; use Remp\MailerModule\Repositories\ListCategoriesRepository; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\SnippetsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\QuestionHelper; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ConfirmationQuestion; class DemoSeedCommand extends Command { private $layoutsRepository; private $templatesRepository; private $snippetsRepository; private $listsRepository; private $listCategoriesRepository; private UserSubscriptionsRepository $userSubscriptionsRepository; private Dummy $dummyUserProvider; public function __construct( LayoutsRepository $layoutsRepository, TemplatesRepository $templatesRepository, SnippetsRepository $snippetRepository, ListsRepository $listsRepository, ListCategoriesRepository $listCategoriesRepository, UserSubscriptionsRepository $userSubscriptionsRepository ) { parent::__construct(); $this->layoutsRepository = $layoutsRepository; $this->templatesRepository = $templatesRepository; $this->snippetsRepository = $snippetRepository; $this->listsRepository = $listsRepository; $this->listCategoriesRepository = $listCategoriesRepository; $this->userSubscriptionsRepository = $userSubscriptionsRepository; $this->dummyUserProvider = new Dummy(); } protected function configure(): void { $this->setName('demo:seed') ->setDescription('Seed database with demo values') ->addArgument( 'delete', InputArgument::OPTIONAL, 'Remove seed data?', false ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $deleteSeedData = $input->getArgument('delete'); if ($deleteSeedData === 'delete') { /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); $question = new ConfirmationQuestion('Are you sure you want to delete seed data? ', false); if ($helper->ask($input, $output, $question)) { $output->writeln('<info>***** WARNING: Deleting Seed Data *****</info>'); $this->deleteSeedData(); } return 0; } $output->writeln(''); $output->writeln('<info>***** DEMO SEEDER *****</info>'); $output->writeln(''); $output->write('List categories: '); $category = $this->seedListCategories(); $output->writeln('<info>OK!</info>'); $output->write('Lists: '); $list = $this->seedLists($category); $output->writeln('<info>OK!</info>'); $output->write('Snippets: '); $snippet = $this->seedSnippets(); $output->writeln('<info>OK!</info>'); $output->write('Layouts: '); $layout = $this->seedLayouts(); $output->writeln('<info>OK!</info>'); $output->write('Emails: '); $this->seedEmails($layout, $list); $output->writeln('<info>OK!</info>'); $output->write('User subscriptions: '); $this->seedUserSubscriptions($list); $output->writeln('<info>OK!</info>'); return Command::SUCCESS; } protected function seedListCategories() { /** @var ActiveRow $category */ $category = $this->listCategoriesRepository->findBy('title', 'Newsletters'); if (!$category) { $category = $this->listCategoriesRepository->insert([ 'title' => 'Newsletters', 'sorting' => 100, 'created_at' => new DateTime(), ]); } return $category; } protected function seedLists($category) { /** @var ActiveRow $list */ $list = $this->listsRepository->findBy('code', 'demo-weekly-newsletter'); if (!$list) { $list = $this->listsRepository->add( $category->id, 100, 'demo-weekly-newsletter', 'DEMO Weekly newsletter', 100, false, false, 'Example mail list' ); } return $list; } protected function seedSnippets() { $snippet = $this->snippetsRepository->findBy('code', 'demo-snippet'); $snippetEmail = $this->snippetsRepository->findBy('code', 'demo-snippet-email'); if ($snippet && $snippetEmail) { return true; } $snippetText = <<<EOF Remp co. Street 123 Lorem City 987 654 EOF; $snippetHtml = <<<HTML <p> <strong>Remp co.</strong> <br> Street <em>123</em> <br> Lorem City <br> 987 654 <br> </p> HTML; $emailSnippetText = <<<EOF Written by: John Editor in Chief Doe EOF; $emailSnippetHtml = <<<HTML <p>Written by: <em>John Editor in Chief Doe</em></p> HTML; $snippet = $this->snippetsRepository->add('Demo snippet', 'demo-snippet', $snippetText, $snippetHtml, null); $snippetEmail = $this->snippetsRepository->add('Demo Snippet Email', 'demo-snippet-email', $emailSnippetText, $emailSnippetHtml, null); return true; } protected function seedLayouts() { /** @var ActiveRow $layout */ $layout = $this->layoutsRepository->findBy('name', 'DEMO layout'); if ($layout) { return $layout; } $text = <<<EOF REMP - Reader's Engagement and Monetization Platform {{ content|raw }} &copy; REMP, {{ time|date('Y') }} EOF; $html = <<<HTML <!DOCTYPE html> <html lang="en" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>REMP - Demo email</title> </head> <body style="-webkit-size-adjust: none; -ms-text-size-adjust: 100%; width: 400px; max-width: 400px;"> <h2>REMP - Reader's Engagement and Monetization Platform</h2> {{ content|raw }} <p><em><small>&copy; REMP, {{ time|date('Y') }}</small></em></p> {{ include('demo-snippet') }} </body> </html> HTML; $layout = $this->layoutsRepository->add('DEMO layout', 'demo_layout', $text, $html); return $layout; } protected function seedEmails($layout, $list) { /** @var ActiveRow $email */ $email = $this->templatesRepository->findBy('code', 'demo-email'); if (!$email) { $text = <<<EOF Text content of DEMO email. EOF; $html = <<<HTML <table style="width: 400px; background-color: #eee"> <tr> <td>Text content of <em>DEMO email</em>.</td> </tr> <tr> <td>{{ include('demo-snippet-email') }}</td> </tr> </table> HTML; $this->templatesRepository->add( 'DEMO email', 'demo-email', 'Demonstration-purpose email', 'REMP <info@remp2020.com>', 'REMP - DEMO', $text, $html, $layout->id, $list->id ); } return $email; } protected function seedUserSubscriptions($list) { $users = $this->dummyUserProvider->list([], 1); foreach ($users as $userId => $userData) { $this->userSubscriptionsRepository->subscribeUser($list, $userId, $userData['email']); } } protected function deleteSeedData() { // user subscriptions $users = $this->dummyUserProvider->list([], 1); foreach ($users as $userId => $userData) { $this->userSubscriptionsRepository->getTable()->where([ 'user_id' => $userId, 'user_email' => $userData['email'], ])->delete(); } if ($email = $this->templatesRepository->findBy('code', 'demo-email')) { $this->templatesRepository->delete($email); } if ($layout = $this->layoutsRepository->findBy('name', 'DEMO layout')) { $this->layoutsRepository->delete($layout); } if ($list = $this->listsRepository->findBy('code', 'demo-weekly-newsletter')) { $this->listsRepository->delete($list); } if ($category = $this->listCategoriesRepository->findBy('title', 'Newsletters')) { $this->listCategoriesRepository->delete($category); } if ($snippet = $this->snippetsRepository->findBy('name', 'demo-snippet')) { $this->snippetsRepository->delete($snippet); } if ($snippetEmail = $this->snippetsRepository->findBy('name', 'demo-snippet-email')) { $this->snippetsRepository->delete($snippetEmail); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/MailgunEventsCommand.php
Mailer/extensions/mailer-module/src/Commands/MailgunEventsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use DateInterval; use Mailgun\Model\Event\Event; use Mailgun\Model\Event\EventResponse; use Nette\Utils\DateTime; use Remp\MailerModule\Models\Mailer\MailgunMailer; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Models\Sender\MailerFactory; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class MailgunEventsCommand extends Command { const WAIT_SECONDS = 15; const INTENTIONAL_DELAY_SECONDS = 60; /** @var MailgunMailer */ private $mailgun; private $logsRepository; private $mailerFactory; public function __construct( MailerFactory $mailerFactory, LogsRepository $logsRepository ) { parent::__construct(); $this->logsRepository = $logsRepository; $this->mailerFactory = $mailerFactory; } protected function configure(): void { $this->setName('mailgun:events') ->setDescription('Syncs latest mailgun events with local log') ->addArgument('now', InputArgument::OPTIONAL, 'Offset from "now" of the first event to be processed in seconds', '30') ->addOption('code', null, InputOption::VALUE_REQUIRED, 'Code of Mailgun mailer set in config', null); } protected function execute(InputInterface $input, OutputInterface $output): int { $nowOffset = $input->getArgument('now'); $code = $input->getOption('code'); $this->mailgun = $this->mailerFactory->getMailerByAliasAndCode(MailgunMailer::ALIAS, $code); $output->writeln(''); $output->writeln('<info>***** SYNCING MAILGUN EVENTS *****</info>'); $output->writeln(''); $dateTo = (new DateTime()) ->sub(new DateInterval(sprintf("PT%dS", self::INTENTIONAL_DELAY_SECONDS))); $dateFrom = (clone $dateTo)->sub(new DateInterval(sprintf("PT%dS", $nowOffset))); $eventResponse = $this->getEvents($dateFrom, $dateTo); $latestEventTime = $dateFrom; while (true) { $events = $eventResponse->getItems(); if (count($events) == 0) { $output->writeln(sprintf("%s: all events processed, waiting for %d seconds before proceeding", new DateTime(), self::WAIT_SECONDS)); sleep(self::WAIT_SECONDS); $dateTo = (new DateTime()) ->sub(new DateInterval(sprintf("PT%dS", self::INTENTIONAL_DELAY_SECONDS))); $eventResponse = $this->getEvents($latestEventTime, $dateTo); continue; } /** @var Event $event */ foreach ($events as $event) { $userVariables = $event->getUserVariables(); $date = DateTime::from($event->getEventDate()); if ($date > $latestEventTime) { $latestEventTime = $date; } $eventTimestamp = explode('.', (string) $event->getTimestamp())[0]; $date = DateTime::from($eventTimestamp); if (!isset($userVariables['mail_sender_id'])) { // cannot map to logsRepository instance $output->writeln(sprintf("%s: ignoring event: %s (unsupported)", $date, $event->getEvent())); continue; } $mappedEvent = $this->logsRepository->mapEvent($event->getEvent(), $event->getReason()); if (!$mappedEvent) { // unsupported event type $output->writeln(sprintf("%s: ignoring event: %s (unsupported)", $date, $event->getEvent())); continue; } $logs = $this->logsRepository->findAllBySenderId($userVariables['mail_sender_id']); foreach ($logs as $log) { $updated = $this->logsRepository->update($log, [ $mappedEvent => $date, ]); if (!$updated) { $output->writeln(sprintf("%s: event ignored, missing mail_logs record: %s (%s)", $date, $event->getRecipient(), $event->getEvent())); } else { $output->writeln(sprintf("%s: event processed: %s (%s)", $date, $event->getRecipient(), $event->getEvent())); } } } $eventResponse = $this->mailgun->createMailer()->events()->nextPage($eventResponse); } return Command::SUCCESS; } private function getEvents(DateTime $begin, DateTime $end): EventResponse { return $this->mailgun->createMailer()->events()->get($this->mailgun->option('domain'), [ 'ascending' => true, 'begin' => $begin->getTimestamp(), 'end' => $end->getTimestamp(), 'event' => implode(' OR ', $this->logsRepository->mappedEvents()), ]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/BigintMigrationCleanupCommand.php
Mailer/extensions/mailer-module/src/Commands/BigintMigrationCleanupCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Database\Explorer; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class BigintMigrationCleanupCommand extends Command { use DecoratedCommandTrait; public function __construct( private Explorer $database ) { parent::__construct(); } protected function configure() { $this->setName('mail:bigint_migration_cleanup') ->setDescription('Deletes left-over table after migration to bigint.') ->addArgument( 'table', InputArgument::REQUIRED, "Name of migrated table." ); } protected function execute(InputInterface $input, OutputInterface $output) { $migratedTable = $input->getArgument('table'); if (!in_array($migratedTable, ['mail_user_subscriptions', 'mail_user_subscription_variants', 'autologin_tokens', 'mail_log_conversions', 'mail_logs'], true)) { $this->error("Table `{$migratedTable}` was not one of migrated tables."); return Command::FAILURE; } $v2Table = $migratedTable . '_v2'; if ($this->tableExists($v2Table) && !$this->confirm("Migration table `{$v2Table}` still exists, are you sure that migration was successful?", false)) { $this->error("Cleanup cancelled."); return Command::FAILURE; } $tableToDrop = $migratedTable . '_old'; if (!$this->tableExists($v2Table) && !$this->tableExists($tableToDrop)) { $this->warn("There are no migration tables in your database (`{$tableToDrop}` or `{$v2Table}`). Exiting command."); return Command::SUCCESS; } if (!$this->confirm("This command will permanently drop tables `{$tableToDrop}` and `{$v2Table}`. Make sure that your data was successfully migrated. Proceed?", false)) { $this->error("Cleanup cancelled."); return Command::FAILURE; } $this->database->query("DROP TABLE IF EXISTS {$v2Table};"); $this->database->query("DROP TABLE IF EXISTS {$tableToDrop};"); $this->info('Done.'); return Command::SUCCESS; } private function tableExists(string $tableName): bool { return (bool) $this->database->query("SHOW TABLES LIKE '{$tableName}';")->getRowCount(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/HeartbeatCommand.php
Mailer/extensions/mailer-module/src/Commands/HeartbeatCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Hermes\RedisDriver; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Tomaj\Hermes\Emitter; use Tomaj\Hermes\Message; class HeartbeatCommand extends Command { private $emitter; public function __construct(Emitter $emitter) { parent::__construct(); $this->emitter = $emitter; } protected function configure(): void { $this->setName('application:heartbeat') ->setDescription('Run heartbeat hermes worker') ; } protected function execute(InputInterface $input, OutputInterface $output): int { $this->emitter->emit(new Message('heartbeat', ['executed' => time()]), RedisDriver::PRIORITY_MEDIUM); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/ProcessJobCommand.php
Mailer/extensions/mailer-module/src/Commands/ProcessJobCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Exception; use Nette\Utils\DateTime; use Remp\MailerModule\Models\HealthChecker; use Remp\MailerModule\Models\Job\BatchEmailGenerator; use Remp\MailerModule\Repositories\BatchesRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Tracy\Debugger; use Tracy\ILogger; class ProcessJobCommand extends Command { public const COMMAND_NAME = "mail:process-job"; private int $healthCheckTTLSeconds = 600; public function __construct( private readonly BatchesRepository $batchesRepository, private readonly BatchEmailGenerator $batchEmailGenerator, private readonly HealthChecker $healthChecker, ) { parent::__construct(); } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Process job command') ; } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(sprintf('%s <info>Mail process job</info>', DateTime::from('now'))); $pid = getmypid(); while ($batch = $this->batchesRepository->getBatchReady()) { $originalStatus = $batch->status; try { $this->healthChecker->ping(self::COMMAND_NAME, $this->healthCheckTTLSeconds); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_PROCESSING); $output->writeln(" * processing mail batch <info>#{$batch->id}</info>"); if ($batch->related('mail_job_batch_templates')->count('*') === 0) { $output->writeln("<error>Batch #{$batch->id} has no templates</error>"); $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_CREATED); continue; } $this->batchEmailGenerator->generate($batch); if ($originalStatus === BatchesRepository::STATUS_READY_TO_PROCESS) { $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_PROCESSED); } else { $this->batchesRepository->updateStatus($batch, BatchesRepository::STATUS_QUEUED); } $this->batchesRepository->update($batch, [ 'pid' => $pid, ]); } catch (Exception $e) { Debugger::log($e, ILogger::ERROR); $reschedule = DateTime::from('+5 minutes'); $this->batchesRepository->updateStatus($batch, $originalStatus); $this->batchesRepository->update($batch, [ 'start_at' => $reschedule, ]); $output->writeln(" * <error>processing failed</error>: {$e->getMessage()}; rescheduling to <info>{$reschedule->format(DATE_RFC3339)}</info>"); } } $output->writeln(' * no batch to process'); $this->healthChecker->ping(self::COMMAND_NAME); $output->writeln(''); $output->writeln('Done'); $output->writeln(''); return Command::SUCCESS; } public function setHealthCheckTTLSeconds(int $seconds): void { $this->healthCheckTTLSeconds = $seconds; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/MailTypeStatsCommand.php
Mailer/extensions/mailer-module/src/Commands/MailTypeStatsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Remp\MailerModule\Repositories\MailTypesRepository; use Symfony\Component\Console\Output\OutputInterface; use Remp\MailerModule\Repositories\MailTypeStatsRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; class MailTypeStatsCommand extends Command { /** * @var MailTypesRepository */ private $mailTypesRepository; /** * @var MailTypeStatsRepository */ private $mailTypeStatsRepository; /** * @var UserSubscriptionsRepository */ private $userSubscriptionsRepository; public function __construct( MailTypesRepository $mailTypesRepository, MailTypeStatsRepository $mailTypeStatsRepository, UserSubscriptionsRepository $userSubscriptionsRepository ) { parent::__construct(); $this->mailTypesRepository = $mailTypesRepository; $this->mailTypeStatsRepository = $mailTypeStatsRepository; $this->userSubscriptionsRepository = $userSubscriptionsRepository; } protected function configure(): void { $this->setName('mail:subscriber-stats') ->setDescription('Run mail type stats update'); } public function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(''); $output->writeln('<info>***** UPDATING MAIL TYPE STATS *****</info>'); $output->writeln(''); $allMailTypes = $this->mailTypesRepository->all()->fetchPairs('id', 'title'); $allMailTypeIds = array_keys($allMailTypes); $subscribersData = $this->userSubscriptionsRepository ->getAllSubscribersDataForMailTypes($allMailTypeIds); foreach ($subscribersData as $row) { if ($row->subscribed) { $this->mailTypeStatsRepository->add( $row->mail_type_id, $row->count ); } } $output->writeln(''); $output->writeln('Done'); $output->writeln(''); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/DatabaseSeedCommand.php
Mailer/extensions/mailer-module/src/Commands/DatabaseSeedCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Models\ContentGenerator\Replace\RtmClickReplace; use Remp\MailerModule\Models\Mailer\SmtpMailer; use Remp\MailerModule\Repositories\ConfigsRepository; use Remp\MailerModule\Repositories\ListCategoriesRepository; use Remp\MailerModule\Repositories\SourceTemplatesRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class DatabaseSeedCommand extends Command { private $configsRepository; private $listCategoriesRepository; private $sourceTemplatesRepository; public function __construct( ConfigsRepository $configsRepository, ListCategoriesRepository $listCategoriesRepository, SourceTemplatesRepository $sourceTemplatesRepository ) { parent::__construct(); $this->configsRepository = $configsRepository; $this->listCategoriesRepository = $listCategoriesRepository; $this->sourceTemplatesRepository = $sourceTemplatesRepository; } protected function configure(): void { $this->setName('db:seed') ->setDescription('Seed database with required values'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(''); $output->writeln('<info>***** APPLICATION SEEDER *****</info>'); $output->writeln(''); $output->writeln('Required configuration: '); $configValues = [ ['default_mailer', 'Default Mailer', SmtpMailer::ALIAS, '', 'string'], [RtmClickReplace::CONFIG_NAME, 'Mail click tracker', false, '', 'boolean'], ['one_click_unsubscribe', 'One-Click Unsubscribe', false, 'If enabled, adds <code class="muted">List-Unsubscribe=One-Click</code> header to emails that signals support for One-Click unsubscribe from the newsletters according to RFC 8058. The unsubscribe URL must support the POST method, must immediately unsubscribe the user from the newsletter, must not use redirection or any additional user verification; all the necessary data for unsubscribing must be part of the URL address.', 'boolean'] ]; foreach ($configValues as $configValue) { $config = $this->configsRepository->findBy('name', $configValue['0']); if (!$config) { $config = $this->configsRepository->add( $configValue[0], $configValue[1], $configValue[2], $configValue[3], $configValue[4] ); $output->writeln(" * Config <info>{$configValue['0']}</info> created"); } else { $output->writeln(" * Config <info>{$configValue['0']}</info> exists"); } } $listCategories = [ ['title' => 'Newsletters', 'code' => 'newsletters', 'sorting' => 100], ['title' => 'System', 'code' => 'system', 'sorting' => 999], ]; $output->writeln('Newsletter list categories:'); foreach ($listCategories as $category) { if ($this->listCategoriesRepository->getTable()->where(['code' => $category['code']])->count('*') > 0) { $output->writeln(" * Newsletter list <info>{$category['title']}</info> exists"); continue; } $this->listCategoriesRepository->add($category['title'], $category['code'], $category['sorting']); $output->writeln(" * Newsletter list <info>{$category['title']}</info> created"); } $output->writeln('Generator templates:'); $bestPerformingArticleHtml = <<<HTML <table cellpadding="10"> {% for url,item in items %} <tr> <td> <table cellpadding="10" style="border-bottom: 2px solid #efe5e5;"> <tr> <td colspan="2"><strong>{{ item.title }}</strong></td> </tr> <tr> <td><img style="max-height: 100px;" src="{{item.image}}"></td> <td>{{ item.description }}</td> </tr> <tr> <td colspan="2"><a href="{{ url }}">{{ url }}</a></td> </tr> </table> </td> </tr> {% endfor %} </table> HTML; $bestPerformingArticleText = <<<TEXT {% for url,item in items %} {{ item.title }} {{ item.description }} {{ url}} {% endfor %} TEXT; $generatorTemplates = [ [ 'title' => 'Best performing articles', 'code' => 'best-performing-articles', 'generator' => 'best_performing_articles', 'sorting' => 100, 'html' => $bestPerformingArticleHtml, 'text' => $bestPerformingArticleText ] ]; foreach ($generatorTemplates as $template) { if ($this->sourceTemplatesRepository->getTable()->where(['title' => $template['title']])->count('*') > 0) { $output->writeln(" * Generator template <info>{$template['title']}</info> exists"); continue; } $this->sourceTemplatesRepository->add( $template['title'], $template['code'], $template['generator'], $template['html'], $template['text'], $template['sorting'] ); $output->writeln(" * Generator template <info>{$template['title']}</info> created"); } $output->writeln('<info>OK!</info>'); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/ValidateCrmEmailsCommand.php
Mailer/extensions/mailer-module/src/Commands/ValidateCrmEmailsCommand.php
<?php namespace Remp\MailerModule\Commands; use DateInterval; use DateTime; use Exception; use Remp\MailerModule\Models\Crm\Client; use Remp\MailerModule\Models\Crm\UserNotFoundException; use Remp\MailerModule\Repositories\LogsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ValidateCrmEmailsCommand extends Command { public const COMMAND_NAME = "crm:validate-emails"; public function __construct( private LogsRepository $mailLogRepository, private Client $client ) { parent::__construct(); } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Validates mail sent in the last (by default) 10 minutes.') ->addArgument( "interval", InputArgument::OPTIONAL, "How far back the validation interval should extend. By default 10 minutes.", 'PT10M', ); } protected function execute(InputInterface $input, OutputInterface $output): int { $client = $this->client; if (is_null($client)) { $output->writeln("<error>ERROR</error>: CRM client was not initialized, check your config.local.neon."); return Command::FAILURE; } $interval = $input->getArgument('interval'); try { $interval = new DateInterval($interval); } catch (Exception $e) { $output->writeln("Failed to parse interval <comment>{$interval}</comment>:\n" . $e->getMessage()); return Command::FAILURE; } $deliveredAtFrom = (new DateTime())->sub($interval); $emails = $this->mailLogRepository->getTable() ->select('DISTINCT email') ->where('delivered_at >= ?', $deliveredAtFrom) ->fetchPairs(value: 'email'); $now = new DateTime(); $before = (clone $now)->sub($interval); $output->writeln(sprintf( "Validating %d emails, from <info>%s</info> to <info>%s</info>.", count($emails), $before->format(\DateTimeInterface::RFC3339), $now->format(\DateTimeInterface::RFC3339), )); $client->validateMultipleEmails($emails); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/SyncUserSubscriptionsCommand.php
Mailer/extensions/mailer-module/src/Commands/SyncUserSubscriptionsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Remp\MailerModule\Models\Users\IUser; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\ListsRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class SyncUserSubscriptionsCommand extends Command { private $userProvider; private $listsRepository; private $userSubscriptionsRepository; public function __construct( IUser $userProvider, ListsRepository $listsRepository, UserSubscriptionsRepository $userSubscriptionsRepository ) { parent::__construct(); $this->userProvider = $userProvider; $this->listsRepository = $listsRepository; $this->userSubscriptionsRepository = $userSubscriptionsRepository; } protected function configure(): void { $this->setName('mail:sync-user-subscriptions') ->setDescription('Gets all users from user base and subscribes them to emails based on the auto_subscribe flags'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln(''); $output->writeln('<info>***** AUTO-SUBSCRIBING ALL USERS *****</info>'); $output->writeln('(already existing records will not be touched)'); $output->writeln(''); $page = 1; $lists = $this->listsRepository->all(); while ($users = $this->userProvider->list([], $page)) { $emails = []; foreach ($users as $user) { $emails[] = $user['email']; } $mailSubscriptions = $this->userSubscriptionsRepository->getTable()->where(['user_email' => $emails])->fetchAll(); $processed = []; foreach ($mailSubscriptions as $mailSubscription) { $processed[$mailSubscription->user_email][$mailSubscription->mail_type_id] = true; } foreach ($users as $user) { $output->write(sprintf("Processing user: %s (%s) ... ", $user['email'], $user['id'])); /** @var ActiveRow $list */ foreach ($lists as $list) { if (isset($processed[$user['email']][$list->id])) { continue; } if ($list->auto_subscribe) { $this->userSubscriptionsRepository->subscribeUser($list, $user['id'], $user['email']); } else { $this->userSubscriptionsRepository->unsubscribeUser($list, $user['id'], $user['email']); } } $output->writeln('<info>OK!</info>'); } $page++; } $output->writeln(''); $output->writeln('<info>Done.</info>'); return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/ProcessConversionStatsCommand.php
Mailer/extensions/mailer-module/src/Commands/ProcessConversionStatsCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Utils\DateTime; use Remp\MailerModule\Models\Users\IUser; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\IConversionsRepository; use Remp\MailerModule\Repositories\LogConversionsRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ProcessConversionStatsCommand extends Command { private $conversionsRepository; private $templatesRepository; private $userProvider; private $logsRepository; private $logConversionsRepository; private BatchesRepository $batchesRepository; public function __construct( IConversionsRepository $conversionsRepository, TemplatesRepository $templatesRepository, IUser $userProvider, LogsRepository $logsRepository, LogConversionsRepository $logConversionsRepository, BatchesRepository $batchesRepository ) { parent::__construct(); $this->conversionsRepository = $conversionsRepository; $this->templatesRepository = $templatesRepository; $this->userProvider = $userProvider; $this->logsRepository = $logsRepository; $this->logConversionsRepository = $logConversionsRepository; $this->batchesRepository = $batchesRepository; } protected function configure() { $this->setName('mail:conversion-stats') ->setDescription('Process job stats based on conversion data') ->addOption( 'since', null, InputOption::VALUE_OPTIONAL, 'date string specifying which mailJobBatches (since when until now) should be processed', '-1 month' ) ->addOption( 'mode', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'processing mode (job_batch - processing newsletters, direct - processing system emails)', ['job_batch'] ); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(''); $output->writeln('<info>***** UPDATE EMAIL CONVERSION STATS *****</info>'); $output->writeln(''); ProgressBar::setFormatDefinition( 'processStats', "%processing% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%" ); // batch template conversions (from jobs) if (in_array('job_batch', $input->getOption('mode'), true)) { $this->processBatchTemplateConversions($input, $output); } // non batch template conversions (direct sends) if (in_array('direct', $input->getOption('mode'), true)) { $this->processNonBatchTemplateConversions($input, $output); } $output->writeln('Done!'); $output->writeln(''); return 0; } private function processBatchTemplateConversions(InputInterface $input, OutputInterface $output) { $batchTemplatesConversions = $this->conversionsRepository ->getBatchTemplatesConversionsSince(DateTime::from($input->getOption('since'))); $progressBar = new ProgressBar($output, count($batchTemplatesConversions)); $progressBar->setFormat('processStats'); $progressBar->start(); $validMailJobBatchIds = $this->getValidMailJobBatchIds(array_keys($batchTemplatesConversions)); foreach ($batchTemplatesConversions as $mailJobBatchId => $mailTemplateCodes) { if (!in_array($mailJobBatchId, $validMailJobBatchIds, true)) { continue; } foreach ($mailTemplateCodes as $mailTemplateCode => $userIds) { $userData = $this->getUserData(array_keys($userIds)); $mailTemplate = $this->templatesRepository->getByCode($mailTemplateCode); if (!$mailTemplate) { continue; } foreach ($userIds as $userId => $time) { if (!isset($userData[$userId])) { // this might be incorrectly tracker userId; throwing warning won't probably help at this point // as it's not in Beam and the tracking might be already fixed continue; } $latestLog = $this->logsRepository->getTable() ->where([ 'email' => $userData[$userId], 'mail_template_id' => $mailTemplate->id, 'mail_job_batch_id' => $mailJobBatchId ]) ->where('created_at < ?', DateTime::from($time)) ->order('id DESC') ->fetch(); if (!$latestLog) { continue; } $this->logConversionsRepository->upsert($latestLog, DateTime::from($time)); } } $progressBar->advance(); } $progressBar->setMessage('done'); $progressBar->finish(); $output->writeln(""); } private function getValidMailJobBatchIds($mailJobBatchIds): array { $result = []; foreach ($mailJobBatchIds as $mailJobBatchId) { if (!is_numeric($mailJobBatchId)) { continue; } $mailJobBatch = $this->batchesRepository->find($mailJobBatchId); if ($mailJobBatch) { $result[] = $mailJobBatchId; } } return $result; } private function processNonBatchTemplateConversions(InputInterface $input, OutputInterface $output) { $nonBatchTemplatesConversions = $this->conversionsRepository ->getNonBatchTemplatesConversionsSince(DateTime::from($input->getOption('since'))); $progressBar = new ProgressBar($output, count($nonBatchTemplatesConversions)); $progressBar->setFormat('processStats'); $progressBar->start(); foreach ($nonBatchTemplatesConversions as $mailTemplateCode => $userIds) { $userData = $this->getUserData(array_keys($userIds)); $mailTemplate = $this->templatesRepository->getByCode($mailTemplateCode); if (!$mailTemplate) { continue; } foreach ($userIds as $userId => $time) { if (!isset($userData[$userId])) { // this might be incorrectly tracker userId; throwing warning won't probably help at this point // as it's not in Beam and the tracking might be already fixed continue; } $latestLog = $this->logsRepository->getTable() ->where([ 'email' => $userData[$userId], 'mail_template_id' => $mailTemplate->id, ]) ->where('created_at < ?', DateTime::from($time)) ->order('id DESC') ->fetch(); if (!$latestLog) { continue; } $this->logConversionsRepository->upsert($latestLog, DateTime::from($time)); } $progressBar->advance(); } $progressBar->setMessage('done'); $progressBar->finish(); } private function getUserData($userIds) { $userData = []; foreach (array_chunk($userIds, 1000, true) as $userIdsChunk) { $page = 1; while ($users = $this->userProvider->list($userIdsChunk, $page)) { foreach ($users as $user) { $userData[$user['id']] = $user['email']; } $page++; } } return $userData; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/MailWorkerCommand.php
Mailer/extensions/mailer-module/src/Commands/MailWorkerCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Exception; use League\Event\EventDispatcher; use Nette\Mail\SmtpException; use Nette\Utils\DateTime; use Nette\Utils\Json; use Psr\Log\LoggerInterface; use Remp\MailerModule\Events\MailSentEvent; use Remp\MailerModule\Models\HealthChecker; use Remp\MailerModule\Models\Job\MailCache; use Remp\MailerModule\Models\Mailer\EmailAllowList; use Remp\MailerModule\Models\Sender; use Remp\MailerModule\Repositories\ActiveRow; use Remp\MailerModule\Repositories\BatchesRepository; use Remp\MailerModule\Repositories\BatchTemplatesRepository; use Remp\MailerModule\Repositories\JobQueueRepository; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Throwable; use Tomaj\Hermes\Shutdown\ShutdownInterface; use Tracy\Debugger; use Tracy\ILogger; class MailWorkerCommand extends Command { public const COMMAND_NAME = "worker:mail"; private $applicationMailer; private $mailJobBatchRepository; private $mailJobQueueRepository; private $mailLogRepository; private $mailTemplateRepository; private $batchTemplatesRepository; private $mailCache; private $emailAllowList; private $eventDispatcher; private $isFirstLine = true; private $smtpErrors = 0; private $logger; /** @var ShutdownInterface */ private $shutdown; /** @var DateTime */ private $startTime; private HealthChecker $healthChecker; public function __construct( LoggerInterface $logger, Sender $applicationMailer, BatchesRepository $mailJobBatchRepository, JobQueueRepository $mailJobQueueRepository, LogsRepository $mailLogRepository, TemplatesRepository $mailTemplatesRepository, BatchTemplatesRepository $batchTemplatesRepository, MailCache $redis, EmailAllowList $emailAllowList, EventDispatcher $eventDispatcher, HealthChecker $healthChecker ) { parent::__construct(); $this->applicationMailer = $applicationMailer; $this->mailJobBatchRepository = $mailJobBatchRepository; $this->mailJobQueueRepository = $mailJobQueueRepository; $this->mailLogRepository = $mailLogRepository; $this->mailTemplateRepository = $mailTemplatesRepository; $this->batchTemplatesRepository = $batchTemplatesRepository; $this->mailCache = $redis; $this->emailAllowList = $emailAllowList; $this->eventDispatcher = $eventDispatcher; $this->logger = $logger; $this->healthChecker = $healthChecker; } /** * Set implementation of ShutdownInterface which should handle graceful shutdowns. * * @param ShutdownInterface $shutdown */ public function setShutdownInterface(ShutdownInterface $shutdown): void { $this->shutdown = $shutdown; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Start worker sending mails') ->addOption( 'batch', 'b', InputOption::VALUE_NONE, 'Flag whether batch sending should be attempted (will fallback to non-batch if selected mailer doesn\'t support batch sending)' ) ->addOption( 'batch-size', 's', InputOption::VALUE_REQUIRED, 'Size of the batch to be used for sending. Applies only when --batch is used.', 200 ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { // store when command was started $this->startTime = new DateTime(); $sendAsBatch = $input->getOption('batch'); $messagesPerBatch = (int) $input->getOption('batch-size'); if ($messagesPerBatch <= 0) { throw new RuntimeException("The --batch-size option only allows positive integers."); } $output->writeln(''); $output->writeln('<info>***** EMAIL WORKER *****</info>'); $output->writeln(''); $output->write('Checking mail queues'); while (true) { // graceful shutdown check if ($this->shutdown && $this->shutdown->shouldShutdown($this->startTime)) { $now = (new DateTime())->format(DATE_RFC3339); $msg = "Exiting mail worker: shutdown instruction received '{$now}'."; $output->write("\n<comment>{$msg}</comment>\n"); $this->logger->info($msg); return 0; } $this->healthChecker->ping(self::COMMAND_NAME); $batch = $this->mailJobBatchRepository->getBatchToSend(); if (!$batch) { sleep(30); $output->write('.'); $this->isFirstLine = true; continue; } if ($this->isFirstLine) { $output->writeln(''); $this->isFirstLine = false; } if (!$this->mailCache->hasJobs($batch->id)) { $output->writeln("Queue <info>{$batch->id}</info> has no more jobs, cleaning up..."); $this->stopBatchSending($batch, BatchesRepository::STATUS_DONE); continue; } if ($batch->status === BatchesRepository::STATUS_QUEUED) { $this->mailJobBatchRepository->updateStatus($batch, BatchesRepository::STATUS_SENDING); } $output->writeln("Sending batch <info>{$batch->id}</info>..."); $this->logger->info("Sending batch <info>{$batch->id}</info>..."); while (true) { $this->healthChecker->ping(self::COMMAND_NAME); if (!$this->mailCache->isQueueActive($batch->id)) { $output->writeln("Queue <info>{$batch->id}</info> not active anymore..."); $this->logger->info("Queue <info>{$batch->id}</info> not active anymore..."); break; } if (!$this->mailCache->isQueueTopPriority($batch->id)) { $topPriorityQueueScore = $this->mailCache->getTopPriorityQueues(); $topPriorityBatchId = array_key_first($topPriorityQueueScore); $output->writeln("Batch <info>{$batch->id}</info> no longer top priority, switching to <info>$topPriorityBatchId</info>..."); $this->logger->info("Batch <info>{$batch->id}</info> no longer top priority, switching to <info>$topPriorityBatchId</info>..."); if (!$this->mailJobBatchRepository->isSendingBatch($topPriorityBatchId)) { $this->mailCache->removeQueue($topPriorityBatchId); $output->writeln("Top priority batch <info>{$topPriorityBatchId}</info> is not being sent anymore, clearing cache and starting again..."); $this->logger->info("Top priority batch <info>{$topPriorityBatchId}</info> is not being sent anymore, clearing cache and starting again..."); } break; } $mailJobBatchTemplate = $this->batchTemplatesRepository->findByBatchId($batch->id)->fetch(); if (!$mailJobBatchTemplate) { $this->stopBatchSending($batch, BatchesRepository::STATUS_WORKER_STOP); $this->logger->error('Mail job batch template not found for batch: ' . $batch->id); continue 2; } if ($sendAsBatch && $this->applicationMailer->getMailerByTemplate($mailJobBatchTemplate->mail_template)->supportsBatch()) { $rawJobs = $this->mailCache->getJobs($batch->id, $messagesPerBatch); if (empty($rawJobs)) { break; } } else { $rawJobs = $this->mailCache->getJob($batch->id); if (!$rawJobs) { break; } $rawJobs = [$rawJobs]; } $jobsByTemplateCode = []; foreach ($rawJobs as $rawJob) { $job = Json::decode($rawJob); $jobsByTemplateCode[$job->templateCode][] = $job; } foreach ($jobsByTemplateCode as $templateCode => $jobs) { $originalCount = count($jobs); $jobs = $this->filterJobs($jobs, $batch); $jobsCount = count($jobs); $filteredCount = $originalCount - $jobsCount; if ($filteredCount > 0) { $output->writeln(" * $filteredCount jobs of $originalCount were filtered for template <info>{$templateCode}</info>, <info>{$batch->id}</info>"); $this->logger->info(" * $filteredCount jobs of $originalCount were filtered for template <info>{$templateCode}</info>, <info>{$batch->id}</info>"); } if (empty($jobs)) { continue; } $email = $this->applicationMailer ->reset() ->setJobId($batch->mail_job_id) ->setBatchId($batch->id); $template = null; $output->writeln(" * Processing $jobsCount jobs of template <info>{$templateCode}</info>, batch <info>{$batch->id}</info>"); $this->logger->info(" * Processing $jobsCount jobs of template <info>{$templateCode}</info>, batch <info>{$batch->id}</info>"); foreach ($jobs as $i => $job) { if (!$template) { $template = $this->mailTemplateRepository->getByCode($job->templateCode); } $output->writeln(" * sending <info>{$job->templateCode}</info> from batch <info>{$batch->id}</info> to <info>{$job->email}</info>"); $recipientParams = $job->params ? get_object_vars($job->params) : []; $email->addRecipient($job->email, null, $recipientParams); if ($job->context) { $email->setContext($job->context); } } $sentCount = 0; try { $email = $email->setTemplate($template); if ($sendAsBatch && $email->supportsBatch()) { $output->writeln("sending {$templateCode} (batch {$batch->id}) as a batch"); try { $sentCount = $email->sendBatch($this->logger); } catch (Throwable $throwable) { $this->logger->warning('Unexpected error occurred while sending batch ', [ 'message' => $throwable->getMessage(), 'throwable' => $throwable, ]); throw $throwable; } } else { $sentCount = $email->send(); } $output->writeln(" * $sentCount mail(s) of batch <info>{$batch->id}</info> sent"); $this->logger->info(" * $sentCount mail(s) of batch <info>{$batch->id}</info> sent"); foreach ($jobs as $job) { $this->eventDispatcher->dispatch(new MailSentEvent($job->userId, $job->email, $job->templateCode, $batch->id, time())); } $this->smtpErrors = 0; } catch (SmtpException | Sender\MailerBatchException | Exception $exception) { $this->smtpErrors++; $output->writeln("<error>Sending error: {$exception->getMessage()}</error>"); Debugger::log($exception, ILogger::WARNING); $this->logger->warning("Unable to send an email: " . $exception->getMessage(), [ 'batch' => $sendAsBatch && $email->supportsBatch(), 'template' => $templateCode, ]); $this->cacheJobs($jobs, $batch->id); if ($this->smtpErrors >= 10) { $this->mailJobBatchRepository->updateStatus($batch, BatchesRepository::STATUS_WORKER_STOP); break; } sleep(10); } $now = new DateTime(); $first_email = $batch->first_email_sent_at ?: $now; // update stats $this->mailJobBatchRepository->update($batch, [ 'first_email_sent_at' => $first_email, 'last_email_sent_at' => $now, 'sent_emails+=' => $sentCount, 'last_ping' => $now ]); $jobBatchTemplate = $this->batchTemplatesRepository->getTable()->where([ 'mail_template_id' => $template->id, 'mail_job_batch_id' => $batch->id, ])->fetch(); $this->batchTemplatesRepository->update($jobBatchTemplate, [ 'sent+=' => $sentCount, ]); } } } return Command::SUCCESS; } private function cacheJobs(array $jobs, int $batchId): void { foreach ($jobs as $job) { $this->mailCache->addJob($job->userId, $job->email, $job->templateCode, $batchId, $job->context, (array) ($job->params ?? [])); } } private function filterJobs(array $jobs, ActiveRow $batch): array { $mailTemplates = []; $emailsByTemplateCodes = []; $jobsByEmails = []; foreach ($jobs as $i => $job) { if (!isset($mailTemplates[$job->templateCode])) { $mailTemplates[$job->templateCode] = $this->mailTemplateRepository->getByCode($job->templateCode); } $emailsByTemplateCodes[$job->templateCode][] = $job->email; $jobsByEmails[$job->email] = $job; } // get list of allowed emails $filteredEmails = []; foreach ($emailsByTemplateCodes as $templateCode => $emails) { $filteredTemplateEmails = $this->mailLogRepository->filterAlreadySentV2( emails: $emails, mailTemplate: $mailTemplates[$templateCode], job: $batch->mail_job, context: $job->context ?? null, ); $filteredEmails = array_merge($filteredEmails, $filteredTemplateEmails); } // extract list of allowed jobs based on allowed emails $filteredJobs = []; foreach ($filteredEmails as $filteredEmail) { if ($this->emailAllowList->isAllowed($filteredEmail)) { $filteredJobs[] = $jobsByEmails[$filteredEmail]; } } return $filteredJobs; } private function stopBatchSending(ActiveRow $batch, string $batchStatus): void { $this->mailCache->removeQueue($batch->id); $this->mailJobBatchRepository->updateStatus($batch, $batchStatus); $this->mailJobQueueRepository->clearBatch($batch); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/MigrateAutologinTokensCommand.php
Mailer/extensions/mailer-module/src/Commands/MigrateAutologinTokensCommand.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Commands; use Nette\Database\Explorer; use Nette\Utils\DateTime; use Remp\MailerModule\Models\EnvironmentConfig; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; use Remp\MailerModule\Repositories\AutoLoginTokensRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class MigrateAutologinTokensCommand extends Command { use RedisClientTrait; public const AUTOLOGIN_TOKENS_MIGRATION_IS_RUNNING = 'autologin_tokens_migration_running'; public const COMMAND_NAME = "mail:migrate-autologin-tokens"; public function __construct( private Explorer $database, private AutoLoginTokensRepository $autoLoginTokensRepository, private EnvironmentConfig $environmentConfig, RedisClientFactory $redisClientFactory, ) { parent::__construct(); $this->redisClientFactory = $redisClientFactory; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Migrate autologin tokens data to new table.'); } protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('STARTING `autologin_tokens` TABLE DATA MIGRATION'); $output->writeln(''); $autologinTokensTableName = $this->autoLoginTokensRepository->getTable()->getName(); $autologinTokensV2TableName = $this->autoLoginTokensRepository->getNewTable()->getName(); // Set migration running/start time flag in redis $migrationStartTime = new DateTime(); if ($this->redis()->exists(self::AUTOLOGIN_TOKENS_MIGRATION_IS_RUNNING)) { $migrationStartTime = new DateTime($this->redis()->get(self::AUTOLOGIN_TOKENS_MIGRATION_IS_RUNNING)); } else { $this->redis()->set(self::AUTOLOGIN_TOKENS_MIGRATION_IS_RUNNING, $migrationStartTime); } $this->database->query(" SET FOREIGN_KEY_CHECKS=0; SET UNIQUE_CHECKS=0; "); // Paging LOOP $pageSize = 10000; while (true) { $lastMigratedId = $this->database ->query("SELECT id FROM `{$autologinTokensV2TableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; $maxId = $this->database ->query("SELECT id FROM `{$autologinTokensTableName}` WHERE created_at <= ? ORDER BY id DESC LIMIT 1", $migrationStartTime) ->fetch() ?->id ?? 0; if ($maxId === 0 || $lastMigratedId === $maxId) { break; } $this->database->query(" INSERT IGNORE INTO `{$autologinTokensV2TableName}` (`id`, `token`, `user_id`, `email`, `created_at`, `valid_from`, `valid_to`, `used_count`, `max_count`) SELECT `id`, `token`, `user_id`, `email`, `created_at`, `valid_from`, `valid_to`, `used_count`, `max_count` FROM `{$autologinTokensTableName}` WHERE id > {$lastMigratedId} ORDER BY id ASC LIMIT {$pageSize} "); $remaining = $maxId-$lastMigratedId; $output->write("\r\e[0KMIGRATED IDs: {$lastMigratedId} / {$maxId} (REMAINING: {$remaining})"); } $output->writeln(''); $output->writeln('DATA MIGRATED'); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $autologinTokensTableName, $autologinTokensV2TableName, $migrationStartTime ); $output->writeln(''); $output->writeln('SETUPING AUTO_INCREMENT'); // Sat AUTO_INCREMENT for new tables to old table values $dbName = $this->environmentConfig->get('DB_NAME'); $this->database->query(" SELECT MAX(id)+10000 INTO @AutoInc FROM {$autologinTokensTableName}; SET @s:=CONCAT('ALTER TABLE `{$dbName}`.`{$autologinTokensV2TableName}` AUTO_INCREMENT=', @AutoInc); PREPARE stmt FROM @s; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); $output->writeln(''); $output->writeln('RENAMING TABLES'); // Rename tables $this->database->query(" ANALYZE TABLE {$autologinTokensV2TableName}; RENAME TABLE {$autologinTokensTableName} TO {$autologinTokensTableName}_old, {$autologinTokensV2TableName} TO {$autologinTokensTableName}; "); $output->writeln(''); $output->writeln('UPDATING ROWS DIFFERENCES AND INSERTING MISSING ROWS'); $this->fixTableDifferences( $autologinTokensTableName . '_old', $autologinTokensTableName, $migrationStartTime ); $this->database->query(" SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; "); // Remove migration running flag in redis $this->redis()->del(self::AUTOLOGIN_TOKENS_MIGRATION_IS_RUNNING); $output->writeln(''); $output->writeln('DATA MIGRATED SUCCESSFULLY'); return Command::SUCCESS; } public function fixTableDifferences( string $fromTable, string $toTable, DateTime $updatedAfter ) { $this->database->query(" UPDATE {$toTable} at_to JOIN {$fromTable} at_from on at_to.id = at_from.id SET at_to.used_count = at_from.used_count WHERE at_to.used_count != at_from.used_count; "); $missingIds = $this->database->query(" SELECT `id` FROM `{$fromTable}` WHERE created_at > ? AND `id` NOT IN ( SELECT `id` FROM `{$toTable}` WHERE created_at > ? ) ", $updatedAfter, $updatedAfter)->fetchFields(); if ($missingIds) { $this->database->query(" INSERT IGNORE INTO `{$toTable}` (`id`, `token`, `user_id`, `email`, `created_at`, `valid_from`, `valid_to`, `used_count`, `max_count`) SELECT `id`, `token`, `user_id`, `email`, `created_at`, `valid_from`, `valid_to`, `used_count`, `max_count` FROM `{$fromTable}` WHERE `id` IN ? ", $missingIds); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Commands/UnsubscribeInactiveUsersCommand.php
Mailer/extensions/mailer-module/src/Commands/UnsubscribeInactiveUsersCommand.php
<?php namespace Remp\MailerModule\Commands; use Nette\Utils\DateTime; use Remp\MailerModule\Hermes\HermesMessage; use Remp\MailerModule\Models\RedisClientFactory; use Remp\MailerModule\Models\RedisClientTrait; use Remp\MailerModule\Models\Segment\Aggregator; use Remp\MailerModule\Models\Segment\Crm; use Remp\MailerModule\Models\Tracker\EventOptions; use Remp\MailerModule\Models\Tracker\ITracker; use Remp\MailerModule\Models\Tracker\User; use Remp\MailerModule\Repositories\LogsRepository; use Remp\MailerModule\Repositories\TemplatesRepository; use Remp\MailerModule\Repositories\UserSubscriptionsRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Tomaj\Hermes\Emitter; class UnsubscribeInactiveUsersCommand extends Command { use DecoratedCommandTrait, RedisClientTrait; public const COMMAND_NAME = 'mail:unsubscribe-inactive-users'; private const CRM_SEGMENT_NAME = 'unsubscribe_inactive_users_from_newsletters_list'; public const APPLE_BOT_EMAILS = 'apple_bot_emails'; private array $omitMailTypeCodes = ['system', 'system_optional']; public function __construct( private Aggregator $segmentAggregator, private UserSubscriptionsRepository $userSubscriptionsRepository, private TemplatesRepository $templatesRepository, private LogsRepository $logsRepository, private Emitter $hermesEmitter, RedisClientFactory $redisClientFactory, private ITracker|null $tracker = null ) { parent::__construct(); $this->redisClientFactory = $redisClientFactory; } protected function configure(): void { $this->setName(self::COMMAND_NAME) ->setDescription('Unsubscribe inactive users from newsletters') ->addOption('segment-provider', 'sp', InputOption::VALUE_REQUIRED, 'Segment provider code.', Crm::PROVIDER_ALIAS) ->addOption('segment', 's', InputOption::VALUE_REQUIRED, 'Crm segment with list of users to unsubscribe.', self::CRM_SEGMENT_NAME) ->addOption('days', 'd', InputOption::VALUE_REQUIRED, 'Days limit for check opened emails.', 45) ->addOption('disable-apple-bot-check', 'dabc', InputOption::VALUE_NONE, 'Do not make distinction between Apple bot and real user, while checking opened/clicked.') ->addOption('email', 'e', InputOption::VALUE_REQUIRED, 'Email template code of notification email, sent after unsubscribing.') ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Run command without unsubscribing users and sending notifications.') ->addOption('omit-mail-type-code', 'o', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Omit mail type (code), from email delivered and opened check and unsubscribing.'); } protected function execute(InputInterface $input, OutputInterface $output): int { $segmentProvider = $input->getOption('segment-provider'); $segment = $input->getOption('segment'); $dayLimit = $input->getOption('days'); $dryRun = $input->getOption('dry-run'); $disableAppleBotCheck = $input->getOption('disable-apple-bot-check'); $notificationEmailCode = $input->getOption('email'); $omitMailTypeCodes = array_merge($this->omitMailTypeCodes, $input->getOption('omit-mail-type-code')); if ($notificationEmailCode) { $notificationEmailTemplate = $this->templatesRepository->getByCode($input->getOption('email')); if (!$notificationEmailTemplate) { $this->error("Notification email template: '{$input->getOption('email')}' doesn't exist."); return Command::FAILURE; } } $userIds = $this->segmentAggregator->users(['provider' => $segmentProvider, 'code' => $segment]); foreach ($userIds as $userId) { $output->write("* Checking user <info>{$userId}</info>: "); $subscribed = $this->userSubscriptionsRepository->getTable() ->where('user_id', $userId) ->where('mail_type.code NOT IN', $omitMailTypeCodes) ->where('subscribed', 1) ->fetch(); if ($subscribed) { $userEmail = $subscribed->user_email; $logs = $this->logsRepository->getTable() ->where('user_id', $userId) ->where('delivered_at > ', DateTime::from("-{$dayLimit} days")) ->where('mail_template.mail_type.code NOT IN', $omitMailTypeCodes) ->fetchAll(); $logCount = count($logs); if (count($logs) >= 5) { $isAppleBotOpenedEmail = $disableAppleBotCheck ? false : $this->redis()->sismember(self::APPLE_BOT_EMAILS, $userEmail); foreach ($logs as $log) { if ($isAppleBotOpenedEmail && $log->clicked_at) { $output->writeln("Skipping, user is active."); continue 2; } if (!$isAppleBotOpenedEmail && ($log->opened_at || $log->clicked_at)) { $output->writeln("Skipping, user is active."); continue 2; } } if (!$dryRun) { $output->write("<comment>Unsubscribing...</comment> "); $this->userSubscriptionsRepository->unsubscribeUserFromAll($userId, $userEmail, $omitMailTypeCodes); $eventOptions = new EventOptions(); $eventOptions->setUser(new User(['id' => $userId])); $this->tracker?->trackEvent( new DateTime(), 'mail-type', 'auto-unsubscribe', $eventOptions ); if (isset($notificationEmailTemplate)) { $today = new DateTime(); $this->hermesEmitter->emit(new HermesMessage('send-email', [ 'mail_template_code' => $notificationEmailTemplate->code, 'email' => $userEmail, 'context' => "nl_goodbye_all_email.{$userId}.{$notificationEmailTemplate->mail_type->id}.{$today->format('Ymd')}", ])); } } else { $output->write("<comment>Unsubscribing (dry run)...</comment> "); } $output->writeln("OK!"); } else { $output->writeln("Skipping, not enough delivered emails within the {$dayLimit} days period ({$logCount})."); } } else { $output->writeln("Skipping, not subscribed to anything relevant."); } } return Command::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Filters/YesNoFilter.php
Mailer/extensions/mailer-module/src/Filters/YesNoFilter.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Filters; class YesNoFilter { public function process(int $input): string { return (boolean) $input ? 'Yes' : 'No'; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/LayoutsRepository.php
Mailer/extensions/mailer-module/src/Repositories/LayoutsRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; use Nette\Utils\DateTime; class LayoutsRepository extends Repository { use SoftDeleteTrait; protected $tableName = 'mail_layouts'; protected $dataTableSearchable = ['name', 'code', 'layout_text', 'layout_html']; public function all(): Selection { return $this->getTable() ->where('deleted_at', null) ->order('name ASC'); } public function add(string $name, string $code, string $layoutText, string $layoutHtml): ActiveRow { $result = $this->insert([ 'name' => $name, 'code' => $code, 'created_at' => new DateTime(), 'updated_at' => new DateTime(), 'layout_html' => $layoutHtml, 'layout_text' => $layoutText, ]); if (is_numeric($result)) { return $this->getTable()->where('id', $result)->fetch(); } return $result; } public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool { $data['updated_at'] = new DateTime(); return parent::update($row, $data); } public function tableFilter(string $query, string $order, string $orderDirection, ?int $limit = null, ?int $offset = null): Selection { $selection = $this->getTable() ->where('deleted_at', null) ->order($order . ' ' . strtoupper($orderDirection)); if (!empty($query)) { $where = []; foreach ($this->dataTableSearchable as $col) { $where[$col . ' LIKE ?'] = '%' . $query . '%'; } $selection->whereOr($where); } if ($limit != null) { $selection->limit($limit, $offset); } return $selection; } public function search(string $term, int $limit): array { $searchable = ['name']; foreach ($searchable as $column) { $where[$column . ' LIKE ?'] = '%' . $term . '%'; } $results = $this->all() ->select(implode(',', array_merge(['id'], $searchable))) ->whereOr($where) ->limit($limit) ->fetchAssoc('id'); return $results; } public function canBeDeleted(ActiveRow $layout): bool { return !(bool) $layout->related('mail_templates')->where('deleted_at', null)->count('*'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/MailTypesRepository.php
Mailer/extensions/mailer-module/src/Repositories/MailTypesRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; class MailTypesRepository extends Repository { protected $tableName = 'mail_types'; public function all(): Selection { return $this->getTable(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/TemplatesCodeNotUniqueException.php
Mailer/extensions/mailer-module/src/Repositories/TemplatesCodeNotUniqueException.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; use Exception; class TemplatesCodeNotUniqueException 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/Repositories/BeamConversionsRepository.php
Mailer/extensions/mailer-module/src/Repositories/BeamConversionsRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; use Nette\Caching\Storage; use Nette\Database\Explorer; use Remp\Journal\ListRequest; use Remp\MailerModule\Models\Beam\JournalFactory; class BeamConversionsRepository extends Repository implements IConversionsRepository { private $journal; public function __construct( Explorer $database, JournalFactory $journalFactory, Storage $cacheStorage = null ) { parent::__construct($database, $cacheStorage); $this->journal = $journalFactory->getClient(); } public function getBatchTemplatesConversionsSince(\DateTime $since): array { if (!$this->journal) { return []; } $purchases = []; // RTM + UTM fallback (to be removed) $request = (new ListRequest('commerce')) ->addSelect("step", "rtm_campaign", "rtm_content", "rtm_medium", "utm_campaign", "utm_content", "user_id", "token", "time") ->setTimeAfter($since) ->addFilter('step', 'purchase') ->addFilter('rtm_medium', 'email'); // condition translated to (RTM or UTM) on Segments API $result = $this->journal->list($request); foreach ($result as $record) { foreach ($record->commerces as $purchase) { $rtmContent = $purchase->source->rtm_content ?? $purchase->source->utm_content ?? null; $rtmCampaign = $purchase->source->rtm_campaign ?? $purchase->source->utm_campaign ?? null; if (empty($rtmContent)) { // skip conversions without batch reference continue; } if (empty($rtmCampaign)) { // skip conversions without campaign (without reference to mail_template) continue; } $purchases[$rtmContent][$rtmCampaign][$purchase->user->id] = $purchase->system->time; } } return $purchases; } public function getNonBatchTemplatesConversionsSince(\DateTime $since): array { if (!$this->journal) { return []; } $purchases = []; // RTM + UTM fallback (to be removed) $request = (new ListRequest('commerce')) ->addSelect("step", "rtm_campaign", "rtm_content", "rtm_medium", "utm_campaign", "utm_content", "user_id", "token", "time") ->setTimeAfter($since) ->addFilter('step', 'purchase') ->addFilter('rtm_medium', 'email'); // condition translated to (RTM or UTM) on Segments API $result = $this->journal->list($request); foreach ($result as $record) { foreach ($record->commerces as $purchase) { $rtmContent = $purchase->source->rtm_content ?? $purchase->source->utm_content ?? null; $rtmCampaign = $purchase->source->rtm_campaign ?? $purchase->source->utm_campaign ?? null; if (!empty($rtmContent)) { // skip conversions with batch reference continue; } if (empty($rtmCampaign)) { // skip conversions without campaign (without reference to mail_template) continue; } $purchases[$rtmCampaign][$purchase->user->id] = $purchase->system->time; } } return $purchases; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/ListCategoriesRepository.php
Mailer/extensions/mailer-module/src/Repositories/ListCategoriesRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; use Nette\Database\Table\Selection; use Nette\Utils\DateTime; class ListCategoriesRepository extends Repository { protected $tableName = 'mail_type_categories'; public function all(): Selection { return $this->getTable()->order('sorting ASC'); } public function add(string $title, string $code, int $sorting): ActiveRow { return $this->getTable()->insert([ 'title' => $title, 'code' => $code, 'sorting' => $sorting, 'created_at' => new DateTime(), ]); } public function getByCode(string $code): Selection { return $this->getTable()->where(['code' => $code]); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/BatchesRepository.php
Mailer/extensions/mailer-module/src/Repositories/BatchesRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; use Nette\Caching\Storage; use Nette\Database\Explorer; use Nette\Utils\DateTime; use Remp\MailerModule\Hermes\HermesMessage; use Remp\MailerModule\Hermes\RedisDriver; use Remp\MailerModule\Models\DataRetentionInterface; use Remp\MailerModule\Models\DataRetentionTrait; use Remp\MailerModule\Models\Job\MailCache; use Tomaj\Hermes\Emitter; class BatchesRepository extends Repository implements DataRetentionInterface { use DataRetentionTrait; const STATUS_CREATED = 'created'; const STATUS_READY_TO_PROCESS_AND_SEND = 'ready_to_process_and_send'; const STATUS_READY_TO_PROCESS = 'ready_to_process'; const STATUS_PROCESSING = 'processing'; const STATUS_PROCESSED = 'processed'; const STATUS_QUEUED = 'queued'; const STATUS_SENDING = 'sending'; const STATUS_DONE = 'done'; const STATUS_USER_STOP = 'user_stopped'; const STATUS_WORKER_STOP = 'worker_stopped'; const METHOD_RANDOM = 'random'; const EDITABLE_STATUSES = [ BatchesRepository::STATUS_CREATED, BatchesRepository::STATUS_READY_TO_PROCESS_AND_SEND, BatchesRepository::STATUS_READY_TO_PROCESS, ]; const SENDING_STATUSES = [ self::STATUS_QUEUED, // waiting for the next worker to pick up self::STATUS_SENDING, // actually sending ]; const STOP_STATUSES = [ self::STATUS_USER_STOP, self::STATUS_WORKER_STOP, ]; protected $tableName = 'mail_job_batch'; public function __construct( Explorer $database, protected Emitter $emitter, protected MailCache $mailCache, protected BatchTemplatesRepository $batchTemplatesRepository, protected JobQueueRepository $jobQueueRepository, Storage $cacheStorage = null ) { parent::__construct($database, $cacheStorage); } public function add(int $jobId, int $emailCount = null, string $startAt = null, string $method = 'random'): ActiveRow { $result = $this->insert([ 'mail_job_id' => $jobId, 'method' => $method, 'max_emails' => $emailCount, 'start_at' => $startAt ? new DateTime($startAt) : new DateTime(), 'created_at' => new DateTime(), 'updated_at' => new DateTime(), ]); if (is_numeric($result)) { return $this->getTable()->where('id', $result)->fetch(); } return $result; } public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool { $data['updated_at'] = new DateTime(); return parent::update($row, $data); } public function updateStatus(ActiveRow $batch, $status): bool { // Two-step update ensures, that we check if the status was actually change or not. $batchUpdated = parent::update($batch, [ 'status' => $status, ]); $this->update($batch, []); // empty update to trigger updated_at refresh if (in_array($status, self::SENDING_STATUSES, true)) { $priority = $this->getBatchPriority($batch); $this->mailCache->restartQueue($batch->id, $priority); } elseif (in_array($status, self::STOP_STATUSES, true)) { $this->mailCache->pauseQueue($batch->id); } elseif (in_array($status, self::EDITABLE_STATUSES, true)) { $this->mailCache->removeQueue($batch->id); } if ($batchUpdated) { $this->emitter->emit(new HermesMessage('batch-status-change', [ 'mail_job_batch_id' => $batch->id, 'time' => time(), 'status' => $status ]), RedisDriver::PRIORITY_LOW); } return $batchUpdated; } public function addTemplate(ActiveRow $batch, ActiveRow $template, int $weight = 100): ActiveRow { $row = $this->database->table('mail_job_batch_templates')->insert([ 'mail_job_id' => $batch->mail_job_id, 'mail_job_batch_id' => $batch->id, 'mail_template_id' => $template->id, 'weight' => $weight, 'created_at' => new DateTime(), ]); return new ActiveRow($row->toArray(), $row->getTable()); } public function getBatchReady(): ?ActiveRow { return $this->getTable()->select('*')->where([ 'status' => [self::STATUS_READY_TO_PROCESS_AND_SEND, self::STATUS_READY_TO_PROCESS], 'start_at <= ? OR start_at IS NULL' => new DateTime(), ])->limit(1)->fetch(); } public function getBatchToSend(): ?ActiveRow { return $this->getTable() ->select('mail_job_batch.*') ->where([ 'mail_job_batch.status' => self::SENDING_STATUSES, ]) ->order(':mail_job_batch_templates.mail_template.mail_type.priority DESC') ->limit(1) ->fetch(); } public function isSendingBatch(int $batchId): bool { return $this->getTable() ->select('mail_job_batch.*') ->where([ 'mail_job_batch.id' => $batchId, 'mail_job_batch.status' => self::SENDING_STATUSES, ]) ->count('*') > 0; } public function getBatchPriority(ActiveRow $batch): int { return $batch->related('mail_job_batch_templates')->fetch()->mail_template->mail_type->priority; } public function getInProgressBatches(int $limit): Selection { return $this->getTable() ->where([ 'mail_job_batch.status' => [ self::STATUS_READY_TO_PROCESS_AND_SEND, self::STATUS_PROCESSING, self::STATUS_PROCESSED, self::STATUS_SENDING ] ]) ->order('start_at ASC') ->limit($limit); } public function getLastDoneBatches(int $limit): Selection { return $this->getTable() ->where([ 'mail_job_batch.status' => [ self::STATUS_DONE ] ]) ->order('mail_job_batch.last_email_sent_at DESC') ->limit($limit); } public function notEditableBatches(int $jobId): Selection { return $this->getTable() ->select('*') ->where(['mail_job_id' => $jobId]) ->where(['status NOT IN' => self::EDITABLE_STATUSES]); } public function removeData(): ?int { if ($this->retentionForever) { return null; } $threshold = (new \DateTime())->modify('-' . $this->retentionThreshold); $idsToDelete = $this->getTable() ->select('mail_job_batch.id') ->joinWhere(':mail_logs', 'mail_job_batch.id = :mail_logs.mail_job_batch_id') ->where("mail_job_batch.{$this->getRetentionRemovingField()} < ?", $threshold) ->where('status = ?', self::STATUS_PROCESSED) ->where(':mail_logs.id IS NULL') ->fetchPairs('id', 'id'); // delete only batches that were never sent if (!count($idsToDelete)) { return 0; } foreach ($idsToDelete as $batchId) { $this->batchTemplatesRepository->deleteByBatchId($batchId); $this->mailCache->removeQueue($batchId); $this->jobQueueRepository->deleteJobsByBatch($batchId); } return $this->getTable()->where('mail_job_batch.id IN (?)', $idsToDelete)->delete(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/IConversionsRepository.php
Mailer/extensions/mailer-module/src/Repositories/IConversionsRepository.php
<?php declare(strict_types=1); namespace Remp\MailerModule\Repositories; interface IConversionsRepository { public function getBatchTemplatesConversionsSince(\DateTime $since): array; public function getNonBatchTemplatesConversionsSince(\DateTime $since): array; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false