#!/usr/bin/env python3
"""Pemeriksaan TSLaw setelah Bos memperbarui WordPress: alamat, plugin, pengguna, kesehatan, suntikan."""
import base64, json, re, time, urllib.error, urllib.request
import xmlrpc.client

DOM = "www.tslaw.id"
SITUS = f"https://{DOM}"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36"}
POLA_SUNTIK = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b|_86b24", re.I)


def ambil(url, kepala=UA):
    try:
        with urllib.request.urlopen(urllib.request.Request(url, headers=kepala), timeout=60) as x:
            return x.status, x.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:300]
    except Exception as e:
        return "GAGAL", str(e)[:60]


def rest(path):
    try:
        with urllib.request.urlopen(urllib.request.Request(f"{SITUS}{path}", headers=H), timeout=120) as x:
            return json.loads(x.read())
    except urllib.error.HTTPError as e:
        return {"err": e.code}
    except Exception as e:
        return {"err": str(e)[:50]}


print("=== 1. versi WordPress ===")
try:
    p = xmlrpc.client.ServerProxy(f"{SITUS}/xmlrpc.php", allow_none=True)
    o = p.wp.getOptions(0, "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y")
    v = o.get("software_version")
    print("   ", v.get("value") if isinstance(v, dict) else v)
except Exception as e:
    print("   gagal:", str(e)[:80])

print("\n=== 2. alamat artikel (inti masalah) ===")
for slug in ("cara-daftar-cv-pt-online", "law-firm-surabaya", "biaya-jasa-law-firm-surabaya"):
    a, _ = ambil(f"{SITUS}/{slug}/")
    b, _ = ambil(f"{SITUS}/{slug}.htm")
    tanda = " ✅ normal" if a == 200 else (" ⚠ masih .htm" if b == 200 else " ❌ dua-duanya mati")
    print(f"   /{slug[:38]:<40} /slug/ {a} · /slug.htm {b}{tanda}")

st, sm = ambil(f"{SITUS}/sitemap_index.xml")
if st == 200:
    subs = [u for u in re.findall(r"<loc>([^<]+)</loc>", sm) if "post-sitemap" in u]
    if subs:
        _, t = ambil(subs[0])
        urls = re.findall(r"<loc>([^<]+)</loc>", t)
        htm = len([u for u in urls if u.endswith(".htm")])
        print(f"   sitemap artikel: {len(urls)} entri · berakhiran .htm: {htm}")

print("\n=== 3. plugin mencurigakan ===")
pl = rest("/wp-json/wp/v2/plugins?per_page=100&_fields=plugin,name,status")
if isinstance(pl, list):
    curiga = [x for x in pl if re.search(r"wp2p|protect-uploads|developer-toolkit|advanced-backup|starter-optimize", x.get("plugin", ""), re.I)]
    print(f"   total plugin: {len(pl)} · mencurigakan: {len(curiga)}")
    for x in curiga:
        print(f"     [{'AKTIF' if x.get('status')=='active' else 'mati '}] {x.get('name')} · {x.get('plugin')}")
else:
    print("   gagal baca plugin:", str(pl)[:80])

print("\n=== 4. pengguna ===")
us = rest("/wp-json/wp/v2/users?per_page=50&_fields=id,name")
if isinstance(us, list):
    for x in us:
        acak = bool(re.fullmatch(r"[0-9a-f]{8,}|wp2_[\w]+", str(x.get("name", "")), re.I))
        print(f"   #{x['id']:<4} {str(x.get('name'))[:30]}{'  ⚠ mencurigakan' if acak else ''}")
else:
    print("   gagal:", str(us)[:80])

print("\n=== 5. kesehatan halaman & suntikan ===")
for u in (f"{SITUS}/", f"{SITUS}/hubungi/", f"{SITUS}/practice-areas/"):
    st, t = ambil(u)
    if st == 200:
        judul = re.search(r"<title>(.*?)</title>", t, re.S)
        suntik = "ADA" if POLA_SUNTIK.search(t) else "tidak"
        hidden = len(re.findall(r"position:\s*absolute;\s*left:\s*-\d+", t, re.I))
        print(f"   HTTP {st} · skrip suntikan: {suntik} · elemen tersembunyi: {hidden} · "
              f"{re.sub(r'<[^>]+>','',judul.group(1)).strip()[:50] if judul else '-'}")
    else:
        print(f"   HTTP {st} · {u[-40:]}")
    time.sleep(0.6)
