Compare commits

...

7 Commits

11 changed files with 257 additions and 49 deletions

2
DEV_BRANCH_TEST.txt Normal file
View File

@ -0,0 +1,2 @@
Test commit on dev branch.
Created to verify dev branch workflow.

View File

@ -5,8 +5,6 @@
- `index.php` — публичная витрина (разделы, тематики, карточки фото, комментарии),
- `admin.php?token=...` — закрытая админка (управление разделами/тематиками/фото/пользователями/комментариями/настройками).
`index-mysql.php` и `admin-mysql.php` оставлены как алиасы для обратной совместимости.
## Что умеет проект
- Иерархия каталога: разделы + тематики (2 уровня).
@ -40,8 +38,6 @@
photo.andr33v.ru/
├─ index.php # публичная витрина
├─ admin.php # админка по токену
├─ index-mysql.php # alias -> index.php
├─ admin-mysql.php # alias -> admin.php
├─ style.css # базовые стили
├─ favicon.svg
├─ config.php.example # шаблон конфига БД и деплоя
@ -87,6 +83,12 @@ cp config.php.example config.php
2. Заполни доступы к БД в `config.php`.
Для деплоя из админки в `config.php` можно задать:
- `deploy.remote_name` (обычно `origin`),
- `deploy.remote_url` (по умолчанию `git@github.com:wrkandreev/reframe.git`),
- `deploy.branch` (`main` или `dev`).
3. Создай `secrets.php`:
```bash
@ -159,15 +161,16 @@ php scripts/generate_thumbs.php
Деплой запускается из админки (вкладка `Настройки`):
- кнопка `Проверить обновления` делает `git fetch` и сравнивает `HEAD` с `origin/<branch>`,
- кнопка `Проверить обновления` делает `git fetch` и сравнивает `HEAD` с `<remote>/<branch>`,
- если локальная ветка отстает и не расходится (`behind > 0`, `ahead = 0`) — показывается кнопка `Обновить проект`.
Скрипт `scripts/deploy.sh`:
1. делает `git fetch --all --prune`,
2. переключает код на `origin/<branch>` через `git reset --hard`,
3. запускает миграции `php scripts/migrate.php`,
4. сохраняет runtime-папки (`photos`, `thumbs`, `data`).
1. настраивает remote из `REMOTE_NAME`/`REMOTE_URL` (если передан `REMOTE_URL`),
2. делает `git fetch <remote> <branch> --prune`,
3. переключает код на `<remote>/<branch>` через `git reset --hard`,
4. запускает миграции `php scripts/migrate.php`,
5. сохраняет runtime-папки (`photos`, `thumbs`, `data`).
Важно: деплой-скрипт перетирает рабочие изменения в репозитории на сервере.

View File

@ -1,3 +0,0 @@
<?php
// Backward-compat alias
require __DIR__ . '/admin.php';

View File

@ -48,6 +48,11 @@ if ($tokenExpected === '' || !hash_equals($tokenExpected, $tokenIncoming)) {
}
$deployConfig = (array)($config['deploy'] ?? []);
$deployRemoteName = trim((string)($deployConfig['remote_name'] ?? 'origin'));
if ($deployRemoteName === '') {
$deployRemoteName = 'origin';
}
$deployRemoteUrl = trim((string)($deployConfig['remote_url'] ?? ''));
$allowedDeployBranches = ['main', 'dev'];
$defaultDeployBranch = trim((string)($deployConfig['branch'] ?? 'main'));
if (!in_array($defaultDeployBranch, $allowedDeployBranches, true)) {
@ -83,6 +88,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
$result = adminHandlePostAction($action, $isAjax, __DIR__, [
'remote_name' => $deployRemoteName,
'remote_url' => $deployRemoteUrl,
'branch' => $deployBranch,
'script' => $deployScript,
'php_bin' => $deployPhpBin,
@ -285,10 +292,12 @@ function assetUrl(string $path): string { $f=__DIR__ . '/' . ltrim($path,'/'); $
<hr style="border:none;border-top:1px solid #eee;margin:12px 0">
<h4 style="margin:0 0 8px">Обновление проекта</h4>
<p class="small" style="margin:0">Выбери ветку для проверки и обновления: <strong><?= h($deployBranch) ?></strong></p>
<p class="small" style="margin:0">Remote: <strong><?= h($deployRemoteName) ?></strong><?= $deployRemoteUrl !== '' ? ' (' . h($deployRemoteUrl) . ')' : '' ?></p>
<p class="small" style="margin:4px 0 0">Выбери ветку для проверки и обновления: <strong><?= h($deployBranch) ?></strong></p>
<?php if (is_array($deployStatus)): ?>
<?php $deployState = (string)($deployStatus['state'] ?? ''); ?>
<?php $statusRemoteName = (string)($deployStatus['remote_name'] ?? $deployRemoteName); ?>
<?php $statusBranch = (string)($deployStatus['branch'] ?? $deployBranch); ?>
<?php $deployStateMessage = $deployState === 'update_available'
? 'Доступна новая версия.'
@ -299,7 +308,7 @@ function assetUrl(string $path): string { $f=__DIR__ . '/' . ltrim($path,'/'); $
: 'Ветка расходится с origin. Нужна ручная синхронизация.')); ?>
<div class="<?= in_array($deployState, ['local_ahead', 'diverged'], true) ? 'err' : 'ok' ?>" style="margin-top:8px">
<?= h($deployStateMessage) ?><br>
<span class="small">Локально: <?= h((string)($deployStatus['local_ref'] ?? '-')) ?> · origin/<?= h($statusBranch) ?>: <?= h((string)($deployStatus['remote_ref'] ?? '-')) ?> · behind: <?= (int)($deployStatus['behind'] ?? 0) ?> · ahead: <?= (int)($deployStatus['ahead'] ?? 0) ?></span>
<span class="small">Локально: <?= h((string)($deployStatus['local_ref'] ?? '-')) ?> · <?= h($statusRemoteName) ?>/<?= h($statusBranch) ?>: <?= h((string)($deployStatus['remote_ref'] ?? '-')) ?> · behind: <?= (int)($deployStatus['behind'] ?? 0) ?> · ahead: <?= (int)($deployStatus['ahead'] ?? 0) ?></span>
</div>
<?php endif; ?>

View File

@ -9,6 +9,8 @@ return [
'charset' => 'utf8mb4',
],
'deploy' => [
'remote_name' => 'origin',
'remote_url' => 'git@github.com:wrkandreev/reframe.git',
'branch' => 'main',
'script' => __DIR__ . '/scripts/deploy.sh',
'php_bin' => 'php',

View File

@ -1,3 +0,0 @@
<?php
// Backward-compat alias
require __DIR__ . '/index.php';

123
index.php
View File

@ -27,13 +27,21 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') ==
|| str_contains((string)($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json');
$commentSaved = false;
$savedComment = null;
$errorMessage = '';
$errorCode = 422;
if ($token !== '' && $photoId > 0 && $text !== '') {
$u = commenterByToken($token);
if ($u) {
commentAdd($photoId, (int)$u['id'], limitText($text, 1000));
try {
$savedComment = commentAdd($photoId, (int)$u['id'], limitText($text, 1000));
$commentSaved = true;
} catch (Throwable $e) {
error_log('Comment add failed: ' . $e->getMessage());
$errorMessage = 'Не удалось отправить комментарий.';
$errorCode = 500;
}
} else {
$errorMessage = 'Ссылка для комментариев недействительна.';
}
@ -44,11 +52,20 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (string)($_POST['action'] ?? '') ==
if ($isAjax) {
header('Content-Type: application/json; charset=utf-8');
if ($commentSaved) {
echo json_encode(['ok' => true, 'message' => 'Ваш комментарий отправлен.'], JSON_UNESCAPED_UNICODE);
echo json_encode([
'ok' => true,
'message' => 'Ваш комментарий отправлен.',
'comment' => $savedComment ? [
'id' => (int)($savedComment['id'] ?? 0),
'comment_text' => (string)($savedComment['comment_text'] ?? ''),
'created_at' => (string)($savedComment['created_at'] ?? ''),
'display_name' => (string)($savedComment['display_name'] ?? 'Пользователь'),
] : null,
], JSON_UNESCAPED_UNICODE);
exit;
}
http_response_code(422);
http_response_code($errorCode);
echo json_encode(['ok' => false, 'message' => $errorMessage !== '' ? $errorMessage : 'Не удалось отправить комментарий.'], JSON_UNESCAPED_UNICODE);
exit;
}
@ -674,7 +691,7 @@ function outputWatermarked(string $path, string $mime): never
<h3 class="detail-comments-title">Комментарии</h3>
<?php if ($viewer): ?>
<form class="js-comment-form comment-form" method="post" action="?photo_id=<?= (int)$photo['id'] ?><?= $isTopicMode ? '&topic_id=' . $activeTopicId : '&section_id=' . (int)$detailSectionId ?><?= $viewerToken!=='' ? '&viewer=' . urlencode($viewerToken) : '' ?>">
<form class="js-comment-form comment-form" method="post" action="" data-script-path="<?= h((string)($_SERVER['SCRIPT_NAME'] ?? '/index.php')) ?>">
<input type="hidden" name="action" value="add_comment">
<input type="hidden" name="photo_id" value="<?= (int)$photo['id'] ?>">
<input type="hidden" name="section_id" value="<?= $isSectionMode ? (int)$detailSectionId : 0 ?>">
@ -688,9 +705,11 @@ function outputWatermarked(string $path, string $mime): never
<p class="muted">Комментарии может оставлять только пользователь с персональной ссылкой.</p>
<?php endif; ?>
<div class="js-comments-list">
<?php foreach($comments as $c): ?>
<div class="cmt"><strong><?= h((string)($c['display_name'] ?? 'Пользователь')) ?></strong> <span class="muted">· <?= h((string)$c['created_at']) ?></span><br><?= nl2br(h((string)$c['comment_text'])) ?></div>
<?php endforeach; ?>
</div>
<?php if ($detailTotal > 0): ?>
<div class="pager">
@ -889,6 +908,38 @@ function outputWatermarked(string $path, string $mime): never
const commentForm = commentTextarea ? commentTextarea.closest('.js-comment-form') : null;
const commentFeedback = commentForm ? commentForm.querySelector('.js-comment-feedback') : null;
const commentSubmitButton = commentForm ? commentForm.querySelector('button[type="submit"]') : null;
const commentsList = document.querySelector('.js-comments-list');
const prependComment = (comment) => {
if (!commentsList || !comment || typeof comment !== 'object') {
return;
}
const item = document.createElement('div');
item.className = 'cmt';
const author = document.createElement('strong');
author.textContent = String(comment.display_name || 'Пользователь');
const meta = document.createElement('span');
meta.className = 'muted';
meta.textContent = `· ${String(comment.created_at || '')}`;
item.appendChild(author);
item.append(' ');
item.appendChild(meta);
item.appendChild(document.createElement('br'));
const lines = String(comment.comment_text || '').split(/\r\n|\r|\n/);
lines.forEach((line, index) => {
item.append(document.createTextNode(line));
if (index < lines.length - 1) {
item.appendChild(document.createElement('br'));
}
});
commentsList.prepend(item);
};
const setCommentFeedback = (message, isError) => {
if (!commentFeedback) {
@ -945,7 +996,33 @@ function outputWatermarked(string $path, string $mime): never
setCommentFeedback('', false);
try {
const response = await fetch(commentForm.action, {
const endpoints = [];
const pushEndpoint = (url) => {
if (!url) {
return;
}
if (!endpoints.includes(url)) {
endpoints.push(url);
}
};
pushEndpoint(commentForm.action || window.location.href);
const scriptPath = String(commentForm.dataset.scriptPath || '').trim();
if (scriptPath !== '') {
const fallback = new URL(scriptPath, window.location.origin);
fallback.search = window.location.search;
pushEndpoint(fallback.toString());
}
let response = null;
let raw = '';
let payload = null;
let usedEndpoint = '';
for (const endpoint of endpoints) {
usedEndpoint = endpoint;
response = await fetch(endpoint, {
method: 'POST',
body: formData,
headers: {
@ -954,12 +1031,42 @@ function outputWatermarked(string $path, string $mime): never
}
});
const payload = await response.json().catch(() => null);
if (!response.ok || !payload || payload.ok !== true) {
throw new Error(payload && payload.message ? String(payload.message) : 'Не удалось отправить комментарий.');
raw = await response.text();
try {
payload = JSON.parse(raw);
} catch {
payload = null;
}
if (response.status === 404 && endpoints[endpoints.length - 1] !== endpoint) {
continue;
}
break;
}
if (!response) {
throw new Error('Не удалось отправить комментарий.');
}
if (!payload) {
if (response.ok) {
window.location.reload();
return;
}
const rawMessage = raw.trim() !== '' ? raw.slice(0, 220) : '';
throw new Error(rawMessage !== '' ? `HTTP ${response.status}: ${rawMessage}` : `HTTP ${response.status}: ${usedEndpoint}`);
}
if (!response.ok || payload.ok !== true) {
throw new Error(payload.message ? String(payload.message) : 'Не удалось отправить комментарий.');
}
setCommentFeedback(payload.message || 'Ваш комментарий отправлен.', false);
if (payload.comment) {
prependComment(payload.comment);
}
commentTextarea.value = '';
commentTextarea.focus();
} catch (error) {

View File

@ -2,21 +2,26 @@
declare(strict_types=1);
function adminCheckForUpdates(string $projectRoot, string $branch): array
function adminCheckForUpdates(string $projectRoot, string $branch, string $remoteName = 'origin', string $remoteUrl = ''): array
{
if (!is_dir($projectRoot . '/.git')) {
throw new RuntimeException('Репозиторий не найден: .git отсутствует');
}
$fetch = adminRunShellCommand('git fetch origin ' . escapeshellarg($branch) . ' --prune', $projectRoot);
$remoteName = adminNormalizeRemoteName($remoteName);
adminEnsureRemote($projectRoot, $remoteName, $remoteUrl);
$remoteRef = $remoteName . '/' . $branch;
$fetch = adminRunShellCommand('git fetch ' . escapeshellarg($remoteName) . ' ' . escapeshellarg($branch) . ' --prune', $projectRoot);
if ($fetch['code'] !== 0) {
throw new RuntimeException('Не удалось обновить данные из origin: ' . adminTailOutput($fetch['output']));
throw new RuntimeException('Не удалось обновить данные из ' . $remoteName . ': ' . adminTailOutput($fetch['output']));
}
$local = adminRunShellCommand('git rev-parse --short=12 HEAD', $projectRoot);
$remote = adminRunShellCommand('git rev-parse --short=12 origin/' . escapeshellarg($branch), $projectRoot);
$behindRaw = adminRunShellCommand('git rev-list --count HEAD..origin/' . escapeshellarg($branch), $projectRoot);
$aheadRaw = adminRunShellCommand('git rev-list --count origin/' . escapeshellarg($branch) . '..HEAD', $projectRoot);
$remote = adminRunShellCommand('git rev-parse --short=12 ' . escapeshellarg($remoteRef), $projectRoot);
$behindRaw = adminRunShellCommand('git rev-list --count HEAD..' . escapeshellarg($remoteRef), $projectRoot);
$aheadRaw = adminRunShellCommand('git rev-list --count ' . escapeshellarg($remoteRef) . '..HEAD', $projectRoot);
if ($local['code'] !== 0 || $remote['code'] !== 0 || $behindRaw['code'] !== 0 || $aheadRaw['code'] !== 0) {
throw new RuntimeException('Не удалось определить состояние ветки');
@ -36,6 +41,7 @@ function adminCheckForUpdates(string $projectRoot, string $branch): array
return [
'state' => $state,
'remote_name' => $remoteName,
'branch' => $branch,
'local_ref' => trim($local['output']),
'remote_ref' => trim($remote['output']),
@ -45,15 +51,19 @@ function adminCheckForUpdates(string $projectRoot, string $branch): array
];
}
function adminRunDeployScript(string $projectRoot, string $branch, string $scriptPath, string $phpBin): array
function adminRunDeployScript(string $projectRoot, string $branch, string $scriptPath, string $phpBin, string $remoteName = 'origin', string $remoteUrl = ''): array
{
if (!is_file($scriptPath)) {
throw new RuntimeException('Скрипт деплоя не найден: ' . $scriptPath);
}
$remoteName = adminNormalizeRemoteName($remoteName);
$run = adminRunShellCommand('bash ' . escapeshellarg($scriptPath), $projectRoot, [
'BRANCH' => $branch,
'PHP_BIN' => $phpBin,
'REMOTE_NAME' => $remoteName,
'REMOTE_URL' => $remoteUrl,
]);
return [
@ -63,6 +73,50 @@ function adminRunDeployScript(string $projectRoot, string $branch, string $scrip
];
}
function adminEnsureRemote(string $projectRoot, string $remoteName, string $remoteUrl): void
{
$getRemote = adminRunShellCommand('git remote get-url ' . escapeshellarg($remoteName), $projectRoot);
if ($getRemote['code'] !== 0) {
if ($remoteUrl === '') {
throw new RuntimeException('Remote ' . $remoteName . ' не найден');
}
$add = adminRunShellCommand('git remote add ' . escapeshellarg($remoteName) . ' ' . escapeshellarg($remoteUrl), $projectRoot);
if ($add['code'] !== 0) {
throw new RuntimeException('Не удалось добавить remote ' . $remoteName . ': ' . adminTailOutput($add['output']));
}
return;
}
if ($remoteUrl === '') {
return;
}
$currentUrl = trim($getRemote['output']);
if ($currentUrl === $remoteUrl) {
return;
}
$set = adminRunShellCommand('git remote set-url ' . escapeshellarg($remoteName) . ' ' . escapeshellarg($remoteUrl), $projectRoot);
if ($set['code'] !== 0) {
throw new RuntimeException('Не удалось обновить remote ' . $remoteName . ': ' . adminTailOutput($set['output']));
}
}
function adminNormalizeRemoteName(string $remoteName): string
{
$remoteName = trim($remoteName);
if ($remoteName === '') {
return 'origin';
}
if (!preg_match('/^[A-Za-z0-9._-]+$/', $remoteName)) {
throw new RuntimeException('Некорректное имя remote');
}
return $remoteName;
}
function adminRunShellCommand(string $command, string $cwd, array $env = []): array
{
$envPrefix = '';

View File

@ -144,8 +144,10 @@ function adminHandlePostAction(string $action, bool $isAjax, string $projectRoot
}
case 'check_updates': {
$remoteName = (string)($deployOptions['remote_name'] ?? 'origin');
$remoteUrl = (string)($deployOptions['remote_url'] ?? '');
$branch = (string)($deployOptions['branch'] ?? 'main');
$deployStatus = adminCheckForUpdates($projectRoot, $branch);
$deployStatus = adminCheckForUpdates($projectRoot, $branch, $remoteName, $remoteUrl);
$state = (string)($deployStatus['state'] ?? '');
if ($state === 'update_available') {
@ -162,11 +164,13 @@ function adminHandlePostAction(string $action, bool $isAjax, string $projectRoot
}
case 'deploy_updates': {
$remoteName = (string)($deployOptions['remote_name'] ?? 'origin');
$remoteUrl = (string)($deployOptions['remote_url'] ?? '');
$branch = (string)($deployOptions['branch'] ?? 'main');
$scriptPath = (string)($deployOptions['script'] ?? ($projectRoot . '/scripts/deploy.sh'));
$phpBin = (string)($deployOptions['php_bin'] ?? 'php');
$deployStatus = adminCheckForUpdates($projectRoot, $branch);
$deployStatus = adminCheckForUpdates($projectRoot, $branch, $remoteName, $remoteUrl);
if (!(bool)($deployStatus['can_deploy'] ?? false)) {
$state = (string)($deployStatus['state'] ?? '');
if ($state === 'up_to_date') {
@ -182,13 +186,13 @@ function adminHandlePostAction(string $action, bool $isAjax, string $projectRoot
throw new RuntimeException('Нельзя применить обновление в текущем состоянии ветки.');
}
$deployResult = adminRunDeployScript($projectRoot, $branch, $scriptPath, $phpBin);
$deployResult = adminRunDeployScript($projectRoot, $branch, $scriptPath, $phpBin, $remoteName, $remoteUrl);
$deployOutput = (string)($deployResult['output'] ?? '');
if (!(bool)($deployResult['ok'] ?? false)) {
throw new RuntimeException('Деплой завершился с ошибкой: ' . ($deployOutput !== '' ? $deployOutput : ('код ' . (int)($deployResult['code'] ?? 1))));
}
$deployStatus = adminCheckForUpdates($projectRoot, $branch);
$deployStatus = adminCheckForUpdates($projectRoot, $branch, $remoteName, $remoteUrl);
$message = 'Обновление выполнено.';
break;
}

View File

@ -360,10 +360,31 @@ function commentsByPhoto(int $photoId): array
return $st->fetchAll();
}
function commentAdd(int $photoId, int $userId, string $text): void
function commentAdd(int $photoId, int $userId, string $text): array
{
$st = db()->prepare('INSERT INTO photo_comments(photo_id, user_id, comment_text) VALUES (:p,:u,:t)');
$st->execute(['p' => $photoId, 'u' => $userId, 't' => $text]);
$commentId = (int)db()->lastInsertId();
$detail = db()->prepare('SELECT c.*, u.display_name
FROM photo_comments c
LEFT JOIN comment_users u ON u.id=c.user_id
WHERE c.id=:id');
$detail->execute(['id' => $commentId]);
$row = $detail->fetch();
if (!$row) {
return [
'id' => $commentId,
'photo_id' => $photoId,
'user_id' => $userId,
'comment_text' => $text,
'created_at' => date('Y-m-d H:i:s'),
'display_name' => 'Пользователь',
];
}
return $row;
}
function commentDelete(int $id): void

View File

@ -6,10 +6,14 @@ set -euo pipefail
# bash scripts/deploy.sh
# Optional env:
# APP_DIR=/home/USER/www/photo-gallery
# REMOTE_NAME=origin
# REMOTE_URL=git@github.com:wrkandreev/reframe.git
# BRANCH=main
# PHP_BIN=php
APP_DIR="${APP_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
REMOTE_NAME="${REMOTE_NAME:-origin}"
REMOTE_URL="${REMOTE_URL:-}"
BRANCH="${BRANCH:-main}"
PHP_BIN="${PHP_BIN:-php}"
@ -41,8 +45,16 @@ if [ "$current_branch" != "$BRANCH" ]; then
git checkout "$BRANCH"
fi
git fetch --all --prune
git reset --hard "origin/$BRANCH"
if [ -n "$REMOTE_URL" ]; then
if git remote get-url "$REMOTE_NAME" >/dev/null 2>&1; then
git remote set-url "$REMOTE_NAME" "$REMOTE_URL"
else
git remote add "$REMOTE_NAME" "$REMOTE_URL"
fi
fi
git fetch "$REMOTE_NAME" "$BRANCH" --prune
git reset --hard "$REMOTE_NAME/$BRANCH"
# Run DB migrations required by current code
"$PHP_BIN" scripts/migrate.php