#!/usr/bin/env python3
"""Pemeriksaan menyeluruh kerusakan TSLaw: alamat, plugin, pengguna, isi, cloaking, robots, tautan keluar."""
import base64, json, re, time, urllib.error, urllib.request

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_BIASA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36"}
UA_GOOGLE = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}


def ambil(url, kepala=UA_BIASA, login=False):
    kepala = dict(kepala)
    if login:
        kepala["Authorization"] = f"Basic {AUTH}"
    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")[:400]
    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. alamat artikel ===")
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")
    print(f"   /{slug[:40]:<42} /slug/ {a} · /slug.htm {b}")
s, sm = ambil(f"{SITUS}/sitemap_index.xml")
if s == 200:
    subs = re.findall(r"<loc>([^<]+)</loc>", sm)
    posts = [u for u in subs if "post-sitemap" in u]
    if posts:
        _, t = ambil(posts[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=== 2. plugin mencurigakan ===")
pl = rest("/wp-json/wp/v2/plugins?per_page=100&_fields=plugin,name,status")
if isinstance(pl, list):
    curiga = [p for p in pl if re.search(r"wp2p|protect-uploads|developer-toolkit|advanced-backup|starter-optimize", p.get("plugin", ""), re.I)]
    print(f"   total plugin: {len(pl)} · mencurigakan: {len(curiga)}")
    for p in curiga:
        print(f"     [{'AKTIF' if p.get('status')=='active' else 'mati '}] {p.get('name')} · {p.get('plugin')}")
else:
    print("   gagal:", str(pl)[:80])

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

print("\n=== 4. beranda: elemen tersembunyi, tautan keluar, skrip asing ===")
st, html = ambil(f"{SITUS}/")
tersembunyi = len(re.findall(r"position:\s*absolute;\s*left:\s*-\d+", html, re.I))
kecil = len(re.findall(r"overflow:\s*hidden;\s*height:\s*1(?:\.\d)?px", html, re.I))
keluar = sorted(set(re.findall(r'href="https?://(?!www\.tslaw\.id|tslaw\.id|wa\.me|api\.whatsapp|www\.google|goo\.gl|maps\.|www\.instagram|www\.facebook|www\.youtube)[^"]+"', html, re.I)))
judi = sorted({k for k in ("casino", "slot", "togel", "maxwin", "gacor", "judi", "sabung") if k in html.lower()})
print(f"   elemen di luar layar: {tersembunyi} · elemen tinggi 1px: {kecil}")
print(f"   kata judi: {judi if judi else 'tidak ada'}")
print(f"   tautan keluar ({len(keluar)}):")
for u in keluar[:10]:
    print(f"      {u[:90]}")

print("\n=== 5. cloaking (apakah Googlebot melihat isi berbeda) ===")
_, a = ambil(f"{SITUS}/", UA_BIASA)
_, g = ambil(f"{SITUS}/", UA_GOOGLE)
ja = re.search(r"<title>(.*?)</title>", a, re.S)
jg = re.search(r"<title>(.*?)</title>", g, re.S)
print(f"   judul untuk pengunjung : {re.sub(r'<[^>]+>','',ja.group(1)).strip()[:70] if ja else '-'}")
print(f"   judul untuk Googlebot  : {re.sub(r'<[^>]+>','',jg.group(1)).strip()[:70] if jg else '-'}")
print(f"   panjang HTML: pengunjung {len(a)} · googlebot {len(g)} · beda {abs(len(a)-len(g))}")

print("\n=== 6. robots.txt ===")
s, rb = ambil(f"{SITUS}/robots.txt")
print(f"   HTTP {s}")
for baris in rb.splitlines()[:15]:
    print(f"      {baris}")

print("\n=== 7. pengaturan situs ===")
se = rest("/wp-json/wp/v2/settings")
if isinstance(se, dict) and "err" not in se:
    for k in ("title", "description", "url", "email", "timezone"):
        print(f"   {k}: {str(se.get(k))[:70]}")
else:
    print("   gagal:", str(se)[:80])
