shkola/wp-content/themes/dekart/deploy-runner.php
2026-10-02 01:27:48 +00:00

348 lines
13 KiB
PHP
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Deploy Runner — HTTP-triggered migration executor (token-gated)
* Usage: https://site.com/wp-content/themes/dekart/deploy-runner.php?token=SECRET&migrate=003
* (or send the secret in the `X-Deploy-Token` header)
*
* Self-destructs after execution (renames to .done).
* Requires wp-config.php for DB credentials.
*/
// Prevent WordPress from intercepting
define('WP_USE_THEMES', false);
// Load WordPress config for DB credentials (needed by the token gate below).
$wp_config_path = dirname(__FILE__) . '/../../../wp-config.php';
if (!file_exists($wp_config_path)) {
// Try parent directory
$wp_config_path = dirname(__FILE__) . '/../../wp-config.php';
}
if (!file_exists($wp_config_path)) {
$wp_config_path = dirname(__FILE__) . '/../wp-config.php';
}
require_once $wp_config_path;
// ─── Security: token gate (fail closed) ──────────────────────────────
// The endpoint runs DB/theme migrations, so it must never be reachable
// anonymously. The secret is taken from, in order: DEPLOY_RUNNER_TOKEN
// (env var or wp-config constant), or the wp_options row
// `dekart_deploy_token`. With no secret configured, every request is
// denied with 404 — the endpoint stays closed until a secret is set.
// Set the option once (recommended, no file edits):
// wp option update dekart_deploy_token "$(openssl rand -hex 24)"
$dk_expected = '';
if (getenv('DEPLOY_RUNNER_TOKEN')) {
$dk_expected = (string) getenv('DEPLOY_RUNNER_TOKEN');
} elseif (defined('DEPLOY_RUNNER_TOKEN')) {
$dk_expected = (string) DEPLOY_RUNNER_TOKEN;
} else {
$dk_conn = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($dk_conn) {
$dk_sql = "SELECT option_value FROM wp_options WHERE option_name = 'dekart_deploy_token' LIMIT 1";
if ($dk_res = @mysqli_query($dk_conn, $dk_sql)) {
$dk_row = mysqli_fetch_assoc($dk_res);
$dk_expected = isset($dk_row['option_value']) ? (string) $dk_row['option_value'] : '';
}
mysqli_close($dk_conn);
}
}
$dk_given = isset($_GET['token'])
? (string) $_GET['token']
: (isset($_SERVER['HTTP_X_DEPLOY_TOKEN']) ? (string) $_SERVER['HTTP_X_DEPLOY_TOKEN'] : '');
if ($dk_expected === '' || !hash_equals($dk_expected, $dk_given)) {
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
exit("Not found\n");
}
$allowed_migrations = ['003', '004', '005', '006'];
$migrate = isset($_GET['migrate']) ? $_GET['migrate'] : '';
if (!in_array($migrate, $allowed_migrations)) {
header('Content-Type: text/plain');
die("Usage: ?token=SECRET&migrate=003 (allowed: " . implode(', ', $allowed_migrations) . ")\n");
}
header('Content-Type: text/plain; charset=utf-8');
echo "=== Deploy Runner: migration $migrate ===\n\n";
// ─── Shared helpers ──────────────────────────────────────────────────
function dp_get_wpdb()
{
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$conn) {
die("DB connection failed: " . mysqli_connect_error() . "\n");
}
echo "Connected to DB: " . DB_NAME . "\n";
return $conn;
}
function dp_get_theme_dir()
{
// Our deploy-runner lives in the theme root
$theme_dir = dirname(__FILE__);
echo "Theme dir: {$theme_dir}\n";
return $theme_dir;
}
// Позиция //-комментария вне строковых литералов или false
function dp_js_comment_pos($line)
{
$len = strlen($line);
$q = '';
$esc = false;
for ($i = 0; $i < $len; $i++) {
$ch = $line[$i];
if ($q !== '') {
if ($esc) {
$esc = false;
} elseif ($ch === '\\') {
$esc = true;
} elseif ($ch === $q) {
$q = '';
}
continue;
}
if ($ch === '"' || $ch === "'" || $ch === '`') {
$q = $ch;
continue;
}
if ($ch === '/' && $i + 1 < $len && $line[$i + 1] === '/') {
return $i;
}
}
return false;
}
// Удаляет //-комментарии (строки и хвосты), переносы строк сохраняет
function dp_strip_js_comments($code)
{
$parts = preg_split('/(\r\n|\n|\r)/', $code, -1, PREG_SPLIT_DELIM_CAPTURE);
$out = '';
$n = count($parts);
for ($p = 0; $p < $n; $p += 2) {
$text = $parts[$p];
$eol = isset($parts[$p + 1]) ? $parts[$p + 1] : '';
$idx = dp_js_comment_pos($text);
$had = false;
if ($idx !== false) {
$text = rtrim(substr($text, 0, $idx));
$had = true;
}
if ($had && trim($text) === '') {
continue; // строка-комментарий целиком
}
$out .= $text . $eol;
}
return $out;
}
if ($migrate === '003') {
// Fix banner_text typo: rарантированная → гарантированная
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$conn) {
die("DB connection failed: " . mysqli_connect_error() . "\n");
}
echo "Connected to DB: " . DB_NAME . "\n\n";
$post_id = 2;
$meta_keys = ['_banner_text', 'banner_text'];
$fixed = 0;
foreach ($meta_keys as $meta_key) {
$res = mysqli_query(
$conn,
"SELECT meta_id, meta_value FROM wp_postmeta WHERE post_id = $post_id AND meta_key = '$meta_key'"
);
while ($row = mysqli_fetch_assoc($res)) {
$old_val = $row['meta_value'];
$new_val = str_replace('rарантированная', 'гарантированная', $old_val);
$new_val = str_replace('rантированная', 'гантированная', $new_val);
if ($new_val !== $old_val) {
$meta_id = (int)$row['meta_id'];
$escaped = mysqli_real_escape_string($conn, $new_val);
mysqli_query(
$conn,
"UPDATE wp_postmeta SET meta_value = '$escaped' WHERE meta_id = $meta_id"
);
echo "✅ FIXED meta_id=$meta_key key=$meta_key\n";
echo " OLD: $old_val\n";
echo " NEW: $new_val\n\n";
$fixed++;
}
}
}
if ($fixed === 0) {
echo "✅ Nothing to fix — typo already corrected\n";
}
echo "\nTotal meta values updated: $fixed\n";
mysqli_close($conn);
}
if ($migrate === '004') {
// ─── 004a: Remove post 740 (custom-css-js orphan) ───
$conn = dp_get_wpdb();
$post_740 = mysqli_query($conn, "SELECT ID FROM wp_posts WHERE ID = 740 AND post_type = 'custom-css-js'");
if (mysqli_num_rows($post_740) > 0) {
// Hard-delete post + meta
mysqli_query($conn, "DELETE FROM wp_posts WHERE ID = 740");
mysqli_query($conn, "DELETE FROM wp_postmeta WHERE post_id = 740");
echo "✅ DELETED post ID 740 (custom-css-js)\n";
// Remove physical file if exists
$theme_dir = dp_get_theme_dir();
$upload_dir = dirname(dirname($theme_dir)) . '/uploads';
$files_to_check = [
$upload_dir . '/custom-css-js/740.css',
$upload_dir . '/custom-css-js/740.min.css',
];
foreach ($files_to_check as $file) {
if (file_exists($file)) {
unlink($file);
echo "✅ DELETED file: {$file}\n";
}
}
} else {
echo "ℹ️ Post ID 740 not found — already removed\n";
}
// ─── 004b: Clean wp_custom_css option ───
// We need wp-load.php for get_option/update_option
$wp_load = dirname(__FILE__) . '/../../../wp-load.php';
if (!file_exists($wp_load)) {
$wp_load = dirname(__FILE__) . '/../../wp-load.php';
}
if (file_exists($wp_load)) {
require_once $wp_load;
echo "✅ Loaded WordPress\n";
$option_name = 'wp_custom_css';
$current = get_option($option_name, '');
if (!empty($current)) {
$before = strlen($current);
$cleaned = preg_replace('/\.(pksh|ms-|ms-text-)[^}]+}\s*/', '', $current);
$cleaned = preg_replace('/\.(pksh|ms-|ms-text-)[^{]*\{\s*\}\s*/', '', $cleaned);
$cleaned = trim($cleaned);
$after = strlen($cleaned);
$diff = $before - $after;
if ($diff > 0) {
update_option($option_name, $cleaned);
echo "✅ wp_custom_css: {$before} → {$after} chars (removed {$diff})\n";
} else {
echo "ℹ️ wp_custom_css unchanged ({$before} chars)\n";
}
} else {
echo "ℹ️ wp_custom_css option is empty\n";
}
if (function_exists('opcache_reset')) {
opcache_reset();
echo "✅ OPcache reset\n";
}
} else {
echo "⚠️ wp-load.php not found — skipping wp_custom_css cleanup\n";
}
mysqli_close($conn);
}
if ($migrate === '005') {
// Технический SEO: robots.txt в webroot (Clean-param для рекламных меток) + сброс OPcache.
// Деплой синкает только тему, root-файлы (robots.txt) в webroot не попадают — пишем напрямую.
$abspath = dirname(__DIR__, 3); // themes/dekart -> themes -> wp-content -> ABSPATH
$robots = $abspath . '/robots.txt';
$needle = 'Clean-param: clckid&yclid&gclid&etext&y_ref /';
echo "ABSPATH: $abspath\n";
echo "robots: $robots\n";
if (!file_exists($robots)) {
echo "⚠️ robots.txt не найден — пропуск\n";
} else {
$cur = file_get_contents($robots);
if (strpos($cur, $needle) !== false) {
echo "✅ Clean-param уже есть — ничего не делаем\n";
} else {
if (preg_match('/^Clean-param: ref&_openstat&sid \/$/m', $cur)) {
$cur = preg_replace('/^(Clean-param: ref&_openstat&sid \/)$/m', "$1\n" . $needle, $cur, 1);
} else {
$cur = rtrim($cur) . "\n" . $needle . "\n";
}
$n = file_put_contents($robots, $cur);
echo "✅ robots.txt обновлён: " . var_export($n, true) . " байт\n";
}
echo "--- первые строки ---\n" . substr(file_get_contents($robots), 0, 500) . "\n";
}
if (function_exists('opcache_reset')) {
opcache_reset();
echo "✅ OPcache reset\n";
} else {
echo "ℹ️ opcache_reset недоступен\n";
}
}
if ($migrate === '006') {
// Чистка построчных //-комментариев в inline-JS сниппете плагина custom-css-js (post 518 «B24form»).
// Правим и БД, и физический файл uploads/custom-css-js/518.js (плагин отдаёт его как есть).
$conn = dp_get_wpdb();
$post_id = 518;
$res = mysqli_query($conn, "SELECT post_content FROM wp_posts WHERE ID = $post_id AND post_type = 'custom-css-js'");
$row = $res ? mysqli_fetch_assoc($res) : null;
if (!$row) {
echo "⚠️ Snippet $post_id (custom-css-js) not found — skip\n";
} else {
$content = (string) $row['post_content'];
$clean = dp_strip_js_comments($content);
if ($clean === $content) {
echo "ℹ️ DB content unchanged — no // comments\n";
} else {
$esc = mysqli_real_escape_string($conn, $clean);
mysqli_query($conn, "UPDATE wp_posts SET post_content = '$esc' WHERE ID = $post_id");
echo "✅ DB post $post_id: " . strlen($content) . " → " . strlen($clean) . " chars\n";
}
$theme_dir = dp_get_theme_dir();
$upload_dir = dirname(dirname($theme_dir)) . '/uploads/custom-css-js';
foreach (["$post_id.js", "$post_id.min.js"] as $fname) {
$file = $upload_dir . '/' . $fname;
if (!is_file($file)) {
echo "ℹ️ File absent: $fname\n";
continue;
}
$raw = file_get_contents($file);
$fixed = dp_strip_js_comments($raw);
if ($fixed !== $raw) {
file_put_contents($file, $fixed);
echo "✅ File $fname: " . strlen($raw) . " → " . strlen($fixed) . " bytes\n";
} else {
echo "ℹ️ File unchanged: $fname\n";
}
}
}
mysqli_close($conn);
}
echo "\n=== Migration complete ===\n";
// Self-destruct: rename this file (кроме 005 — оставляем для повторного сброса OPcache)
$self = __FILE__;
$done = $self . '.done';
if ($migrate !== '005') {
rename($self, $done);
echo "Self-destruct: renamed to " . basename($done) . "\n";
} else {
echo "Self-destruct skipped (legacy-safe migration 005).\n";
}