Lettersail: online English school for kids on MODX 3 (templates, chunks, snippets, plugins, scripts)

This commit is contained in:
jimagie committed 2026-11-01 18:30:36 +05:00
commit 3799cf8de5
96 files changed
+4423

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
<?php
require_once '/var/www/html/elements/lib/altcha/autoload.php';
use AltchaOrg\Altcha\Algorithm\Pbkdf2;
use AltchaOrg\Altcha\Altcha;
use AltchaOrg\Altcha\CreateChallengeOptions;
$secret = hash_hmac('sha256', 'lettersail-captcha', (string) $modx->getOption('site_id', null, 'lettersail'));
$challenge = (new Altcha(hmacSignatureSecret: $secret))->createChallenge(
new CreateChallengeOptions(
algorithm: new Pbkdf2(),
cost: 2000,
counter: random_int(1000, 2000),
expiresAt: time() + 1200,
)
)->toArray();
$stamp = (string) (int) (microtime(true) * 1000);
setcookie('ls_t', $stamp . '.' . hash_hmac('sha256', $stamp, $secret), [
'expires' => time() + 86400,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]);
while (ob_get_level()) {
ob_end_clean();
}
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Robots-Tag: noindex');
echo json_encode($challenge, JSON_UNESCAPED_UNICODE);
exit;
+67
View File
@@ -0,0 +1,67 @@
<?php
require_once '/var/www/html/elements/lib/altcha/autoload.php';
use AltchaOrg\Altcha\Algorithm\Pbkdf2;
use AltchaOrg\Altcha\Altcha;
use AltchaOrg\Altcha\Payload;
use AltchaOrg\Altcha\VerifySolutionOptions;
$fail = static function (string $field, string $message) use ($hook): bool {
$hook->addError($field, $message);
return false;
};
$value = static fn(string $key): string => trim((string) $hook->getValue($key));
$host = strtolower((string) parse_url('//' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST));
$origin = (string) ($_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'] ?? '');
$originHost = strtolower((string) parse_url($origin, PHP_URL_HOST));
if ($origin === '' || $host === '' || $originHost !== $host) {
return $fail('guard', 'origin');
}
$secret = hash_hmac('sha256', 'lettersail-captcha', (string) $modx->getOption('site_id', null, 'lettersail'));
$cookie = explode('.', (string) ($_COOKIE['ls_t'] ?? ''), 2);
$opened = (int) ($cookie[0] ?? 0);
if ($opened <= 0 || !hash_equals(hash_hmac('sha256', (string) $opened, $secret), (string) ($cookie[1] ?? ''))) {
return $fail('guard', 'time');
}
$elapsed = (int) (microtime(true) * 1000) - $opened;
if ($elapsed < 2500 || $elapsed > 86400000) {
return $fail('guard', 'time');
}
$digits = preg_replace('/\D/', '', $value('phone'));
if (strlen($digits) < 10 || strlen($digits) > 15) {
return $fail('phone', $modx->lexicon('ls_err_phone'));
}
$raw = $value('altcha');
if ($raw === '' || strlen($raw) > 4000) {
return $fail('guard', 'captcha');
}
try {
$payload = Payload::fromBase64($raw);
$result = (new Altcha(hmacSignatureSecret: $secret))->verifySolution(
new VerifySolutionOptions(algorithm: new Pbkdf2(), payload: $payload)
);
} catch (\Throwable $error) {
return $fail('guard', 'captcha');
}
if (!$result->verified || $payload->challenge->signature === null) {
return $fail('guard', 'captcha');
}
$used = 'altcha_' . hash('sha256', (string) $payload->challenge->signature);
$cacheOptions = [xPDO::OPT_CACHE_KEY => 'lead'];
if ($modx->cacheManager->get($used, $cacheOptions)) {
return $fail('guard', 'captcha');
}
$one = 1;
$modx->cacheManager->set($used, $one, 3600, $cacheOptions);
$hook->setValue('phone', '+' . $digits);
$hook->setValue('sent_at', date('d.m.Y H:i:s'));
$hook->setValue('page', mb_substr((string) ($_SERVER['HTTP_REFERER'] ?? ''), 0, 200));
$hook->setValue('consent_version', (string) $modx->getOption('ls_consent_version', null, '22.10.2026'));
return true;
+21
View File
@@ -0,0 +1,21 @@
<?php
$to = trim((string) $modx->getOption('ls_lead_to'));
if ($to === '') {
return true;
}
$body = $modx->getChunk('ls.lead.mail', $hook->getValues());
$modx->getService('mail', 'mail.modPHPMailer');
$modx->mail->set(MODX\Revolution\Mail\modMail::MAIL_BODY, $body);
$modx->mail->set(MODX\Revolution\Mail\modMail::MAIL_FROM, (string) $modx->getOption('emailsender', null, $to));
$modx->mail->set(MODX\Revolution\Mail\modMail::MAIL_FROM_NAME, 'Lettersail');
$modx->mail->set(MODX\Revolution\Mail\modMail::MAIL_SENDER, (string) $modx->getOption('emailsender', null, $to));
$modx->mail->set(MODX\Revolution\Mail\modMail::MAIL_SUBJECT, 'Заявка на пробный урок');
$modx->mail->address('to', $to);
$modx->mail->setHTML(true);
if (!$modx->mail->send()) {
$modx->log(MODX\Revolution\modX::LOG_LEVEL_ERROR, 'lsLeadMail: письмо не отправлено: ' . $modx->mail->mailer->ErrorInfo);
}
$modx->mail->reset();
return true;
+28
View File
@@ -0,0 +1,28 @@
<?php
$errors = [];
foreach (['name', 'phone', 'age', 'consent', 'guard', 'save'] as $field) {
$message = trim(strip_tags((string) $modx->getPlaceholder('fi.error.' . $field)));
if ($message !== '') {
$errors[$field] = $message;
}
}
$success = (string) $modx->getPlaceholder('fi.success') === '1' && $errors === [];
$general = (string) $modx->getPlaceholder('fi.validation_error_message');
$body = ['ok' => $success];
if (!$success) {
$field = array_key_first($errors) ?? '';
$body['field'] = in_array($field, ['name', 'phone', 'age', 'consent'], true) ? $field : '';
$body['message'] = $field === 'guard' ? $modx->lexicon('ls_err_guard_retry') : ($errors[$field] ?? $modx->lexicon('ls_err_save'));
$body['code'] = $field === 'guard' ? ($errors['guard'] ?? 'guard') : '';
}
while (ob_get_level()) {
ob_end_clean();
}
http_response_code($success ? 200 : 422);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Robots-Tag: noindex');
echo json_encode($body, JSON_UNESCAPED_UNICODE);
exit;
+50
View File
@@ -0,0 +1,50 @@
<?php
$parent = (int) $modx->getOption('ls_leads');
if ($parent <= 0) {
$modx->log(MODX\Revolution\modX::LOG_LEVEL_ERROR, 'lsLeadSave: не задана настройка ls_leads');
$hook->addError('save', $modx->lexicon('ls_err_save'));
return false;
}
$name = (string) $hook->getValue('name');
$phone = (string) $hook->getValue('phone');
$lines = [
'Имя: ' . $name,
'Телефон: ' . $phone,
'Возраст ребёнка: ' . (string) $hook->getValue('age'),
'Согласие на обработку данных: да',
'Дата и время: ' . (string) $hook->getValue('sent_at'),
'Редакция согласия: ' . (string) $hook->getValue('consent_version'),
'Страница отправки: ' . (string) $hook->getValue('page'),
];
$lead = $modx->newObject(MODX\Revolution\modDocument::class);
$lead->fromArray([
'context_key' => 'data',
'parent' => $parent,
'pagetitle' => $name . ', ' . $phone,
'alias' => 'lead-' . date('YmdHis') . '-' . bin2hex(random_bytes(3)),
'introtext' => (string) $hook->getValue('sent_at'),
'content' => implode("\n", $lines),
'published' => false,
'hidemenu' => true,
'searchable' => false,
'richtext' => false,
'template' => 0,
]);
if (!$lead->save()) {
$modx->log(MODX\Revolution\modX::LOG_LEVEL_ERROR, 'lsLeadSave: заявка не сохранена');
$hook->addError('save', $modx->lexicon('ls_err_save'));
return false;
}
$expired = $modx->getIterator(MODX\Revolution\modResource::class, [
'context_key' => 'data',
'parent' => $parent,
'createdon:<' => strtotime('-12 months'),
]);
foreach ($expired as $old) {
$old->remove();
}
return true;
+140
View File
@@ -0,0 +1,140 @@
<?php
$language = (string) $modx->getOption('cultureKey', null, 'ru');
$homeId = (int) $modx->getOption('site_start');
$siteUrl = (string) $modx->makeUrl($homeId, '', '', 'full');
$rootUrl = 'https://' . $modx->getOption('http_host') . '/';
$words = [];
foreach (['trial', 'trial_text', 'plan', 'per_month', 'course', 'teaches', 'job', 'catalog'] as $wordKey) {
$words[$wordKey] = (string) $modx->lexicon('ls_schema_' . $wordKey);
}
$list = static function (string $tv) use ($modx, $homeId): array {
$modx->runSnippet('getImageList', ['tvname' => $tv, 'docid' => $homeId, 'toJsonPlaceholder' => 'ls_schema_list']);
return json_decode((string) $modx->getPlaceholder('ls_schema_list'), true) ?: [];
};
$text = static fn(string $value): string => trim(preg_replace('/\s+/u', ' ', strip_tags($value)));
$home = $modx->getObject(modResource::class, $homeId);
$name = 'Lettersail';
$description = $text((string) $home->get('description'));
$title = $text((string) ($home->get('longtitle') ?: $home->get('pagetitle')));
$offers = [];
foreach ($list('prices') as $row) {
$offers[] = [
'@type' => 'Offer',
'@id' => $siteUrl . '#offer-' . $row['MIGX_id'],
'name' => $words['plan'] . $text($row['title']),
'description' => $text($row['price'] . $words['per_month'] . $row['text']),
'priceSpecification' => [
'@type' => 'UnitPriceSpecification',
'price' => (int) $row['price'],
'priceCurrency' => 'PLN',
'unitCode' => 'MON',
],
];
}
array_unshift($offers, [
'@type' => 'Offer',
'@id' => $siteUrl . '#offer-trial',
'name' => $words['trial'],
'description' => $words['trial_text'],
'price' => 0,
'priceCurrency' => 'PLN',
]);
$courses = [];
foreach ($list('programs') as $index => $row) {
$age = $text($row['title']);
[$min, $max] = array_map('intval', explode('-', $age) + [1 => 0]);
$courses[] = [
'@type' => 'Course',
'name' => sprintf($words['course'], $age),
'description' => $text($row['text']),
'teaches' => $words['teaches'],
'timeRequired' => 'PT45M',
'audience' => ['@type' => 'PeopleAudience', 'suggestedMinAge' => $min, 'suggestedMaxAge' => $max],
'hasCourseInstance' => ['@type' => 'CourseInstance', 'courseMode' => 'online', 'maximumAttendeeCapacity' => 6],
'offers' => $index === 0 ? $offers : array_map(static fn(array $offer): array => ['@id' => $offer['@id']], $offers),
];
}
$teachers = [];
foreach ($list('teachers') as $row) {
$teachers[] = [
'@type' => 'Person',
'name' => $text($row['title']),
'jobTitle' => $words['job'] . ($language === 'ru' ? $text($row['age']) : lcfirst($text($row['age']))),
'description' => $text($row['text']),
'image' => $rootUrl . ltrim((string) $row['photo'], '/'),
];
}
$reviews = [];
foreach ($list('reviews') as $row) {
$reviews[] = [
'@type' => 'Review',
'author' => ['@type' => 'Person', 'name' => $text($row['title'])],
'reviewBody' => $text($row['text']),
'reviewRating' => ['@type' => 'Rating', 'ratingValue' => (int) $row['rating'], 'bestRating' => 5, 'worstRating' => 1],
];
}
$questions = [];
foreach ($list('faq') as $row) {
$questions[] = [
'@type' => 'Question',
'name' => $text($row['title']),
'acceptedAnswer' => ['@type' => 'Answer', 'text' => $text($row['text'])],
];
}
$school = [
'@type' => 'EducationalOrganization',
'@id' => $siteUrl . '#school',
'name' => $name,
'url' => $siteUrl,
'description' => $description,
'logo' => ['@type' => 'ImageObject', 'url' => $rootUrl . 'assets/site/icon-512.png', 'width' => 512, 'height' => 512],
'contactPoint' => [
'@type' => 'ContactPoint',
'contactType' => 'customer support',
'email' => (string) $modx->getOption('ls_contact_email'),
'availableLanguage' => $language,
],
'knowsLanguage' => array_values(array_unique(['en', $language])),
'hasOfferCatalog' => ['@type' => 'OfferCatalog', 'name' => $words['catalog'], 'itemListElement' => $courses],
'employee' => $teachers,
'review' => $reviews,
];
$blocks = [
[
'@type' => 'WebPage',
'@id' => $siteUrl . '#webpage',
'url' => $siteUrl,
'name' => $title,
'description' => $description,
'inLanguage' => $language,
'mainEntity' => $school,
],
[
'@type' => 'WebSite',
'@id' => $siteUrl . '#website',
'url' => $siteUrl,
'name' => $name,
'inLanguage' => $language,
],
[
'@type' => 'FAQPage',
'@id' => $siteUrl . '#faq',
'inLanguage' => $language,
'mainEntity' => $questions,
],
];
$output = '';
foreach ($blocks as $block) {
$output .= '<script type="application/ld+json">' . json_encode(['@context' => 'https://schema.org'] + $block, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG) . "</script>\n";
}
return $output;
+4
View File
@@ -0,0 +1,4 @@
<?php
$rating = max(1, min(5, (int) ($rating ?? 5)));
return '<span class="rev__stars" role="img" aria-label="' . $modx->lexicon('ls_rating_label', ['n' => $rating]) . '">' . str_repeat('★', $rating) . '</span>';
+18
View File
@@ -0,0 +1,18 @@
<?php
$text = trim((string) ($text ?? ''));
$mode = $mode ?? 'line';
$escape = static fn(string $value): string => htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
if ($mode === 'words') {
$words = preg_split('/\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
$out = [];
foreach ($words as $index => $word) {
$out[] = '<span class="kick-word" style="--w:' . $index . '">' . $escape($word) . '</span>';
}
return implode(' ', $out);
}
$lines = preg_split('/\R/u', $text);
$lines = array_map(static fn(string $line): string => $escape(trim($line)), $lines);
return implode($mode === 'br' ? '<br>' : ' ', $lines);
+18
View File
@@ -0,0 +1,18 @@
<?php
$data = [
'lang' => (string) $modx->getOption('cultureKey'),
'close' => $modx->lexicon('ls_close'),
'name' => $modx->lexicon('ls_err_name'),
'phone' => $modx->lexicon('ls_err_phone'),
'age' => $modx->lexicon('ls_err_age'),
'consent' => $modx->lexicon('ls_err_consent'),
'guard' => $modx->lexicon('ls_err_guard'),
'limit' => $modx->lexicon('ls_err_limit'),
'network' => $modx->lexicon('ls_err_network'),
'docs' => [
$modx->makeUrl((int) $modx->getOption('ls_privacy_id'), '', '', 'full'),
$modx->makeUrl((int) $modx->getOption('ls_consent_id'), '', '', 'full'),
],
];
return '<script type="application/json" data-ui>' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG) . '</script>';
+2
View File
@@ -0,0 +1,2 @@
<?php
return date('Y');