<?php
// Remove wp-helper/hseo from active_plugins, backup value first. Usage: BDIR=.. php _fix_active_ro.php /site/dir
$dir=rtrim($argv[1]??'','/');$cfg=$dir.'/wp-config.php';
if(!is_file($cfg)){fwrite(STDERR,"no wp-config\n");exit(2);}
$s=file_get_contents($cfg);
function gc($s,$k){return preg_match('/define\(\s*[\x27\x22]'.$k.'[\x27\x22]\s*,\s*[\x27\x22]([^\x27\x22]*)/',$s,$m)?$m[1]:'';}
$pfx=preg_match('/\$table_prefix\s*=\s*[\x27\x22]([^\x27\x22]+)/',$s,$m)?$m[1]:'wp_';
$host=gc($s,'DB_HOST');$port=0;if(strpos($host,':')!==false){list($host,$port)=explode(':',$host,2);$port=(int)$port;}
$m=@new mysqli($host,gc($s,'DB_USER'),gc($s,'DB_PASSWORD'),gc($s,'DB_NAME'),$port?:3306);
if($m->connect_errno){fwrite(STDERR,"  DB ERR ".$m->connect_error."\n");exit(1);}
$site=basename($dir);$bdir=getenv('BDIR');
$r=$m->query("SELECT option_value FROM {$pfx}options WHERE option_name='active_plugins'");
if(!$r||!$r->num_rows){echo "  $site: active_plugins introuvable\n";exit(0);}
$val=$r->fetch_row()[0];
if($bdir)file_put_contents($bdir."/".$site."-active_plugins.bak",$val);
$arr=@unserialize($val);
if(!is_array($arr)){fwrite(STDERR,"  $site: illisible\n");exit(1);}
$b=count($arr);
$arr=array_values(array_filter($arr,function($x){return strpos($x,'wp-helper-')===false && strpos($x,'hseo/')===false;}));
if(count($arr)===$b){echo "  $site: deja propre ($b plugins)\n";exit(0);}
$st=$m->prepare("UPDATE {$pfx}options SET option_value=? WHERE option_name='active_plugins'");
$n=serialize($arr);$st->bind_param('s',$n);$st->execute();
echo "  $site: active_plugins $b -> ".count($arr)." (retire ".($b-count($arr)).")\n";
$m->close();
