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/Repositories/AuditLogRepository.php | Mailer/extensions/mailer-module/src/Repositories/AuditLogRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Database\Explorer;
use Nette\Security\IUserStorage;
class AuditLogRepository extends Repository
{
/** @var string */
protected $tableName = 'audit_logs';
/** @var IUserStorage */
protected $userStorage;
const OPERATION_CREATE = 'create';
const OPERATION_READ = 'read';
const OPERATION_UPDATE = 'update';
const OPERATION_DELETE = 'delete';
public function __construct(Explorer $database, IUserStorage $userStorage)
{
parent::__construct($database);
$this->database = $database;
$this->userStorage = $userStorage;
}
public function add(string $operation, string $tableName, string $signature, array $data = [])
{
$identity = $this->userStorage->getIdentity();
$userId = $identity ? $identity->getId() : null;
return $this->insert([
'operation' => $operation,
'user_id' => $userId,
'table_name' => $tableName,
'signature' => $signature,
'data' => json_encode($data),
'created_at' => date('Y-m-d H:i:s'),
]);
}
}
| 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/MailTypeStatsRepository.php | Mailer/extensions/mailer-module/src/Repositories/MailTypeStatsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Caching\Storage;
use Nette\Database\Explorer;
use Nette\Utils\DateTime;
class MailTypeStatsRepository extends Repository
{
protected $tableName = 'mail_type_stats';
public function __construct(
Explorer $database,
private ListsRepository $listsRepository,
?Storage $cacheStorage = null
) {
parent::__construct($database, $cacheStorage);
}
public function add(
int $mailTypeId,
int $subscribersCount
): ActiveRow {
return $this->getTable()->insert([
'mail_type_id' => $mailTypeId,
'created_at' => new DateTime(),
'subscribers_count' => $subscribersCount,
]);
}
public function getDashboardDataGroupedByTypes(DateTime $from, DateTime $to): array
{
return $this->getTable()
->select('mail_type_id, DATE(created_at) AS created_date, MAX(subscribers_count) AS count')
->where('created_at >= ?', $from)
->where('created_at <= ?', $to)
->where('mail_type_id', $this->listsRepository->all())
->group('mail_type_id, created_date')
->order('created_date ASC')
->fetchAll();
}
public function getDashboardDetailData($id, DateTime $from, DateTime $to): array
{
return $this->getTable()
->select('MAX(subscribers_count) AS count, DATE(created_at) AS created_date')
->where('mail_type_id = ?', $id)
->where('created_at >= ?', $from)
->where('created_at <= ?', $to)
->group('mail_type_id, created_date')
->order('mail_type_id ASC, created_date ASC')
->fetchAll();
}
}
| 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/TemplateTranslationsRepository.php | Mailer/extensions/mailer-module/src/Repositories/TemplateTranslationsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
class TemplateTranslationsRepository extends Repository
{
protected $tableName = 'mail_template_translations';
public function upsert(
ActiveRow $mailTemplate,
string $locale,
string $from,
string $subject,
string $mailBodyText,
string $mailBodyHtml
) {
$data = [
'mail_template_id' => $mailTemplate->id,
'locale' => $locale,
'from' => $from,
'subject' => $subject,
'mail_body_text' => $mailBodyText,
'mail_body_html' => $mailBodyHtml,
];
$row = $this->getTable()
->where('mail_template_id', $mailTemplate->id)
->where('locale', $locale)
->fetch();
if ($row) {
return $this->update($row, $data);
}
return $this->insert($data);
}
public function duplicate(ActiveRow $mailTemplate, ActiveRow $duplicatedMailTemplate): void
{
$templateTranslations = $this->getTable()->where('mail_template_id', $mailTemplate->id);
foreach ($templateTranslations as $templateTranslation) {
$this->insert([
'mail_template_id' => $duplicatedMailTemplate->id,
'locale' => $templateTranslation->locale,
'from' => $templateTranslation->from,
'subject' => $templateTranslation->subject,
'mail_body_text' => $templateTranslation->mail_body_text,
'mail_body_html' => $templateTranslation->mail_body_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/Repositories/HermesTasksRepository.php | Mailer/extensions/mailer-module/src/Repositories/HermesTasksRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
use Nette\Utils\Json;
use Tomaj\Hermes\MessageInterface;
class HermesTasksRepository extends Repository
{
const STATE_DONE = 'done';
const STATE_ERROR = 'error';
protected $tableName = 'hermes_tasks';
public function add(MessageInterface $message, string $state): ActiveRow
{
$createdAt = DateTime::createFromFormat('U.u', sprintf('%.4f', $message->getCreated()));
$executeAt = $message->getExecuteAt() ?
DateTime::createFromFormat('U.u', sprintf('%.4f', $message->getExecuteAt())) :
null;
return $this->insert([
'message_id' => $message->getId(),
'type' => $message->getType(),
'payload' => Json::encode($message->getPayload()),
'retry' => $message->getRetries(),
'state' => $state,
'created_at' => $createdAt,
'execute_at' => $executeAt,
'processed_at' => new DateTime(),
]);
}
public function getStateCounts(): array
{
return $this->getTable()->group('state, type')->select('state, type, count(*) AS count')->order('count DESC');
}
}
| 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/AutoLoginTokensRepository.php | Mailer/extensions/mailer-module/src/Repositories/AutoLoginTokensRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
use Remp\MailerModule\Models\DataRetentionInterface;
use Remp\MailerModule\Models\DataRetentionTrait;
class AutoLoginTokensRepository extends Repository implements DataRetentionInterface
{
use NewTableDataMigrationTrait;
use DataRetentionTrait;
protected $tableName = 'autologin_tokens';
public function getInsertData(string $token, string $email, DateTime $validFrom, DateTime $validTo, int $maxCount = 1): array
{
return [
'token' => $token,
'email' => $email,
'valid_from' => $validFrom,
'valid_to' => $validTo,
'max_count' => $maxCount,
'used_count' => 0,
'created_at' => new DateTime(),
];
}
/**
* @param array<string> $emails
*/
public function deleteAllForEmails(array $emails): int
{
if (count($emails) === 0) {
return 0;
}
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where([
'email' => $emails
])->delete();
}
return $this->getTable()->where([
'email' => $emails
])->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/TemplatesRepository.php | Mailer/extensions/mailer-module/src/Repositories/TemplatesRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
use Nette\Utils\Random;
class TemplatesRepository extends Repository
{
use SoftDeleteTrait;
protected $tableName = 'mail_templates';
protected $dataTableSearchable = ['name', 'code', 'description', 'subject'];
protected $dataTableSearchableFullText = ['mail_body_html'];
public function all(): Selection
{
return $this->getTable()
->where('mail_templates.deleted_at', null)
->order('mail_templates.created_at DESC, mail_templates.id DESC');
}
public function pairs(int $listId): array
{
return $this->all()->select('id, name')->where(['mail_type_id' => $listId])->fetchPairs('id', 'name');
}
public function filteredPairs(int $listId, array $filterTemplateIds, ?int $limit = null): array
{
$query = $this->all()
->select('id, name')
->where([
'mail_type_id' => $listId,
'id NOT IN' => $filterTemplateIds
]);
if (isset($limit)) {
$query->limit($limit);
}
return $query->fetchPairs('id', 'name');
}
public function findByList(int $listId, ?int $limit = null): Selection
{
$query = $this->all()
->where([
'mail_type_id' => $listId
]);
if (isset($limit)) {
$query->limit($limit);
}
return $query;
}
public function findByListCategory(int $listCategoryId, ?int $limit = null): Selection
{
$query = $this->all()
->where([
'mail_type.mail_type_category_id' => $listCategoryId
])
->group('mail_templates.id');
if (isset($limit)) {
$query->limit($limit);
}
return $query;
}
public function triples(): array
{
$result = [];
foreach ($this->all()->select('id, name, mail_type_id') as $template) {
$result[$template->mail_type_id][] = [
'value' => $template->id,
'label' => $template->name,
];
}
return $result;
}
public function add(
string $name,
string $code,
string $description,
string $from,
string $subject,
string $templateText,
string $templateHtml,
int $layoutId,
int $typeId,
?bool $clickTracking = null,
?string $extrasJson = null,
?string $paramsJson = null,
bool $attachmentsEnabled = true
): ActiveRow {
if ($this->exists($code)) {
throw new TemplatesCodeNotUniqueException("Template code [$code] is already used.");
}
$result = $this->insert([
'name' => $name,
'code' => $code,
'description' => $description,
'from' => $from,
'autologin' => true,
'subject' => $subject,
'click_tracking' => $clickTracking,
'mail_body_text' => $templateText,
'mail_body_html' => $templateHtml,
'mail_layout_id' => $layoutId,
'mail_type_id' => $typeId,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'extras' => $extrasJson,
'params' => $paramsJson,
'attachments_enabled' => $attachmentsEnabled,
'public_code' => $this->generatePublicCode(),
]);
if (is_numeric($result)) {
return $this->getTable()->where('id', $result)->fetch();
}
return $result;
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
// if code changed, check if it's unique
if (isset($data['code']) && $row['code'] != $data['code'] && $this->exists($data['code'])) {
throw new TemplatesCodeNotUniqueException("Template code [" . $data['code'] . "] is already used.");
}
$data['updated_at'] = new DateTime();
return parent::update($row, $data);
}
public function duplicate(ActiveRow $template)
{
return $this->insert([
'name' => $template->name . ' (copy)',
'code' => $this->getUniqueTemplateCode($template->code),
'description' => $template->description,
'from' => $template->from,
'subject' => $template->subject,
'mail_body_text' => $template->mail_body_text,
'mail_body_html' => $template->mail_body_html,
'mail_layout_id' => $template->mail_layout_id,
'mail_type_id' => $template->mail_type_id,
'copy_from' => $template->id,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'extras' => $template->extras,
'params' => $template->params,
'attachments_enabled' => $template->attachments_enabled,
'public_code' => $this->generatePublicCode(),
]);
}
public function exists(string $code): bool
{
return $this->getTable()->where('code', $code)->count('*') > 0;
}
public function getByCode($code)
{
return $this->getTable()->where('code', $code)->fetch();
}
public function getByPublicCode($publicCode)
{
return $this->getTable()->where('public_code', $publicCode)->fetch();
}
public function getUniqueTemplateCode($codeBase)
{
$code = $codeBase;
while ($this->exists($code)) {
$code = $codeBase . '_' . Random::generate(4);
}
return $code;
}
public function tableFilter(string $query, string $order, string $orderDirection, ?array $mailTypeIds = null, ?array $mailLayoutIds = null, ?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 . '%';
}
foreach ($this->dataTableSearchableFullText as $col) {
$where['MATCH('.$col . ') AGAINST(? IN BOOLEAN MODE)'] = '+' . $query . '*';
}
$selection->whereOr($where);
}
if ($mailTypeIds !== null) {
$selection->where([
'mail_type_id' => $mailTypeIds
]);
}
if ($mailLayoutIds !== null) {
$selection->where([
'mail_layout_id' => $mailLayoutIds
]);
}
if ($limit !== null) {
$selection->limit($limit, $offset);
}
return $selection;
}
public function search(string $term, int $limit)
{
$searchable = ['code', 'name', 'subject', 'description'];
foreach ($searchable as $column) {
$whereFast[$column . ' LIKE ?'] = $term . '%';
$whereWild[$column . ' LIKE ?'] = '%' . $term . '%';
}
$resultsFast = $this->all()
->whereOr($whereFast)
->limit($limit)
->fetchAll();
if (count($resultsFast) === $limit) {
return $resultsFast;
}
$resultsWild = $this->all()
->whereOr($whereWild)
->limit($limit - count($resultsFast))
->fetchAll();
return array_merge($resultsFast, $resultsWild);
}
public function generatePublicCode()
{
return Random::generate(8);
}
public function getByMailTypeIds(array $mailTypeIds)
{
return $this->all()->where('mail_type_id', $mailTypeIds);
}
public function getByMailTypeCategoryCode(string $mailTypeCategoryCode): Selection
{
return $this->all()->where('mail_type.mail_type_category.code = ?', $mailTypeCategoryCode);
}
}
| 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/JobQueueRepository.php | Mailer/extensions/mailer-module/src/Repositories/JobQueueRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\Json;
class JobQueueRepository extends Repository
{
protected $tableName = 'mail_job_queue';
public const STATUS_NEW = 'new';
public const STATUS_DONE = 'done';
public const STATUS_ERROR = 'error';
public function multiInsert(array $rows): void
{
$status = self::STATUS_NEW;
$insertLogsData = [];
foreach ($rows as $row) {
$insertLogsData[] = [
'mail_batch_id' => $row['batch'],
'mail_template_id' => $row['templateId'],
'status' => $status,
'sorting' => $row['sorting'],
'email' => $row['email'],
'context' => $row['context'],
'params' => $row['params'] ?? Json::encode([]),
];
}
$this->database->query("INSERT INTO {$this->tableName}", $insertLogsData);
}
public function clearBatch(ActiveRow $batch): int
{
return $this->getTable()->where(['mail_batch_id' => $batch->id])->delete();
}
public function stripEmails(ActiveRow $batch, int $leaveEmails, int $limit = 10000): void
{
if (!$leaveEmails) {
return;
}
$total = $this->getTable()->where(['mail_batch_id' => $batch->id])->count('*');
$remove = $total - $leaveEmails;
if ($remove <= 0) {
return;
}
$sql = <<<SQL
SELECT id FROM {$this->tableName}
WHERE mail_batch_id = {$batch->id}
ORDER BY RAND()
LIMIT ?
SQL;
while ($remove > $limit) {
$ids = $this->getDatabase()->query($sql, $limit)->fetchPairs(null, 'id');
$this->deleteAllByIds($ids);
$remove -= $limit;
}
$ids = $this->getDatabase()->query($sql, $remove)->fetchPairs(null, 'id');
$this->deleteAllByIds($ids);
}
public function removeAlreadySent(ActiveRow $batch, int $limit = 10000): void
{
$job = $batch->job;
$sql = <<<SQL
SELECT id FROM {$this->tableName}
WHERE mail_batch_id = {$batch->id}
AND email IN (SELECT email FROM mail_logs WHERE mail_job_id = {$job->id})
LIMIT $limit
SQL;
while ($ids = $this->getDatabase()->query($sql)->fetchPairs(null, 'id')) {
$this->deleteAllByIds($ids);
}
}
public function removeAlreadyQueued(ActiveRow $batch, int $limit = 10000): void
{
$job = $batch->job;
$sql = <<<SQL
SELECT mjq1.id FROM mail_job_queue mjq1
JOIN mail_job_queue mjq2 ON mjq1.email = mjq2.email
WHERE mjq1.mail_batch_id = $batch->id
AND mjq2.mail_batch_id IN (SELECT id FROM mail_job_batch WHERE mail_job_id = $job->id AND id <> $batch->id)
LIMIT $limit
SQL;
while ($ids = $this->getDatabase()->query($sql)->fetchPairs(null, 'id')) {
$this->deleteAllByIds($ids);
}
}
public function removeUnsubscribed(ActiveRow $batch, int $limit = 10000): void
{
$q = $this->getTable()
->select('mail_template_id')
->where(['mail_batch_id' => $batch->id])
->group('mail_template_id');
foreach ($q as $row) {
$sql = <<<SQL
SELECT mail_job_queue.id
FROM mail_job_queue
WHERE mail_job_queue.mail_batch_id = {$batch->id}
AND mail_job_queue.mail_template_id = {$row->mail_template_id}
AND mail_job_queue.email NOT IN (
SELECT user_email
FROM mail_user_subscriptions
WHERE mail_user_subscriptions.mail_type_id = {$row->mail_template->mail_type_id}
AND mail_user_subscriptions.subscribed = 1
)
SQL;
$ids = $this->getDatabase()->query($sql)->fetchPairs(null, 'id');
foreach (array_chunk($ids, $limit, true) as $idsChunk) {
$this->deleteAllByIds($idsChunk);
}
}
}
public function removeOtherVariants(ActiveRow $batch, int $variantId, int $limit = 10000): void
{
$sql = <<<SQL
SELECT mail_job_queue.id
FROM mail_job_queue
WHERE mail_job_queue.mail_batch_id = {$batch->id}
AND mail_job_queue.email NOT IN (
SELECT mail_user_subscriptions.user_email
FROM mail_user_subscriptions
INNER JOIN mail_user_subscription_variants
ON mail_user_subscription_variants.mail_user_subscription_id = mail_user_subscriptions.id
AND mail_user_subscription_variants.mail_type_variant_id = '{$variantId}'
AND mail_user_subscriptions.subscribed = 1
)
LIMIT $limit
SQL;
while ($ids = $this->getDatabase()->query($sql)->fetchPairs(null, 'id')) {
$this->deleteAllByIds($ids);
}
}
public function removeAlreadySentContext(ActiveRow $batch, string $context, int $limit = 10000): void
{
$sql = <<<SQL
SELECT q.id
FROM mail_job_queue q
JOIN mail_logs ml ON q.mail_batch_id = ? AND q.email = ml.email AND ml.context = ?
LIMIT $limit
SQL;
while ($ids = $this->getDatabase()->query($sql, $batch->id, $context)->fetchPairs(null, 'id')) {
$this->deleteAllByIds($ids);
}
$sql = <<<SQL
SELECT mjq1.id
FROM mail_job_queue mjq1
INNER JOIN mail_job_queue mjq2 ON mjq1.email = mjq2.email AND
mjq2.context = mjq1.context AND
mjq2.mail_batch_id != {$batch->id}
WHERE mjq1.mail_batch_id = {$batch->id}
LIMIT $limit
SQL;
while ($ids = $this->getDatabase()->query($sql)->fetchPairs(null, 'id')) {
$this->deleteAllByIds($ids);
}
}
public function getBatchEmails(ActiveRow $mailBatch, int $lastId = 0, $count = null): Selection
{
$selection = $this->getTable()->where(['id > ?' => $lastId, 'mail_batch_id' => $mailBatch->id])->order('id ASC');
if ($count !== null) {
$selection->limit($count);
}
return $selection;
}
public function getBatchUsersCount(ActiveRow $mailBatch): int
{
return $this->getTable()->where(['mail_batch_id' => $mailBatch->id])->count('*');
}
public function getJob(string $email, int $batchId): ?ActiveRow
{
return $this->getTable()->where(['email' => $email, 'mail_batch_id' => $batchId])->limit(1)->fetch();
}
public function deleteJobsByBatch(int $batchId, bool $newOnly = false): int
{
$table = $this->getTable()->where(['mail_batch_id' => $batchId]);
if ($newOnly) {
$table->where(['status' => 'new']);
}
return $table->delete();
}
/**
* @param array<string> $emails
*/
public function deleteAllByEmails(array $emails): int
{
if (count($emails) === 0) {
return 0;
}
return $this->getTable()->where([
'email' => $emails
])->delete();
}
/**
* @param array<int> $ids
*/
public function deleteAllByIds(array $ids): int
{
if (count($ids) === 0) {
return 0;
}
return $this->getTable()->where([
'id' => $ids
])->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/MailTemplateLinkClicksRepository.php | Mailer/extensions/mailer-module/src/Repositories/MailTemplateLinkClicksRepository.php | <?php
namespace Remp\MailerModule\Repositories;
use DateTime;
class MailTemplateLinkClicksRepository extends Repository
{
protected $tableName = 'mail_template_link_clicks';
public function add(\Nette\Database\Table\ActiveRow $mailTemplateLink, DateTime $clicked_at)
{
$result = $this->insert([
'mail_template_link_id' => $mailTemplateLink->id,
'clicked_at' => $clicked_at,
]);
if (is_numeric($result)) {
return $this->getTable()->where('id', $result)->fetch();
}
return $result;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/ActiveRowFactory.php | Mailer/extensions/mailer-module/src/Repositories/ActiveRowFactory.php | <?php
namespace Remp\MailerModule\Repositories;
use Nette\Database\Conventions\StaticConventions;
use Nette\Database\Explorer;
class ActiveRowFactory
{
public const TABLE_NAME_DATAROW = 'datarow';
private Explorer $explorer;
public function __construct(Explorer $explorer)
{
$this->explorer = $explorer;
}
public function create(array $data): ActiveRow
{
$staticConventions = new StaticConventions();
$selection = new Selection(
$this->explorer,
$staticConventions,
'datarow'
);
return new ActiveRow($data, $selection);
}
}
| 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/NewTableDataMigrationTrait.php | Mailer/extensions/mailer-module/src/Repositories/NewTableDataMigrationTrait.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Remp\MailerModule\Models\RedisClientFactory;
use Remp\MailerModule\Models\RedisClientTrait;
trait NewTableDataMigrationTrait
{
use RedisClientTrait;
protected ?string $newTableName = null;
protected ?string $newTableDataMigrationIsRunningFlag = null;
public function setNewTableName(string $table): void
{
$this->newTableName = $table;
}
public function setNewTableDataMigrationIsRunningFlag(string $flag): void
{
$this->newTableDataMigrationIsRunningFlag = $flag;
}
public function setRedisClientFactory(RedisClientFactory $redisClientFactory): void
{
$this->redisClientFactory = $redisClientFactory;
}
public function getNewTable(): Selection
{
return new Selection($this->database, $this->database->getConventions(), $this->newTableName, $this->cacheStorage);
}
public function newTableDataMigrationIsRunning(): bool
{
return (bool) $this->redis()->exists($this->newTableDataMigrationIsRunningFlag);
}
public function insert(array $data)
{
$result = parent::insert($data);
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->insert($result->toArray());
}
return $result;
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$result = parent::update($row, $data);
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where('id', $row->id)->update($data);
}
return $result;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/BatchTemplatesRepository.php | Mailer/extensions/mailer-module/src/Repositories/BatchTemplatesRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
class BatchTemplatesRepository extends Repository
{
protected $tableName = 'mail_job_batch_templates';
private $eventMap = [
'delivered_at' => 'delivered',
'clicked_at' => 'clicked',
'opened_at' => 'opened',
'spam_complained_at' => 'spam_complained',
'hard_bounced_at' => 'hard_bounced',
'dropped_at' => 'dropped',
];
public function getDashboardGraphDataForTypes(DateTime $from, DateTime $to): Selection
{
return $this->getTable()
->select('
SUM(COALESCE(mail_job_batch_templates.sent, 0)) AS sent_mails,
mail_template.mail_type_id,
mail_template.mail_type.title AS mail_type_title,
mail_job_batch.first_email_sent_at')
->where('mail_job_batch.first_email_sent_at IS NOT NULL')
->where('mail_template.mail_type_id IS NOT NULL')
->where('DATE(mail_job_batch.first_email_sent_at) >= DATE(?)', $from->format('Y-m-d'))
->where('DATE(mail_job_batch.first_email_sent_at) <= DATE(?)', $to->format('Y-m-d'))
->group('
DATE(mail_job_batch.first_email_sent_at),
mail_template.mail_type_id,
mail_template.mail_type.title
')
->order('mail_template.mail_type_id')
->order('mail_job_batch.first_email_sent_at DESC');
}
public function add(int $jobId, int $batchId, int $templateId, int $weight = 100): ActiveRow
{
$result = $this->insert([
'mail_job_id' => $jobId,
'mail_job_batch_id' => $batchId,
'mail_template_id' => $templateId,
'weight' => $weight,
'created_at' => new DateTime(),
]);
if (is_numeric($result)) {
return $this->getTable()->where('id', $result)->fetch();
}
return $result;
}
public function findByBatchId(int $batchId): Selection
{
return $this->getTable()->where(['mail_job_batch_id' => $batchId]);
}
public function deleteByBatchId(int $batchId): int
{
return $this->findByBatchId($batchId)->delete();
}
public function mapEvent($event): ?string
{
return $this->eventMap[$event] ?? null;
}
public function updateAllConverted()
{
return $this->database->query('
update mail_job_batch_templates
left join (
select count(*) as count, mail_job_batch_id, mail_template_id
from mail_log_conversions
left join mail_logs on mail_log_id = mail_logs.id
group by mail_job_batch_id, mail_template_id
) t1 on mail_job_batch_templates.mail_template_id = t1.mail_template_id and
mail_job_batch_templates.mail_job_batch_id = t1.mail_job_batch_id
set converted = coalesce(t1.count, 0)
');
}
public function incrementColumn($column, $mailTemplateId, $mailJobBatchId)
{
return $this->getTable()->where([
'mail_template_id' => $mailTemplateId,
'mail_job_batch_id' => $mailJobBatchId,
])->update([
"{$column}+=" => 1,
]);
}
}
| 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/ListsRepository.php | Mailer/extensions/mailer-module/src/Repositories/ListsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
class ListsRepository extends Repository
{
use SoftDeleteTrait;
protected $tableName = 'mail_types';
protected $dataTableSearchable = ['code', 'title', 'description'];
public function all(): Selection
{
return $this->getTable()
->where('deleted_at', null)
->order('sorting ASC');
}
public function add(
int $categoryId,
int $priority,
string $code,
string $name,
int $sorting,
bool $isAutoSubscribe,
bool $isLocked,
string $description,
?string $previewUrl = null,
?string $pageUrl = null,
?string $imageUrl = null,
bool $publicListing = true,
?string $mailFrom = null,
int $subscribeEmailTemplateId = null,
int $unSubscribeEmailTemplateId = null,
bool $isMultiVariant = false,
int $defaultVariantId = null,
): ActiveRow {
$result = $this->insert([
'mail_type_category_id' => $categoryId,
'priority' => $priority,
'code' => $code,
'title' => $name,
'mail_from' => $mailFrom,
'description' => $description,
'sorting' => $sorting,
'auto_subscribe' => $isAutoSubscribe,
'locked' => $isLocked,
'public_listing' => $publicListing,
'image_url' => $imageUrl,
'preview_url' => $previewUrl,
'page_url' => $pageUrl,
'subscribe_mail_template_id' => $subscribeEmailTemplateId,
'unsubscribe_mail_template_id' => $unSubscribeEmailTemplateId,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'is_multi_variant' => $isMultiVariant,
'default_variant_id' => $defaultVariantId,
]);
if (is_numeric($result)) {
return $this->getTable()->where('id', $result)->fetch();
}
return $result;
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
unset($data['id']);
$data['updated_at'] = new DateTime();
return parent::update($row, $data);
}
public function updateSorting(int $newCategoryId, int $newSorting, ?int $oldCategoryId = null, ?int $oldSorting = null): void
{
if ($newSorting === $oldSorting) {
return;
}
if ($oldSorting !== null) {
$this->getTable()
->where(
'sorting > ? AND mail_type_category_id = ?',
$oldSorting,
$oldCategoryId
)->update(['sorting-=' => 1]);
}
$this->getTable()->where(
'sorting >= ? AND mail_type_category_id = ?',
$newSorting,
$newCategoryId
)->update(['sorting+=' => 1]);
}
public function findByCode(string $code): Selection
{
return $this->getTable()->where(['code' => $code]);
}
public function findByCategory(int $categoryId): Selection
{
return $this->getTable()->where(['mail_type_category_id' => $categoryId]);
}
public function tableFilter(): Selection
{
return $this->getTable()
->where('deleted_at', null)
->order('mail_type_category.sorting, mail_types.sorting');
}
public function search(string $term, int $limit): array
{
foreach ($this->dataTableSearchable as $column) {
$where[$column . ' LIKE ?'] = '%' . $term . '%';
}
$results = $this->all()
->select(implode(',', array_merge(['id'], $this->dataTableSearchable)))
->whereOr($where ?? [])
->limit($limit)
->fetchAssoc('id');
return $results;
}
public function getUsedMailersAliases(): array
{
return $this->getTable()->select('DISTINCT mailer_alias')
->where('deleted_at', null)
->where('mailer_alias IS NOT NULL')
->fetchPairs(null, 'mailer_alias');
}
public function canBeDeleted(ActiveRow $list): bool
{
return !(bool) $list->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/SourceTemplatesRepository.php | Mailer/extensions/mailer-module/src/Repositories/SourceTemplatesRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
class SourceTemplatesRepository extends Repository
{
use SoftDeleteTrait;
protected $tableName = 'mail_source_template';
protected $dataTableSearchable = ['title'];
public function all(): Selection
{
return $this->getTable()
->where('deleted_at', null)
->order('sorting ASC');
}
public function add(string $title, string $code, string $generator, string $html, string $text, int $sorting = 100): ActiveRow
{
return $this->insert([
'title' => $title,
'code' => $code,
'generator' => $generator,
'content_html' => $html,
'content_text' => $text,
'sorting' => $sorting,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
]);
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$data['updated_at'] = new \DateTime();
return parent::update($row, $data);
}
public function exists(string $title): int
{
return $this->getTable()->where('title', $title)->count('*');
}
public function findLast()
{
return $this->getTable()->order('sorting DESC')->limit(1);
}
public function tableFilter(string $query, ?string $order, ?string $orderDirection, ?int $limit = null, ?int $offset = null): Selection
{
$selection = $this->getTable()->where('deleted_at', null);
if ($order && $orderDirection) {
$selection->order($order . ' ' . strtoupper($orderDirection));
} else {
$selection->order('sorting ASC');
}
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 getSortingPairs(): array
{
return $this->all()
->fetchPairs('sorting', 'title');
}
public function updateSorting(int $newSorting, ?int $oldSorting = null): void
{
if ($newSorting === $oldSorting) {
return;
}
if ($oldSorting !== null) {
$this->getTable()
->where(
'sorting > ?',
$oldSorting
)->update(['sorting-=' => 1]);
}
$this->getTable()->where(
'sorting >= ?',
$newSorting
)->update(['sorting+=' => 1]);
}
public function getByCode(string $code)
{
return $this->getTable()->where('code = ?', $code)->fetch();
}
}
| 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/Repository.php | Mailer/extensions/mailer-module/src/Repositories/Repository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Caching\Storage;
use Nette\Database\Explorer;
use Nette\Utils\DateTime;
class Repository
{
use DateFieldsProcessorTrait;
protected $auditLogRepository;
protected $tableName = 'undefined';
public function __construct(
protected Explorer $database,
protected ?Storage $cacheStorage = null
) {
}
public function getTable(): Selection
{
return new Selection($this->database, $this->database->getConventions(), $this->tableName, $this->cacheStorage);
}
public function find($id): ?ActiveRow
{
return $this->getTable()->where(['id' => $id])->fetch();
}
public function findBy(string $column, string $value): ?ActiveRow
{
return $this->getTable()->where([$column => $value])->fetch();
}
public function totalCount(): int
{
$primary = $this->getTable()->getPrimary();
if (is_string($primary)) {
return $this->getTable()->count("DISTINCT({$primary})");
}
return $this->getTable()->count('*');
}
public function getDatabase(): Explorer
{
return $this->database;
}
/**
* Update updates provided record with given $data array and mutates the provided instance. Operation is logged
* to audit log.
*
* @param ActiveRow|\Nette\Database\Table\ActiveRow $row
* @param array $data values to update
* @return bool
*
* @throws \Exception
*/
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$data = $this->processDateFields($data);
$oldValues = $row->toArray();
$res = $this->getTable()->wherePrimary($row->getPrimary())->update($data);
if (!$res) {
return false;
}
if ($this->auditLogRepository) {
// filter internal columns
$data = $this->filterValues($data);
// filter unchanged columns
if (!empty($oldValues)) {
$oldValues = $this->filterValues($oldValues);
$oldValues = array_intersect_key($oldValues, $data);
$data = array_diff_assoc($data, $oldValues); // get changed values
$oldValues = array_intersect_key($oldValues, $data); // get rid of unchanged $oldValues
}
$data = [
'version' => '1',
'from' => $oldValues,
'to' => $data,
];
$this->auditLogRepository->add(AuditLogRepository::OPERATION_UPDATE, $this->tableName, $row->getSignature(), $data);
}
$row = $this->getTable()->wherePrimary($row->getPrimary())->fetch();
return true;
}
/**
* Delete deletes provided record from repository and mutates the provided instance. Operation is logged to audit log.
*
* @param ActiveRow $row
* @return bool
*/
public function delete(ActiveRow &$row): bool
{
$oldValues = [];
if ($row instanceof ActiveRow) {
$oldValues = $row->toArray();
}
$res = $this->getTable()->wherePrimary($row->getPrimary())->delete();
if (!$res) {
return false;
}
if ($this->auditLogRepository) {
$data = [
'version' => '1',
'from' => $this->filterValues($oldValues),
'to' => [],
];
$this->auditLogRepository->add(AuditLogRepository::OPERATION_DELETE, $this->tableName, $row->getSignature(), $data);
}
return true;
}
/**
* Insert inserts data to the repository. If single ActiveRow is returned, it attempts to log audit information.
*
* @param array $data
* @return bool|int|ActiveRow
*/
public function insert(array $data)
{
$data = $this->processDateFields($data);
$row = $this->getTable()->insert($data);
if (!$row instanceof ActiveRow) {
return $row;
}
if ($this->auditLogRepository) {
$data = [
'version' => '1',
'from' => [],
'to' => $this->filterValues($data),
];
$this->auditLogRepository->add(AuditLogRepository::OPERATION_CREATE, $this->tableName, $row->getSignature(), $data);
}
return $row;
}
private function filterValues(array $values): array
{
foreach ($values as $i => $field) {
if (is_bool($field)) {
$values[$i] = (int) $field;
} elseif ($field instanceof DateTime) {
$values[$i] = $field->format('Y-m-d H:i:s');
} elseif (!is_scalar($field)) {
unset($values[$i]);
}
}
return $values;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/MailTemplateStatsRepository.php | Mailer/extensions/mailer-module/src/Repositories/MailTemplateStatsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Caching\Storage;
use Nette\Database\Explorer;
use Nette\Utils\DateTime;
class MailTemplateStatsRepository extends Repository
{
protected $tableName = 'mail_template_stats';
public function __construct(
Explorer $database,
private ListsRepository $listsRepository,
?Storage $cacheStorage = null
) {
parent::__construct($database, $cacheStorage);
}
public function byDateAndMailTemplateId(DateTime $date, int $id): ?ActiveRow
{
return $this->getTable()
->where('mail_template_id', $id)
->where('date', $date->format('Y-m-d'))
->fetch();
}
public function byMailTemplateId(int $id): Selection
{
return $this->getTable()
->where('mail_template_id', $id);
}
public function byMailTypeId(int $id): Selection
{
return $this->getTable()
->where('mail_template.mail_type_id', $id)
->group('mail_template.mail_type_id');
}
public function all(): Selection
{
return $this->getTable();
}
public function getMailTypeGraphData(int $mailTypeId, DateTime $from, DateTime $to, string $groupBy = 'day'): Selection
{
$dateFormat = match ($groupBy) {
'week' => '%x-%v',
'month' => '%Y-%m',
'day' => '%Y-%m-%d',
default => throw new \Exception('Unrecognized $groupBy value:' . $groupBy),
};
return $this->getTable()
->select('
SUM(COALESCE(mail_template_stats.sent, 0)) AS sent_mails,
SUM(COALESCE(mail_template_stats.opened, 0)) AS opened_mails,
SUM(COALESCE(mail_template_stats.clicked, 0)) AS clicked_mails,
DATE_FORMAT(date, ?) AS label_date
', $dateFormat)
->where('mail_template.mail_type_id = ?', $mailTypeId)
->where('date >= DATE(?)', $from)
->where('date <= DATE(?)', $to)
->group('
label_date
')
->order('label_date DESC');
}
public function getAllMailTemplatesGraphData(DateTime $from, DateTime $to): Selection
{
return $this->getTable()
->select('
SUM(COALESCE(mail_template_stats.sent, 0)) AS sent_mails,
date
')
->where('date > DATE(?)', $from)
->where('date <= DATE(?)', $to)
->group('date');
}
public function getTemplatesGraphDataGroupedByMailType(DateTime $from, DateTime $to): Selection
{
return $this->getTable()
->select('
SUM(COALESCE(mail_template_stats.sent, 0)) AS sent_mails,
mail_template.mail_type_id,
date
')
->where('mail_template.mail_type_id', $this->listsRepository->all())
->where('mail_template_stats.date >= DATE(?)', $from)
->where('mail_template_stats.date <= DATE(?)', $to)
->group('
date,
mail_template.mail_type_id
')
->order('mail_template.mail_type_id')
->order('mail_template_stats.date DESC');
}
}
| 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/LayoutTranslationsRepository.php | Mailer/extensions/mailer-module/src/Repositories/LayoutTranslationsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
class LayoutTranslationsRepository extends Repository
{
protected $tableName = 'mail_layout_translations';
public function upsert(ActiveRow $layout, string $locale, string $text, string $html)
{
$data = [
'mail_layout_id' => $layout->id,
'locale' => $locale,
'layout_text' => $text,
'layout_html' => $html,
];
$row = $this->getTable()
->where('mail_layout_id', $layout->id)
->where('locale', $locale)
->fetch();
if ($row) {
return $this->update($row, $data);
}
return $this->insert($data);
}
public function deleteByLayoutLocale(ActiveRow $layout, string $locale): void
{
$this->getTable()
->where('mail_layout_id', $layout->id)
->where('locale', $locale)
->delete();
}
public function getTranslationsForLocale(string $locale): Selection
{
return $this->getTable()->where('locale', $locale);
}
public function getAllTranslationsForLayout(ActiveRow $layout): Selection
{
return $this->getTable()->where('mail_layout_id', $layout->id);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/SoftDeleteTrait.php | Mailer/extensions/mailer-module/src/Repositories/SoftDeleteTrait.php | <?php
namespace Remp\MailerModule\Repositories;
use Nette\Utils\Random;
trait SoftDeleteTrait
{
public function softDelete(ActiveRow $row)
{
$this->update($row, [
'code' => $row->code . '_DELETED_' . Random::generate(8),
'updated_at' => new \DateTime(),
'deleted_at' => new \DateTime(),
]);
}
}
| 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/MailTemplateLinksRepository.php | Mailer/extensions/mailer-module/src/Repositories/MailTemplateLinksRepository.php | <?php
namespace Remp\MailerModule\Repositories;
class MailTemplateLinksRepository extends Repository
{
protected $tableName = 'mail_template_links';
public function add(string $mailTemplateId, string $url, string $hash)
{
$sql = <<<SQL
INSERT IGNORE INTO `mail_template_links`(mail_template_id, url, hash, created_at)
VALUES (?, ?, ?, ?)
SQL;
$this->database->query($sql, $mailTemplateId, $url, $hash, new \DateTime());
}
public function upsert(int $mailTemplateId, string $url, string $hash)
{
$exists = $this->findLinkByHash($hash);
if (!isset($exists)) {
$this->add($mailTemplateId, $url, $hash);
}
}
public function findLinkByHash(string $hash): ?\Nette\Database\Table\ActiveRow
{
return $this->getTable()->where([
'hash' => $hash
])->fetch();
}
public function getLinksForTemplate(\Nette\Database\Table\ActiveRow $template): array
{
$result = [];
$links = $template->related('mail_template_links')->order('mail_template_links.id');
foreach ($links as $link) {
$result[$link->hash] = [
'url' => $link->url,
'clickCount' => $link->click_count
];
}
return $result;
}
public function incrementClickCount(\Nette\Database\Table\ActiveRow $mailTemplateLink)
{
$this->update($mailTemplateLink, [
'click_count+=' => 1
]);
}
}
| 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/LogsRepository.php | Mailer/extensions/mailer-module/src/Repositories/LogsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Database\Table\ActiveRow as NetteActiveRow;
use Nette\Utils\DateTime;
class LogsRepository extends Repository
{
use NewTableDataMigrationTrait;
protected $tableName = 'mail_logs';
protected array $dataTableSearchable = ['email'];
private array $eventMap = [
'delivered' => 'delivered_at',
'clicked' => 'clicked_at',
'opened' => 'opened_at',
'complained' => 'spam_complained_at',
'bounced' => 'hard_bounced_at',
'failed' => 'dropped_at',
'dropped' => 'dropped_at',
];
private array $bouncesMap = [
'suppress-bounce' => 'hard_bounced_at',
'suppress-complaint' => 'hard_bounced_at',
'suppress-unsubscribe' => 'hard_bounced_at',
];
public function allForEmail(string $email): Selection
{
return $this->allForEmails([$email]);
}
/**
* @param array<string> $emails
*/
public function allForEmails(array $emails): Selection
{
return $this->getTable()->where('email', $emails);
}
public function add(string $email, string $subject, int $templateId, ?int $jobId = null, ?int $batchId = null, ?string $mailSenderId = null, ?int $attachmentSize = null, ?string $context = null, ?int $userId = null): ActiveRow
{
return $this->insert(
$this->getInsertData($email, $subject, $templateId, $jobId, $batchId, $mailSenderId, $attachmentSize, $context, $userId)
);
}
public function getInsertData(string $email, string $subject, int $templateId, ?int $jobId = null, ?int $batchId = null, ?string $mailSenderId = null, ?int $attachmentSize = null, ?string $context = null, ?int $userId = null): array
{
return [
'email' => $email,
'user_id' => $userId,
'subject' => $subject,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'mail_template_id' => $templateId,
'mail_job_id' => $jobId,
'mail_job_batch_id' => $batchId,
'mail_sender_id' => $mailSenderId,
'attachment_size' => $attachmentSize,
'context' => $context,
];
}
/**
* @param array<string> $emails
*/
public function deleteAllForEmails(array $emails): int
{
if (count($emails) === 0) {
return 0;
}
return $this->getTable()->where([
'email' => $emails
])->delete();
}
public function getEmailLogs(string $email): Selection
{
return $this->getTable()->where('email', $email)->order('created_at DESC');
}
public function getJobLogs(int $jobId): Selection
{
return $this->getTable()->where('mail_job_id', $jobId)->order('created_at DESC');
}
public function findBySenderId(string $senderId): ?ActiveRow
{
return $this->getTable()->where('mail_sender_id', $senderId)->limit(1)->fetch();
}
public function findAllBySenderId(string $senderId): Selection
{
return $this->getTable()->where('mail_sender_id', $senderId);
}
public function getBatchTemplateStats(ActiveRow $batchTemplate): ?ActiveRow
{
$columns = [
'mail_job_batch_id',
'COUNT(delivered_at) AS delivered',
'COUNT(dropped_at) AS dropped',
'COUNT(spam_complained_at) AS spam_complained',
'COUNT(hard_bounced_at) AS hard_bounced',
'COUNT(clicked_at) AS clicked',
'COUNT(opened_at) AS opened'
];
return $this->getTable()
->select(implode(',', $columns))
->where([
'mail_job_batch_id' => $batchTemplate->mail_job_batch_id,
'mail_template_id' => $batchTemplate->mail_template_id,
])
->limit(1)
->fetch();
}
public function getNonBatchTemplateStats(array $templateIds): ?ActiveRow
{
$columns = [
'COUNT(created_at) AS sent',
'COUNT(delivered_at) AS delivered',
'COUNT(dropped_at) AS dropped',
'COUNT(spam_complained_at) AS spam_complained',
'COUNT(hard_bounced_at) AS hard_bounced',
'COUNT(clicked_at) AS clicked',
'COUNT(opened_at) AS opened',
'COUNT(:mail_log_conversions.converted_at) AS converted',
];
return $this->getTable()
->select(implode(',', $columns))
->where([
'mail_template_id' => $templateIds,
'mail_job_batch_id IS NULL',
])
->limit(1)
->fetch();
}
public function tableFilter(
string $query,
string $order,
string $orderDirection,
?int $limit = null,
?int $offset = null,
?int $templateId = null,
?DateTime $createdAtFrom = null,
?DateTime $createdAtTo = null
): Selection {
$selection = $this->getTable()
->order($order . ' ' . strtoupper($orderDirection));
if ($templateId !== null) {
$selection->where('mail_template_id = ?', $templateId);
}
if ($createdAtFrom !== null) {
$selection->where('created_at >= ?', $createdAtFrom);
}
if ($createdAtTo !== null) {
$selection->where('created_at <= ?', $createdAtTo);
}
if (!empty($query)) {
$selection->where('email = ?', $query);
}
if ($limit !== null) {
$selection->limit($limit, $offset);
}
return $selection;
}
public function alreadySentForJob(string $email, int $jobId): bool
{
return $this->getTable()->where([
'mail_logs.mail_job_id' => $jobId,
'mail_logs.email' => $email
])->count('*') > 0;
}
public function alreadySentForEmail(string $mailTemplateCode, string $email): bool
{
return $this->getTable()->where([
'mail_logs.email' => $email,
'mail_template.code' => $mailTemplateCode
])->count('*') > 0;
}
/**
* @deprecated Method is not performant due to unnecessary joins. Use filterAlreadySentV2 instead.
*/
public function filterAlreadySent(array $emails, string $mailTemplateCode, int $jobId, ?string $context = null): array
{
$query = $this->getTable()->where([
'mail_logs.email' => $emails,
'mail_template.code' => $mailTemplateCode
])->whereOr([
'mail_logs.email' => $emails,
'mail_logs.mail_job_id' => $jobId,
]);
if ($context) {
$query->whereOr([
'mail_logs.email' => $emails,
'mail_logs.context' => $context,
]);
}
$alreadySentEmails = $query->select('email')->fetchPairs(null, 'email');
return array_diff($emails, $alreadySentEmails);
}
public function filterAlreadySentV2(
array $emails,
NetteActiveRow $mailTemplate,
NetteActiveRow $job,
?string $context = null
) {
$query = $this->getTable()->where('CONVERT(email USING UTF8)', $emails);
$orCondition = [
'mail_template_id' => $mailTemplate->id,
'mail_job_id' => $job->id,
];
if ($context) {
$orCondition['context'] = $context;
}
$alreadySentEmails = $query
->select('email')
->whereOr($orCondition)
->fetchPairs(null, 'email');
return array_diff($emails, $alreadySentEmails);
}
public function alreadySentContext(string $email, string $context): bool
{
return $this->getTable()->where([
'mail_logs.email' => $email,
'mail_logs.context' => $context,
])->count('*') > 0;
}
public function mappedEvents(): array
{
return array_keys($this->eventMap);
}
public function mapEvent(string $externalEvent, ?string $reason): ?string
{
if (!isset($this->eventMap[$externalEvent])) {
return null;
}
if ($externalEvent === 'failed' && in_array($reason, $this->bouncesMap, true)) {
return $this->bouncesMap[$reason];
}
return $this->eventMap[$externalEvent];
}
public function insert(array $data)
{
$result = parent::insert($data);
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->insert($result->toArray());
}
return $result;
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$data['updated_at'] = new \DateTime();
$result = parent::update($row, $data);
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where('id', $row->id)->update($data);
}
return $result;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/UserSubscriptionsRepository.php | Mailer/extensions/mailer-module/src/Repositories/UserSubscriptionsRepository.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 Tomaj\Hermes\Emitter;
class UserSubscriptionsRepository extends Repository
{
use NewTableDataMigrationTrait;
protected $tableName = 'mail_user_subscriptions';
protected $dataTableSearchable = ['user_email'];
public function __construct(
Explorer $database,
private UserSubscriptionVariantsRepository $userSubscriptionVariantsRepository,
private ListVariantsRepository $listVariantsRepository,
private Emitter $emitter,
Storage $cacheStorage = null
) {
parent::__construct($database, $cacheStorage);
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$data['updated_at'] = new DateTime();
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where('id', $row->id)->update($data);
}
return parent::update($row, $data);
}
/**
* @param array<string> $emails
*/
public function deleteAllForEmails(array $emails): int
{
if (count($emails) === 0) {
return 0;
}
$this->userSubscriptionVariantsRepository->removeSubscribedVariantsForEmails($emails);
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where([
'user_email' => $emails
])->delete();
}
return $this->getTable()->where([
'user_email' => $emails
])->delete();
}
public function findByUserId(int $userId): array
{
return $this->getTable()->where(['user_id' => $userId])->fetchAll();
}
public function findByEmail(string $email): array
{
return $this->getTable()->where(['user_email' => $email])->fetchAll();
}
public function allSubscribers(): array
{
$result = [];
$lastUserId = 0;
$query = $this->getTable()
->select('DISTINCT user_id')
->order('user_id')
->limit(10000);
while (true) {
$userIds = (clone $query)
->where('user_id > ?', $lastUserId)
->fetchPairs('user_id', 'user_id');
if (!count($userIds)) {
break;
}
$result += $userIds;
$lastUserId = array_key_last($userIds);
}
return $result;
}
public function findSubscribedUserIdsByMailTypeCode(string $mailTypeCode): array
{
$result = [];
$lastUserId = 0;
$query = $this->getTable()
->select('DISTINCT user_id')
->where([
'mail_type.code' => $mailTypeCode,
'subscribed' => true,
])
->order('user_id')
->limit(10000);
while (true) {
$userIds = (clone $query)
->where('user_id > ?', $lastUserId)
->fetchPairs('user_id', 'user_id');
if (!count($userIds)) {
break;
}
$result += $userIds;
$lastUserId = array_key_last($userIds);
}
return $result;
}
public function isEmailSubscribed(string $email, int $typeId): bool
{
return $this->getTable()->where(['user_email' => $email, 'mail_type_id' => $typeId, 'subscribed' => true])->count('*') > 0;
}
public function isEmailUnsubscribed(string $email, int $typeId): bool
{
return $this->getTable()->where(['user_email' => $email, 'mail_type_id' => $typeId, 'subscribed' => false])->count('*') > 0;
}
public function isUserUnsubscribed($userId, $mailTypeId): bool
{
return $this->getTable()->where(['user_id' => $userId, 'mail_type_id' => $mailTypeId, 'subscribed' => false])->count('*') > 0;
}
public function isUserSubscribed($userId, $mailTypeId): bool
{
return $this->getTable()->where(['user_id' => $userId, 'mail_type_id' => $mailTypeId, 'subscribed' => true])->count('*') > 0;
}
public function filterSubscribedEmails(array $emails, int $typeId): array
{
return $this->getTable()->where([
'user_email' => $emails,
'mail_type_id' => $typeId,
'subscribed' => true,
])->select('user_email')->fetchPairs('user_email', 'user_email');
}
public function filterSubscribedEmailsAndIds(array $emails, int $typeId): array
{
return $this->getTable()->where([
'user_email' => $emails,
'mail_type_id' => $typeId,
'subscribed' => true,
])->select('user_id, user_email')->fetchPairs('user_email', 'user_id');
}
public function subscribeUser(
ActiveRow $mailType,
int $userId,
string $email,
int $variantId = null,
bool $sendWelcomeEmail = true,
array $rtmParams = [],
bool $forceNoVariantSubscription = false,
): ActiveRow {
if ($variantId === null) {
$variantId = $mailType->default_variant_id;
}
// TODO: handle user ID even when searching for actual subscription
/** @var ActiveRow $actual */
$actual = $this->getTable()
->where(['user_email' => $email, 'mail_type_id' => $mailType->id])
->limit(1)
->fetch();
if (!$actual) {
$actual = $this->insert([
'user_id' => $userId,
'user_email' => $email,
'mail_type_id' => $mailType->id,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'subscribed' => true,
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]);
$this->emitUserSubscribedEvent($userId, $email, $mailType->id, $sendWelcomeEmail, $rtmParams);
} elseif (!$actual->subscribed) {
$this->update($actual, [
'subscribed' => true,
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]);
$actual = $this->find($actual->id);
$this->emitUserSubscribedEvent($userId, $email, $mailType->id, $sendWelcomeEmail, $rtmParams);
}
if (!$forceNoVariantSubscription) {
if ($variantId) {
$variantSubscribed = $this->userSubscriptionVariantsRepository->variantSubscribed($actual, $variantId);
if (!$variantSubscribed) {
if (!$mailType->is_multi_variant) {
$this->userSubscriptionVariantsRepository->removeSubscribedVariants($actual);
}
$this->userSubscriptionVariantsRepository->addVariantSubscription($actual, $variantId, $rtmParams);
}
} elseif (!$variantId && $mailType->is_multi_variant) {
// subscribe all mail variants for multi_variant type without default variant
foreach ($this->listVariantsRepository->getVariantsForType($mailType)->fetchAll() as $variant) {
$variantSubscribed = $this->userSubscriptionVariantsRepository->variantSubscribed($actual, $variant->id);
if (!$variantSubscribed) {
$this->userSubscriptionVariantsRepository->addVariantSubscription($actual, $variant->id, $rtmParams);
}
}
}
}
return $actual;
}
public function unsubscribeUser(
ActiveRow $mailType,
int $userId,
string $email,
array $rtmParams = [],
bool $sendGoodbyeEmail = true
): void {
// TODO: check for userId also when searching for actual subscription
/** @var ActiveRow $actual */
$actual = $this->getTable()->where([
'user_email' => $email,
'mail_type_id' => $mailType->id,
])->limit(1)->fetch();
if (!$actual) {
$this->insert([
'user_id' => $userId,
'user_email' => $email,
'mail_type_id' => $mailType->id,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'subscribed' => false,
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]);
} else {
if ($actual->subscribed) {
$this->update($actual, [
'subscribed' => false,
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]);
$this->userSubscriptionVariantsRepository->removeSubscribedVariants($actual);
$this->emitUserUnsubscribedEvent($userId, $email, $mailType->id, $sendGoodbyeEmail, $rtmParams);
}
}
}
public function unsubscribeUserFromAll(
int $userId,
string $email,
array $filterOutMailTypeCodes = []
) {
$subscriptions = $this->getTable()
->where('user_email', $email)
->where('user_id', $userId)
->where('mail_type.code NOT IN', $filterOutMailTypeCodes)
->where('subscribed', 1);
foreach ($subscriptions as $subscription) {
$this->update($subscription, [
'subscribed' => false,
]);
$this->userSubscriptionVariantsRepository->removeSubscribedVariants($subscription);
}
}
public function unsubscribeEmail(ActiveRow $mailType, string $email, array $rtmParams = []): void
{
/** @var ActiveRow $actual */
$actual = $this->getTable()->where([
'user_email' => $email,
'mail_type_id' => $mailType->id,
'subscribed' => true,
])->limit(1)->fetch();
if (!$actual) {
return;
}
$this->update($actual, [
'subscribed' => false,
'updated_at' => new DateTime(),
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]);
$this->userSubscriptionVariantsRepository->removeSubscribedVariants($actual);
}
public function getAllSubscribersDataForMailTypes(array $mailTypeIds): Selection
{
return $this->getTable()
->select('COUNT(*) AS count, mail_type_id, subscribed')
->where('mail_type_id', $mailTypeIds)
->group('mail_type_id, subscribed');
}
public function getUserSubscription(ActiveRow $mailType, int $userId, string $email): ?ActiveRow
{
/** @var ActiveRow $row */
$row = $this->getTable()->where([
'user_id' => $userId,
'mail_type_id' => $mailType->id,
'user_email' => $email,
])->limit(1)->fetch();
return $row;
}
public function getEmailSubscription(ActiveRow $mailType, string $email): ?ActiveRow
{
/** @var ActiveRow $row */
$row = $this->getTable()->where([
'mail_type_id' => $mailType->id,
'user_email' => $email,
])->limit(1)->fetch();
return $row;
}
public function unsubscribeUserVariant(
ActiveRow $userSubscription,
ActiveRow $variant,
array $rtmParams = [],
bool $sendGoodbyeEmail = true,
bool $keepMailTypeSubscription = false
): void {
$this->userSubscriptionVariantsRepository->removeSubscribedVariant($userSubscription, $variant->id);
if (!$keepMailTypeSubscription &&
$this->userSubscriptionVariantsRepository->subscribedVariants($userSubscription)->count('*') == 0) {
$this->unSubscribeUser($userSubscription->mail_type, $userSubscription->user_id, $userSubscription->user_email, $rtmParams, $sendGoodbyeEmail);
}
}
public function getMailTypeGraphData(int $mailTypeId, \DateTime $from, \DateTime $to, string $groupBy = 'day'): Selection
{
$dateFormat = match ($groupBy) {
'week' => '%x-%v',
'month' => '%Y-%m',
default => '%Y-%m-%d'
};
return $this->getTable()
->select('
count(id) AS unsubscribed_users,
DATE_FORMAT(updated_at, ?) AS label_date
', $dateFormat)
->where('subscribed = 0')
->where('mail_type_id = ?', $mailTypeId)
->where('updated_at >= DATE(?)', $from)
->where('updated_at <= DATE(?)', $to)
->where('updated_at != created_at')
->group('label_date')
->order('label_date DESC');
}
public function tableFilter(string $query, string $order, string $orderDirection, int $listId, ?int $limit = null, ?int $offset = null): Selection
{
$selection = $this->getTable()
->where([
'mail_type_id' => $listId,
'subscribed' => true
])
->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;
}
private function emitUserSubscribedEvent($userId, $email, $mailTypeId, $sendWelcomeEmail, $rtmParams = [])
{
$this->emitter->emit(new HermesMessage('user-subscribed', [
'user_id' => $userId,
'user_email' => $email,
'mail_type_id' => $mailTypeId,
'send_welcome_email' => $sendWelcomeEmail,
'time' => new DateTime(),
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]));
}
private function emitUserUnsubscribedEvent($userId, $email, $mailTypeId, $sendGoodbyeEmail, $rtmParams = [])
{
$this->emitter->emit(new HermesMessage('user-unsubscribed', [
'user_id' => $userId,
'user_email' => $email,
'mail_type_id' => $mailTypeId,
'send_goodbye_email' => $sendGoodbyeEmail,
'time' => new DateTime(),
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? 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/Repositories/SnippetTranslationsRepository.php | Mailer/extensions/mailer-module/src/Repositories/SnippetTranslationsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
class SnippetTranslationsRepository extends Repository
{
protected $tableName = 'mail_snippet_translations';
public function upsert(ActiveRow $snippet, string $locale, string $text, string $html)
{
$data = [
'mail_snippet_id' => $snippet->id,
'locale' => $locale,
'text' => $text,
'html' => $html,
];
$row = $this->getTable()
->where('mail_snippet_id', $snippet->id)
->where('locale', $locale)
->fetch();
if ($row) {
return $this->update($row, $data);
}
return $this->insert($data);
}
public function deleteBySnippetLocale(ActiveRow $snippet, string $locale): void
{
$this->getTable()
->where('mail_snippet_id', $snippet->id)
->where('locale', $locale)
->delete();
}
public function getTranslationsForSnippet(ActiveRow $snippet): Selection
{
return $this->getTable()->where('mail_snippet_id', $snippet->id);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/DateFieldsProcessorTrait.php | Mailer/extensions/mailer-module/src/Repositories/DateFieldsProcessorTrait.php | <?php
namespace Remp\MailerModule\Repositories;
trait DateFieldsProcessorTrait
{
public function processDateFields($fields)
{
foreach ($fields as $i => $field) {
if ($field instanceof \DateTime) {
$fields[$i] = $field->setTimezone(new \DateTimeZone(date_default_timezone_get()));
}
}
return $fields;
}
}
| 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/UserSubscriptionVariantsRepository.php | Mailer/extensions/mailer-module/src/Repositories/UserSubscriptionVariantsRepository.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 Tomaj\Hermes\Emitter;
class UserSubscriptionVariantsRepository extends Repository
{
use NewTableDataMigrationTrait;
protected $tableName = 'mail_user_subscription_variants';
public function __construct(
Explorer $database,
private Emitter $emitter,
?Storage $cacheStorage = null
) {
parent::__construct($database, $cacheStorage);
}
public function subscribedVariants(ActiveRow $userSubscription): Selection
{
return $this->getTable()->where(['mail_user_subscription_id' => $userSubscription->id]);
}
public function multiSubscribedVariants($userSubscriptions): Selection
{
return $this->getTable()
->where(['mail_user_subscription_id' => $userSubscriptions])
->select('mail_user_subscription_variants.*, mail_type_variant.code, mail_type_variant.title');
}
public function variantSubscribed(ActiveRow $userSubscription, int $variantId): bool
{
return $this->getTable()->where([
'mail_user_subscription_id' => $userSubscription->id,
'mail_type_variant_id' => $variantId,
])->count('*') > 0;
}
public function removeSubscribedVariants(ActiveRow $userSubscription): int
{
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()
->where(['mail_user_subscription_id' => $userSubscription->id])
->delete();
}
return $this->getTable()
->where(['mail_user_subscription_id' => $userSubscription->id])
->delete();
}
/**
* @param array<string> $emails
*/
public function removeSubscribedVariantsForEmails(array $emails): int
{
/* use nicer delete when bug in nette/database is fixed https://github.com/nette/database/issues/255
return $this->getTable()
->where('mail_user_subscription.user_email', $email)
->delete();
*/
$variantsToRemove = $this->getTable()
->where(['mail_user_subscription.user_email' => $emails])
->fetchAll();
$result = 0;
foreach ($variantsToRemove as $variant) {
$deleted = $this->delete($variant);
if ($deleted) {
$result++;
}
}
return $result;
}
public function removeSubscribedVariant(ActiveRow $userSubscription, int $variantId): int
{
$where = [
'mail_user_subscription_id' => $userSubscription->id,
'mail_type_variant_id' => $variantId
];
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where($where)->delete();
}
$this->emitter->emit(new HermesMessage('user-unsubscribed-variant', [
'user_id' => $userSubscription->user_id,
'user_email' => $userSubscription->user_email,
'mail_type_id' => $userSubscription->mail_type->id,
'mail_type_variant_id' => $variantId,
'time' => new DateTime(),
]));
return $this->getTable()->where($where)->delete();
}
public function addVariantSubscription(ActiveRow $userSubscription, int $variantId, array $rtmParams = []): ActiveRow
{
$this->emitter->emit(new HermesMessage('user-subscribed-variant', [
'user_id' => $userSubscription->user_id,
'user_email' => $userSubscription->user_email,
'mail_type_id' => $userSubscription->mail_type->id,
'mail_type_variant_id' => $variantId,
'time' => new DateTime(),
'rtm_source' => $rtmParams['rtm_source'] ?? null,
'rtm_medium' => $rtmParams['rtm_medium'] ?? null,
'rtm_campaign' => $rtmParams['rtm_campaign'] ?? null,
'rtm_content' => $rtmParams['rtm_content'] ?? null,
]));
return $this->insert([
'mail_user_subscription_id' => $userSubscription->id,
'mail_type_variant_id' => $variantId,
'created_at' => new DateTime(),
]);
}
public function variantsStats(ActiveRow $mailType, DateTime $from, DateTime $to): Selection
{
return $this->getTable()->where([
'mail_user_subscription.subscribed' => 1,
'mail_user_subscription.mail_type_id' => $mailType->id,
'mail_user_subscription_variants.created_at > ?' => $from,
'mail_user_subscription_variants.created_at < ?' => $to,
])->group('mail_type_variant_id')
->select('COUNT(*) AS count, mail_type_variant_id, MAX(mail_type_variant.title) AS title, MAX(mail_type_variant.code) AS code')
->order('count DESC');
}
public function delete(ActiveRow &$row): bool
{
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->wherePrimary($row->getPrimary())->delete();
}
return parent::delete($row);
}
}
| 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/ConfigsRepository.php | Mailer/extensions/mailer-module/src/Repositories/ConfigsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
class ConfigsRepository extends Repository
{
protected $tableName = 'configs';
public function all()
{
return $this->getTable()->order('sorting ASC');
}
public function add(string $name, string $displayName, $value, ?string $description, string $type): ActiveRow
{
$result = $this->insert([
'name' => $name,
'display_name' => $displayName,
'value' => $value,
'description' => $description,
'type' => $type,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
]);
if (is_numeric($result)) {
return $this->getTable()->where('id', $result)->fetch();
}
return $result;
}
public function loadByName(string $name): ?ActiveRow
{
return $this->getTable()->where('name', $name)->fetch();
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$data['updated_at'] = new DateTime();
return parent::update($row, $data);
}
}
| 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/LogConversionsRepository.php | Mailer/extensions/mailer-module/src/Repositories/LogConversionsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Database\Table\ActiveRow as NetteActiveRow;
use Nette\Utils\DateTime;
class LogConversionsRepository extends Repository
{
use NewTableDataMigrationTrait;
protected $tableName = 'mail_log_conversions';
public function upsert(NetteActiveRow $mailLog, DateTime $convertedAt): void
{
$conversion = $this->getTable()->where([
'mail_log_id' => $mailLog->id,
])->fetch();
if ($conversion) {
$this->update($conversion, [
'converted_at' => $convertedAt,
]);
} else {
$this->insert([
'mail_log_id' => $mailLog->id,
'converted_at' => $convertedAt,
]);
}
}
public function deleteForMailLogs(array $mailLogIds): int
{
if (empty($mailLogIds)) {
return 0;
}
$result = $this->getTable()->where([
'mail_log_id IN (?)' => $mailLogIds
])->delete();
if ($this->newTableDataMigrationIsRunning()) {
$this->getNewTable()->where([
'mail_log_id IN (?)' => $mailLogIds
])->delete();
}
return $result;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/InvalidSlugException.php | Mailer/extensions/mailer-module/src/Repositories/InvalidSlugException.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
class InvalidSlugException 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/JobsRepository.php | Mailer/extensions/mailer-module/src/Repositories/JobsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Exception;
use Nette\Caching\Storage;
use Nette\Database\Explorer;
use Nette\Utils\DateTime;
use Remp\MailerModule\Models\Job\JobSegmentsManager;
class JobsRepository extends Repository
{
const STATUS_NEW = 'new';
protected $tableName = 'mail_jobs';
protected $dataTableSearchable = [
':mail_job_batch_templates.mail_template.name',
];
public function __construct(
Explorer $database,
private BatchesRepository $batchesRepository,
Storage $cacheStorage = null
) {
parent::__construct($database, $cacheStorage);
}
public function all(): Selection
{
return $this->getTable()->order('mail_jobs.created_at DESC');
}
public function add(JobSegmentsManager $jobSegmentsManager, ?string $context = null, ?ActiveRow $mailTypeVariant = null): ?ActiveRow
{
$data = [
'segments' => $jobSegmentsManager->toJson(),
'context' => $context,
'status' => static::STATUS_NEW,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'mail_type_variant_id' => $mailTypeVariant->id ?? null
];
return $this->insert($data);
}
public function tableFilter(string $query, string $order, string $orderDirection, array $listIds = [], ?int $limit = null, ?int $offset = null): Selection
{
$selection = $this->getTable()
->order($order . ' ' . strtoupper($orderDirection));
if (!empty($query)) {
$where = [];
foreach ($this->dataTableSearchable as $col) {
$where[$col . ' LIKE ?'] = '%' . $query . '%';
}
$selection->whereOr($where);
}
if ($listIds) {
$selection->where([
':mail_job_batch_templates.mail_template.mail_type_id' => $listIds,
]);
}
if ($limit !== null) {
$selection->limit($limit, $offset);
}
return $selection;
}
public function update(\Nette\Database\Table\ActiveRow $row, array $data): bool
{
$this->getDatabase()->beginTransaction();
if (!$this->isEditable($row->id)) {
$this->getDatabase()->rollBack();
throw new Exception("Job can't be updated. One or more Mail Job Batches were already started.");
}
$data['updated_at'] = new \DateTime();
$result = parent::update($row, $data);
$this->getDatabase()->commit();
return $result;
}
public function isEditable(int $jobId): bool
{
if ($this->batchesRepository->notEditableBatches($jobId)->count() > 0) {
return false;
}
return true;
}
public function search(string $term, int $limit): Selection
{
foreach ($this->dataTableSearchable as $column) {
$where[$column . ' LIKE ?'] = '%' . $term . '%';
}
return $this->all()
->whereOr($where ?? [])
->order('created_at DESC')
->limit($limit);
}
}
| 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/ActiveRow.php | Mailer/extensions/mailer-module/src/Repositories/ActiveRow.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Database\Table\ActiveRow as NetteActiveRow;
class ActiveRow extends NetteActiveRow
{
public function delete(): int
{
throw new \Exception('Direct delete is not allowed, use repository\'s update');
}
public function update(iterable $data): bool
{
throw new \Exception('Direct update is not allowed, use repository\'s update');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Repositories/Selection.php | Mailer/extensions/mailer-module/src/Repositories/Selection.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette;
use Nette\Caching\Storage;
use Nette\Database\Conventions;
use Nette\Database\Explorer;
use Nette\Database\Table\Selection as NetteSelection;
class Selection extends NetteSelection
{
use DateFieldsProcessorTrait;
/**
* @inheritdoc
*/
public function __construct(
Explorer $explorer,
Conventions $conventions,
string $tableName,
Storage $cacheStorage = null
) {
parent::__construct($explorer, $conventions, $tableName, $cacheStorage);
}
public function createSelectionInstance(string $table = null): NetteSelection
{
return new self(
$this->context,
$this->conventions,
$table ?: $this->name,
$this->cache ? $this->cache->getStorage() : null
);
}
public function createRow(array $row): Nette\Database\Table\ActiveRow
{
return new ActiveRow($row, $this);
}
public function condition($condition, array $params, $tableChain = null): void
{
$params = $this->processDateFields($params);
parent::condition($condition, $params, $tableChain);
}
public function insert(iterable $data): ActiveRow
{
return parent::insert($data);
}
// not sure if we need this
public function insertMulti(iterable $data): int
{
return parent::insert($data);
}
}
| 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/SnippetsRepository.php | Mailer/extensions/mailer-module/src/Repositories/SnippetsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
use Remp\MailerModule\Models\Traits\SlugTrait;
class SnippetsRepository extends Repository
{
use SlugTrait;
protected $tableName = 'mail_snippets';
protected $dataTableSearchable = ['name', 'text', 'html'];
public function all()
{
return $this->getTable()->order('name ASC');
}
public function add(string $name, string $code, string $layoutText, string $layoutHtml, ?int $mailTypeId)
{
$this->assertSlug($code);
$result = $this->insert([
'name' => $name,
'code' => $code,
'created_at' => new DateTime(),
'updated_at' => new DateTime(),
'html' => $layoutHtml,
'text' => $layoutText,
'mail_type_id' => $mailTypeId
]);
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);
}
/**
* @param string $query
* @param string $order
* @param string $orderDirection
* @param int|null $limit
* @param int|null $offset
* @return Selection
*/
public function tableFilter(string $query, string $order, string $orderDirection, ?int $limit = null, ?int $offset = null)
{
$selection = $this->getTable()
->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 getSnippetsForMailType($mailTypeId): Selection
{
$mailTypeSnippets = $this->getTable()->where('mail_type_id', $mailTypeId)->fetchPairs(null, 'code');
$where = [];
if (empty($mailTypeSnippets)) {
$where['mail_type_id'] = null;
} else {
$where['(code IN (?) AND mail_type_id = ?) OR (code NOT IN (?) AND mail_type_id IS NULL)'] = [$mailTypeSnippets, $mailTypeId, $mailTypeSnippets];
}
return $this->getTable()->where($where);
}
public function findByCodeAndMailType($code, $mailTypeId): ?ActiveRow
{
return $this->getTable()->where([
'code' => $code,
'mail_type_id' => $mailTypeId
])->fetch();
}
}
| 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/ListVariantsRepository.php | Mailer/extensions/mailer-module/src/Repositories/ListVariantsRepository.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Repositories;
use Nette\Utils\DateTime;
class ListVariantsRepository extends Repository
{
protected $tableName = 'mail_type_variants';
protected $dataTableSearchable = ['code', 'title'];
public function add(ActiveRow $mailType, string $title, string $code, int $sorting = null)
{
if (!isset($sorting)) {
$sorting = $this->getNextSorting($mailType);
}
return $this->insert([
'mail_type_id' => $mailType->id,
'title' => $title,
'code' => $code,
'sorting' => $sorting,
'created_at' => new DateTime()
]);
}
private function getNextSorting(ActiveRow $mailType): int
{
$row = $this->getTable()->where([
'mail_type_id' => $mailType->id,
'deleted_at' => null
])->order('sorting DESC')->limit(1)->fetch();
if ($row) {
return $row->sorting + 100;
}
return 100;
}
public function findByIdAndMailTypeId(int $id, int $mailTypeId): ?ActiveRow
{
return $this->getTable()->where(['id' => $id, 'mail_type_id' => $mailTypeId, 'deleted_at' => null])->fetch();
}
public function findByCode(string $code): ?ActiveRow
{
return $this->getTable()->where(['code' => $code, 'deleted_at' => null])->fetch();
}
public function findByCodeAndMailTypeId(string $code, int $mailTypeId): ?ActiveRow
{
return $this->getTable()->where(['code' => $code, 'mail_type_id' => $mailTypeId, 'deleted_at' => null])->fetch();
}
public function getVariantsForType(ActiveRow $mailType): Selection
{
return $this->getTable()->where('mail_type_id', $mailType->id)->where('deleted_at', null);
}
public function getVariantsForTypeId(int $mailTypeId): Selection
{
return $this->getTable()->where('mail_type_id', $mailTypeId)->where('deleted_at', null);
}
public function tableFilter(string $query, string $order, string $orderDirection, ?array $listIds = null, ?int $limit = null, ?int $offset = null): Selection
{
$selection = $this->getTable()
->select('mail_type_variants.*, COUNT(:mail_user_subscription_variants.id) AS count')
->where('deleted_at', null)
->group('mail_type_variants.id');
if ($order === 'count') {
$selection->order('COUNT(*) DESC');
} else {
$selection->order($order . ' ' . strtoupper($orderDirection));
}
if (!empty($query)) {
$where = [];
foreach ($this->dataTableSearchable as $col) {
$where[$col . ' LIKE ?'] = '%' . $query . '%';
}
$selection->whereOr($where);
}
if ($listIds !== null) {
$selection->where([
'mail_type_id' => $listIds,
]);
}
if ($limit !== null) {
$selection->limit($limit, $offset);
}
return $selection;
}
public function softDelete(ActiveRow $mailTypeVariant): bool
{
return parent::update($mailTypeVariant, ['deleted_at' => new DateTime()]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Events/BeforeUsersDeleteEvent.php | Mailer/extensions/mailer-module/src/Events/BeforeUsersDeleteEvent.php | <?php
namespace Remp\MailerModule\Events;
/**
* Event receives list of user emails to delete.
* Event is emitted inside SQL transaction to ensure all the data is deleted at once.
*/
class BeforeUsersDeleteEvent
{
private array $emails;
public function __construct(array $emails)
{
$this->emails = $emails;
}
public function getEmails(): array
{
return $this->emails;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Events/MailSentEvent.php | Mailer/extensions/mailer-module/src/Events/MailSentEvent.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Events;
class MailSentEvent
{
private $userId;
private $email;
private $templateCode;
private $batchId;
private $time;
public function __construct(int $userId, string $email, string $templateCode, int $batchId, int $time)
{
$this->userId = $userId;
$this->email = $email;
$this->templateCode = $templateCode;
$this->batchId = $batchId;
$this->time = $time;
}
public function getUserId(): int
{
return $this->userId;
}
public function getEmail(): string
{
return $this->email;
}
public function getTemplateCode(): string
{
return $this->templateCode;
}
public function getBatchId(): int
{
return $this->batchId;
}
public function getTime(): int
{
return $this->time;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Events/MailSentEventHandler.php | Mailer/extensions/mailer-module/src/Events/MailSentEventHandler.php | <?php
declare(strict_types=1);
namespace Remp\MailerModule\Events;
use Nette\Utils\DateTime;
use Psr\Log\LoggerAwareTrait;
use Remp\MailerModule\Models\Tracker\EventOptions;
use Remp\MailerModule\Models\Tracker\ITracker;
use Remp\MailerModule\Models\Tracker\User;
class MailSentEventHandler
{
use LoggerAwareTrait;
private $tracker;
public function __construct(ITracker $tracker)
{
$this->tracker = $tracker;
}
public function __invoke(MailSentEvent $event)
{
$options = new EventOptions();
$options->setUser(new User([
'id' => $event->getUserId(),
]));
$options->setFields([
'email' => $event->getEmail(),
'template_code' => $event->getTemplateCode(),
'mail_job_batch_id' => $event->getBatchId(),
]);
$this->tracker->trackEvent(
DateTime::from($event->getTime()),
'mail',
'sent',
$options
);
return 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/Events/UsersDeletedEvent.php | Mailer/extensions/mailer-module/src/Events/UsersDeletedEvent.php | <?php
namespace Remp\MailerModule\Events;
/**
* Event receives list of already deleted user emails.
*/
class UsersDeletedEvent
{
private array $emails;
public function __construct(array $emails)
{
$this->emails = $emails;
}
public function getEmails(): array
{
return $this->emails;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Events/BeforeUserEmailChangeEvent.php | Mailer/extensions/mailer-module/src/Events/BeforeUserEmailChangeEvent.php | <?php
namespace Remp\MailerModule\Events;
class BeforeUserEmailChangeEvent
{
public function __construct(
public readonly string $originalEmail,
public readonly string $newEmail,
) {
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/mailer-module/src/Events/UserEmailChangedEvent.php | Mailer/extensions/mailer-module/src/Events/UserEmailChangedEvent.php | <?php
namespace Remp\MailerModule\Events;
class UserEmailChangedEvent
{
public function __construct(
public readonly string $originalEmail,
public readonly string $newEmail,
) {
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/newrelic-module/src/DI/Config.php | Mailer/extensions/newrelic-module/src/DI/Config.php | <?php
declare(strict_types=1);
namespace Remp\NewrelicModule\DI;
class Config
{
private bool $logRequestListenerErrors = true;
public function getLogRequestListenerErrors(): bool
{
return $this->logRequestListenerErrors;
}
public function setLogRequestListenerErrors(bool $logErrors): void
{
$this->logRequestListenerErrors = $logErrors;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/newrelic-module/src/DI/NewrelicModuleExtension.php | Mailer/extensions/newrelic-module/src/DI/NewrelicModuleExtension.php | <?php
declare(strict_types=1);
namespace Remp\NewrelicModule\DI;
use Nette;
use Nette\Application\Application;
use Nette\DI\CompilerExtension;
use Nette\DI\Definitions\ServiceDefinition;
use Remp\NewrelicModule\Listener\NewrelicRequestListener;
use Tracy\Debugger;
final class NewrelicModuleExtension extends CompilerExtension
{
public function loadConfiguration()
{
$builder = $this->getContainerBuilder();
$config = $builder->addDefinition('newrelicConfig')
->setType(Config::class);
if (isset($this->config->logRequestListenerErrors)) {
$config->addSetup('setLogRequestListenerErrors', [$this->config->logRequestListenerErrors]);
}
}
public function getConfigSchema(): Nette\Schema\Schema
{
return Nette\Schema\Expect::structure([
'logRequestListenerErrors' => Nette\Schema\Expect::bool(true)->dynamic()
]);
}
public function beforeCompile(): void
{
parent::beforeCompile();
$builder = $this->getContainerBuilder();
$builder->addDefinition($this->prefix('newrelicRequestListener'))
->setType(NewrelicRequestListener::class)
->setAutowired(false);
$applicationService = $builder->getByType(Application::class) ?: 'application';
if ($builder->hasDefinition($applicationService)) {
$applicationServiceDefinition = $builder->getDefinition($applicationService);
if (!$applicationServiceDefinition instanceof ServiceDefinition) {
Debugger::log(
"Unable to initialize NewrelicModuleExtension, 'application' is not a service definition",
Debugger::ERROR
);
return;
}
$applicationServiceDefinition->addSetup(
'$service->onRequest[] = ?',
[
[$this->prefix('@newrelicRequestListener'), 'onRequest'],
]
);
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/extensions/newrelic-module/src/Listener/NewrelicRequestListener.php | Mailer/extensions/newrelic-module/src/Listener/NewrelicRequestListener.php | <?php
declare(strict_types=1);
namespace Remp\NewrelicModule\Listener;
use Nette\Application\Application;
use Nette\Application\Request;
use Remp\Mailer\Bootstrap;
use Remp\NewrelicModule\DI\Config;
use Tracy\Debugger;
use Tracy\ILogger;
final class NewrelicRequestListener
{
private Config $config;
public function __construct(Config $config)
{
$this->config = $config;
}
public function onRequest(Application $application, Request $request)
{
if (!extension_loaded('newrelic')) {
if ($this->config->getLogRequestListenerErrors()) {
Debugger::log("You're using Newrelic module without 'newrelic' PHP extension. Either install the extension or disable the module in app's configuration.", ILogger::WARNING);
}
return;
}
if (Bootstrap::isCli()) {
newrelic_name_transaction('$ ' . basename($_SERVER['argv'][0]) . ' ' . implode(' ', array_slice($_SERVER['argv'], 1)));
newrelic_background_job(true);
return;
}
$params = $request->getParameters();
$name = $request->getPresenterName() . (isset($params['action']) ? ':' . $params['action'] : '');
// All API requests are routed through same presenter, append endpoint url.
if ($name === 'Api:Api:default') {
$apiEndpoint = 'api/v' . implode('/', [
$params['version'] ?? '',
$params['package'] ?? '',
$params['apiAction'] ?? '',
]);
$name .= " ({$apiEndpoint})";
}
newrelic_name_transaction($name);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/tests/init.php | Mailer/tests/init.php | <?php
// attempt to fix access rights issues in writable folders caused by different web/cli users writing to logs
use Dotenv\Dotenv;
use Nette\Bootstrap\Configurator;
umask(0);
(Dotenv::createImmutable(__DIR__))->load();
$configurator = new Configurator;
$environment = $_ENV['ENV'];
$configurator->setDebugMode(true);
$configurator->enableTracy(__DIR__ . '/../log');
$configurator->setTimeZone($_ENV['TIMEZONE']);
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()
->addDirectory(__DIR__)
->register();
// Root config, so MailerModule can register extensions, etc...
$configurator->addConfig(__DIR__ . '/../vendor/remp/mailer-module/src/config/config.root.neon');
$configurator->addConfig(__DIR__ . '/../app/config/config.neon');
$configurator->addConfig(__DIR__ . '/../app/config/config.test.neon');
$container = $configurator->createContainer();
$GLOBALS['configurator'] = $configurator;
$GLOBALS['container'] = $configurator->createContainer();
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/tests/Unit/NullTracker.php | Mailer/tests/Unit/NullTracker.php | <?php
declare(strict_types=1);
namespace Tests\Unit;
use Nette\Utils\DateTime;
use Remp\MailerModule\Models\Tracker\EventOptions;
use Remp\MailerModule\Models\Tracker\ITracker;
class NullTracker implements ITracker
{
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/tests/Unit/Generator/DennikNBestPerformingArticlesGeneratorTest.php | Mailer/tests/Unit/Generator/DennikNBestPerformingArticlesGeneratorTest.php | <?php
declare(strict_types=1);
namespace Tests\Unit\Generator;
use Nette\Database\Table\Selection;
use PHPUnit\Framework\TestCase;
use Remp\Mailer\Models\PageMeta\Content\DenniknContent;
use Remp\Mailer\Models\PageMeta\Content\DenniknShopContent;
use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory;
use Remp\MailerModule\Models\Generators\GenericBestPerformingArticlesGenerator;
use Remp\MailerModule\Models\PageMeta\Transport\TransportInterface;
use Remp\MailerModule\Repositories\ActiveRow;
use Remp\MailerModule\Repositories\SourceTemplatesRepository;
class DennikNBestPerformingArticlesGeneratorTest extends TestCase
{
private $sourceTemplateRepository;
private $engineFactory;
protected function setUp(): void
{
$htmlContent = <<<TEMPLATE
<table>
{% for url,item in items %}
<tr>
<td>{{ item.title }}</td>
<td>{{ item.description }}</td>
<td><img src="{{ item.image }}"></td>
<td>{{ url }}</td>
</tr>
{% endfor %}
</table>
TEMPLATE;
$textContent = <<<TEMPLATE
{% for url,item in items %}
{{ item.title }}
{{ item.description }}
{{ url}}
{% endfor %}
TEMPLATE;
$mailSourceTemplate = [
"content_html" => $htmlContent,
"content_text" => $textContent
];
$this->sourceTemplateRepository = $this->createConfiguredMock(SourceTemplatesRepository::class, [
'find' => new ActiveRow($mailSourceTemplate, $this->createMock(Selection::class))
]);
$this->engineFactory = $GLOBALS['container']->getByType(EngineFactory::class);
}
public function testProcess()
{
$transport = new class() implements TransportInterface
{
public function getContent(string $url): ?string
{
return <<<HTML
<!DOCTYPE html><html lang="sk-SK"><head><meta charset="utf-8"><link rel="manifest" href="/manifest.json"><meta name="viewport" content="width=device-width, viewport-fit=cover"><meta name="mobile-web-app-capable" content="yes"><meta property="article:publisher" content="https://www.facebook.com/projektn.sk"><meta property="article:published_time" content="2018-06-01T06:00:42+00:00"><meta property="article:modified_time" content="2018-06-01T20:25:58+00:00"><meta property="og:updated_time" content="2018-06-01T20:25:58+00:00"><meta property="article:section" content="Slovensko"><meta name="description" content="Doteraz som počúvala, že pracujem v provládnom médiu, a zo dňa na deň z nás urobili opozičných neoliberálov, hovorí odchádzajúca reportérka RTVS."><meta property="og:description" content="Doteraz som počúvala, že pracujem v provládnom médiu, a zo dňa na deň z nás urobili opozičných neoliberálov, hovorí odchádzajúca reportérka RTVS."><meta name="twitter:description" content="Doteraz som počúvala, že pracujem v provládnom médiu, a zo dňa na deň z nás urobili opozičných neoliberálov, hovorí odchádzajúca reportérka RTVS."><meta name="author" content="Dušan Mikušovič"><meta property="article:author" content="https://www.facebook.com/mikusovic"><meta property="fb:app_id" content="1078070992224692"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:site" content="@dennikN"><meta name="twitter:creator" content="@dennikN"><title>Zuzana Kovačič Hanzelová: Dúfala som, že vydržím dlhšie – Denník N</title><meta property="og:title" content="Zuzana Kovačič Hanzelová: Dúfala som, že vydržím dlhšie"><meta name="twitter:title" content="Zuzana Kovačič Hanzelová: Dúfala som, že vydržím dlhšie"><meta property="og:locale" content="sk_SK"><meta property="og:site_name" content="Denník N"><meta property="og:image" content="https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=2400&h=1260&fit=crop&fm=png&markx=10w&marky=5w&markpost=bottom-right&markw=15w&mark=2019/06/sk.png"><meta name="twitter:image" content="https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=2400&h=1260&fit=crop&fm=png&markx=10w&marky=5w&markpost=bottom-right&markw=15w&mark=2019/06/sk.png"><meta property="og:type" content="article"><link rel="canonical" href="https://dennikn.sk/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/"><meta property="og:url" content="https://dennikn.sk/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/"><meta name="og:image:width" content="2400"><meta name="og:image:height" content="1260"><script id="dnra" type="application/json">{}</script><script id="dnru" type="application/json">{"basic":{"id":29953,"email":"miro.svitok@gmail.com","first_name":null,"last_name":null},"addresses":[],"autologin_tokens":[],"user_meta":[{"no_ad":"true"}],"subscriptions":[{"start_time":1566079200,"end_time":1597615200,"code":"donation_from_company_year_online","is_recurrent":false,"types":["web"]},{"start_time":1576796400,"end_time":1576882800,"code":"demo-predplatne","is_recurrent":true,"types":["web"]},{"start_time":1576796400,"end_time":1576882800,"code":"demo-predplatne","is_recurrent":true,"types":["web"]},{"start_time":1550012400,"end_time":1576796400,"code":"discount_10_months_web_app_klub","is_recurrent":false,"types":["web","ad_free","mobile","club"]},{"start_time":1568035411,"end_time":1572562800,"code":"chceme_promo_web_standard","is_recurrent":false,"types":["web","standard","mobile"]}],"payments":[],"recurrent_payments":[],"invoices":[],"address_change_requests":[],"orders":[],"coverpage_api_logs":[],"mail":[{"code":"system"},{"code":"newsletter_daily"},{"code":"newsletter_special"},{"variants":["1073","324","3559"],"code":"follow_authors"},{"variants":["7844","8562"],"code":"follow_tags"},{"code":"blogs"},{"code":"dennike"}],"access_tokens":[],"content_shares":[],"thank_yous":[],"bookmarks":[{"id":656859,"updated":1565602594,"status":"new","remote_id":"1551567"},{"id":604982,"updated":1562255778,"status":"new","remote_id":"1519002"},{"id":532461,"updated":1557857824,"status":"new","remote_id":"1467630"},{"id":483626,"updated":1554272312,"status":"new","remote_id":"1430984"},{"id":431774,"updated":1550497654,"status":"new","remote_id":"1378254"},{"id":397929,"updated":1547821765,"status":"new","remote_id":"1351003"},{"id":371360,"updated":1545486571,"status":"new","remote_id":"1331684"}]}</script><script>(function(){var rfs=["dnra","dnru"];for(var i=rfs.length-1;i>=0;i--){var rf=rfs[i],re=document.getElementById(rf);if(re){try{window[rf]=JSON.parse(document.getElementById(rf).innerHTML);}catch(e){}}}})();</script><script>function rc(e){for(var e=e+"=",t=document.cookie.split(";"),n=0;n<t.length;n++)if(t.hasOwnProperty(n)){for(var r=t[n];" "==r.charAt(0);)r=r.substring(1,r.length);if(0==r.indexOf(e))return decodeURIComponent(r.substring(e.length,r.length))}return null}function su(){var e={},t=(new Date).getTime();if(!dnru||!dnru.basic)return null;for(var n in dnru)if(dnru.hasOwnProperty(n)){var r=dnru[n];if("basic"==n&&r.id&&r.email)e.id=r.id,e.email=r.email,r.first_name&&r.last_name&&(e.name=[r.first_name,r.last_name]);else if("mail"==n&&n.length)e.newsletters=r.map(function(e,t){return e.code});else if("subscriptions"==n&&n.length){e.tags=[],e.subscriptions=[],e.active=0;for(var i in r)if(r.hasOwnProperty(i)){var a=1e3*r[i].start_time,s=1e3*r[i].end_time;e.subscriptions.push([a,s]),t<s&&(e.active=Math.max(s,e.active)),t>a&&t<s&&(r[i].types&&(e.tags=e.tags.concat(r[i].types)),e.recurrent=r[i].is_recurrent)}e.active&&(e.active=Math.ceil((e.active-t)/864e5))}}return e}var Token=rc("n_token"),User=su();</script><script>( function ( i, s, o, g, r, a, m ) { i["GoogleAnalyticsObject"] = r; i[r] = i[r] || function() { ( i[r].q = i[r].q || [] ).push( arguments ) }, i[r].l = 1 * new Date(); a = s.createElement( o ), m = s.getElementsByTagName( o )[0]; a.async = 1; a.src = g; m.parentNode.insertBefore( a, m ) } )( window, document, "script", "//www.google-analytics.com/analytics.js", "ga" );ga( "create", "UA-55921068-1", "auto" ); if ( User && User.active ) { ga( "set", "dimension1", 2 ); } else if ( User ) { ga( "set", "dimension1", 1 ); } else { ga ( "set", "dimension1", 0 ) } ga( "set", "dimension5", ( User && User.tags && User.tags.indexOf ( "club" ) != -1 ) ? 1 : 0 ); if ( User && User.id ) { ga( "set", "userId", User.id ); } ga( "set", "dimension2", "dusan.m" ); ga( "set", "dimension4", "slovensko" ); ga( "set", "dimension3", "rozhovory" ); ga( "send", "pageview" );</script><link rel='dns-prefetch' href='//s.w.org' />
<link rel="alternate" type="application/rss+xml" title="RSS kanál: Denník N »" href="https://dennikn.sk/feed/" />
<link rel="alternate" type="application/rss+xml" title="RSS kanál komentárov webu Denník N » ku článku Zuzana Kovačič Hanzelová: Dúfala som, že vydržím dlhšiecabrioST(1138873,"");" href="https://dennikn.sk/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/feed/" />
<link rel='stylesheet' id='dn_2_sk_style-css' href='https://dennikn.sk/wp-content/themes/dn-2-sk/style.1568641980739.css' type='text/css' media='all' />
<script type='text/javascript' src='https://dennikn.sk/wp-content/plugins/dn-remp-cabrio/dn-remp-cabrio.js?ver=4.9.8'></script>
<link rel='prev' title='Súťaž o jazdu v skutočnej formule pokračuje!cabrioST(1137204,"");' href='https://dennikn.sk/1137204/sutaz-o-jazdu-v-skutocnej-formuly-pokracuje/' />
<link rel='next' title='Poliaci boli presvedčení, že v lietadle s vietnamskou delegáciou obviňovanou z únosu je aj KaliňákcabrioST(1139290,"");' href='https://dennikn.sk/1139290/poliaci-boli-presvedceni-ze-v-lietadle-s-vietnamskou-delegaciou-obvinovanou-z-unosu-je-aj-kalinak/' />
<link rel='shortlink' href='https://dennikn.sk/?p=1138873' />
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script><script>var Setup={"ajax":"https://dennikn.sk/wp-admin/admin-ajax.php","ajax_error":"Chyba komunikácie zo serverom. Skúste znova.","home":"https://dennikn.sk/","cookie":".dennikn.sk","terms":"https://dennikn.sk/vseobecne-obchodne-podmienky/","mail":"info@dennikn.sk","store":"https://ustore.dennikn.sk/api/v1/article?source=dennikn","wall":"https://predplatne.dennikn.sk/","wall_unlock":"api/v1/content/share-url","wall_more":"viac/","wall_profile":"subscriptions/subscriptions/my/","wall_signin":"sign/in/","wall_login":"api/v1/users/login/","wall_locked_head":"sales-funnel/sales-funnel/funnel-newpayment-popup?referer=","os_minute_appid":"153b15a7-c86f-4684-a45f-fc446d1e3d54","os_minute_safariwebid":"web.onesignal.auto.3f550615-46c0-4fa5-9ee8-42953ece3d19","os_minute_prompt":10,"lock":"hard"};</script><link rel="shortcut icon" type="image/x-icon" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-favicon.ico"><link rel="icon" type="image/png" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-favicon.png"><link rel="mask-icon" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-maskicon.svg" color="#b00c28"><meta name="msapplication-TileImage" content="https://dennikn.sk/wp-content/themes/dn-2/dennikn-144x144.png"><meta name="msapplication-TileColor" content="#b00c28"><meta name="theme-color" content="#b00c28"><link rel="apple-touch-icon" sizes="114x114" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-114x114.png"><link rel="icon" sizes="114x114" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-114x114.png"><link rel="apple-touch-icon" sizes="144x144" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-144x144.png"><link rel="icon" sizes="144x144" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-144x144.png"><link rel="apple-touch-icon" sizes="192x192" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-192x192.png"><link rel="icon" sizes="192x192" href="https://dennikn.sk/wp-content/themes/dn-2/dennikn-192x192.png"><script async="async" src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script><script>window.Ads={"slots":{"_gemius":".K5FNjQp2X_h.KCT_kBKoKSc78ZGpI_E.9koeR2hQ.b.U7","header_lead":{"d":["Slovensko/megaboard","megaboard"],"m":["Slovensko/msquare1","msquare"]},"sidebar_middle":{"d":["Slovensko/vrectangle","vrectangle"],"m":["Slovensko/mrectangle","mrectangle"]},"article_bottom":{"d":["Slovensko/hrectangle","hrectangle"]},"index_bottom":{"m":["Slovensko/msquare2","msquare"]},"interscroller":{"m":["Slovensko/interscroller","interscroller"]}},"sizes":{"megaboard":[[1,1],[1000,200],[1000,150],[1000,300],[970,90],[980,120],[728,90],[980,90],[750,100],[990,100],[970,250],[930,180],[960,90],[750,300],[750,200]],"vrectangle":[[300,100],[180,90],[160,90],[250,250],[300,250],[250,360],[300,50],[300,600],[200,90],[300,300],[240,400],[125,125],[120,600],[180,150],[200,200],[160,600]],"hrectangle":[[1,1],[300,100],[300,250],[320,100],[336,280],[468,60],[580,400],[586,300]],"msquare":[[125,125],[160,90],[180,90],[180,150],[200,90],[200,200],[250,250],[300,50],[300,100],[300,250],[300,300],[320,50],[320,100]],"mrectangle":[[160,60],[120,600],[240,400],[300,600],[250,360],[125,125],[160,90],[180,90],[180,150],[200,90],[200,200],[250,250],[300,50],[300,100],[300,250],[300,300],[320,50],[320,100]],"interscroller":[[1,1],[160,60],[120,600],[240,400],[300,600],[250,360],[125,125],[160,90],[180,90],[180,150],[200,90],[200,200],[250,250],[300,50],[300,100],[300,250],[300,300],[320,50],[320,100]],"mbutton":[[320,100],[220,90],[300,100],[300,50],[320,50]],"dbutton":[[480,120],[320,100],[220,90],[300,100],[300,50],[320,50],[468,60]]},"prefixes":"/172785668/SK_dennikN_","targets":{"Pagetype":["post","default"],"Term":["Rozhovory","RTVS za Rezníka","Slovensko"],"ArticleID":"1138873","Author":["Dušan Mikušovič"]}};</script> <script>
window.Banners = [];
window.googletag = window.googletag || { cmd:[] };
googletag.cmd.push( function() {
window.Ads.subscriber = !!( window.User && window.User.active );
window.Ads.block = !!( window.dnru && window.dnru.user_meta && window.dnru.user_meta.map( function( i ) { if ( i.no_ad ) { return true; } } )[0] === true );
window.Ads.width = window.innerWidth || document.documentElement.clientWidth;
window.Ads.places = {};
for ( var slot in window.Ads.slots ) {
if ( !window.Ads.slots.hasOwnProperty( slot ) || window.Ads.block || slot == '_gemius' ) {
continue;
}
var place = window.Ads.slots[ slot ][ ( Ads.width < 700 ) ? 'm' : 'd' ];
if ( typeof( place ) == 'undefined' ) {
continue;
}
place = [ window.Ads.prefixes + place[ 0 ] + ( Ads.subscriber ? '_sub' : '_nosub' ), typeof( place[ 1 ] ) == 'object' ? place[ 1 ] : window.Ads.sizes[ place[ 1 ] ] ];
window.Ads.places[ slot ] = place;
googletag.defineSlot( place[ 0 ], place[ 1 ], slot ).addService( googletag.pubads() );
}
for ( var target in window.Ads.targets ) {
if ( !window.Ads.targets.hasOwnProperty( target ) ) {
continue;
}
googletag.pubads().setTargeting( target, window.Ads.targets[ target ] );
}
googletag.pubads().addEventListener( 'slotRenderEnded', function( event ) {
window.Banners.push( event.slot.getSlotElementId() );
} );
googletag.pubads().collapseEmptyDivs();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
</script>
</head><body id="s_s" class="__theme_dn2sk __single __single_1138873 __tag_3656 __tag_5494 __category_430 __author_805"><header id="s_h" class="s_h s_h_mnu__hidden s_h_fin__hidden s_h_usr__hidden" data-header data-ref="menu"><div class="s_h_row"><p class="s_h_tit"><a title="Denník N" href="https://dennikn.sk/"><img src="https://dennikn.sk/wp-content/themes/dn-2-sk/logo.svg" alt="Denník N"></a></p><button class="s_h_toggle" title="Rubriky"></button><nav class="s_h_mnu"><ul id="menu-hlavicka-2" class="s_h_mnu_top"><li id="menu-item-1233448" class="s_h_mnu_itm s_h_mnu_itm__0 __1233448 s_h_mnu_itm__active_parent"><a href="https://dennikn.sk/slovensko/">Slovensko</a></li><li id="menu-item-1233449" class="s_h_mnu_itm s_h_mnu_itm__0 __1233449"><a href="https://dennikn.sk/komentare/">Komentáre</a></li><li id="menu-item-1233447" class="s_h_mnu_itm s_h_mnu_itm__0 __1233447"><a href="https://dennikn.sk/svet/">Svet</a></li><li id="menu-item-1233450" class="s_h_mnu_itm s_h_mnu_itm__0 __1233450"><a href="https://dennikn.sk/blog/">Blog</a></li><li id="menu-item-1554112" class="s_h_mnu_itm s_h_mnu_itm__0 __1554112"><a href="https://www.dennike.sk/">Denník E</a></li><li id="menu-item-1233469" class="s_h_mnu_itm s_h_mnu_itm__0 __1233469"><a href="https://dennikn.sk/najnovsie/">Najnovšie a najčítanejšie</a></li><li id="menu-item-1233467" class="s_h_mnu_itm s_h_mnu_itm__0 __1233467 s_h_mnu_itm__save"><a href="https://dennikn.sk/citat-neskor/"><span>Čítať neskôr</span> <span></span></a></li><li id="menu-item-1233452" class="s_h_mnu_itm s_h_mnu_itm__0 __1233452 s_h_mnu_itm__more s_h_mnu_itm__parent"><a href="#">Ďalšie</a><ul class="sub-menu"><li id="menu-item-1233456" class="s_h_mnu_itm s_h_mnu_itm__1 __1233456"><a href="https://dennikn.sk/komentare/shooty/">Shooty</a></li><li id="menu-item-1233461" class="s_h_mnu_itm s_h_mnu_itm__1 __1233461"><a href="https://dennikn.sk/tema/newsfilter/">Newsfilter</a></li><li id="menu-item-1233460" class="s_h_mnu_itm s_h_mnu_itm__1 __1233460"><a href="https://dennikn.sk/veda/">Veda</a></li><li id="menu-item-1233458" class="s_h_mnu_itm s_h_mnu_itm__1 __1233458"><a href="https://dennikn.sk/rodina-a-vztahy/">Rodina a vzťahy</a></li><li id="menu-item-1372710" class="s_h_mnu_itm s_h_mnu_itm__1 __1372710"><a href="https://dennikn.sk/tema/rozhovory/">Rozhovory</a></li><li id="menu-item-1233457" class="s_h_mnu_itm s_h_mnu_itm__1 __1233457"><a href="https://dennikn.sk/kultura/">Kultúra</a></li><li id="menu-item-1233459" class="s_h_mnu_itm s_h_mnu_itm__1 __1233459"><a href="https://dennikn.sk/sport/">Šport a pohyb</a></li><li id="menu-item-1233463" class="s_h_mnu_itm s_h_mnu_itm__1 __1233463"><a href="https://dennikn.sk/tema/podcast/">Podcast</a></li><li id="menu-item-1254785" class="s_h_mnu_itm s_h_mnu_itm__1 __1254785"><a target="_blank" href="http://dennikn.sk/minuta/?ref=menu">MNT.sk</a></li><li id="menu-item-1502908" class="s_h_mnu_itm s_h_mnu_itm__1 __1502908"><a href="https://dennikn.sk/temy/">Všetky témy</a></li></ul></li></ul></nav><nav class="s_h_usr"><ul id="menu-uzivatel-2" class="s_h_usr_top"><li id="menu-item-1235411" class="s_h_usr_itm s_h_usr_itm__0 __1235411 s_h_usr_itm__buy"><a href="https://predplatne.dennikn.sk/sales-funnel/sales-funnel/funnel-newpayment-popup"><span>Kúpiť</span> <span>predplatné</span></a></li><li id="menu-item-1233482" class="s_h_usr_itm s_h_usr_itm__0 __1233482 s_h_usr_itm__rebuy"><a href="https://predplatne.dennikn.sk/sales-funnel/sales-funnel/funnel-newpayment-popup"><span>Predĺžiť</span> <span>predplatné</span></a></li><li id="menu-item-1233484" class="s_h_usr_itm s_h_usr_itm__0 __1233484 s_h_usr_itm__options s_h_usr_itm__parent"><a href="#">Moje konto</a><ul class="sub-menu"><li class="s_h_usr_itm" data-login><div class="s_h_usr_profile"><div class="s_h_usr_tit">Prihlásený ako<a class="s_h_usr_logout" href="https://predplatne.dennikn.sk/users/sign/out/">Odhlásiť</a></div><strong class="s_h_usr_email"></strong><a class="e_button e_button__blue e_button__arr" href="https://predplatne.dennikn.sk/subscriptions/subscriptions/my/">Moje konto</a></div><form class="s_h_usr_login"><div class="s_h_usr_tit">Prihláste sa<a class="s_h_usr_forgot" href="https://predplatne.dennikn.sk/users/users/request-password/">Zabudli ste heslo?</a></div><input class="s_h_usr_inp" type="email" placeholder="Vaša e-mailová adresa" required><input class="s_h_usr_inp" type="password" placeholder="Vaše heslo" required><button class="e_button e_button__blue e_button__arr">Prihlásiť sa</button></form></li><li id="menu-item-1233488" class="s_h_usr_itm s_h_usr_itm__1 __1233488 s_h_usr_itm__emails s_h_usr_itm__top"><a href="https://predplatne.dennikn.sk/email-settings">Nastavenie newslettrov</a></li><li id="menu-item-1245969" class="s_h_usr_itm s_h_usr_itm__1 __1245969 s_h_usr_itm__follow s_h_usr_itm__bot"><a href="https://predplatne.dennikn.sk/follow/settings">Odber autorov a tém e-mailom</a></li><li id="menu-item-1233493" class="s_h_usr_itm s_h_usr_itm__1 __1233493"><a href="https://predplatne.dennikn.sk/">Kúpiť predplatné</a></li><li id="menu-item-1243586" class="s_h_usr_itm s_h_usr_itm__1 __1243586"><a href="https://itunes.apple.com/us/developer/n-press-s.r.o./id963123524">Aplikácie iOs</a></li><li id="menu-item-1242370" class="s_h_usr_itm s_h_usr_itm__1 __1242370"><a href="https://play.google.com/store/apps/developer?id=N+Press&hl=en">Aplikácie Android</a></li><li id="menu-item-1233495" class="s_h_usr_itm s_h_usr_itm__1 __1233495"><a href="https://dennikn.sk/klub/">Klub N</a></li><li id="menu-item-1233500" class="s_h_usr_itm s_h_usr_itm__1 __1233500"><a href="https://obchod.dennikn.sk/">Knihy</a></li><li id="menu-item-1233502" class="s_h_usr_itm s_h_usr_itm__1 __1233502"><a href="https://noviny.dennikn.sk/">Noviny</a></li></ul></li></ul></nav><form class="s_h_fin" action="https://dennikn.sk/"><button class="s_h_fin_cls" type="reset" title="Zatvoriť vyhľadávanie"></button><input class="s_h_fin_inp" type="text" name="s" placeholder="Zadajte vyhľadávaný výraz" required><button class="s_h_fin_sbt" type="submit" title="Hľadaj"></button></form></div></header><div class="s_place s_place__head_below"><div class="remp-banner banner-placeholder" id="remp-banner-under-header"></div></div><div class="s_a s_a__lead"><div id="header_lead" class="e_ads e_ads__1000x200"></div><script>( window.Ads && window.Ads.block ) ? document.getElementById( "header_lead" ).remove() : googletag.cmd.push( function() { googletag.display( "header_lead" ); } );</script></div><main id="s_b" class="s_b s_b__tiny">
<div class="b_place b_place__body_above"><div class="remp-banner banner-placeholder" id="remp-banner-above-content"></div></div> <div class="g_r">
<div class="g_c g_c__tiny">
<article class="b_single b_single__default" data-ref="in">
<header class="b_single_h">
<nav class="e_terms"><a class="e_terms_term e_terms_tag" href="https://dennikn.sk/tema/rozhovory/">Rozhovory</a><a class="e_terms_term e_terms_tag" href="https://dennikn.sk/tema/rtvs/">RTVS za Rezníka</a><time class="e_terms_term e_terms_posted" title="1. júna 2018 6:00" datetime="2018-06-01T06:00:42+00:00">1. júna 2018 6:00</time></nav><h1 class="e_title e_title__serif"><span data-cabriot="1138873">Zuzana Kovačič Hanzelová: Dúfala som, že vydržím dlhšie</span><script>cabrioST(1138873,"");</script></h1><div class="e_tools e_tools__header"><div class="e_authors"><div class="e_author"><a class="e_author_l" href="https://dennikn.sk/autor/dusan-m/"><figure class="e_author_i"><img width="40" height="40"data-src="https://img.projektn.sk/wp-static/2015/02/dusan-mikusovic.jpg?fm=jpg&q=85&w=40&h=40&fit=crop" class="attachment-40x40 size-40x40" alt="Dušan Mikušovič" data-sizes="40px" data-srcset="https://img.projektn.sk/wp-static/2015/02/dusan-mikusovic.jpg?fm=jpg&q=85&w=40&h=40&fit=crop 40w, https://img.projektn.sk/wp-static/2015/02/dusan-mikusovic.jpg?fm=jpg&q=85&w=80&h=80&fit=crop 80w" /></figure><cite class="e_author_t">Dušan Mikušovič</cite></a><button class="e_follow" title="Zapnúť články e-mailom" data-follow-active="Vypnúť články e-mailom" data-follow-hover="Zrušiť odber" data-follow-type="author" data-follow-id="805" data-follow-title="Dušan Mikušovič"></button></div></div><a class="e_facebook" title="Facebook" href="https://www.facebook.com/sharer/sharer.php?u=https://dennikn.sk/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/" target="_blank" data-ga="e_facebook.e_tools__header"></a><button class="e_unlock" title="Odomknúť" data-unlock="/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/"></button><button class="e_save" title="Čítať neskôr" data-save-active="Uložené" data-save-hover="Odstrániť z uložených" data-save="1138873 https://dennikn.sk/1138873/zuzana-kovacic-hanzelova-dufala-som-ze-vydrzim-dlhsie/"></button></div><figure class="b_single_i"><a href="https://a-static.projektn.sk/2018/05/unnamed-file.jpg"><img width="586"data-src="https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=586&h=0&fit=crop" class="attachment-586x0 size-586x0 wp-post-image" alt="Zuzana Kovačič Hanzelová. Foto N - Tomáš Benedikovič" data-sizes="(max-width: 660px) 100vw, 586px" data-srcset="https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=586&h=0&fit=crop 586w, https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=690&h=0&fit=crop 690w, https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=1172&h=0&fit=crop 1172w, https://img.projektn.sk/wp-static/2018/05/unnamed-file.jpg?fm=jpg&q=85&w=1380&h=0&fit=crop 1380w" /></a><figcaption class="e_caption">Zuzana Kovačič Hanzelová. Foto N – Tomáš Benedikovič</figcaption></figure><div class="b_single_e"><p>Doteraz som počúvala, že pracujem v provládnom médiu, a zo dňa na deň z nás urobili opozičných neoliberálov, hovorí odchádzajúca reportérka RTVS. </p>
</div><div id="article_top" class="e_ads e_ads__t"></div><script>( window.Ads && window.Ads.block ) ? document.getElementById( "article_top" ).remove() : googletag.cmd.push( function() { googletag.display( "article_top" ); } );</script> </header>
<div class="__1138873 a_single a_single__post a_single__default" data-single><p><em>Zuzana Kovačič Hanzelová (29) pracovala šesť rokov ako reportérka a moderátorka RTVS. Ku koncu mája dala s jedenástimi ďalšími kolegami výpoveď. V rozhovore hovorí o tom:</em></p>
<ul>
<li><em>prečo spolu s kolegami odchádza z RTVS,</em></li>
<li><em>ako mala oslavná reportáž o Matici „zmäkčovať“ vzťah s RTVS,</em></li>
<li><em>ako sa do vysielania dostal Dankov šachový turnaj,</em></li>
<li><em>ako vraj pre pôrody šéfka rozhlasových správ obvolávala iné médiá,</em></li>
<li><em>o chybách, prehnaných reakciách a statusoch na Facebooku,</em></li>
<li><em>ale aj o tom, či už vie, kam pôjde ďalej.</em></li>
</ul>
<p> </p>
<p class="western"><b>Kedy ste si po prvý raz uvedomili, že z RTVS pravdepodobne odídete?</b></p>
<p class="western">Tušila som to celý posledný mesiac. Od začiatku mája som presviedčala viac ľudí, aby s výpoveďou počkali do konca mesiaca. Osobne som to mala úplne ujasnené po štyroch výpovediach pre mojich kolegov z televízneho spravodajstva, a aj po tom, čo mi zakázali robiť politiku, aj keď potom tvrdili, že to bol len žart.</p>
<p class="western"><b>Minulotýždňové stretnutie Spravodajských odborov RTVS s Jaroslavom Rezníkom teda na vaše rozhodnutie už veľký vplyv nemalo?</b></p>
<p class="western">Stále sme tomu dávali nejakú šancu, ak by generálny riaditeľ prišiel na stretnutie s nejakým reálnym návrhom. Z našich skúseností z posledných mesiacov sme však mali pocit, že to nebude mať veľký zmysel. Tak to presne aj dopadlo. Neprišiel s ničím, o čom by sme sa mohli baviť.</p>
<p class="western"><b>Objavil sa jeden konkrétny moment, po ktorom ste sa odhodlali k výpovedi?</b></p>
<p class="western">Zrelo to postupne. Veľmi na mňa vplývalo, že z redakcie chceli odísť moji kolegovia. Naše výpovede sú tak trochu kolektívne rozhodnutie, napriek tomu, že sa celý spor v spravodajstve často prezentuje ako nejaký „môj boj“.</p>
<p class="western"><b>Kríza v spravodajstve naplno verejne vypukla po tom, čo ste s kolegami <a data-link="int" href="https://dennikn.sk/1083803/takmer-60-novinarov-z-rtvs-kritizuje-vedenie-pracujeme-v-nepriatelskej-atmosfere/" target="_blank" rel="noopener">napísali otvorený list</a> o nepriateľskej atmosfére v redakcii. Kedy sa však začala prejavovať interne?</b></p>
<p class="western">V januári, vtedy sa udialo viacero vecí. Došlo k zastaveniu relácie Reportéri a začalo sa v redakcii objavovať čoraz viac zvláštnych krokov, nielen v spravodajstve, ale aj na športe. Vyústilo to do prvého interného listu, v ktorom sme si vyžiadali stretnutie s Jaroslavom Rezníkom.</p>
<p class="western"><b>Túto „veľkú poradu v rozhlase“, ktorá sa uskutočnila na začiatku roka, spomína viac ľudí, ktorí z RTVS odišli. Čo sa na nej dialo?</b></p>
<p class="western">Ak dobre rátam, bolo na nej asi 70 ľudí z rozhlasu aj televízie. Preberalo sa asi päť bodov, jedným z nich bolo zastavenie Reportérov, ďalším moja služobná cesta do Prahy na české prezidentské voľby, ktorú mi generálny riaditeľ zakázal. Mali sme pocit, že ak si na začiatku nenastavíme, do čoho môže generálny riaditeľ rozprávať, príde k oveľa väčšiemu problému v nejakých turbulentnejších časoch. Preberala sa aj situácia v rozhlase, kde zrušili celé oddelenie aktuálnej publicistiky. A hovorili sme aj o jednej novoročnej reportáži o Matici slovenskej, ktorá vyznela veľmi oslavne.</p>
<p class="western"><b>To bol regionálny príspevok o ich novoročnom koncerte vo Zvolenskej Slatine?</b></p>
<p class="western">Áno. V reportáži sa hovorilo o tom, že Matica bola pri všetkých štátotvorných momentoch tejto krajiny. Dodnes nerozumiem, prečo sme ju v rámci aktuálneho spravodajstva vysielali.</p>
<p class="western"><b>Súvisela táto reportáž s tým, že sa Matica predtým sťažovala na kritickú reportáž o prerozdeľovaní prostriedkov pre jej regionálne pobočky, ktorú odvysielali Reportéri?</b></p>
<p class="western">Bola to téma porady. Jaroslav Rezník, ktorý je v komunikácii vždy zdržanlivejší, si na poradu zobral aj šéfa rozhlasu Michala Dzurjanina. Z jeho úst padlo, že „keď je problém, treba zmäkčovať“.<span id="p_lock" class="p_lock p_lock__hard"></span> Slovo „zmäkčovať“ vtedy zarezonovalo v celej redakcii.</p>
<p class="western">„<b>Zmäkčovať“ malo znamenať spraviť ústretovejšiu reportáž, ktorá si nakloní Maticu sťažujúcu sa na príspevok v Reportéroch?</b></p>
<p class="western">Tak to interpretoval. Vyvolalo to extrémnu nevôľu medzi ľuďmi, ktorí tam sedeli. Jaroslava Rezníka som sa spýtala, či je pravda, že na vianočnom večierku jednej z mojich kolegýň povedal, že sa dohodol s Maticou na odvysielaní dvoch pozitívnych reportáží, ako akúsi kompenzáciu. Jaroslav Rezník to poprel, moja kolegyňa tvrdí, že sa to stalo.</p>
<article class="__1138011 a_art a_art__link"><a data-link="int" class="a_art_l" href="https://dennikn.sk/1138011/spravy-rtvs-opusta-dalsi-tucet-novinarov-vratane-kovacic-hanzelovej-kalinskeho-ci-minicha/"><figure class="a_art_i"><img width="150" height="100"data-src="https://img.projektn.sk/wp-static/2018/05/unnamed-3.jpg?fm=jpg&q=85&w=150&h=100&fit=crop" class="attachment-150x100 size-150x100 wp-post-image" alt="Snímok z redakcie spravodajstva RTVS, väčšina z týchto redaktorov už v RTVS skončila alebo skončí. Foto - archív" data-sizes="150px" data-srcset="https://img.projektn.sk/wp-static/2018/05/unnamed-3.jpg?fm=jpg&q=85&w=150&h=100&fit=crop 150w, https://img.projektn.sk/wp-static/2018/05/unnamed-3.jpg?fm=jpg&q=85&w=300&h=200&fit=crop 300w" /></figure><div class="a_art_b"><span class="e_terms">Prečítajte si tiež</span><h3 class="a_art_t"><span data-cabriot="1138011">Správy RTVS opúšťa ďalší tucet novinárov vrátane Kovačič Hanzelovej, Kalinského či Minicha</span><script>cabrioST(1138011,"");</script></h3></div></a></article>
<p class="western"><b>Ako sa vaša kolegyňa volá?</b></p>
<p class="western">Nechcem ju ohroziť, ale dá sa logicky domyslieť, kto to asi bol.</p>
<p style="text-align: center;"><em>Video: Reportéri vysvetľujú výpovede</em></p>
<div class="iframely-embed" style="max-width: 1339px;">
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | true |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/tests/Unit/Generator/NewsfilterGeneratorTest.php | Mailer/tests/Unit/Generator/NewsfilterGeneratorTest.php | <?php
declare(strict_types=1);
namespace Tests\Unit\Generator;
use PHPUnit\Framework\TestCase;
use Remp\MailerModule\Models\ContentGenerator\Engine\EngineFactory;
use Remp\MailerModule\Models\Generators\HtmlArticleLocker;
use Remp\MailerModule\Models\Generators\EmbedParser;
use Remp\Mailer\Models\Generators\NewsfilterGenerator;
use Remp\MailerModule\Models\Generators\WordpressHelpers;
use Remp\MailerModule\Models\PageMeta\Content\ContentInterface;
use Remp\MailerModule\Repositories\SourceTemplatesRepository;
class NewsfilterGeneratorTest extends TestCase
{
private $generator;
protected function setUp(): void
{
$engineFactory = $GLOBALS['container']->getByType(EngineFactory::class);
$this->generator = new NewsfilterGenerator(
$this->createMock(SourceTemplatesRepository::class),
$this->createMock(WordpressHelpers::class),
$this->createMock(ContentInterface::class),
$this->createMock(EmbedParser::class),
$this->createMock(HtmlArticleLocker::class),
$engineFactory
);
}
public function testPreprocessParameters()
{
$wpJson = <<<EOD
{
"sender_email": "Jon Snow <user@example.com>",
"post_authors": [
{
"user_url": "http:\/\/localhost\/dnwp\/wordpress\/autor\/ria-gehrerova\/",
"ID": "663",
"user_nicename": "ria-gehrerova",
"user_email": "ria.gehrerova@gmail.com",
"display_name": "Ria Gehrerová"
}
],
"post_url": "http:\/\/localhost\/dnwp\/wordpress\/1084435\/matej-sajfa-cifra-mladi-dnes-chcu-byt-za-pol-roka-slavni-mna-si-v-radiu-prve-styri-roky-ani-nevsimli\/",
"ID": 1084435,
"post_author": "663",
"post_date": "2018-04-04 17:49:08",
"post_date_gmt": "2018-04-04 15:49:08",
"post_content": "<i>Matej “Sajfa” Cifra v rozhovore hovorí aj o tom:<\/i>\r\n<ul>\r\n \t<li><i>prečo si do relácie zavolal Kisku a prečo žartovali o ovracanom lietadle;<\/i><\/li>\r\n \t<li><i>kedy zavolá Fica a koho určite nepozve;<\/i><\/li>\r\n \t<li><i>či by moderoval aj politický míting;<\/i><\/li>\r\n \t<li><i>ako zarábajú slovenskí youtuberi a či sa majú angažovať pred voľbami;<\/i><\/li>\r\n \t<li><i>a prečo je podľa neho rádio budúcnosť.<\/i><\/li>\r\n<\/ul>\r\n \r\n\r\n<b>Ľudia vás poznajú najmä ako moderátora v rádiu. Kedy ste pochopili, že budúcnosťou sú vlogy?<\/b>\r\n\r\nBol som v situácii, keď som mal pocit, že v rádiu trocha stagnujem, hoci som bol obklopený svojimi kamarátmi, ktorých si vážim a vedia mi povedať, kde mám zabrať. Navyše som zistil, že moje pôsobenie v slovenskom mediálnom priestore je limitované tým, komu sa páčim a komu sa nepáčim. Zvyčajne o tom rozhoduje nejaký generálny alebo programový riaditeľ. Robil som v televízii veľa projektov, ale vždy ma potrebovali zapasovať do takej polohy, v ktorej by som sa páčil šesťdesiatročnej pani, trinásťročnému človeku a aby si aj 35-ročný manažér z Bratislavy povedal, že ten Sajfa je vlastne v pohode. Pôsobilo to na mňa zväzujúco a mal som pocit, že vtedy nie som úplne sám sebou. Preto som hľadal platformu, kde by som taký mohol byť. Na YouTube môže človek robiť, čo chce, ako chce a kedy chce. Ak to, samozrejme, spĺňa nejaké etické kritériá. Zistil som, že tá platforma na Slovensku ostáva nevyužitá pre staršiu cieľovú skupinu, ku ktorej patrím aj ja, a povedal som si, že je to niečo, čo by ma pravdepodobne bavilo.\r\n\r\n<b>Vo svojich vlogoch máte rôznych ľudí – od prezidenta <a href=\"https:\/\/www.youtube.com\/watch?v=9pqFVGYSOKc\" target=\"_blank\" rel=\"noopener\">Andreja Kisku<\/a> po <a href=\"https:\/\/www.youtube.com\/watch?v=ZaIX_yIEQvk\" target=\"_blank\" rel=\"noopener\">Braňa Mojseja<\/a>. So speváčkou <a href=\"https:\/\/www.youtube.com\/watch?v=CO7gAAcZWP8\" target=\"_blank\" rel=\"noopener\">Emmou Drobnou<\/a> ste sa stretli pár dní po tom, čo v televízii tvrdila, že zem je plochá. Vo videách sa zdá, že so všetkými skvelo vychádzate a k nikomu nie ste kritický. Prečo?<\/b>\r\n\r\nPretože k ľuďom pristupujem tak, ako chcem, aby pristupovali ku mne. Nehľadám na nich chyby. To, že chcem vychádzať s každým, neznamená, že nemám pevné jadro. Nemám rád, keď niekto hovorí, že je pod jeho úroveň s niekým hovoriť. Ja to nikdy nepoviem. Aj s Braňom Mojsejom sa budem rozprávať o tom, ako chodí objímať stromy alebo ako bojuje s alkoholom. Tak isto sa budem s rešpektom baviť s Kiskom a s MMA bojovníkom, ktorý má podľa mnohých vymlátený mozog. Dám im priestor vyniknúť a ukázať, akí sú. To je moje životné nastavenie. Hľadám v ľuďoch to dobré a myslím si, že v každom z nás, i keď veľmi hlboko, niečo dobré musí byť.\r\n\r\n[greybox]<strong>Tento rozhovor je súčasťou magazínu Denníka N, ktorý opisuje, ako fungujú médiá. Magazín vďaka podporovateľom zadarmo doručíme do 430 škôl.<\/strong>\r\n\r\n[articlelink id=\"1083233\"] [\/greybox]\r\n\r\n<b>Úplne v každom?<\/b>\r\n\r\nStretol som sa s rôznymi ľuďmi. Stretol som sa aj s Piťom <em>(bratislavský mafiánsky boss Juraj Ondrejčák, momentálne vo väzení, pozn. red.)<\/em> a myslím si, že s ním mám niekde aj fotku, lebo sme sa poznali z mesta. Teraz nehovorím, že je dobrým človekom, ale neodídem z podniku len preto, lebo by tam sedel aj on. A neprestanem chodiť do Steam&Coffee, lebo to vlastnili Kaliňák s Počiatkom.[lock] Svojho času to bola najbližšia kaviareň k rádiu. Ku všetkým ľuďom vo vlogoch pristupujem ako ku kamarátom, lebo viem, že sa mi oveľa viac otvoria, keď zistia, že Sajfa nie je ten arogantný hajzel, čo si o nich myslí, že sú primitívi.\r\n\r\n<b>Ak by vám dali televízie dostatočnú voľnosť, tak by ste sa vlogerom nestali?<\/b>\r\n\r\nTelevízie mi neposkytli dostatočný priestor, kde by som sa mohol sebarealizovať, čo ma na jednej strane veľmi mrzelo a istý čas som sa kvôli tomu aj trápil. Hovorili mi, že som v pohode, ale že so mnou nemôžu riskovať, lebo ak im ten program so mnou nevyjde, tak to môže byť problém. Vtedy som sa rozhodol, že na to, aby o mne existovalo všeobecné povedomie a mohol som moderovať akcie, televíziu nepotrebujem.\r\n\r\n<b>Ako by ste si predstavovali vašu reláciu v televízii?<\/b>\r\n\r\nV minulosti sa mi v televízii najlepšie robila relácia Webmaster. Pozýval som si tam hostí a rozhovory s nimi prekladal zábavnými videami z internetu. Možné však je aj to, že sa do televízie jednoducho nehodím. Internet mi v súčasnosti extrémne vyhovuje.\r\n\r\nV televízii mi ponúkali, aby som šiel robiť niektoré formáty, o ktorých som bol presvedčený, že by som sa do nich nehodil. Spýtali sa ma: A ty nechceš robiť v televízii? A ja som povedal, že nie, nepotrebujem byť v televízii len preto, aby som bol v televízii. Keď príde projekt, ktorý ma osloví, rád sa ho zúčastním. To bolo jedno z najoslobodzujúcejších stretnutí a pocitov, aké som kedy mal. Ten riaditeľ vyzeral, akoby sa s tým ešte nestretol a všetci okamžite siahali po šanciach robiť v televízii, nech je to čokoľvek.\r\n\r\n<b>Viete si predstaviť, že by ste v budúcnosti už robili len vlogy?<\/b>\r\n\r\nJasné. Nehovorím, že to budem robiť doživotne, ale myslím si, že internet len tak ľahko nezanikne a že sa tam v nejakej forme budem vedieť realizovať stále.\r\n\r\n<b>Premýšľate pri nakrúcaní vlogov aj nad tým, čo by mohlo zaujímať dnešných tridsiatnikov alebo štyridsiatnikov?<\/b>\r\n\r\nNie, robím to, čo ma zaujíma, baví a keďže už v médiách pracujem takmer dvadsať rokov, tak viem odhadnúť, čo môže fungovať. Množstvo vecí je však veľmi spontánnych. Napríklad som si kúpil tenisky, ktoré môj známy aj moja žena považovali za ohavné a iným sa, naopak, páčili. Zrazu do toho boli ľudia takí zaangažovaní, že hrozne chceli povedať svoj názor. Je to niečo, čo ich chytilo. Nie je to niečo, čo vyrieši zdravotníctvo. Ale začne to debatu o niečom, o čom ľudia chcú hovoriť.\r\n<p style=\"text-align: center;\"><strong><em>Sajfa vo vládnom špeciáli s prezidentom Andrejom Kiskom<\/em><\/strong><\/p>\r\nhttps:\/\/www.youtube.com\/watch?v=ayWhADwC81g&\r\n\r\n<b>Vo svojich <\/b><a href=\"https:\/\/www.youtube.com\/watch?v=ayWhADwC81g&t=310s\"><b>vlogoch<\/b><\/a><b> aj v relácii <\/b><a href=\"https:\/\/www.youtube.com\/watch?v=9pqFVGYSOKc\"><b>Level Lama<\/b><\/a><b> ste mali prezidenta Kisku. Urobili by ste to isté aj s premiérom Robertom Ficom?<\/b>\r\n\r\nKeď Fico kandidoval na prezidenta, <a href=\"https:\/\/www.youtube.com\/watch?v=5ml0wnfJyzw\">v rádiu som s ním robil rozhovor<\/a>. Pred parlamentnými voľbami som mu pozval pozvánku rovnako, ako iným politickým stranám, ale nakoniec to zrušil. Nemám problém si s ním sadnúť a porozprávať sa s ním, to je to najmenej.\r\n\r\n<b>Zavolali by ste ho aj do svojej relácie Level Lama, kde so známymi ľuďmi hráte počítačové hry a zároveň s nimi robíte rozhovory?<\/b>\r\n\r\nJa by som ho zavolal. A Erik Tomáš by povedal, že určite príde. Je to taká zaujímavá situácia, že sa stavím, že aj vy by ste sa s ním určite vedeli porozprávať. S Kaliňákom sa dá rozprávať do tretej ráno o hocičom. Sú to vzdelaní a inteligentní ľudia, ktorí robia, čo robia. Ťažko, samozrejme, povedať, či s najlepším vedomím a svedomím. Fica si zavolám o pätnásť rokov, keď bude vydávať svoje pamäti.\r\n\r\n<b>Ale Kisku ste si zavolali teraz.<\/b>\r\n\r\nKiska je mi sympatický a má priaznivé vnútorné vyžarovanie. Pri tých ostatných ľuďoch o tom možno trocha pochybujem. Ale tiež ich nesúdim. Nehovorím, že sú zlí ľudia, len asi jednoducho majú iné nastavenie svojho fungovania, svedomia a vedomia.\r\n\r\n[greybox]\r\n\r\n[caption id=\"attachment_1084488\" align=\"alignright\" width=\"200\"]<a href=\"https:\/\/a-static.projektn.sk\/2018\/04\/N37A3338_F-1000x1500.jpg\"><img class=\"wp-image-1084488 size-medium\" src=\"https:\/\/a-static.projektn.sk\/2018\/04\/N37A3338_F-e1522856523713-200x220.jpg\" alt=\"\" width=\"200\" height=\"220\" \/><\/a> Foto - Tomas Thurzo[\/caption]\r\n<h3><i>Matej “Sajfa” Cifra (1979) <\/i><\/h3>\r\n<i>Slovenský moderátor a vloger. Vyštudoval slovenčinu a angličtinu na Filozofickej fakulte Univerzity Komenského v Bratislave. Počas štúdia na vysokej škole začal pracovať v rádiu B1, z ktorého prešiel do Fun Rádia a pôsobí v ňom dodnes v relácii Popoludnie so Sajfom. Moderoval viaceré televízne šou ako napríklad VyVolení alebo Hviezdy na ľade.<\/i>\r\n\r\n[\/greybox]\r\n\r\n<b>Koho by ste si do relácie nezavolali?<\/b>\r\n\r\nAsi ultrapravicovo zmýšľajúcich ľudí, lebo by to zrejme bolo kontraproduktívne. Aj keď by to možno bolo zaujímavé a práve tam by som mal priestor im povedať: Nebláznite, čo máte v tej hlave?\r\n\r\n<b>V jednom z vašich <\/b><a href=\"https:\/\/www.youtube.com\/watch?v=ayWhADwC81g&t=310s\"><b>vlogov žartujete s prezidentom Kiskom<\/b><\/a><b> a jeho tímom o ovracanom lietadle. Začali o tom hovoriť sami alebo ste ich presviedčali?<\/b>\r\n\r\nV tom vlogu nie je žiadna inscenácia. Prezidentovho hovorcu Romana Krpelana som sa spýtal, či v lietadle môžem zapnúť kameru a on mi povedal, že áno. Tak som nakrútil aj to, ako mi začali ukazovať, kde všade to bolo ovracané a ako sa ma prezident pýta, kde mám vedierko. Krpelanovi som ešte pred uverejnením zavolal, že vedia, kedy som mal kameru zapnutú a či sú s tým teda okej. A on znova povedal, že áno. Toto je však jediný raz, keď som niečo dopredu konzultoval. Urobil som to preto, lebo si vážim ten úrad, prezidenta aj Romana. Ak mi niekto povie, nech ho nedávam do vlogu, vždy to akceptujem, lebo si kvôli tomu nechcem kaziť vzťahy.\r\n\r\n<b>Mnohí známi ľudia ako Martin Nikodým robia mítingy pre politické strany. Prijali by ste takú ponuku?<\/b>\r\n\r\nMal som možnosť také niečo robiť, ale vždy som si povedal, že mi to za to nestojí. Znie to asi hrozne, ale také prachy sveta neexistujú. Alebo mi neboli ponúknuté.\r\n\r\n[articlelink id=\"975747\"]\r\n\r\n<b>Za koľko by ste to vzali?<\/b>\r\n\r\nAk by mi Fico povedal, že poďte robiť mítingy a ja vám dám päť triliónov, tak čo ja viem. Ale taká suma je nereálna, čiže to teraz vôbec nie je na stole. Nie som taký magnet, že za mnou idú všetci dôchodcovia, a preto si ma musia zaplatiť. Ale rozumiem Nikodýmovi, rozumiem Kočišovi. Je to pre nich kšeft, tie peniaze si odložia na bankový účet a možno za to neskôr pôjdu s rodinou na dovolenku. Nesúhlasím s tým, čo robia, nie je mi to sympatické, ale rozumiem tomu. Keď mi volali z Progresívneho Slovenska, nech im prídem otvoriť snem, tak som im povedal: Chlapci, sympatizujem s vami, makajte, ale toto pre mňa ešte nie je.\r\n\r\n<b>Máte v zmluve s rádiom napísané, čo môžete a nemôžete robiť popri rádiu?<\/b>\r\n\r\nTú zmluvu som si nečítal, neviem. Ale myslím si, že nie, lebo moje zásadné živobytie je moderovanie eventov a večierkov, kde nemám žiadne obmedzenie. Som „eseročka“, ktorú si rádio najíma na svoje vysielanie, takže som slobodný človek.\r\n\r\nhttps:\/\/www.instagram.com\/p\/BeaLYLuhBBk\/?hl=sk&taken-by=sajfa\r\n\r\n<b>Čím ste najviac? Moderátorom v rádiu, moderátorom súkromných akcií alebo vlogerom?<\/b>\r\n\r\nPredovšetkým som moderátorom rádia. Mám ho hrozne rád a neopúšťam ho, lebo som na ňom vyrástol a poskytuje mi zaujímavý priestor. Keďže vás ľudia nevidia a komunikujete s nimi iba hlasom, má to svoju mágiu, ktorú je ťažké vysvetliť. Keď som bol mladý, nepremýšľal som o tom, že by som chcel byť moderátorom. Chcel som robiť v rádiu. Videl som film, ktorý sa volá „Private parts“ (Súkromné neresti), ktorý je vlastne autobiografiou jedného z najznámejším amerických rozhlasových moderátorov Howarda Sterna. V rádiu pracuje štyridsať rokov a urobil veľkú rádiovú revolúciu. Bol jedným z prvých kontroverzných moderátorov a presne tak som sa o dvadsať rokov videl aj ja. Povedal som si: Ty kokos toto je ono! V rádiu človek môže povedať: Dámy a páni, pekné popoludnie, sedí tu vedľa mňa Robert Fico a chcel by vám niečo povedať. Robo, poď niečo povedať. Nechce sa ti? Okej, asi má toho plné zuby. Človek sa s tým môže hrať. Howard Stern robil podobné veci. Napríklad tvrdil, že s ním v štúdiu sedí Ringo Star, ale nechce hrať na bicie, tak mu ľudia majú zavolať do štúdia, aby ho presvedčili. V sedemdesiatych rokoch chodili do rádia všetci v oblekoch a takéto správanie bolo čudné. Jednoducho bol voľnomyšlienkár.\r\n<p style=\"text-align: center;\"><strong><em>Video: Sajfa v rádiu s Robertom Ficom ako prezidentským kandidátom v roku 2014<\/em><\/strong><\/p>\r\nhttps:\/\/www.youtube.com\/watch?v=5ml0wnfJyzw\r\n\r\n<b>Hlavnými konkurentmi rádií sú dnes streamovacie služby ako Spotify či podcasty. Počúvate ich aj vy?<\/b>\r\n\r\nJasné. Spomedzi médií je rádio stále extrémne silné. V mnohých ohľadoch je dokonca silnejšie ako televízia a rovnako rýchle ako internet. Keď sa niečo stane, rádio s tým vie ísť okamžite von. Nepotrebuje obraz ako televízia ani žiadne ďalšie spracovanie. Som si na sto percent istý, že hlas je budúcnosť. Ľudia sedia v aute a počúvajú rádio, ráno vstanú, počúvajú rádio, vezú deti zo školy, znova počúvajú rádio. Mnohé veci začíname ovládať hlasom. Myslím si, že v rádiu nepotrebujeme hitparády najlepších pesničiek, lebo tie majú naši poslucháči stiahnuté v telefónoch. Rádio má poskytovať niečo viac. Má byť autoritou, ktorá povie, že veci sú takéto a takéto. Alebo poslucháčom ponúka niekoho, koho radi počúvajú a chcú vedieť jeho názor. Možno je to aj budúcnosť správ. Keď si večer zapnem televízne správy, tak už ich nemusím pozerať, lebo presne viem, čo sa počas dňa stalo. Mňa večer zaujíma to, ako si to vysvetliť. Myslím si, že novinárskou úlohou je dať veci do kontextu. Či už je to v rádiu alebo v televízii.\r\n\r\n<b>Takže by sa rádio malo odkloniť od hudby a sústrediť sa viac na diskusiu a vysvetľovanie?<\/b>\r\n\r\nSkôr by si malo dať záležať na tom, aby jeho moderátori boli osobnosťami, ktorí ľuďom vedia niečo priniesť. To znamená, že ich počúvajú, lebo si ich vážia, lebo ich rozosmejú alebo preto, že si povedia svoj názor. Prípadne nech sa rádiá sústredia len na to, čo chcú robiť. Buď nech informujú alebo nech hrajú iba hudbu. Aby od neho každý dostal to, čo naozaj chce.\r\n\r\n<b>Aké médiá počas dňa čítate alebo počúvate?<\/b>\r\n\r\nKeď som v aute, zvyčajne prelaďujem rádiá. Dnes ráno som napríklad počúval Devín, hrali blues. Veľakrát mám pustené Spotify, kde mám viacero obľúbených podcastov o technológiách a internete. Som asi jeden z mála ľudí na Slovensku, ktorí sú aj na Twitteri. Hoci nie aktívne, ale prescrollujem si ho. Facebook mi zvyčajne slúži na to, aby som zhruba vedel, čo ľudia riešia. To však môže byť zradné, lebo človek má na Facebooku kamarátov, to znamená, že žije v bubline. Dnes som bol na Hlavnej stanici nahrávať Sajfov mikrofón, čo je jedna z mojich rubrík, v ktorej sa ľudí pýtam nezmyselné otázky. Dnes som sa ich pýtal: Na východnom Slovensku sa usídlila talianska mafia. Myslíte si, že to súvisí s tým, že východné Slovensko má priamu hranicu s Talianskom? A tí ľudia vzhľadom na to, že vidia mňa a chcú byť za múdrych, tak začnú prikyvovať. My a ani iní novinári často netušíme, čo ľudia riešia. Deväť z desiatich ľudí, ktorí boli na stanici, nevedelo nič o talianskej mafii na východnom Slovensku. V rádiu sme dlho riešili, do akej miery, treba napríklad smrť Jána Kuciaka riešiť, pretože ľudia nevedia, o čo ide. Majú štyristo eur mesačne a je im to jedno. Nehovorím, že tí ľudia sú horší alebo hlúpejší, len majú úplne iné starosti.\r\n\r\n<b>Čo všetko musí vedieť človek, ktorý chce robiť v rádiu? Stačí aby vedel plynule hovoriť?<\/b>\r\n\r\nTo je najbežnejšia predstava, ktorú ľudia majú. Ľudia mi hovoria, že by tiež mohli robiť v rádiu, lebo im strašne ide huba a kamoši im hovoria, že sú vtipní. Tak im hovorím: No a práve ty by si v rádiu nemal robiť. Tam nejde o to, či niekomu mele huba. Nemyslím si, že mne huba mele. Skôr si myslím, že sa treba sústrediť na to, či ten človek má čo povedať alebo nie. Či je jeho názor zaujímavý, vtipný, čudný. Nič nie je horšie ako človek, ktorý robí v médiách a chce sa páčiť všetkým. Bytostne s tým nesúhlasím. Aj ja polarizujem ľudí. Päťdesiat percent ma má rado a päťdesiat percent si myslí, že som idiot. Ale je dobré, ak si väčšina ľudí povie, že aj keď ma nemajú radi, tak ma rešpektujú, lebo nie som blbý. Každého človeka, ktorý ma nemá rád a myslí si, že som idiot, som schopný na osobnom stretnutí presvedčiť, že to tak nie je. Lebo ľudia si o mne v časopise prečítajú, že som bol na dovolenke v Dubaji a povedia si, že som hajzel z Bratislavy. Ale ja som sa pritom narodil do skromných pomerov. Môj otec je polymérny vedec a moja mama je stredoškolská učiteľka. Ľudia si z toho mediálneho obrazu niečo vyberú a podľa toho si ma zaradia. Ak ma ľudia sledujú na sociálnych sieťach, tam ma môžu vidieť takého, aký som.\r\n<p style=\"text-align: center;\"><strong><em>Video: Andrej Danko u Sajfu v rádiu<\/em><\/strong><\/p>\r\nhttps:\/\/www.youtube.com\/watch?v=bZXOXOj48G4&index=16&list=PLGpPhicKtVUR800b7F6girxIbFjG0PRRn\r\n\r\n<b>Aký by teda mal byť človek, ktorý chce robiť v rádiu? Musí zvládať aj zložitú techniku?<\/b>\r\n\r\nKedysi sme s Adelou Banášovou hovorili len do mikrofónu a niekto iný mixoval. Ale keď Adela odišla, musel som sa to naučiť robiť sám. Ovládať techniku sa však za dva mesiace naučí aj cvičená opica, vôbec to nie je ťažké. Ľudia sa ma napríklad pýtajú, akú kameru používam na vlogovanie. A ja im hovorím, že je to jedno, lebo ide o obsah a môže to byť nasnímané aj telefónom. Ak je to obsahovo slabé, môže to byť natočené aj päťtisícovou kamerou. Tak to funguje aj v rádiu. Nemusia mať všetci hlas ako Mišo Hudák, lebo on má geniálny hlas. Oproti nemu mám podľa mňa nepríjemný piskľavý hlas. Ide skôr o to, čo ľuďom hovoríš a či ťa chcú počúvať. Ale áno, ak má niekto priškrtený hlas, tak v rádiu zrejme nebude pracovať. Ani v televízii nepracujú úplne ohavní ľudia.\r\n\r\n<b>Môže človek pracujúci v rádiu šušlať alebo račkovať?<\/b>\r\n\r\nUrčite áno. Môže to byť niečo, podľa čoho, si ho ľudia zapamätajú. Napríklad moderátor Markízy Boris Pršo račkuje ako blázon, ale je obľúbený, lebo vie niečo zaujímavé ponúknuť a je to dobrý človek.\r\n\r\n<b>Dá sa na Slovensku z vlogovania vyžiť?<\/b>\r\n\r\nZáleží na tom, aké máte štandardy. To, čo zarobím v rádiu, miniem na zaplatenie lízingu, nájomného a podobne. Peniaze pre seba si zarobím moderovaním rôznych akcií. Ale to je moje individuálne nastavenie. Ak niekomu stačí tisícka mesačne, môže robiť len YouTube, ak bude mať dostatok fanúšikov. Ak však máte mesačný štandard desaťtisíc eur, tak vám vlogovanie nebude stačiť. Mne YouTube poskytuje peniaze, ktoré ma potešia, ale veľmi ich nevnímam. Raz keď Kočner odniekadiaľ dostal tri milióny, povedal, že si to na účte ani nevšimol, tak podobne je to aj s mojimi peniazmi od YouTube. Aj chalani ako Expl0ited, Slážo alebo Gogo zarábajú oveľa viac peňazí na spoluprácach ako na peniazoch od YouTube. Ak by Gogo, ktorý má 1,6 milióna, odberateľov pôsobil v Amerike, od YouTube by dostával oveľa viac peňazí, ako tu, kde je obmedzený na Slovensko a Česko.\r\n\r\n<b>Selassie spolupracoval s Nadáciou otvorenej spoločnosti na vlogoch z rómskej osady, Gogo zasa robil projekt, v ktorom darovali auto rómskej rodine a tiež mladých ľudí vyzýval voliť. Viete si predstaviť, že by ste do svojich vlogov tiež vložili nejaké podobné posolstvo?<\/b>\r\n\r\nKeď ma niekto osloví, tak s tým zrejme nebudem mať problém. Len to musí byť zaujímavý projekt, ktorý bude mať hlavu a pätu. Ja sám také niečo nevymýšľam, ale som tomu otvorený. Na sto percent viem napríklad povedať, že keď bude pred voľbami, tak budem tiež mladých vyzývať, aby sa na to nevykašľali.\r\n\r\nhttps:\/\/www.instagram.com\/p\/Bat2qJshzMZ\/?hl=sk&taken-by=sajfa\r\n\r\n<b>Vo svojich videách stále viac hovoríte o tom, čo je správne a čo nie. Je to aj preto, že si uvedomujete svoj vplyv na mladých ľudí?<\/b>\r\n\r\nUvedomujem si to, ale vychádza to zo mňa akosi spontáne. Mám 38 rokov a hoci nie som rodičom, už mám čosi osobne aj profesionálne zažité. Môžem teda mladým ľuďom povedať, aby boli trpezliví a aby nemali predstavu, že nič nebudú robiť zadarmo a že do pol roka budú senior manažérom. Pretože takú predstavu má dnes množstvo mladých. A vy ste sa s koňom zrazili? Každý sme niekde začínali a každý sa nejako vyvíjal, to znamená, že trpezlivosť je extrémne dôležitá a nič nejde rýchlo a skratkou. Ani Superstar nie je skratka k večnej sláve, lebo tiež sa z tej šou uchytilo len pár ľudí, ktorí na sebe makali aj po skončení šou. Či už v rádiu alebo kdekoľvek inde treba sledovať dlhodobé ciele a nie to, kam sa dostanem za pol roka. Za pol roka v rádiu som sa nedostal nikam. Štyri roky som tam chodil a ľudia nevedeli ani ako sa volám. Dnes chcú byť mladí ľudia hneď veľké hviezdy a hovoria, že chcú robiť v rádiu, lebo o pol roka chcú byť ako ja a mať dvestotisíc ľudí na Instagrame. To sa však nedá urobiť za dva dni, je to dlhodobá práca. V rádiu ma spočiatku držalo najmä to, že som ako jeden z mála vedel po anglicky. Veľmi veľa vecí som preto prekladal alebo tlmočil. Okrem toho som čítal správy, chodil som na Slovan hlásiť výsledok futbalu, chodil som na tlačovky do Slovenského národného divadla. Až po rokoch som začal skutočne moderovať.\r\n\r\n<b>Myslíte si, že sú mladí ľudia dnes apatickejší, než staršie generácie?<\/b>\r\n\r\nNie, nemyslím si to. A nemám rád, keď niekto hovorí, že mladí ľudia sú stále len na internete a nechodia dostatočne von. Súhlasím s tým, že by deti mali oveľa viac športovať, lebo inak už nikdy nezískame žiadnu olympijskú medailu. Ale to, že sú teraz mladí ľudia oveľa viac pri počítačoch, je jednoducho súčasná situácia a nemôžeme preto techniku démonizovať. Treba povedať, že technológia im zároveň môže pomôcť realizovať sa, nájsť samých seba a tak ďalej.\r\n\r\nAj keď som mal z toho jemné obavy, nedávno som sa zúčastnil Siedmeho neba s Vilom Rozborilom. Mám voči tomu projektu výhrady, ale objavil sa tu jedenásťročný chalan <a href=\"https:\/\/www.youtube.com\/channel\/UCJurOtLRifGtwHUWr9TD9Uw\">Mako SK<\/a>, ktorý je pripútaný na vozík a robí internetové videá. Tak sme ho šli s prezidentom pozrieť. Ten chalan je pripútaný na vozík, nevie si ísť zahrať futbal ani plávať, ale technológia mu umožňuje sa realizovať a byť šťastným a spokojným. Okej, tak deti teraz robia len toto a nechodia von. Je taká doba a o desať, pätnásť rokov to možno bude úplne inak. Môžeme byť radi, že tu nemáme mor, lebo by to bolo oveľa horšie, než to, že deti sedia za počítačom.\r\n<p style=\"text-align: center;\"><strong><em>Video: Sajfa s Makom<\/em><\/strong><\/p>\r\nhttps:\/\/www.youtube.com\/watch?v=uL4kM1p0Fjo\r\n\r\n<b>Je ťažké naučiť sa robiť vlogy?<\/b>\r\n\r\nNaučil som sa to tak, že som to neustále skúšal. Nemyslím si, že to robím na nejakej profesionálnej grafickej úrovni, ale stále sa zdokonaľujem a robím, čo viem. Základom je obsah. A ak je aj technická realizácia lepšia, tak o to lepšie sa to potom pozerá. Naučil som sa to sám aj na staré kolená. Ak mi niekto povie, že by to s videami skúsil, ale nevie strihať, tak mu na to poviem, nech sa na to teda vykašle. Všetko sa dá naučiť. Prvý vlog mi trvalo zostrihať šesť hodín a teraz mi to trvá tri hodiny, niekedy to stihnem aj za dve. Nejaký čas tomu musím obetovať. Zatiaľ nechcem, aby to robil niekto namiesto mňa, pretože ma to baví.\r\n\r\n<b>Robíte si videá úplne sám?<\/b>\r\n\r\nMám v rádiu kolegu Borisa, ktorý zo 180 vlogov postrihal asi tri, lebo sa to týkalo mojich narodenín, ktoré pre mňa boli prekvapením. Niekedy sa s ním poradím, ale v podstate to robím celé ja.\r\n\r\n<b>Vo vlogoch používate aj drony. Na Slovensku sú veľmi prísne pravidlá, ktoré ich takmer nikde a na nič nepovoľujú používať. Máte ich povolené?<\/b>\r\n\r\nVšetky papiere mám vybavené, ale nie pre Slovensko. Tu nemám nič.\r\n\r\n[articlelink id=\"788231\"]\r\n\r\n<b>Nebojíte sa, že kvôli tomu môžete mať problémy?<\/b>\r\n\r\nViete si predstaviť, že by ma zatkla polícia? Veď ja zavolám Kaliňákovi, že Robo neblázni. (smiech) Rozumiem tomu postoju, ale otvorene priznávam, že nemám pilotné ani letecké skúšky. Mohli by za mnou prísť policajti a odviesť ma v putách. Keď to spravia, tak to možno bude zaujímavý obsah do vlogu. Nikdy s dronom nelietam nad štadiónom plným ľudí a vždy ho mám v dohľade. Viem, že tu nejaké legislatíva existuje a som si vedomý toho, že ju zrejme porušujem.\r\n\r\nhttps:\/\/www.instagram.com\/p\/BVxYnqihZAd\/?hl=sk&taken-by=sajfa\r\n\r\n<b>Pred rokom ste hovorili, že za post na Instagrame si vypýtate asi päťsto eur. Teraz máte oveľa viac followerov. Zmenila sa odvtedy cena?<\/b>\r\n\r\nCena závisí od toho, aký je to klient a čo odo mňa chce. O tých päťsto eur mi nejde, zarobím si ich aj niekde inde. Musí to byť niečo, čo mi dáva zmysel a obohacuje ma to a potom si za to rád vypýtam peniaze. Ale ten pomer vecí, ktoré som vzal a ktoré som poodmietal je asi jedna k deviatim. Radšej si vyberiem dlhodobejšiu spoluprácu, než človeka, ktorý za mnou príde s turbovysávačom a žiada ma, nech sa s ním odfotím. Mladí ľudia dnes vedia veľmi dobre odhadnúť, čo je prirodzené a čo nie. Je potom na mojej šikovnosti, či im viem čosi zaplatené zaobaliť do prirodzena.\r\n\r\n<b>Vo svojich vlogoch často vystupujete so svojou ženou. Stanovili ste si v súkromí nejaké hranice, za ktoré s kamerou nejdete?<\/b>\r\n\r\nObaja robíme v médiách a obaja podvedome vieme, kde je tá hranica. Nikdy sme sa nedohodli, že ľuďom nikdy neukážeme svoju kúpeľňu alebo posteľ. Prirozdene vieme, čo sa do toho vlogu dá použiť a čo nie. Keď sa pohádame, nedáme to do vlogu, lebo je to zbytočné. Niektorí mi hovoria, že tými vlogmi odhaľujem veľmi veľa súkromia. Ale nerozumiem, čo zásadné som zo svojho súkromia odhalil. Nechodím s tou kamerou stále a nenakrúcam všetko. Z dvoch alebo troch dní urobím dvanásťminútové video. A ak niekto nechce byť točený, tak to rešpektujem. Ale nestáva sa mi často, že by niekto nechcel. Skôr sa ma pýtajú, prečo so sebou nemám kameru. Nechodím s ňou napríklad na eventy, ktoré moderujem, lebo mi dodatočnú reklamu vo vlogu nezaplatili.\r\n\r\n<b>V jednom vlogu ste omylom uverejnili číslo na Goga a jemu potom celý deň vyvolávali nadšené deti. Za túto chybu ste sa mu potom ospravedlnili. Je ešte niečo, čo ste po zverejnení videa oľutovali?<\/b>\r\n\r\nRaz som nechtiac uverejnil aj svoje číslo, lebo mi kuriér čosi priniesol a keď som tú zásielku podpisoval, nakrútil som aj svoje telefónne číslo. V mobile mám aj kvôli tomu uložených asi 150 telefónnych čísel ako „Nedvíhať“.",
"post_title": "Matej Sajfa Cifra: Mladí dnes chcú byť za pol roka slávni, mňa si v rádiu prvé štyri roky ani nevšimli",
"post_excerpt": "Matej Cifra sa nedohodol s televíziami a tak prešiel na internet. Mladí ho dnes nepoznajú z rádia, ale z YouTubu, kde má už viac ako 140-tisíc odberateľov.",
"post_status": "publish",
"post_name": "matej-sajfa-cifra-mladi-dnes-chcu-byt-za-pol-roka-slavni-mna-si-v-radiu-prve-styri-roky-ani-nevsimli",
"post_modified": "2018-04-04 17:52:54",
"post_modified_gmt": "2018-04-04 15:52:54",
"post_type": "post",
"post_tags": [],
"post_categories": [
{
"term_url": "http:\/\/localhost\/dnwp\/wordpress\/slovensko\/",
"term_id": 430,
"name": "Slovensko",
"slug": "slovensko"
}
]
}
EOD;
$wpJson = str_replace(["\n", "\r", "\t"], ["", "", ""], $wpJson);
$data = json_decode($wpJson);
$output = $this->generator->preprocessParameters($data);
self::assertEquals("Jon Snow <user@example.com>", $output->from);
self::assertEquals("Matej Sajfa Cifra: Mladí dnes chcú byť za pol roka slávni, mňa si v rádiu prvé štyri roky ani nevšimli", $output->title);
self::assertEquals("Ria Gehrerová", $output->editor);
self::assertEquals("http://localhost/dnwp/wordpress/1084435/matej-sajfa-cifra-mladi-dnes-chcu-byt-za-pol-roka-slavni-mna-si-v-radiu-prve-styri-roky-ani-nevsimli/", $output->url);
self::assertStringContainsString("Matej Cifra sa nedohodol s televíziami a tak", $output->summary);
self::assertStringContainsString("ako zarábajú slovenskí youtuberi", $output->newsfilter_html);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/bin/latte-lint.php | Mailer/bin/latte-lint.php | <?php
declare(strict_types=1);
use Nette\Bootstrap\Configurator;
require_once __DIR__ . '/../vendor/autoload.php';
echo '
Latte linter
------------
';
if ($argc < 2) {
echo "Usage: latte-lint <path>\n";
exit(1);
}
$configurator = new Configurator;
$configurator->setDebugMode(true);
$configurator->enableTracy(__DIR__ . '/../log');
$configurator->setTempDirectory(__DIR__ . '/../temp');
$configurator->createRobotLoader()
->addDirectory(__DIR__)
->register();
// Root config, so MailerModule can register extensions, etc...
$configurator->addConfig(__DIR__ . '/../vendor/remp/mailer-module/src/config/config.root.neon');
$configurator->addConfig(__DIR__ . '/../app/config/config.neon');
$configurator->addConfig(__DIR__ . '/../app/config/config.test.neon');
$container = $configurator->createContainer();
/** @var \Nette\Bridges\ApplicationLatte\LatteFactory $latteFactory */
$latteFactory = $container->getByName('nette.latteFactory');
$engine = $latteFactory->create();
$debug = in_array('--debug', $argv, true);
$path = $argv[1];
$linter = new Latte\Tools\Linter($engine, $debug);
$ok = $linter->scanDirectory($path);
exit($ok ? 0 : 1);
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/bin/command.php | Mailer/bin/command.php | <?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/Bootstrap.php';
use Nette\Database\DriverException;
use Remp\MailerModule\Models\PhinxRegistrator;
use Remp\MailerModule\Models\EnvironmentConfig;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
$container = Remp\Mailer\Bootstrap::boot()
->createContainer();
$input = new ArgvInput();
$output = new ConsoleOutput();
try {
$application = $container->getByType(Application::class);
} catch (DriverException | InvalidArgumentException $e) {
$output->getErrorOutput()->writeln("<question>NOTICE:</question> Looks like the new fresh install - or wrong configuration - '{$e->getMessage()}'.");
$output->getErrorOutput()->writeln("<question>NOTICE:</question> Commands limited to migrations.");
$application = new Application('mailer-migration');
}
$appRootDir = dirname(__DIR__);
$phinxRegistrator = new PhinxRegistrator(
$application,
$container->getByType(EnvironmentConfig::class),
$appRootDir
);
$application->run($input, $output);
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/www/index.php | Mailer/www/index.php | <?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../app/Bootstrap.php';
Remp\Mailer\Bootstrap::boot()
->createContainer()
->getByType(Nette\Application\Application::class)
->run();
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Mailer/www/.maintenance.php | Mailer/www/.maintenance.php | <?php
header('HTTP/1.1 503 Service Unavailable');
header('Retry-After: 300'); // 5 minutes in seconds
?>
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="robots" content="noindex">
<meta name="generator" content="Nette Framework">
<style>
body { color: #333; background: white; width: 500px; margin: 100px auto }
h1 { font: bold 47px/1.5 sans-serif; margin: .6em 0 }
p { font: 21px/1.5 Georgia,serif; margin: 1.5em 0 }
</style>
<title>Site is temporarily down for maintenance</title>
<h1>We're Sorry</h1>
<p>The site is temporarily down for maintenance. Please try again in a few minutes.</p>
<?php
exit;
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/AggregateRequest.php | Composer/remp-commons/src/journal/AggregateRequest.php | <?php
namespace Remp\Journal;
class AggregateRequest
{
protected $category;
protected $action;
protected $filterBy = [];
protected $groupBy = [];
protected $timeBefore;
protected $timeAfter;
protected $timeHistogram = [];
public static function from($category, $action = null)
{
return new self($category, $action);
}
public function __construct($category, $action = null)
{
$this->category = $category;
$this->action = $action;
}
public function addInverseFilter(string $tag, ...$values): AggregateRequest
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => true,
];
return $this;
}
public function addFilter(string $tag, ...$values): AggregateRequest
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => false,
];
return $this;
}
public function addGroup(string ...$tags): AggregateRequest
{
$this->groupBy = array_merge($this->groupBy, $tags);
return $this;
}
public function setTimeHistogram(string $interval, ?string $timeZone = null): AggregateRequest
{
$this->timeHistogram = [
'interval' => $interval,
];
if ($timeZone) {
$this->timeHistogram['time_zone'] = $timeZone;
}
return $this;
}
public function setTimeBefore(\DateTime $timeBefore): AggregateRequest
{
$this->timeBefore = $timeBefore;
return $this;
}
public function setTimeAfter(\DateTime $timeAfter): AggregateRequest
{
$this->timeAfter = $timeAfter;
return $this;
}
public function setTime(\DateTime $timeAfter, \DateTime $timeBefore): AggregateRequest
{
$this->timeAfter = $timeAfter;
$this->timeBefore = $timeBefore;
return $this;
}
public function buildUrl($template): string
{
if ($this->action) {
return sprintf($template, $this->category, $this->action);
}
return sprintf($template, $this->category);
}
public function buildUrlWithItem($template, $item): string
{
return sprintf($template, $this->category, $this->action, $item);
}
public function getCategory()
{
return $this->category;
}
public function getAction()
{
return $this->action;
}
public function getFilterBy(): array
{
return $this->filterBy;
}
public function getGroupBy(): array
{
return $this->groupBy;
}
public function getTimeBefore(): ?\DateTime
{
return $this->timeBefore;
}
public function getTimeAfter(): ?\DateTime
{
return $this->timeAfter;
}
public function getTimeHistogram(): array
{
return $this->timeHistogram;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/ConcurrentsRequest.php | Composer/remp-commons/src/journal/ConcurrentsRequest.php | <?php
namespace Remp\Journal;
class ConcurrentsRequest
{
protected $filterBy = [];
protected $groupBy = [];
protected $timeBefore;
protected $timeAfter;
public function addInverseFilter(string $tag, ...$values)
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => true,
];
}
public function addFilter(string $tag, ...$values)
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => false,
];
}
public function addGroup(string ...$tags)
{
$this->groupBy = array_merge($this->groupBy, $tags);
}
public function setTimeBefore(\DateTime $timeBefore)
{
$this->timeBefore = $timeBefore;
}
public function setTimeAfter(\DateTime $timeAfter)
{
$this->timeAfter = $timeAfter;
}
public function getFilterBy(): array
{
return $this->filterBy;
}
public function getGroupBy(): array
{
return $this->groupBy;
}
public function getTimeBefore(): ?\DateTime
{
return $this->timeBefore;
}
public function getTimeAfter(): ?\DateTime
{
return $this->timeAfter;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/JournalException.php | Composer/remp-commons/src/journal/JournalException.php | <?php
namespace Remp\Journal;
class JournalException extends \Exception
{
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/JournalContract.php | Composer/remp-commons/src/journal/JournalContract.php | <?php
namespace Remp\Journal;
interface JournalContract
{
public function categories(): array;
public function commerceCategories(): array;
public function flags(): array;
public function actions($group, $category): array;
public function count(AggregateRequest $request): array;
public function sum(AggregateRequest $request): array;
public function avg(AggregateRequest $request): array;
public function unique(AggregateRequest $request): array;
public function list(ListRequest $request): array;
public function concurrents(ConcurrentsRequest $request): array;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/TokenProvider.php | Composer/remp-commons/src/journal/TokenProvider.php | <?php
namespace Remp\Journal;
interface TokenProvider
{
public function getToken(): ?string;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/ListRequest.php | Composer/remp-commons/src/journal/ListRequest.php | <?php
namespace Remp\Journal;
class ListRequest
{
protected $category;
protected $select = [];
protected $filterBy = [];
protected $groupBy = [];
protected $timeBefore;
protected $timeAfter;
protected $loadTimespent = false;
public static function from($category): ListRequest
{
return new self($category);
}
public function __construct($category)
{
$this->category = $category;
}
public function addSelect(string ...$fields): ListRequest
{
$this->select = array_merge($this->select, $fields);
return $this;
}
public function addInverseFilter(string $tag, ...$values): ListRequest
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => true,
];
return $this;
}
public function addFilter(string $tag, ...$values): ListRequest
{
foreach ($values as &$v) {
$v = (string) $v;
}
$this->filterBy[] = [
"tag" => $tag,
"values" => $values,
"inverse" => false,
];
return $this;
}
public function addGroup(string ...$tags): ListRequest
{
$this->groupBy = array_merge($this->groupBy, $tags);
return $this;
}
public function setLoadTimespent(): ListRequest
{
$this->loadTimespent = true;
return $this;
}
public function setTimeBefore(\DateTime $timeBefore): ListRequest
{
$this->timeBefore = $timeBefore;
return $this;
}
public function setTimeAfter(\DateTime $timeAfter): ListRequest
{
$this->timeAfter = $timeAfter;
return $this;
}
public function setTime(\DateTime $timeAfter, \DateTime $timeBefore)
{
$this->timeAfter = $timeAfter;
$this->timeBefore = $timeBefore;
return $this;
}
public function buildUrl($template): string
{
return sprintf($template, $this->category);
}
public function getSelect(): array
{
return $this->select;
}
public function getFilterBy(): array
{
return $this->filterBy;
}
public function getGroupBy(): array
{
return $this->groupBy;
}
public function getTimeBefore(): ?\DateTime
{
return $this->timeBefore;
}
public function getTimeAfter(): ?\DateTime
{
return $this->timeAfter;
}
public function getLoadTimespent(): bool
{
return $this->loadTimespent;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/Journal.php | Composer/remp-commons/src/journal/Journal.php | <?php
namespace Remp\Journal;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
class Journal implements JournalContract
{
const ENDPOINT_EVENT_CATEGORIES = 'journal/events/categories';
const ENDPOINT_COMMERCE_CATEGORIES = 'journal/commerce/categories';
const ENDPOINT_PAGEVIEW_CATEGORIES = 'journal/pageviews/categories';
const ENDPOINT_GROUP_CATEGORY_ACTIONS = 'journal/%s/categories/%s/actions';
const ENDPOINT_GROUP_FLAGS = 'journal/flags';
const ENDPOINT_GENERIC_COUNT_ACTION = 'journal/%s/actions/%s/count';
const ENDPOINT_GENERIC_COUNT = 'journal/%s/count';
const ENDPOINT_GENERIC_SUM_ACTION = 'journal/%s/actions/%s/sum';
const ENDPOINT_GENERIC_SUM = 'journal/%s/sum';
const ENDPOINT_GENERIC_AVG = 'journal/%s/actions/%s/avg';
const ENDPOINT_GENERIC_UNIQUE = 'journal/%s/actions/%s/unique/%s';
const ENDPOINT_GENERIC_LIST = 'journal/%s/list';
const ENDPOINT_CONCURRENTS_COUNT = 'journal/concurrents/count';
private $client;
private $redis;
private $tokenProvider;
public function __construct(Client $client, \Predis\Client $redis, TokenProvider $tokenProvider = null)
{
$this->client = $client;
$this->redis = $redis;
$this->tokenProvider = $tokenProvider;
}
public function categories(): array
{
try {
$pageviewResponse = $this->client->get(self::ENDPOINT_PAGEVIEW_CATEGORIES);
$commerceResponse = $this->client->get(self::ENDPOINT_COMMERCE_CATEGORIES);
$eventResponse = $this->client->get(self::ENDPOINT_EVENT_CATEGORIES);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:ListCategories endpoint: {$e->getMessage()}");
}
$pageviewCategories = json_decode($pageviewResponse->getBody());
$commerceCategories = json_decode($commerceResponse->getBody());
$eventCategories = json_decode($eventResponse->getBody());
return [
'pageviews' => $pageviewCategories,
'commerce' => $commerceCategories,
'events' => $eventCategories,
];
}
public function commerceCategories(): array
{
try {
$commerceResponse = $this->client->get(self::ENDPOINT_COMMERCE_CATEGORIES);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:ListCategories endpoint: {$e->getMessage()}");
}
return json_decode($commerceResponse->getBody());
}
public function flags(): array
{
try {
$response = $this->client->get(self::ENDPOINT_GROUP_FLAGS);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:ListCategories endpoint: {$e->getMessage()}");
}
$flags = json_decode($response->getBody(), true);
return $flags;
}
public function actions($group, $category): array
{
try {
$response = $this->client->get(sprintf(self::ENDPOINT_GROUP_CATEGORY_ACTIONS, $group, $category));
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:ListActions endpoint: {$e->getMessage()}");
}
$list = json_decode($response->getBody());
return $list;
}
public function count(AggregateRequest $request): array
{
return $this->aggregateCall(
$request,
$request->getAction() ?
$request->buildUrl(self::ENDPOINT_GENERIC_COUNT_ACTION) :
$request->buildUrl(self::ENDPOINT_GENERIC_COUNT)
);
}
public function sum(AggregateRequest $request): array
{
return $this->aggregateCall(
$request,
$request->getAction() ?
$request->buildUrl(self::ENDPOINT_GENERIC_SUM_ACTION) :
$request->buildUrl(self::ENDPOINT_GENERIC_SUM)
);
}
public function avg(AggregateRequest $request): array
{
return $this->aggregateCall($request, $request->buildUrl(self::ENDPOINT_GENERIC_AVG));
}
public function unique(AggregateRequest $request): array
{
// Unique page views are distinguished by different browsers
return $this->aggregateCall(
$request,
$request->buildUrlWithItem(self::ENDPOINT_GENERIC_UNIQUE, 'browsers')
);
}
private function aggregateCall(AggregateRequest $request, string $url): array
{
try {
$json = [
'filter_by' => $request->getFilterBy(),
'group_by' => $request->getGroupBy(),
];
if ($this->tokenProvider) {
$token = $this->tokenProvider->getToken();
if ($token) {
$json['filter_by'][] = [
'tag' => 'token',
'values' => [$token],
'inverse' => false,
];
}
}
if ($request->getTimeAfter()) {
$json['time_after'] = $this->roundSecondsDown($request->getTimeAfter())->format(DATE_RFC3339);
}
if ($request->getTimeBefore()) {
$json['time_before'] = $this->roundSecondsDown($request->getTimeBefore())->format(DATE_RFC3339);
}
if ($request->getTimeHistogram()) {
$json['time_histogram'] = $request->getTimeHistogram();
}
$cacheKey = $this->requestHash($url, $json);
$body = $this->redis->get($cacheKey);
if (!$body) {
$response = $this->client->post($url, [
'json' => $json,
]);
$body = $response->getBody();
// cache body
$this->redis->set($cacheKey, $body);
$this->redis->expire($cacheKey, 60);
}
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal endpoint {$url}: {$e->getMessage()}");
} catch (ClientException $e) {
\Log::error(json_encode([
'url' => $url,
'payload' => $json,
'message' => $e->getResponse()->getBody()->getContents(),
]));
throw $e;
}
$list = json_decode($body);
return $list;
}
public function list(ListRequest $request): array
{
try {
$json = [
'select_fields' => $request->getSelect(),
'conditions' => [
'filter_by' => $request->getFilterBy(),
'group_by' => $request->getGroupBy(),
],
];
if ($request->getTimeAfter()) {
$json['conditions']['time_after'] = $request->getTimeAfter()->format(DATE_RFC3339);
}
if ($request->getTimeBefore()) {
$json['conditions']['time_before'] = $request->getTimeBefore()->format(DATE_RFC3339);
}
if ($request->getLoadTimespent()) {
$json['load_timespent'] = true;
}
$response = $this->client->post($request->buildUrl(self::ENDPOINT_GENERIC_LIST), [
'json' => $json,
]);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:List endpoint: {$e->getMessage()}");
} catch (ClientException $e) {
\Log::error($e->getResponse()->getBody()->getContents());
throw $e;
}
$list = json_decode($response->getBody());
return $list;
}
public function concurrents(ConcurrentsRequest $request): array
{
$cacheKey = null;
try {
$json = [
'filter_by' => $request->getFilterBy(),
'group_by' => $request->getGroupBy(),
];
if ($this->tokenProvider) {
$token = $this->tokenProvider->getToken();
if ($token) {
$json['filter_by'][] = [
'tag' => 'token',
'values' => [$token],
'inverse' => false,
];
}
}
if ($request->getTimeAfter()) {
$json['time_after'] = $this->roundSecondsDown($request->getTimeAfter())->format(DATE_RFC3339);
}
if ($request->getTimeBefore()) {
$json['time_before'] = $this->roundSecondsDown($request->getTimeBefore())->format(DATE_RFC3339);
}
$cacheKey = $this->requestHash(self::ENDPOINT_CONCURRENTS_COUNT, $json);
$body = $this->redis->get($cacheKey);
if (!$body) {
$response = $this->client->post(self::ENDPOINT_CONCURRENTS_COUNT, [
'json' => $json,
]);
$body = $response->getBody();
// cache body
$this->redis->set($cacheKey, $body);
$this->redis->expire($cacheKey, 60);
}
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal:concurrents endpoint: {$e->getMessage()}");
} catch (ClientException $e) {
\Log::error($e->getResponse()->getBody()->getContents());
throw $e;
}
$list = json_decode($body);
return $list;
}
/**
* roundSecondsDown rounds second down to the closest multiple of 10.
*
* For example $dt containing 2019-05-28 16:43:28 will be modified to 2019-05-28 16:43:20.
*
* @param \DateTime $dt
* @return \DateTime
*/
private function roundSecondsDown(\DateTime $dt): \DateTime
{
$c = Carbon::instance($dt);
$c->second($c->second - ($c->second % 10));
return $c;
}
private function requestHash($path, $json)
{
return $path . '_' . md5(json_encode($json));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/journal/DummyTokenProvider.php | Composer/remp-commons/src/journal/DummyTokenProvider.php | <?php
namespace Remp\Journal;
class DummyTokenProvider implements TokenProvider
{
public function getToken(): ?string
{
// Always returns empty token
return null;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/multi-armed-bandit/Lever.php | Composer/remp-commons/src/multi-armed-bandit/Lever.php | <?php
namespace Remp\MultiArmedBandit;
/**
* Results for individual arms.
*
* @package Remp\MultiArmedBandit
*/
class Lever
{
protected $id;
protected $rewards;
protected $attempts;
public function __construct(string $id, int $rewards, int $attempts)
{
$this->id = $id;
$this->rewards = $rewards;
$this->attempts = $attempts;
}
public function getId(): string
{
return $this->id;
}
public function getRewards(): int
{
return $this->rewards;
}
public function getAttempts(): int
{
return $this->attempts;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/remp-commons/src/multi-armed-bandit/Machine.php | Composer/remp-commons/src/multi-armed-bandit/Machine.php | <?php
namespace Remp\MultiArmedBandit;
use gburtini\Distributions\Beta;
class Machine
{
protected $draws;
/** @var Lever[] */
protected $levers = [];
public function __construct(int $draws = 1000)
{
$this->draws = $draws;
}
public function addLever(Lever $lever)
{
$this->levers[$lever->getId()] = $lever;
}
/**
* @return float[]
*/
public function run(): array
{
$results = [];
if (empty($this->levers)) {
return [];
}
foreach (range(1, $this->draws) as $_) {
$simulatedData = [];
foreach ($this->levers as $lever => $arm) {
if ($arm->getAttempts() === $arm->getRewards()) {
$simulatedData[$lever] = 1;
continue;
}
// get random variates
$beta = new Beta($arm->getRewards(), $arm->getAttempts() - $arm->getRewards());
$simulatedData[$lever] = $beta->rand();
}
// select winning lever
arsort($simulatedData);
$results[] = key($simulatedData);
}
// calculate probability of win for each lever based on number of draws
$distribution = array_count_values($results);
$probabilities = [];
foreach ($this->levers as $leverId => $lever) {
$probabilities[$leverId] = ($distribution[$leverId] ?? 0) / $this->draws;
}
return $probabilities;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Http/Middleware/VerifyJwtToken.php | Composer/laravel-sso/src/Http/Middleware/VerifyJwtToken.php | <?php
namespace Remp\LaravelSso\Http\Middleware;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use League\Uri\Components\Query;
use League\Uri\Http;
use League\Uri\QueryString;
use League\Uri\Uri;
use Remp\LaravelSso\Contracts\Jwt\Guard;
use Remp\LaravelSso\Contracts\Jwt\User;
use Remp\LaravelSso\Contracts\SsoContract;
use Remp\LaravelSso\Contracts\SsoExpiredException;
class VerifyJwtToken
{
private $sso;
private $guard;
public function __construct(SsoContract $sso, Guard $guard)
{
$this->sso = $sso;
$this->guard = $guard;
}
public function handle($request, Closure $next)
{
$token = $this->guard->getToken();
try {
if ($request->has('token')) {
return $this->handleCallback($request);
}
// invalidate token after logging user out
if ($token && $this->guard->guest()) {
$tokenInvalidated = $this->sso->invalidate($token);
$this->guard->setToken(null);
return redirect($tokenInvalidated['redirect']);
}
// check whether guard has a user
if (!$this->guard->check()) {
// empty introspect to get redirect URL from SSO
$this->sso->introspect(null);
}
// check whether token is still valid
$this->sso->introspect($token);
} catch (SsoExpiredException $tokenExpired) {
try {
if ($request->wantsJson()) {
throw new AuthenticationException($tokenExpired->getCode());
}
$tokenResponse = $this->sso->refresh($token);
$this->guard->setToken($tokenResponse['token']);
} catch (SsoExpiredException $refreshExpired) {
$redirectUrl = Uri::new($tokenExpired->redirect);
$query = Query::new($redirectUrl->getQuery());
$query = $query
->appendTo('successUrl', $request->fullUrl())
->appendTo('errorUrl', config('services.remp_sso.error_url') ?: route('sso.error'));
return redirect($redirectUrl->withQuery($query->value()));
}
}
return $next($request);
}
/**
* handleCallback processes request when returning back from SSO with a token. It gets user data via introspect
* call, stores them to Guard and returns RedirectResponse.
*/
private function handleCallback(Request $request)
{
$token = $request->query('token');
$userArr = $this->sso->introspect($token);
$user = new User();
$user->id = $userArr['id'];
$user->name = $userArr['name'];
$user->email = $userArr['email'];
$user->scopes = $userArr['scopes'];
$this->guard->setUser($user);
$this->guard->setToken($token);
// now get rid of token param once handled
$url = Uri::new($request->url());
$query = Query::new($url->getQuery());
return redirect($url->withQuery(
query: $query->withoutPairByKey('token')
));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/SsoExpiredException.php | Composer/laravel-sso/src/Contracts/SsoExpiredException.php | <?php
namespace Remp\LaravelSso\Contracts;
class SsoExpiredException extends \Exception
{
public $redirect;
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/JwtException.php | Composer/laravel-sso/src/Contracts/JwtException.php | <?php
namespace Remp\LaravelSso\Contracts;
class JwtException extends \Exception
{
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/SsoContract.php | Composer/laravel-sso/src/Contracts/SsoContract.php | <?php
namespace Remp\LaravelSso\Contracts;
interface SsoContract
{
public function introspect($token): array;
public function refresh($token): array;
public function apiToken($token): bool;
public function invalidate($token): array;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/SsoException.php | Composer/laravel-sso/src/Contracts/SsoException.php | <?php
namespace Remp\LaravelSso\Contracts;
class SsoException extends \Exception
{
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/Token/User.php | Composer/laravel-sso/src/Contracts/Token/User.php | <?php
namespace Remp\LaravelSso\Contracts\Token;
use Remp\LaravelSso\Contracts\SsoException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Support\Arrayable;
class User implements Authenticatable, Arrayable
{
public $token;
public $scopes;
/**
* Get the name of the unique identifier for the user.
* @return string
* @throws SsoException
*/
public function getAuthIdentifierName()
{
return 'token';
}
/**
* Get the unique identifier for the user.
* @return mixed
* @throws SsoException
*/
public function getAuthIdentifier()
{
return $this->token;
}
/**
* Get the password for the user.
* @return string
* @throws SsoException
*/
public function getAuthPassword()
{
throw new SsoException("token doesn't support password authentication");
}
/**
* @throws SsoException
*/
public function getAuthPasswordName()
{
throw new SsoException("token doesn't support password authentication");
}
/**
* Get the token value for the "remember me" session.
* @return string
* @throws SsoException
*/
public function getRememberToken()
{
throw new SsoException("token doesn't support remember token");
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
* @throws SsoException
*/
public function setRememberToken($value)
{
throw new SsoException("token doesn't support remember token");
}
/**
* Get the column name for the "remember me" token.
* @return string
* @throws SsoException
*/
public function getRememberTokenName()
{
throw new SsoException("token doesn't support remember token");
}
/**
* Get the instance as an array.
*
* @return array
*/
public function toArray()
{
return [
'token' => $this->token,
'scopes' => $this->scopes,
];
}
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/Token/Guard.php | Composer/laravel-sso/src/Contracts/Token/Guard.php | <?php
namespace Remp\LaravelSso\Contracts\Token;
use Remp\LaravelSso\Contracts\JwtException;
use Remp\LaravelSso\Contracts\SsoContract;
use Remp\LaravelSso\Contracts\SsoException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard as AuthGuard;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class Guard implements AuthGuard
{
private $user;
public function __construct(SsoContract $ssoContract, Request $request)
{
$this->ssoContract = $ssoContract;
$this->request = $request;
$this->inputKey = 'api_token';
$this->storageKey = 'api_token';
}
public function authenticate()
{
throw new JwtException("token guard doesn't support authenticate()");
}
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return boolval($this->user());
}
/**
* Determine if the current user is a guest.
*
* @return bool
*/
public function guest()
{
return $this->user === null;
}
/**
* Get the currently authenticated user.
* @return Authenticatable|null
* @throws SsoException
*/
public function user()
{
if (! is_null($this->user)) {
return $this->user;
}
$user = null;
$token = $this->getTokenForRequest();
if (!empty($token)) {
try {
$valid = $this->ssoContract->apiToken($token);
if ($valid) {
$user = new User;
$user->token = $token;
$user->scopes = [];
}
} catch (SsoException $e) {
return null;
}
}
return $this->user = $user;
}
/**
* Get the ID for the currently authenticated user.
*
* @return int|null
*/
public function id()
{
return $this->user()->getAuthIdentifier();
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
* @throws JwtException
*/
public function validate(array $credentials = [])
{
throw new JwtException("token guard doesn't support credentials validation");
}
/**
* Set the current user.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @return void
*/
public function setUser(Authenticatable $user)
{
$this->user = $user;
}
public function hasUser()
{
return !$this->guest();
}
public function getTokenForRequest()
{
$token = $this->request->query($this->inputKey);
if (empty($token)) {
$token = $this->request->input($this->inputKey);
}
if (empty($token)) {
$token = $this->request->bearerToken();
}
if (empty($token)) {
// Support for multiple header values
$authorizationHeader = $this->request->header('Authorization');
if ($authorizationHeader) {
foreach (explode(',', $authorizationHeader) as $headerValue) {
$headerValue = trim($headerValue);
if (Str::startsWith($headerValue, 'Bearer ')) {
$token = Str::substr($headerValue, 7);
}
}
}
}
if (empty($token)) {
$token = $this->request->getPassword();
}
return $token;
}
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/Remp/Sso.php | Composer/laravel-sso/src/Contracts/Remp/Sso.php | <?php
namespace Remp\LaravelSso\Contracts\Remp;
use Remp\LaravelSso\Contracts\SsoContract;
use Remp\LaravelSso\Contracts\SsoException;
use Remp\LaravelSso\Contracts\SsoExpiredException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class Sso implements SsoContract
{
const ENDPOINT_INTROSPECT = '/api/auth/introspect';
const ENDPOINT_REFRESH = '/api/auth/refresh';
const ENDPOINT_CHECK_TOKEN = '/api/auth/check-token';
const ENDPOINT_INVALIDATE = '/api/auth/invalidate';
private $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function introspect($token): array
{
try {
$response = $this->client->request('GET', self::ENDPOINT_INTROSPECT, [
'headers' => [
'Authorization' => 'Bearer '.$token,
]
]);
} catch (ClientException $e) {
$response = $e->getResponse();
$contents = $response->getBody()->getContents();
$body = \GuzzleHttp\Utils::jsonDecode($contents);
switch ($response->getStatusCode()) {
case 400:
case 401:
case 404:
$e = new SsoExpiredException();
$e->redirect = $body->redirect;
throw $e;
default:
throw new SsoException($contents);
}
}
$user = \GuzzleHttp\Utils::jsonDecode($response->getBody()->getContents(), true);
return $user;
}
public function refresh($token): array
{
try {
$response = $this->client->request('POST', self::ENDPOINT_REFRESH, [
'headers' => [
'Authorization' => 'Bearer '.$token,
]
]);
} catch (ClientException $e) {
$response = $e->getResponse();
$contents = $response->getBody()->getContents();
$body = \GuzzleHttp\Utils::jsonDecode($contents);
switch ($response->getStatusCode()) {
case 400:
case 401:
case 404:
$e = new SsoExpiredException();
$e->redirect = $body->redirect;
throw $e;
default:
throw new SsoException($contents);
}
}
$tokenResponse = \GuzzleHttp\Utils::jsonDecode($response->getBody()->getContents(), true);
return $tokenResponse;
}
public function apiToken($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();
throw new SsoException($contents);
}
return $response->getStatusCode() == 200;
}
public function invalidate($token): array
{
try {
$response = $this->client->request('POST', self::ENDPOINT_INVALIDATE, [
'headers' => [
'Authorization' => 'Bearer '.$token,
]
]);
} catch (ClientException $e) {
$response = $e->getResponse();
$contents = $response->getBody()->getContents();
throw new SsoException($contents);
}
$tokenResponse = \GuzzleHttp\Utils::jsonDecode($response->getBody()->getContents(), true);
return $tokenResponse;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/Jwt/User.php | Composer/laravel-sso/src/Contracts/Jwt/User.php | <?php
namespace Remp\LaravelSso\Contracts\Jwt;
use Remp\LaravelSso\Contracts\SsoException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Support\Arrayable;
class User implements Authenticatable, Arrayable
{
public $id;
public $name;
public $email;
public $scopes;
/**
* Get the name of the unique identifier for the user.
* @return string
* @throws SsoException
*/
public function getAuthIdentifierName()
{
return 'id';
}
/**
* Get the unique identifier for the user.
* @return mixed
* @throws SsoException
*/
public function getAuthIdentifier()
{
return $this->id;
}
/**
* @throws SsoException
*/
public function getAuthPassword()
{
throw new SsoException("jwt doesn't support password authentication");
}
/**
* @throws SsoException
*/
public function getAuthPasswordName()
{
throw new SsoException("jwt doesn't support password authentication");
}
/**
* Get the token value for the "remember me" session.
* @return string
* @throws SsoException
*/
public function getRememberToken()
{
throw new SsoException("jwt doesn't support remember token");
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
* @throws SsoException
*/
public function setRememberToken($value)
{
throw new SsoException("jwt doesn't support remember token");
}
/**
* Get the column name for the "remember me" token.
* @return string
* @throws SsoException
*/
public function getRememberTokenName()
{
throw new SsoException("jwt doesn't support remember token");
}
/**
* Get the instance as an array.
*
* @return array
*/
public function toArray()
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'scopes' => $this->scopes,
];
}
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Contracts/Jwt/Guard.php | Composer/laravel-sso/src/Contracts/Jwt/Guard.php | <?php
namespace Remp\LaravelSso\Contracts\Jwt;
use Remp\LaravelSso\Contracts\JwtException;
use Remp\LaravelSso\Contracts\SsoException;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Guard as AuthGuard;
use Illuminate\Contracts\Session\Session;
class Guard implements AuthGuard
{
const JWT_USER_SESSION = 'jwt.user';
const JWT_TOKEN_SESSION = 'jwt.token';
private $session;
public function __construct(Session $session)
{
$this->session = $session;
}
public function authenticate()
{
throw new JwtException("authenticating?");
}
/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return boolval($this->user());
}
/**
* Determine if the current user is a guest.
*
* @return bool
*/
public function guest()
{
return $this->session->get(self::JWT_USER_SESSION) === null;
}
/**
* Get the currently authenticated user.
* @return Authenticatable|null
* @throws SsoException
*/
public function user()
{
$sessionUser = $this->session->get(self::JWT_USER_SESSION);
if (!$sessionUser) {
return null;
}
$user = unserialize($sessionUser);
if (! $user instanceof Authenticatable) {
throw new SsoException("stored JWT user is not instance of Authenticatable");
}
return $user;
}
/**
* Get the ID for the currently authenticated user.
*
* @return int|null
*/
public function id()
{
return $this->user()->getAuthIdentifier();
}
/**
* Validate a user's credentials.
*
* @param array $credentials
* @return bool
* @throws JwtException
*/
public function validate(array $credentials = [])
{
throw new JwtException("jwt guard doesn't support credentials validation");
}
/**
* Set the current user.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @return void
*/
public function setUser(Authenticatable $user)
{
$sessionUser = serialize($user);
$this->session->put(self::JWT_USER_SESSION, $sessionUser);
}
public function hasUser()
{
return !$this->guest();
}
/**
* setToken stores JWT token to session.
*
* @param $token
*/
public function setToken($token)
{
$this->session->put(self::JWT_TOKEN_SESSION, $token);
}
/**
* getToken retrieves stored token from session.
*
* @return string
*/
public function getToken()
{
return $this->session->get(self::JWT_TOKEN_SESSION);
}
public function getName()
{
return self::JWT_USER_SESSION;
}
public function logout()
{
$this->session->remove(self::JWT_USER_SESSION);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/src/Providers/SsoServiceProvider.php | Composer/laravel-sso/src/Providers/SsoServiceProvider.php | <?php
namespace Remp\LaravelSso\Providers;
use Remp\LaravelSso\Contracts\Jwt\Guard as JWTGuard;
use Remp\LaravelSso\Contracts\Token\Guard as TokenGuard;
use Remp\LaravelSso\Contracts\SsoContract;
use Remp\LaravelSso\Contracts\Remp\Sso;
use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Auth;
class SsoServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../config/services.php');
$config = $this->app['config']->get('services', []);
$this->app['config']->set('services', array_merge(require $path, $config));
Auth::extend('jwt', function ($app, $name, array $config) {
return $app->make(JWTGuard::class);
});
// this is to resolve jwt auth conflict in SSO in a non-breaking fasion
Auth::extend('jwtx', function ($app, $name, array $config) {
return $app->make(JWTGuard::class);
});
Auth::extend('token', function($app, $name, array $config) {
return $app->make(TokenGuard::class);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->bind(SsoContract::class, function($app){
$client = new Client([
'base_uri' => $app['config']->get('services.remp.sso.web_addr'),
]);
return new Sso($client);
});
}
public function provides()
{
return [Sso::class];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-sso/config/services.php | Composer/laravel-sso/config/services.php | <?php
return [
'remp' => [
'sso' => [
'web_addr' => env('REMP_SSO_ADDR'),
'error_url' => env('REMP_SSO_ERROR_URL'),
]
],
]; | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-widgets/src/DataTable.php | Composer/laravel-widgets/src/DataTable.php | <?php
namespace Remp\Widgets;
use Arrilot\Widgets\AbstractWidget;
/**
* Class DataTable
*
* Usage example
*
* {!! Widget::run('DataTable', [
* 'colSettings' => [
* 'title',
* 'pageview_sum' => ['header' => 'pageviews'],
* 'timespent_sum' => ['header' => 'total time read', 'render' => 'duration'],
* 'avg_sum' => ['header' => 'avg', 'render' => 'duration'],
* 'authors[, ].name' => ['header' => 'authors', 'orderable' => false, 'filter' => $authors],
* 'sections[, ].name' => ['header' => 'sections', 'orderable' => false, 'filter' => $sections],
* 'published_at' => ['header' => 'published at', 'render' => 'date'],
* ],
* 'dataSource' => route('articles.dtPageviews'),
* 'displaySearchAndPaging' => true,
* 'order' => [4, 'desc'],
* 'paging' => [[10,30,100], 30],
* 'requestParams' => [
* 'published_from' => '$("[name=\"published_from\"]").data("DateTimePicker").date().set({hour:0,minute:0,second:0,millisecond:0}).toISOString()',
* 'published_to' => '$("[name=\"published_to\"]").data("DateTimePicker").date().set({hour:23,minute:59,second:59,millisecond:999}).toISOString()',
* ],
* 'refreshTriggers' => [
* [
* 'event' => 'dp.change',
* 'selector' => '[name="published_from"]'
* ],
* [
* 'event' => 'dp.change',
* 'selector' => '[name="published_to"]',
* ]
* ],
* ]) !!}
*
* @package Remp\Widgets
*/
class DataTable extends AbstractWidget
{
/**
* The configuration array.
*
* @var array
*/
protected $config = [
'dataSource' => '',
'colSettings' => [],
'order' => [],
'tableId' => '',
'rowActions' => [],
'rowHighlights' => [], // column-value conditions that have to be met to highlight the row
'requestParams' => [], // extra request parameters attached to JSON dataSource request
'refreshTriggers' => [], // external triggers that should execute datatable ajax reload
'displaySearchAndPaging' => true, // display header with search & pagination
'exportColumns' => [],
];
/**
* Treat this method as a controller action.
* Return view() or other content to display.
*/
public function run()
{
$cols = [];
array_walk($this->config['colSettings'], function ($item, $key) use (&$cols) {
if (!is_array($item)) {
throw new DataTableException('Missing configuration array for colum: "' . $item . '"');
}
if (!array_key_exists('priority', $item)) {
throw new DataTableException('Missing "priority" item in DataTable configuration array for column: "' . $key . '"');
}
$cols[] = array_merge([
'name' => $key,
'colIndex' => array_search($key,
array_keys($this->config['colSettings'])
)
], $item);
});
$tableId = md5(json_encode([
$this->config['dataSource'],
$cols,
$this->config['rowActions'],
]));
return view("widgets::data_table", [
'dataSource' => $this->config['dataSource'],
'cols' => $cols,
'tableId' => $tableId,
'rowActions' => $this->config['rowActions'],
'rowHighlights' => $this->config['rowHighlights'],
'order' => $this->config['order'],
'paging' => $this->config['paging'] ?? [[10,25,50,100], 10],
'requestParams' => $this->config['requestParams'],
'refreshTriggers' => $this->config['refreshTriggers'],
'displaySearchAndPaging' => $this->config['displaySearchAndPaging'],
'exportColumns' => $this->config['exportColumns'],
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-widgets/src/DataTableException.php | Composer/laravel-widgets/src/DataTableException.php | <?php
namespace Remp\Widgets;
class DataTableException extends \Exception
{
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-widgets/src/Providers/WidgetServiceProvider.php | Composer/laravel-widgets/src/Providers/WidgetServiceProvider.php | <?php
namespace Remp\Widgets\Providers;
use Illuminate\Support\ServiceProvider;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$path = realpath(__DIR__.'/../../config/laravel-widgets.php');
$config = $this->app['config']->get('laravel-widgets', []);
$this->app['config']->set('laravel-widgets', array_merge(require $path, $config));
$this->loadViewsFrom(__DIR__.'/../resources/views', 'widgets');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-widgets/src/resources/views/data_table.blade.php | Composer/laravel-widgets/src/resources/views/data_table.blade.php | <div class="table-responsive">
@if ($displaySearchAndPaging)
<div class="action-header m-0 palette-White bg clearfix">
<div id="dt-search-{{ $tableId }}" class="ah-search" style="display: none;">
<input placeholder="Search" class="ahs-input b-0" type="text" id="dt-search-{{ $tableId }}">
<i class="ah-search-close zmdi zmdi-long-arrow-left" data-ma-action="ah-search-close"></i>
</div>
<div class="ah-right">
<ul id="dt-nav-{{ $tableId }}" class="ah-actions actions a-alt">
<li><button class="btn palette-Cyan bg ah-search-trigger" data-ma-action="ah-search-open"><i class="zmdi zmdi-search"></i></button></li>
<li class="ah-length dropdown">
<button class="btn palette-Cyan bg" data-toggle="dropdown">{{ $paging[1] }}</button>
<ul class="dropdown-menu dropdown-menu-right">
@foreach($paging[0] as $pageCount)
<li data-value="{{$pageCount}}"><a class="dropdown-item dropdown-item-button">{{$pageCount}}</a></li>
@endforeach
</ul>
</li>
<li class="ah-pagination ah-prev"><button class="btn palette-Cyan bg"><i class="zmdi zmdi-chevron-left"></i></button></li>
<li class="ah-pagination ah-curr"><button class="btn palette-Cyan bg disabled">1</button></li>
<li class="ah-pagination ah-next"><button class="btn palette-Cyan bg"><i class="zmdi zmdi-chevron-right"></i></button></li>
</ul>
<div id="dt-buttons-{{ $tableId }}" class="ah-buttons"></div>
</div>
</div>
@endif
<table id="{{ $tableId }}" class="table table-striped table-bordered table-hover" aria-busy="false">
<thead>
<tr>
@foreach ($cols as $col)
<th>
@if (isset($col['header']))
{{ $col['header'] }}
@else
{{ $col['name'] }}
@endif
@if (isset($col['tooltip']))
<i class="zmdi zmdi-info" data-toggle="tooltip" data-placement="top" title="{{ $col['tooltip'] }}"></i>
@endif
</th>
@endforeach
@if (!empty($rowActions))
<th>actions</th>
@endif
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script>
var filterData = filterData || {};
filterData['{{ $tableId }}'] = {
@foreach ($cols as $col)
@continue(!isset($col['filter']))
'{{ $col['name'] }}': {!! json_encode($col['filter']) !!},
@endforeach
};
$(document).ready(function() {
var dataTable = $('#{{ $tableId }}').DataTable({
'pageLength': {{ $paging[1] }},
'responsive': true,
'columns': [
@foreach ($cols as $col)
{
data: {!! @json($col['name']) !!},
name: {!! @json($col['name']) !!},
@isset($col['orderable'])
orderable: {!! @json($col['orderable']) !!},
@endisset
@isset($col['searchable'])
searchable: {!! @json($col['searchable']) !!},
@endisset
@isset($col['className'])
className: {!! @json($col['className']) !!},
@endisset
@isset($col['priority'])
responsivePriority: {!! @json($col['priority']) !!},
@endisset
@isset($col['visible'])
visible: {!! @json($col['visible']) !!},
@endisset
@isset($col['orderSequence'])
orderSequence: {!! @json($col['orderSequence']) !!},
@endisset
render: function () {
@if (isset($col['render']))
if (typeof $.fn.dataTables.render[{!! @json($col['render']) !!}] === 'function') {
return $.fn.dataTables.render[{!! @json($col['render']) !!}]({!! @json($col['renderParams'] ?? '') !!});
}
if (typeof $.fn.dataTable.render[{!! @json($col['render']) !!}] === 'function') {
return $.fn.dataTable.render[{!! @json($col['render']) !!}]({!! @json($col['renderParams'] ?? '') !!});
}
@endif
return $.fn.dataTable.render.text({!! @json($col['renderParams'] ?? '') !!});
}(),
},
@endforeach
@if (!empty($rowActions))
{
data: 'actions',
name: 'actions',
orderable: false,
searchable: false,
responsivePriority: 1,
render: $.fn.dataTables.render.actions({!! @json($rowActions) !!})
},
@endif
],
'autoWidth': false,
'sDom': 'tr',
'processing': true,
'serverSide': true,
'order': {!! @json($order) !!},
'ajax': {
'url': '{!! $dataSource !!}',
'data': function (data) {
var url = window.location.href
var param = null;
@foreach ($requestParams as $var => $def)
param = '{!! $var !!}';
data[param] = {!! $def !!};
// update browser URL to persist the selection
url = $.fn.dataTables.upsertQueryStringParam(url, param, data[param]);
@endforeach
window.history.pushState(null, null, url);
}
},
'createdRow': function (row, data, index) {
var highlight = true;
@forelse($rowHighlights as $column => $value)
if (!data.hasOwnProperty({!! @json($column) !!}) || data['{{ $column }}'] !== {!! @json($value) !!}) {
highlight = false;
}
@empty
highlight = false;
@endforelse
if (highlight) {
$(row).addClass('highlight');
}
},
'drawCallback': function(settings) {
$.fn.dataTables.pagination(settings, 'dt-nav-{{ $tableId }}');
},
'initComplete': function (a,b,c,d) {
var state = this.api().state().columns;
this.api().columns().every( function () {
var column = this;
var columns = column.settings().init().columns;
var columnDef = columns[column.index()];
if (filterData['{{ $tableId }}'][columnDef.name]) {
$.fn.dataTables.selectFilters(column, filterData['{{ $tableId }}'][columnDef.name], state);
}
} );
}
});
@if (!empty($exportColumns))
new $.fn.dataTable.Buttons(dataTable, {
buttons: [ {
extend: 'csvHtml5',
text: 'Download CSV',
className: 'btn palette-Cyan bg',
exportOptions: {
format: {
header: function (data) {
var html = $.parseHTML(data);
return html[0].data.replace(/(\r\n|\n|\r)/gm,"");
},
body: function (data, row, column, node) {
var $dateItem = $(node).find('.datatable-exportable-item');
if ($dateItem.length) {
return $dateItem.attr('title');
}
return $(node).text().replace(/(\r\n|\n|\r)/gm,"");
}
},
columns: {!! json_encode($exportColumns) !!}
}
} ]
});
dataTable.buttons().container()
.appendTo( $('#dt-buttons-{{ $tableId }}') );
@endif
$.fn.dataTables.search(dataTable, 'dt-search-{{ $tableId }}');
$.fn.dataTables.navigation(dataTable, 'dt-nav-{{ $tableId }}');
$.fn.dataTableExt.errMode = function (e, settings, techNote, message) {
console.warn(techNote);
if (e.jqXHR.status < 500) {
console.error(e.jqXHR.responseJSON);
let message = Object.values(e.jqXHR.responseJSON.errors)
.reduce((acc, errors) => acc.concat(errors), [])
.join(',');
alert('Unable to display one of the data tables: ' + message + ' Is your URL correct?');
} else {
alert('Error while loading data table, try again later please.');
}
};
@foreach ($refreshTriggers as $def)
var triggerEvent = '{!! $def['event'] !!}';
@if ($def['selector'] === 'document')
var triggerElement = $(document);
@else
var triggerElement = $('{!! $def['selector'] !!}');
@endif
triggerElement.on(triggerEvent, function() {
dataTable.draw();
});
@endforeach
});
</script>
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-widgets/config/laravel-widgets.php | Composer/laravel-widgets/config/laravel-widgets.php | <?php
return [
'default_namespace' => 'Remp\Widgets',
'use_jquery_for_ajax_calls' => false,
/*
* Set Ajax widget middleware
*/
'route_middleware' => [],
/*
* Relative path from the base directory to a regular widget stub.
*/
'widget_stub' => 'vendor/arrilot/laravel-widgets/src/Console/stubs/widget.stub',
/*
* Relative path from the base directory to a plain widget stub.
*/
'widget_plain_stub' => 'vendor/arrilot/laravel-widgets/src/Console/stubs/widget_plain.stub',
];
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-helpers/src/laravel_helpers.php | Composer/laravel-helpers/src/laravel_helpers.php | <?php
if (! function_exists('blade_class')) {
function blade_class(array $array)
{
$classes = [];
foreach ($array as $key => $value) {
if (is_int($key) and $value) {
$classes[] = $value;
}
else if ($value) {
$classes[] = $key;
}
}
if ($classes) {
return 'class="'.implode(' ', $classes).'"';
}
return '';
}
}
if (! function_exists('routes_active')) {
function route_active(array $routeNames, string $classes = '', string $activeClasses = '')
{
$currentRouteName = \Route::currentRouteName();
$currentRouteSegmentsCount = count(explode(".", $currentRouteName));
foreach ($routeNames as $routeName) {
$passedRouteSegmentsCount = count(explode(".", $routeName));
if (strpos($currentRouteName, $routeName) === 0 && abs($currentRouteSegmentsCount-$passedRouteSegmentsCount) <= 1) {
return "class=\"{$classes} active {$activeClasses}\"";
}
}
return "class=\"{$classes}\"";
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-helpers/src/Database/MySqlConnection.php | Composer/laravel-helpers/src/Database/MySqlConnection.php | <?php
namespace Remp\LaravelHelpers\Database;
use DateTimeInterface;
class MySqlConnection extends \Illuminate\Database\MySqlConnection
{
/**
* prepareBindings converts any DateTimeInterface objects to the default timezone.
*
* This conversion is necessary so the datetimes are correctly formatted as UTC dates before passed to the DB
* for querying. Otherwise there would be a chance that locally formatted date would get to the query and the
* wouldn't match the expectation.
*
* Application expects the whole communication with database to be in the UTC timezone. Both app timezone and
* database timezone are hardcoded within the app config and not configurable.
*/
public function prepareBindings(array $bindings)
{
foreach ($bindings as $key => $value) {
if ($value instanceof DateTimeInterface) {
$bindings[$key] = $value->setTimezone(new \DateTimeZone(date_default_timezone_get()));
}
}
return parent::prepareBindings($bindings);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-helpers/src/Resources/JsonResource.php | Composer/laravel-helpers/src/Resources/JsonResource.php | <?php
namespace Remp\LaravelHelpers\Resources;
use Illuminate\Http\Resources\Json\JsonResource as LaravelJsonResource;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
class JsonResource extends LaravelJsonResource
{
public function toArray(Request $request)
{
if ($this->resource instanceof \Exception) {
return [
'message' => $this->resource->getMessage(),
];
}
if (!isset($this->resource) || is_array($this->resource)) {
return null;
}
return parent::toArray($request);
}
public function withResponse($request, $response)
{
parent::withResponse($request, $response);
if ($this->resource instanceof \Exception) {
if ($this->resource instanceof HttpException) {
$response->setStatusCode($this->resource->getStatusCode());
} else {
$response->setStatusCode(500);
}
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Composer/laravel-helpers/src/Providers/HelperServiceProvider.php | Composer/laravel-helpers/src/Providers/HelperServiceProvider.php | <?php
namespace Remp\LaravelHelpers\Providers;
use Carbon\FactoryImmutable;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
public function boot()
{
FactoryImmutable::getDefaultInstance()->setToStringFormat(DATE_RFC3339);
Schema::defaultStringLength(191);
$this->responseMacros();
$this->bladeDirectives();
}
public function responseMacros()
{
Response::macro('format', function ($formats) {
if (Request::wantsJson() && array_key_exists('json', $formats)) {
return $formats['json'];
}
return $formats['html'];
});
}
public function bladeDirectives()
{
Blade::directive('yesno', function ($expression) {
return "{$expression} ? 'Yes' : 'No'";
});
Blade::directive('json', function ($expression) {
return "\json_encode({$expression}, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)";
});
Blade::directive('class', function ($expression) {
return "<?php echo blade_class({$expression}); ?>";
});
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/server.php | Beam/server.php | <?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/GorseApi.php | Beam/app/GorseApi.php | <?php
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class GorseApi
{
private const POST_FEEDBACK_URL = '/api/feedback';
private Client $client;
public function __construct()
{
$this->client = new Client([
'base_uri' => config('services.gorse_recommendation.endpoint'),
'headers' => [
'X-API-Key' => config('services.gorse_recommendation.api_key'),
],
]);
}
public function insertFeedback(array $feedback)
{
try {
$result = $this->client->post(self::POST_FEEDBACK_URL, [
'json' => $feedback
]);
return json_decode((string) $result->getBody(), false);
} catch (ClientException $e) {
throw new \Exception($e->getResponse()->getBody()->getContents());
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/GenderBalance.php | Beam/app/GenderBalance.php | <?php
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Support\Facades\Log;
class GenderBalance
{
private Client $client;
public function __construct()
{
$this->client = new Client([
'base_uri' => config('services.azure_computer_vision.endpoint'),
'headers' => [
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => config('services.azure_computer_vision.api_key'),
],
]);
}
public function getGenderCounts($imageUrl): array
{
$totalMenCount = 0;
$totalWomenCount = 0;
$personCropUrls = $this->identifyPeople($imageUrl);
foreach ($personCropUrls as $personCropUrl) {
$isWoman = $this->getPersonGender($personCropUrl);
if (is_null($isWoman)) {
continue;
}
if ($isWoman) {
$totalWomenCount++;
} else {
$totalMenCount++;
}
usleep(5000);//5ms to prevent API usage block
}
return [
'men' => $totalMenCount,
'women' => $totalWomenCount,
];
}
private function identifyPeople($imageUrl): array
{
$imageUrl = preg_replace('/img.projektn.sk\/wp-static/', 'a-static.projektn.sk', $imageUrl);
try {
$response = $this->client->post('computervision/imageanalysis:analyze', [
'query' => [
'api-version' => config('services.azure_computer_vision.api_version'),
'gender-neutral-caption' => 'false',
'features' => 'people',
],
'json' => [
'url' => $imageUrl,
]
]);
} catch (ClientException $exception) {
throw new \Exception($exception->getResponse()->getBody()->getContents());
}
$contents = json_decode($response->getBody()->getContents(), false);
$personCropUrls = [];
foreach ($contents->peopleResult->values as $boundingObj) {
// Have at least 60% confidence rectangle contains person (empirical value)
if ($boundingObj->confidence > 0.6) {
$x = $boundingObj->boundingBox->x;
$y = $boundingObj->boundingBox->y;
$w = $boundingObj->boundingBox->w;
$h = $boundingObj->boundingBox->h;
// Ignore bounding boxes smaller than 40x40px
if ($w <= 40 || $h <= 40) {
continue;
}
$newImageUrl = preg_replace('/a-static.projektn.sk\//', 'img.projektn.sk/wp-static/', $imageUrl);
$newImageUrl .= "?crop=$w,$h,$x,$y";
$personCropUrls[] = $newImageUrl;
}
}
return $personCropUrls;
}
private function getPersonGender($imageUrl): ?int
{
try {
$response = $this->client->post('computervision/imageanalysis:analyze', [
'query' => [
'api-version' => config('services.azure_computer_vision.api_version'),
'gender-neutral-caption' => 'false',
'features' => 'caption,tags',
],
'json' => [
'url' => $imageUrl,
]
]);
} catch (ClientException $exception) {
throw new \Exception($exception->getResponse()->getBody()->getContents());
}
$c = json_decode($response->getBody()->getContents(), false);
$tags = $c->tagsResult->values;
foreach ($tags as $tag) {
// Tags are sorted by confidence
if ($tag->confidence < 0.6) {
break;
}
if ($tag->name === 'man') {
return 0;
}
if ($tag->name === 'woman') {
return 1;
}
}
$caption = $c->captionResult->text;
if (str_contains($caption, 'a man')) {
return 0;
}
if (str_contains($caption, 'a woman')) {
return 1;
}
return null;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/CrmApi.php | Beam/app/CrmApi.php | <?php
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
class CrmApi
{
private const POST_USERS_LIST_URL = '/api/v1/users/list';
private Client $client;
public function __construct()
{
$this->client = new Client([
'base_uri' => config('services.crm.addr'),
'headers' => [
'Authorization' => 'Bearer ' . config('services.crm.api_key'),
],
]);
}
public function getUsersList(array $userIds, int $page = 1)
{
try {
$result = $this->client->post(self::POST_USERS_LIST_URL, [
'form_params' => [
'user_ids' => json_encode(array_values($userIds)),
'with_uuid' => true,
'page' => $page
]
]);
return json_decode((string) $result->getBody(), false);
} catch (ClientException $e) {
throw new \Exception($e->getResponse()->getBody()->getContents());
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Jobs/GenderBalanceJob.php | Beam/app/Jobs/GenderBalanceJob.php | <?php
namespace App\Jobs;
use App\GenderBalance;
use App\Model\ArticleMeta;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Remp\BeamModule\Model\Article;
class GenderBalanceJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public const MEN_COUNT_KEY = 'article_image_men_count';
public const WOMEN_COUNT_KEY = 'article_image_women_count';
private Article $article;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Article $article)
{
$this->article = $article;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(GenderBalance $genderBalance)
{
$result = $genderBalance->getGenderCounts($this->article->image_url);
if (isset($result['men'])) {
ArticleMeta::updateOrCreate(
['article_id' => $this->article->id, 'key' => self::MEN_COUNT_KEY],
['value' => $result['men']]
);
}
if (isset($result['women'])) {
ArticleMeta::updateOrCreate(
['article_id' => $this->article->id, 'key' => self::WOMEN_COUNT_KEY],
['value' => $result['women']]
);
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Model/ArticleMeta.php | Beam/app/Model/ArticleMeta.php | <?php
namespace App\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\BaseModel;
class ArticleMeta extends BaseModel
{
protected $table = 'article_meta';
use HasFactory;
protected $fillable = [
'article_id',
'key',
'value',
];
public function article()
{
return $this->belongsTo(Article::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Http/Controllers/Controller.php | Beam/app/Http/Controllers/Controller.php | <?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Observers/GenderBalanceObserver.php | Beam/app/Observers/GenderBalanceObserver.php | <?php
namespace App\Observers;
use App\Jobs\GenderBalanceJob;
use Remp\BeamModule\Model\Article;
class GenderBalanceObserver
{
public function saved(Article $article)
{
// do nothing if null or same value
if (is_null($article->image_url) || $article->isClean('image_url')) {
return;
}
GenderBalanceJob::dispatch($article);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Console/UploadPageviewsToGorse.php | Beam/app/Console/UploadPageviewsToGorse.php | <?php
namespace App\Console;
use App\CrmApi;
use App\GorseApi;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Remp\Journal\JournalContract;
use Remp\Journal\ListRequest;
class UploadPageviewsToGorse extends Command
{
private const COMMAND = 'gorse:upload';
private const ARTICLE_TIMESPENT_THRESHOLD = 20;
protected $signature = self::COMMAND . ' {--now=}';
protected $description = 'Upload pageviews to Gorse Recommendation Engine';
public function handle(JournalContract $journalContract, GorseApi $gorseApi, CrmApi $crmApi)
{
$now = $this->option('now') ? \Illuminate\Support\Carbon::parse($this->option('now')) : Carbon::now();
$timeBefore = $now->floorMinutes(10);
$timeAfter = (clone $timeBefore)->subMinutes(10);
$urlFilter = explode(',', config('services.gorse_recommendation.url_filter'));
$this->line('');
$this->line(sprintf("Fetching pageviews and timespent data from <info>%s</info> to <info>%s</info>.", $timeAfter, $timeBefore));
$r = ListRequest::from('pageviews')
->setTimeAfter($timeAfter)
->setTimeBefore($timeBefore)
->addInverseFilter('url', ...$urlFilter)
->setLoadTimespent();
$events = $journalContract->list($r);
$filtered = collect($events[0]->pageviews)->filter(function ($event) {
return isset($event->article);
});
$uniqueUserIds = $filtered->map(function ($source) {
return $source->user->id ?? null;
})->filter()->unique()->values()->all();
$userIdToUuidMap = $this->getUserIdToUuidMapping($crmApi, $uniqueUserIds);
$feedback = [];
foreach ($filtered as $source) {
// if there is no mapping to uuid, use browser_id as user_id
$userId = isset($source->user->id)
? ($userIdToUuidMap[$source->user->id] ?? $source->user->browser_id)
: $source->user->browser_id;
$feedback[] = [
'FeedbackType' => 'read',
'ItemId' => $source->article->id,
'Timestamp' => $source->system->time,
'UserId' => $userId,
];
if (isset($source->user->timespent) && $source->user->timespent >= self::ARTICLE_TIMESPENT_THRESHOLD) {
$feedback[] = [
'FeedbackType' => 'timespent',
'ItemId' => $source->article->id,
'Timestamp' => $source->system->time,
'UserId' => $userId,
];
}
}
$gorseResponse = $gorseApi->insertFeedback($feedback);
$this->output->writeln('DONE.');
$this->output->writeln('RowAffected: ' . $gorseResponse->RowAffected);
}
private function getUserIdToUuidMapping(CrmApi $crmApi, array $userIds): array
{
if (empty($userIds)) {
return [];
}
$mapping = [];
$page = 1;
do {
$response = $crmApi->getUsersList($userIds, $page);
foreach ($response->users ?? [] as $user) {
$mapping[$user->id] = $user->uuid;
}
} while (($response->totalPages ?? 0) > $page++);
return $mapping;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Console/MigrateMakeCommand.php | Beam/app/Console/MigrateMakeCommand.php | <?php
namespace App\Console;
use Illuminate\Database\Console\Migrations\BaseCommand;
use Illuminate\Database\Console\Migrations\TableGuesser;
use Illuminate\Database\Migrations\MigrationCreator;
use Illuminate\Support\Composer;
use Illuminate\Support\Str;
class MigrateMakeCommand extends BaseCommand
{
private const DEFAULT_MIGRATION_PATH = 'extensions/beam-module/database/migrations';
protected $signature = 'make:migration {name : The name of the migration}
{--create= : The table to be created}
{--table= : The table to migrate}
{--path= : The location where the migration file should be created (default path is extension/be)}
{--realpath : Indicate any provided migration file paths are pre-resolved absolute paths}
{--fullpath : Output the full path of the migration}';
protected $description = 'Create a new migration file';
public function __construct(
protected MigrationCreator $creator,
protected Composer $composer
) {
parent::__construct();
}
public function handle(): void
{
if (!$this->input->getOption('path')) {
$this->input->setOption('path', self::DEFAULT_MIGRATION_PATH);
}
// It's possible for the developer to specify the tables to modify in this
// schema operation. The developer may also specify if this table needs
// to be freshly created so we can create the appropriate migrations.
$name = Str::snake(trim($this->input->getArgument('name')));
$table = $this->input->getOption('table');
$create = $this->input->getOption('create') ?: false;
// If no table was given as an option but a create option is given then we
// will use the "create" option as the table name. This allows the devs
// to pass a table name into this option as a short-cut for creating.
if (! $table && is_string($create)) {
$table = $create;
$create = true;
}
// Next, we will attempt to guess the table name if this the migration has
// "create" in the name. This will allow us to provide a convenient way
// of creating migrations that create new tables for the application.
if (! $table) {
[$table, $create] = TableGuesser::guess($name);
}
// Now we are ready to write the migration out to disk. Once we've written
// the migration out, we will dump-autoload for the entire framework to
// make sure that the migrations are registered by the class loaders.
$this->writeMigration($name, $table, $create);
$this->composer->dumpAutoloads();
}
protected function writeMigration($name, $table, $create)
{
$file = $this->creator->create(
$name,
$this->getMigrationPath(),
$table,
$create
);
if (! $this->option('fullpath')) {
$file = pathinfo($file, PATHINFO_FILENAME);
}
$this->line("<info>Created Migration:</info> {$file}");
}
protected function getMigrationPath()
{
if (! is_null($targetPath = $this->input->getOption('path'))) {
return ! $this->usingRealPath()
? $this->laravel->basePath().'/'.$targetPath
: $targetPath;
}
return parent::getMigrationPath();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Console/ProcessGenderBalanceCommand.php | Beam/app/Console/ProcessGenderBalanceCommand.php | <?php
namespace App\Console;
use App\GenderBalance;
use App\Jobs\GenderBalanceJob;
use App\Model\ArticleMeta;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Remp\BeamModule\Model\Article;
class ProcessGenderBalanceCommand extends Command
{
protected $signature = 'dennikn:gender-balance
{--from= : Articles published after the date}
{--to= : Articles published before the date}';
protected $description = 'Create a new migration file';
public function handle(GenderBalance $genderBalance): void
{
$articlesQuery = Article::query()->whereNotNull('image_url');
if ($fromOption = $this->option('from')) {
$from = new Carbon($fromOption);
$articlesQuery->whereDate('published_at', '>=', $from);
}
if ($toOption = $this->option('to')) {
$to = new Carbon($toOption);
$articlesQuery->whereDate('published_at', '<', $to);
}
$articles = $articlesQuery->cursor();
$this->output->writeln('Starting gender balance processing:');
/** @var Article $article */
foreach ($articles as $article) {
$this->output->write(" * {$article->url}: ");
try {
GenderBalanceJob::dispatchSync($article);
} catch (\Exception $e) {
$this->output->writeln("ERROR ({$e->getMessage()}");
}
$menCountMeta = ArticleMeta::where('article_id', $article->id)
->where('key', GenderBalanceJob::MEN_COUNT_KEY)
->first()
?->value;
$womenCountMeta = ArticleMeta::where('article_id', $article->id)
->where('key', GenderBalanceJob::WOMEN_COUNT_KEY)
->first()
?->value;
$this->output->writeln("OK ({$menCountMeta}M, {$womenCountMeta}F)");
}
$this->output->writeln('DONE!');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Widgets/GenderBalanceWidget.php | Beam/app/Widgets/GenderBalanceWidget.php | <?php
namespace App\Widgets;
use App\Jobs\GenderBalanceJob;
use App\Model\ArticleMeta;
use Arrilot\Widgets\AbstractWidget;
class GenderBalanceWidget extends AbstractWidget
{
public function run()
{
if (!config('internal.gender_balance_enabled')) {
return '';
}
$article = request()->article;
if (!isset($article)) {
throw new \Exception('GenderBalanceWidget used in view without article.');
}
$menCountMeta = ArticleMeta::where('article_id', $article->id)
->where('key', GenderBalanceJob::MEN_COUNT_KEY)
->first();
$womenCountMeta = ArticleMeta::where('article_id', $article->id)
->where('key', GenderBalanceJob::WOMEN_COUNT_KEY)
->first();
if (isset($menCountMeta, $womenCountMeta) && ((int) $womenCountMeta->value + (int) $menCountMeta->value) > 0) {
$womenPercentage = round(100 * (int) $womenCountMeta->value / ((int) $womenCountMeta->value + (int) $menCountMeta->value), 2);
}
return view('widgets.gender_balance', [
'menCount' => $menCountMeta->value ?? null,
'womenCount' => $womenCountMeta->value ?? null,
'womenPercentage' => $womenPercentage ?? null
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Providers/AppServiceProvider.php | Beam/app/Providers/AppServiceProvider.php | <?php
namespace App\Providers;
use App\Console\MigrateMakeCommand;
use App\Console\ProcessGenderBalanceCommand;
use App\Console\UploadPageviewsToGorse;
use App\Observers\GenderBalanceObserver;
use Illuminate\Database\Connection;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Composer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Remp\BeamModule\Http\Resources\SearchResource;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Config\ConversionRateConfig;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\LaravelHelpers\Database\MySqlConnection;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if (class_exists('Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider')) {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
Paginator::useBootstrapThree();
// Global selector of current property token
if (!config('beam.disable_token_filtering')) {
View::composer('*', function ($view) {
$selectedProperty = resolve(SelectedProperty::class);
$view->with('accountPropertyTokens', $selectedProperty->selectInputData());
});
}
SearchResource::withoutWrapping();
$this->commands([
ProcessGenderBalanceCommand::class,
UploadPageviewsToGorse::class,
]);
if (config('internal.gender_balance_enabled')) {
Article::observe(GenderBalanceObserver::class);
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
/**
* @deprecated Use static `ConversionRateConfig::build()` method instead of resolving from container.
*/
$this->app->singleton(ConversionRateConfig::class);
Connection::resolverFor('mysql', function ($connection, $database, $prefix, $config) {
// Use local resolver to control DateTimeInterface bindings.
return new MySqlConnection($connection, $database, $prefix, $config);
});
$this->app->extend('command.migrate.make', function ($app) {
return new MigrateMakeCommand(
$this->app->get('migration.creator'),
$this->app->get(Composer::class)
);
});
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/app/Providers/WidgetServiceProvider.php | Beam/app/Providers/WidgetServiceProvider.php | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Widget;
class WidgetServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Widget::group('article.show.info')->addWidget('\App\Widgets\GenderBalanceWidget');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/BeamServiceProvider.php | Beam/extensions/beam-module/src/BeamServiceProvider.php | <?php
namespace Remp\BeamModule;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Database\Connection;
use Illuminate\Foundation\Application;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Remp\BeamModule\Console\Commands\AggregateArticlesViews;
use Remp\BeamModule\Contracts\Mailer\Mailer;
use Remp\BeamModule\Contracts\Mailer\MailerContract;
use Remp\BeamModule\Http\Controllers\JournalProxyController;
use Remp\BeamModule\Http\Resources\SearchResource;
use Remp\BeamModule\Model\Config\ConversionRateConfig;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\Journal\DummyTokenProvider;
use Remp\Journal\Journal;
use Remp\Journal\JournalContract;
use Remp\Journal\JournalException;
use Remp\Journal\TokenProvider;
use Remp\LaravelHelpers\Database\MySqlConnection;
class BeamServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
if (config('app.force_https')) {
URL::forceScheme('https');
}
Paginator::useBootstrapThree();
// Global selector of current property token
if (!config('beam.disable_token_filtering')) {
View::composer('*', function ($view) {
$selectedProperty = resolve(SelectedProperty::class);
$view->with('accountPropertyTokens', $selectedProperty->selectInputData());
});
}
SearchResource::withoutWrapping();
$this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
Route::group([
'prefix' => 'api',
'middleware' => 'api',
'as' => 'api.',
], function () {
$this->loadRoutesFrom(__DIR__ . '/../routes/api.php');
});
Route::group([
'middleware' => 'web'
], function () {
$this->loadRoutesFrom(__DIR__ . '/../routes/web.php');
});
$this->loadViewsFrom(__DIR__ . '/../resources/views', 'beam');
$this->registerCommands();
if ($this->app->runningInConsole()) {
$publishPaths = [
__DIR__ . '/../public/' => public_path('vendor/beam'),
__DIR__ .'/../config/beam.php' => config_path('beam.php'),
__DIR__ .'/../config/services.php' => config_path('services.remp.php'),
__DIR__ .'/../config/system.php' => config_path('system.php'),
];
// MySqlSchemaState::load uses hard-coded "mysql" command as well, this might change in the future because
// of the mariadb executable moving away.
$checkCommand = (PHP_OS_FAMILY === 'Windows') ? 'where' : 'which';
$mysqlClientCheck = Process::run("$checkCommand mysql");
if ($mysqlClientCheck->successful()) {
$publishPaths[__DIR__ .'/../database/schema/mysql-schema.sql'] = database_path('schema/mysql-schema.sql');
}
$this->publishes($publishPaths, ['beam-assets', 'laravel-assets']);
$this->app->booted(function () {
$schedule = $this->app->make(Schedule::class);
(new Scheduler())->schedule($schedule);
});
}
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
/**
* @deprecated Use static `ConversionRateConfig::build()` method instead of resolving from container.
*/
$this->app->singleton(ConversionRateConfig::class);
Connection::resolverFor('mysql', function ($connection, $database, $prefix, $config) {
// Use local resolver to control DateTimeInterface bindings.
return new MySqlConnection($connection, $database, $prefix, $config);
});
// RempJournal
$decider = function (
$retries,
Request $request,
Response $response = null,
RequestException $exception = null
) {
if ($retries >= 11) {
return false;
}
if ($exception instanceof JournalException) {
return true;
}
if ($response) {
if ($response->getStatusCode() >= 500) {
return true; // Retry on server errors
}
}
return false;
};
$handlerStack = HandlerStack::create(new CurlHandler());
$handlerStack->push(Middleware::retry($decider));
if (config('beam.disable_token_filtering')) {
$this->app->bind(TokenProvider::class, DummyTokenProvider::class);
} else {
$this->app->bind(TokenProvider::class, SelectedProperty::class);
}
$tokenProvider = $this->app->make(TokenProvider::class);
$this->app->when(AggregateArticlesViews::class)
->needs(JournalContract::class)
->give(function (Application $app) use ($handlerStack, $tokenProvider) {
$client = new Client([
'base_uri' => $app['config']->get('services.remp.beam.segments_addr'),
'handler' => $handlerStack,
]);
$redis = $app->make('redis')->connection()->client();
return new Journal($client, $redis, $tokenProvider);
});
$this->app->bind(JournalContract::class, function (Application $app) use ($tokenProvider) {
$client = new Client([
'base_uri' => $app['config']->get('services.remp.beam.segments_addr'),
]);
$redis = $app->make('redis')->connection()->client();
return new Journal($client, $redis, $tokenProvider);
});
$this->app->when(JournalProxyController::class)
->needs(Client::class)
->give(function (Application $app) {
$client = new Client([
'base_uri' => $app['config']->get('services.remp.beam.segments_addr'),
]);
return $client;
});
// RempMailer
$this->app->bind(MailerContract::class, function ($app) {
$client = new Client([
'base_uri' => $app['config']->get('services.remp.mailer.web_addr'),
'headers' => [
'Authorization' => 'Bearer ' . $app['config']->get('services.remp.mailer.api_token'),
],
]);
return new Mailer($client);
});
}
protected function registerCommands(): void
{
$this->commands([
Console\Commands\AggregateArticlesViews::class,
Console\Commands\AggregateConversionEvents::class,
Console\Commands\AggregatePageviewLoadJob::class,
Console\Commands\AggregatePageviews::class,
Console\Commands\AggregatePageviewTimespentJob::class,
Console\Commands\CompressAggregations::class,
Console\Commands\CompressSnapshots::class,
Console\Commands\ComputeAuthorsSegments::class,
Console\Commands\ComputeSectionSegments::class,
Console\Commands\DashboardRefresh::class,
Console\Commands\DeleteDuplicatePageviews::class,
Console\Commands\DeleteOldAggregations::class,
Console\Commands\ElasticDataRetention::class,
Console\Commands\ElasticWriteAliasRollover::class,
Console\Commands\PostInstallCommand::class,
Console\Commands\ProcessConversionSources::class,
Console\Commands\ProcessPageviewLoyalVisitors::class,
Console\Commands\SendNewslettersCommand::class,
Console\Commands\SnapshotArticlesViews::class,
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Scheduler.php | Beam/extensions/beam-module/src/Scheduler.php | <?php
namespace Remp\BeamModule;
use Illuminate\Console\Scheduling\Schedule;
use Remp\BeamModule\Console\Commands\AggregateArticlesViews;
use Remp\BeamModule\Console\Commands\AggregateConversionEvents;
use Remp\BeamModule\Console\Commands\AggregatePageviews;
use Remp\BeamModule\Console\Commands\CompressAggregations;
use Remp\BeamModule\Console\Commands\CompressSnapshots;
use Remp\BeamModule\Console\Commands\ComputeAuthorsSegments;
use Remp\BeamModule\Console\Commands\ComputeSectionSegments;
use Remp\BeamModule\Console\Commands\DashboardRefresh;
use Remp\BeamModule\Console\Commands\DeleteOldAggregations;
use Remp\BeamModule\Console\Commands\SendNewslettersCommand;
use Remp\BeamModule\Console\Commands\SnapshotArticlesViews;
class Scheduler
{
public function schedule(Schedule $schedule)
{
// Related commands are put into private functions
$this->concurrentsSnapshots($schedule);
$this->aggregations($schedule);
$this->authorSegments($schedule);
$this->dashboard($schedule);
// All other unrelated commands
$schedule->command(SendNewslettersCommand::COMMAND)
->everyMinute()
->runInBackground()
->appendOutputTo(storage_path('logs/send_newsletters.log'));
// Aggregate any conversion events that weren't aggregated before due to Segments API fail
// or other unexpected event
$schedule->command(AggregateConversionEvents::COMMAND)
->dailyAt('3:30')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/aggregate_conversion_events.log'));
}
/**
* Snapshot of concurrents for dashboard + regular compression
* @param Schedule $schedule
*/
private function concurrentsSnapshots(Schedule $schedule)
{
$schedule->command(SnapshotArticlesViews::COMMAND)
->everyMinute()
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/snapshot_articles_views.log'));
$schedule->command(CompressSnapshots::COMMAND)
->dailyAt('02:30')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/compress_snapshots.log'));
}
/**
* Author segments related aggregation and processing
* @param Schedule $schedule
*/
private function authorSegments(Schedule $schedule)
{
$schedule->command(AggregateArticlesViews::COMMAND, [
'--skip-temp-aggregation',
'--step' => config('system.commands.aggregate_article_views.default_step'),
])
->dailyAt('01:00')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/aggregate_article_views.log'));
$schedule->command(ComputeAuthorsSegments::COMMAND)
->dailyAt('02:00')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/compute_author_segments.log'));
$schedule->command(ComputeSectionSegments::COMMAND)
->dailyAt('03:00')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/compute_section_segments.log'));
}
/**
* Pageviews, timespent and session pageviews aggregation and cleanups
* @param Schedule $schedule
*/
private function aggregations(Schedule $schedule)
{
// Aggregates current 20-minute interval (may not be completed yet)
$schedule->command(AggregatePageviews::COMMAND, ["--now='+20 minutes'"])
->everyMinute()
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/aggregate_pageviews.log'));
// Aggregates last 20-minute interval only once
$schedule->command(AggregatePageviews::COMMAND)
->cron('1-59/20 * * * *')
->runInBackground()
->appendOutputTo(storage_path('logs/aggregate_pageviews.log'));
$schedule->command(DeleteOldAggregations::COMMAND)
->dailyAt('00:10')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/delete_old_aggregations.log'));
$schedule->command(CompressAggregations::COMMAND)
->dailyAt('00:20')
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/compress_aggregations.log'));
}
private function dashboard(Schedule $schedule)
{
$schedule->command(DashboardRefresh::COMMAND)
->everyMinute()
->runInBackground()
->withoutOverlapping(config('system.commands_overlapping_expires_at'))
->appendOutputTo(storage_path('logs/dashboard_refresh.log'));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Jobs/AggregateConversionEventsJob.php | Beam/extensions/beam-module/src/Jobs/AggregateConversionEventsJob.php | <?php
namespace Remp\BeamModule\Jobs;
use Remp\BeamModule\Console\Commands\AggregateConversionEvents;
use Remp\BeamModule\Model\Conversion;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;
class AggregateConversionEventsJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $conversion;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Conversion $conversion)
{
$this->conversion = $conversion;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Artisan::call(AggregateConversionEvents::COMMAND, [
'--conversion_id' => $this->conversion->id
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Jobs/ProcessConversionJob.php | Beam/extensions/beam-module/src/Jobs/ProcessConversionJob.php | <?php
namespace Remp\BeamModule\Jobs;
use Remp\BeamModule\Model\Conversion;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ProcessConversionJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $conversion;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Conversion $conversion)
{
$this->conversion = $conversion;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->chain([
new AggregateConversionEventsJob($this->conversion),
new ProcessConversionSourcesJob($this->conversion)
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Jobs/ProcessConversionSourcesJob.php | Beam/extensions/beam-module/src/Jobs/ProcessConversionSourcesJob.php | <?php
namespace Remp\BeamModule\Jobs;
use Remp\BeamModule\Console\Commands\ProcessConversionSources;
use Remp\BeamModule\Model\Conversion;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;
class ProcessConversionSourcesJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $conversion;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Conversion $conversion)
{
$this->conversion = $conversion;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Artisan::call(ProcessConversionSources::COMMAND, [
'--conversion_id' => $this->conversion->id
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ConversionCommerceEventProduct.php | Beam/extensions/beam-module/src/Model/ConversionCommerceEventProduct.php | <?php
namespace Remp\BeamModule\Model;
class ConversionCommerceEventProduct extends BaseModel
{
protected $fillable = [
'product_id',
];
public $timestamps = false;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Account.php | Beam/extensions/beam-module/src/Model/Account.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Remp\BeamModule\Database\Factories\AccountFactory;
class Account extends BaseModel
{
use HasFactory;
protected $fillable = ['uuid', 'name'];
protected static function newFactory(): AccountFactory
{
return AccountFactory::new();
}
public function properties(): HasMany
{
return $this->hasMany(Property::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.