Skip to content
This repository was archived by the owner on Nov 2, 2026. It is now read-only.

fix: purge cross-site content silently and recompute bbPress counters - #385

Merged
chubes4 merged 3 commits into
mainfrom
fix-383-purge-context
Sep 7, 2026
Merged

chubes4 merged 3 commits into
mainfrom
fix-383-purge-context

Conversation

@chubes4

@chubes4 chubes4 commented Sep 7, 2026

Copy link
Copy Markdown
Member

Closes #383

Root cause

extrachill_users_purge_user_content() runs from whatever site the CLI was invoked on and does switch_to_blog() per object. switch_to_blog() does not load the target site's plugins, so:

  1. Post types owned by the switched-to site (topic, reply, artist_link_page, artist_profile, ...) are not registered in the request. Core's delete path (and any network-active plugin hooked into before_delete_post/delete_post) runs current_user_can() against those posts, and map_meta_cap() emits a _doing_it_wrong notice per object. Deletes still succeeded — the notices were the bug.
  2. bbPress is not loaded, so bbp_delete_reply / bbp_delete_topic never fire and none of bbPress' denormalized counters are updated, leaving the parent topic/forum stale (exactly the topic 1698 drift from the issue).

Fix 1 — cap notices: minimal post type stub

Chose the stub registration approach (issue option (a)). Per deleted post whose post_type fails post_type_exists(), a minimal stub is registered before wp_delete_post() and unregistered before restore_current_blog() (post type registrations are global state, so the stub must not survive the blog switch).

One deliberate deviation from the option as sketched: the stub uses map_meta_cap => true with the default capability_type => 'post', not map_meta_cap => false. Reason, verified against wp-includes/capabilities.php:

  • For an unregistered type, map_meta_cap() falls back to $caps[] = 'edit_others_posts' — a cap administrators actually have, so today's checks pass.
  • A map_meta_cap => false stub would map delete_post to the per-type primitive (delete_topic, ...) which nobody is granted, silently flipping cap-check outcomes in hooked code — a behavior regression hiding behind the notice fix.
  • A map_meta_cap => true + capability_type => 'post' stub maps checks to the exact same standard caps a regular post uses (delete_others_posts etc.), byte-identical to the effective pre-fix outcome, minus the notice.

Attachments were left alone: attachment is a core type and always registered, so wp_delete_attachment() (and its file cleanup) runs untouched.

Fix 2 — bbPress counter recompute

bbPress is never loaded in this context (no function_exists('bbp_*') guards — they'd always be false), so the recompute reads $wpdb directly, mirroring the exact semantics of bbPress' own updaters (read from bbpress/includes/{common,topics,forums,replies}/functions.php):

Pre-delete capture (extrachill_users_capture_bbp_context()): before any deletions, for every purged topic/reply the reply → topic → forum chain is read from posts (threaded replies resolved by climbing post_parent, depth-guarded, mirroring bbp_get_reply_topic_id()). Capture must happen before the loop because a reply's topic may itself be purged later in the same loop.

Topic recompute (extrachill_users_bbp_update_topic_counters()), matching bbp_update_topic_*:

  • _bbp_reply_count = COUNT of reply rows with post_status = 'publish' linked by the _bbp_topic_id meta mirror or post_parent (bbPress counts via the meta mirror; the parent fallback covers rows missing meta that bbPress itself would still resolve)
  • _bbp_reply_count_hidden = same linkage, post_status IN ('trash','spam','pending') (bbPress' non-public set)
  • _bbp_last_reply_id = newest publish reply with post_parent = topic, ordered post_date DESC, ID DESC (bbp_get_public_child_last_id() ordering), else 0
  • _bbp_last_active_id = that reply, else the topic ID
  • _bbp_last_active_time = that post's post_date (only written when non-empty, like bbPress)

Forum recompute (extrachill_users_bbp_update_forum_counters()), matching bbp_update_forum_*:

  • _bbp_topic_count / _bbp_topic_count_hidden = public (publish,closed) / hidden (trash,spam,pending) topics via the _bbp_forum_id meta mirror or post_parent
  • _bbp_reply_count / _bbp_reply_count_hidden = replies via the _bbp_forum_id meta mirror only (a reply's post_parent is always a topic — no parent fallback exists, same as bbPress' meta-based counting)
  • _bbp_total_topic_count / _bbp_total_reply_count = direct + recursive public sub-forum totals (cycle-guarded), like bbp_update_forum_topic_count()
  • _bbp_last_topic_id = newest public topic parented to the forum, ordered by _bbp_last_active_time (DATETIME) with post_date fallback, ID DESC tiebreak
  • _bbp_last_reply_id / _bbp_last_active_id = newest publish reply across the forum's topics vs the highest public topic ID — larger wins (bbPress' own comparison), 0 when the forum has no public topics
  • _bbp_last_active_time = post_date of the last active ID, skipped when 0

Topics/forums that were themselves purged are skipped (no orphan meta resurrection).

Tests

tests/unit/ModerationContentPurgeTest.php (3 tests, multisite-aware, skips gracefully if blog creation is unavailable):

  1. test_purge_of_unregistered_post_type_emits_no_map_meta_cap_notices — fixture post of a custom type on a second blog; type unregistered (mirroring the production request context); purge runs from blog 1; asserts zero map_meta_cap notices (counted via doing_it_wrong_run) and hard deletion. A before_delete_post hook calling current_user_can('delete_post', ...) deterministically reproduces the hooked-plugin cap checks that surfaced this on production.
  2. test_purge_recomputes_bbp_topic_and_forum_counters — forum + topic + 3 public replies (one by the purged user, seeded as the topic's newest activity with stale counters and bbPress hierarchy meta); after purge asserts the purged reply is gone and every topic/forum counter, pointer, and last-active field matches the recomputed reality.
  3. test_purge_of_topic_zeroes_forum_pointers — purged user authors a whole topic; asserts the topic is gone and the forum's topic counts/pointers are zeroed.

Verification

  • phpcs --standard=WordPress on both changed files: clean; byte-identical finding set to main for content.php (3 pre-existing errors + 4 warnings on unchanged lines — zero new findings).
  • phpstan analyse (level 5, repo config): 8 errors, all pre-existing on main (identical count and locations); zero in the changed files.
  • php -l clean on both files.
  • PHPUnit could not be executed locally: the WP Codebox managed test harness on this VPS requires the runner-provisioned database service (HOMEBOY_RUNTIME_SETTINGS_HELPER + WP_CODEBOX_DB_* secret env) that only exists in the homeboy runner/CI environment — local homeboy test fails at adapter bootstrap before any test executes (same for historical local runs in /mnt/extrachill-workspace/homeboy-runtime). The CI workflow (homeboy review test, which provisions MySQL 8.0 as a service container) is the authoritative gate and runs on this PR; failures, if any, will be addressed on this branch.

AI-authored: this PR was written by Extra Chill Bot (GLM agent) from issue #383's reproduction notes.

Purging a user from a different site's request context (switch_to_blog
does not load that site's plugins) had two defects:

1. wp_delete_post()/cap checks against unregistered post types
   (topic, reply, artist_link_page, ...) emitted map_meta_cap
   _doing_it_wrong notices for every deleted object. Register a
   minimal post type stub (map_meta_cap => true, capability_type
   'post' — identical cap semantics to a regular post) for the
   duration of each delete and unregister it before
   restore_current_blog().

2. bbPress' delete-time counter updates never fired (bbPress is not
   loaded in the switched context), leaving parent topic/forum
   _bbp_reply_count, _bbp_last_reply_id, _bbp_last_active_id/time and
   hidden counts stale after hard-deleting replies/topics. Capture the
   reply -> topic -> forum ancestry before deleting, then recompute the
   same meta keys directly from the database mirroring bbPress' own
   bbp_update_topic_* / bbp_update_forum_* semantics.

Adds tests/unit/ModerationContentPurgeTest.php covering both defects
against a real second network site.

Refs #383
@homeboy-ci

homeboy-ci Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Homeboy Results — extrachill-users

Review lint

✅ review lint — passed

ℹ️ Full options: homeboy self docs commands/lint
Deep dive: homeboy review lint extrachill-users --changed-since 04468c4

Artifacts and drill-down
  • CI results artifact: homeboy-ci-results-extrachill-users-review-lint-homeboy-Linux-php8.4-node24 contains immediate command JSON for this action invocation.
  • Observation artifact: homeboy-observations-extrachill-users-review-lint-homeboy-Linux-php8.4-node24 contains exported Homeboy run history for deeper queries.
  • Drill-down: download the observation artifact, then run homeboy runs import <dir>, homeboy runs list, and homeboy runs findings <run-id>.
  • Artifacts are attached to the workflow run: https://github.com/Extra-Chill/extrachill-users/actions/runs/34134212042

Review test

✅ review test — passed

  • 3 passed

ℹ️ Auto-fix lint issues: homeboy refactor extrachill-users --from lint --write
ℹ️ Collect coverage: homeboy review test extrachill-users --coverage
ℹ️ Save test baseline: homeboy review test extrachill-users --baseline
ℹ️ Pass args to test runner: homeboy review test -- [args]
ℹ️ Full options: homeboy self docs commands/test
Deep dive: homeboy review test extrachill-users --changed-since 04468c4

Artifacts and drill-down
  • CI results artifact: homeboy-ci-results-extrachill-users-review-test-homeboy-Linux-php8.4-node24 contains immediate command JSON for this action invocation.
  • Observation artifact: homeboy-observations-extrachill-users-review-test-homeboy-Linux-php8.4-node24 contains exported Homeboy run history for deeper queries.
  • Drill-down: download the observation artifact, then run homeboy runs import <dir>, homeboy runs list, and homeboy runs findings <run-id>.
  • Artifacts are attached to the workflow run: https://github.com/Extra-Chill/extrachill-users/actions/runs/34134212042
Tooling versions
  • Homeboy CLI: homeboy 0.369.1+37387a7fc7dc
  • Extension: wordpress from https://github.com/Extra-Chill/homeboy-extensions
  • Extension revision: 199c1d7b
  • Action: Extra-Chill/homeboy-action@v2

…st_parent reads

The forum last-reply lookup used a posts-to-posts self-join, which the
shared-table SQL engine in sandboxed WP Codebox runtimes rejects
("Can't reopen table"), leaving _bbp_last_reply_id at the pre-purge
value (observed 6 vs expected 9 in CI). Resolve the forum's public topic
IDs first, then find the newest public reply via get_posts with
post_parent__in — the same shape bbPress' own WP_Query usage takes.

Read post_parent via get_post_field() so phpstan's WP_Post|array stub
does not flag property access on the switched-blog objects.
@chubes4
chubes4 merged commit 0850a7c into main Sep 7, 2026
2 checks passed
chubes4 added a commit that referenced this pull request Sep 8, 2026
…ning fixtures

Code-side:
- inc/auth-tokens/service.php: add_query_arg() inserts new values without
  encoding, so the raw 2FA continuation URL terminated its own redirect_to
  query value at the first &. rawurlencode() it (same pattern as
  read-redirect.php).
- inc/core/moderation/email.php: ! empty( $result['success'] ) fatals when
  the queue returns WP_Error ('Cannot use object of type WP_Error as
  array'); restore the is_array() guard (#385 regression, latent on main
  because the covering test never executed under broken process isolation).

Test-side:
- ArtistDispatchAccessTest: deterministically swap the real analytics ability
  for the capture double (same WP 6.9 simulated-init pattern as the
  onboarding suite) and restore it in tearDown.
- ArtistInvitationRegistrationTest: stub the wp-native-auth token primitives
  (network-activated in production, absent in the sandbox).
- BrowserHandoffTokenTest: stub cache implements delete_multiple().
- RegistrationEmailFailureTest: initialize canonical site rows in setUp so
  wpdb table-missing errors cannot pollute the error_log assertions; the
  null-result formatter expectation follows the deliberate #110 refinement
  (ec_send_email returned null).
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ban --purge from main-site context emits map_meta_cap notices and leaves bbPress topic/forum counters stale

1 participant