Skip to content

Remove short ot_ prefix from postmeta keys & identifiers; debug-gate error_log (1.1.1) - #25

Merged
nolderoos merged 2 commits into
mainfrom
fix/ot-prefix-cleanup
May 14, 2026
Merged

nolderoos merged 2 commits into
mainfrom
fix/ot-prefix-cleanup

Conversation

@nolderoos

@nolderoos nolderoos commented May 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Proactive hardening pass before the WordPress.org resubmission. Round 1 of the review scoped the prefix finding to CPT slugs (already fixed in 1.1.0 → opentr_*). This PR extends the cleanup to every other shared/global identifier so a stricter re-reviewer can't reopen the argument, and gates the plugin's error_log() calls behind WP_DEBUG to pre-empt a Plugin Check warning.

Neither item was flagged by the reviewer — both are pre-emptive.

What changed

Postmeta keys — _ot_* → _opentrust_* across all ~44 plugin-owned keys, with a v4→v5 DB migration (OpenTrust::rename_postmeta_keys_v5()) that mirrors the proven v4 CPT-rename pattern: idempotent bulk UPDATEs keyed on meta_key (catches posts, revisions, attachments), runs once on upgrade, retries safely if interrupted (opentrust_db_version only advances at the tail of maybe_upgrade()), and busts caches via the existing tail logic.

Query vars — ot_policy_slug / ot_version → opentrust_policy_slug / opentrust_version. Rewrite rules are recompiled by the existing end-of-maybe_upgrade() flush transient; pretty-permalink URLs are unaffected.

Request-scoped identifiers — meta-box IDs, admin list-table column IDs, import/export form field names, and the $_FILES key → opentrust_*. No migration needed.

LEGACY_META_MAP — new constant in OpenTrust_CPT, the single source of truth powering the v5 migration, the IO import remap (remap_legacy_meta_keys() keeps pre-1.1.1 export archives importable), and uninstall cleanup.

error_log() — 3 unconditional calls routed through a new WP_DEBUG-gated OpenTrust::debug_log() helper (one justified phpcs:ignore instead of three).

Peripheral — wpml-config.xml keys renamed (+ the previously-missing _opentrust_cert_artifact_id); uninstall.php clears orphaned attachment + user meta; version bumped to 1.1.1, DB schema to 5, POT regenerated.

Out of scope by design

CSS classes (ot-*), data-ot-* attributes, local $ot_* variables, and the ot_enc_v1: ciphertext marker — none are reviewable shared registries; renaming them is churn/risk with zero compliance value.

Back-compat

Scenario Outcome
Fresh install DB stamped at v5, no migration runs
Existing install (any v1–v4) maybe_upgrade() runs the v5 postmeta rename; content, revisions, version history, translations and URLs all preserved
Interrupted migration Idempotent bulk UPDATEs + version-advanced-at-tail → safe retry
Old (≤1.1.0) export archive imported remap_legacy_meta_keys() rewrites keys at import time
Plugin downgrade Not supported — same as the existing v4 CPT rename; WordPress doesn't support plugin downgrades

Test plan

  • PHP lint / PHPStan / Semgrep / Plugin Check / POT-freshness / Version-consistency CI all green
  • Fresh install (WP_DEBUG=true): create one of each CPT, fill every meta box, save, reload — fields persist; trust center + policy/version URLs render; CPT list columns show
  • Upgrade path: install 1.1.0 (DB v4), create content, deactivate → install this build → confirm maybe_upgrade() runs v5, all content still renders, wp_postmeta has zero _ot_* rows
  • Deep chain: same from a DB v1/v2 install
  • Import/export round-trip: export from 1.1.0 build → import into this build (exercises remap_legacy_meta_keys())
  • WP_DEBUG off → no error_log output; on → diagnostics still fire

🤖 Generated with Claude Code

Summary by CodeRabbit

Release v1.1.1

  • Improvements

    • Better error logging when WordPress debug mode is enabled for clearer troubleshooting.
    • Consistent internal identifiers for more reliable admin UI behavior and policy/version handling.
  • Bug Fixes

    • Cleaner removal of leftover metadata during plugin uninstall.
  • Chores

    • Database schema bumped to v5 with automatic migration.
    • Refreshed translations and updated admin interface text.

Review Change Stack

Proactive hardening before the wp.org resubmission. The round-1 review
scoped the prefix finding to CPT slugs (fixed in 1.1.0 → opentr_*); this
extends the cleanup to every other shared/global identifier so a stricter
re-reviewer can't reopen it.

- Postmeta keys: _ot_* → _opentrust_*, with a v4→v5 DB migration
  (rename_postmeta_keys_v5) that mirrors the proven v4 CPT-rename pattern:
  idempotent bulk UPDATEs, runs once on upgrade, retries safely if
  interrupted, busts caches via the existing maybe_upgrade() tail.
- Query vars ot_policy_slug/ot_version → opentrust_*; rewrite rules
  recompiled by the existing flush transient.
- Meta-box IDs, admin column IDs, import/export form field names and the
  $_FILES key → opentrust_* (request-scoped, no migration).
- LEGACY_META_MAP added as the single source of truth for the migration,
  the IO import-remap (keeps pre-1.1.1 export archives importable), and
  uninstall cleanup.
- error_log() calls routed through a new WP_DEBUG-gated OpenTrust::debug_log().
- wpml-config.xml keys renamed (+ the previously-missing cert artifact id);
  uninstall.php clears orphaned attachment + user meta.
- Version bumped to 1.1.1, DB schema to 5, POT regenerated.

Out of scope by design: CSS classes, data-ot-* attributes, local $ot_
variables, and the ot_enc_v1: ciphertext marker — none are reviewable
shared registries.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented May 14, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR migrates the OpenTrust plugin from legacy _ot_* and ot_* identifiers to a new _opentrust_* and opentrust_* prefix scheme. It introduces an idempotent database migration (v4→v5), updates all CPT meta box UI and postmeta storage, adds conditional debug logging gated by WP_DEBUG, and handles import/export compatibility with legacy data.

Changes

OpenTrust Metadata Key and Identifier Migration

Layer / File(s) Summary
Version bump, debug logging, and database schema update
opentrust.php, readme.txt, includes/class-opentrust.php
Version bumped to 1.1.1 and DB version to 5. Adds OpenTrust::debug_log() gated by WP_DEBUG. Introduces v4→v5 idempotent postmeta-key migration helper (rename_postmeta_keys_v5()).
Legacy postmeta key mapping constant and UUID stamping
includes/class-opentrust-cpt.php, includes/class-opentrust.php
Adds OpenTrust_CPT::LEGACY_META_MAP mapping legacy _ot_* keys to _opentrust_*. UUID stamping and backfill now target _opentrust_uuid.
CPT meta boxes, form fields, and postmeta persistence
includes/class-opentrust-cpt.php
All CPT meta boxes (Certification, Policy, Subprocessor, Data Practice, FAQ) now render and persist using opentrust_* form field IDs/names and _opentrust_* postmeta keys. Policy saving supports opentrust_publish_new_version + opentrust_version_summary and normalizes repeater inputs. Admin columns updated to reference new keys.
Import/export form fields, handlers, and I/O logic
includes/class-opentrust-admin-tools.php, includes/class-opentrust-io.php
Admin export/import UI and handlers renamed to opentrust_* inputs; OpenTrust_IO updates allowlists and lookup meta keys to _opentrust_*. Adds remap_legacy_meta_keys() to rewrite inbound manifest record meta from _ot_* → _opentrust_*.
Repository projections and metadata retrieval
includes/class-opentrust-repository.php
Fetchers and projections updated to read _opentrust_* meta keys (certifications, policies, subprocessors, data practices, FAQs) and updated meta_key ordering fields.
Policy versioning and public rendering
includes/class-opentrust-version.php, includes/class-opentrust-render.php
Version bumping, revision tagging, and version history use _opentrust_version* keys. Public policy routes and renderers read opentrust_policy_slug/opentrust_version query vars and _opentrust_policy_* meta.
Chat corpus, summarizer, and provider logging
includes/class-opentrust-chat-corpus.php, includes/class-opentrust-chat-summarizer.php, includes/class-opentrust-admin-ai.php, includes/providers/class-opentrust-chat-provider.php
Chat corpus and summarizer constants now use _opentrust_policy_chat_summary* keys. Cron/provider streaming failure logs now call OpenTrust::debug_log() instead of error_log().
Admin UI scripts and catalog seeding
assets/js/admin.js, includes/class-opentrust-admin.php, includes/class-opentrust-catalog.php
Admin JS maps _opentrust_ meta keys to opentrust_ DOM ids and updates toggle selectors. Enqueue gating uses $is_opentrust_screen. FAQ seeding writes _opentrust_seeded/_opentrust_seed_slug.
Certification and data-practice catalog schema
includes/data/certification-catalog.php, includes/data/data-practice-catalog.php
Catalog arrays and template keys renamed to _opentrust_cert_* and _opentrust_dp_* respectively; docblocks updated.
i18n, WPML, and uninstall cleanup
languages/opentrust.pot, wpml-config.xml, uninstall.php
Regenerated POT with updated source references, WPML mappings updated to _opentrust_* keys, and uninstall now removes orphaned import/user meta markers related to the plugin.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through keys both old and new,
_ot_ gave way to _opentrust_ true.
Seeds and versions found their place,
Migrations run with gentle pace,
Debug logs whisper — WP_DEBUG, too.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely summarizes the main change: removing the short 'ot_' prefix from postmeta keys and identifiers, and debug-gating error_log calls. It directly reflects the core objectives of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ot-prefix-cleanup

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
includes/class-opentrust.php (1)

330-346: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

UUID backfill may duplicate UUIDs for existing installations upgrading to v5.

For installs upgrading from v1–v4, the execution order is v4 → v2 → v5. At v2 backfill time:

  1. Existing posts have _ot_uuid (old key)
  2. meta_query checks _opentrust_uuid NOT EXISTS → TRUE
  3. Backfill writes new _opentrust_uuid values
  4. Later, v5 rename converts _ot_uuid → _opentrust_uuid
  5. Result: posts end up with two _opentrust_uuid rows (different values)

Consider either reordering so v5 runs before v2, or updating the backfill to skip posts that already have the legacy _ot_uuid key:

Proposed fix
 private static function backfill_uuids(): void {
     $posts = get_posts([
         'post_type'      => OpenTrust_CPT::ALL,
         'post_status'    => 'any',
         'posts_per_page' => -1,
         'fields'         => 'ids',
         'meta_query'     => [
+            'relation' => 'AND',
             [
                 'key'     => '_opentrust_uuid',
                 'compare' => 'NOT EXISTS',
             ],
+            [
+                'key'     => '_ot_uuid',
+                'compare' => 'NOT EXISTS',
+            ],
         ],
     ]);
     foreach ($posts as $post_id) {
         update_post_meta((int) $post_id, '_opentrust_uuid', wp_generate_uuid4());
     }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@includes/class-opentrust.php` around lines 330 - 346, The backfill_uuids()
routine can create duplicate _opentrust_uuid entries when a legacy _ot_uuid
exists; modify backfill_uuids() to skip posts that already have the legacy key
by extending the meta_query (or add a runtime check inside the foreach) to
ensure neither _opentrust_uuid nor _ot_uuid is present before calling
update_post_meta, so only posts lacking both keys receive a newly generated
wp_generate_uuid4(); reference the backfill_uuids() method and the meta keys
'_opentrust_uuid' and '_ot_uuid' when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@includes/class-opentrust-cpt.php`:
- Around line 867-869: Validate and gate the attachment IDs before calling
update_post_meta: cast the posted IDs with absint but then verify the attachment
exists and is an attachment (use get_post($id) and check $post->post_type ===
'attachment') and only save if valid; for the badge/artifact metas
(_opentrust_cert_badge_id, _opentrust_cert_artifact_id) additionally restrict
mime types as appropriate (e.g., badge -> image/* via wp_get_attachment_metadata
or get_post_mime_type) and for the policy PDF field (the metadata saved around
lines 929-933) enforce get_post_mime_type($id) === 'application/pdf' before
updating; keep sanitize_textarea_field for _opentrust_cert_description and do
not call update_post_meta if validation fails.

---

Outside diff comments:
In `@includes/class-opentrust.php`:
- Around line 330-346: The backfill_uuids() routine can create duplicate
_opentrust_uuid entries when a legacy _ot_uuid exists; modify backfill_uuids()
to skip posts that already have the legacy key by extending the meta_query (or
add a runtime check inside the foreach) to ensure neither _opentrust_uuid nor
_ot_uuid is present before calling update_post_meta, so only posts lacking both
keys receive a newly generated wp_generate_uuid4(); reference the
backfill_uuids() method and the meta keys '_opentrust_uuid' and '_ot_uuid' when
making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 73aafc28-cf06-4c2e-97b4-a23aa829d3cd

📥 Commits

Reviewing files that changed from the base of the PR and between a0d2fcc and 21c4b59.

📒 Files selected for processing (22)
  • assets/js/admin.js
  • includes/class-opentrust-admin-ai.php
  • includes/class-opentrust-admin-tools.php
  • includes/class-opentrust-admin.php
  • includes/class-opentrust-catalog.php
  • includes/class-opentrust-chat-corpus.php
  • includes/class-opentrust-chat-summarizer.php
  • includes/class-opentrust-cpt.php
  • includes/class-opentrust-io.php
  • includes/class-opentrust-render.php
  • includes/class-opentrust-repository.php
  • includes/class-opentrust-version.php
  • includes/class-opentrust.php
  • includes/data/certification-catalog.php
  • includes/data/data-practice-catalog.php
  • includes/data/subprocessor-catalog.php
  • includes/providers/class-opentrust-chat-provider.php
  • languages/opentrust.pot
  • opentrust.php
  • readme.txt
  • uninstall.php
  • wpml-config.xml

Comment on lines +867 to +869
update_post_meta($post_id, '_opentrust_cert_badge_id', absint( wp_unslash( $_POST['opentrust_cert_badge_id'] ?? 0 ) ));
update_post_meta($post_id, '_opentrust_cert_artifact_id', absint( wp_unslash( $_POST['opentrust_cert_artifact_id'] ?? 0 ) ));
update_post_meta($post_id, '_opentrust_cert_description', sanitize_textarea_field( wp_unslash( $_POST['opentrust_cert_description'] ?? '' ) ));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validate attachment IDs and enforce the promised PDF constraint.

These fields still trust the posted attachment IDs too much: the certification badge/artifact paths accept any integer, and the policy path accepts any attachment MIME even though the UI presents it as a PDF upload. A bad media selection or crafted POST can leave broken or mislabeled asset links in admin/public views.

Suggested fix
-        update_post_meta($post_id, '_opentrust_cert_badge_id', absint( wp_unslash( $_POST['opentrust_cert_badge_id'] ?? 0 ) ));
-        update_post_meta($post_id, '_opentrust_cert_artifact_id', absint( wp_unslash( $_POST['opentrust_cert_artifact_id'] ?? 0 ) ));
+        $badge_id = absint( wp_unslash( $_POST['opentrust_cert_badge_id'] ?? 0 ) );
+        if ($badge_id > 0 && get_post_type($badge_id) === 'attachment') {
+            update_post_meta($post_id, '_opentrust_cert_badge_id', $badge_id);
+        } else {
+            delete_post_meta($post_id, '_opentrust_cert_badge_id');
+        }
+
+        $artifact_id = absint( wp_unslash( $_POST['opentrust_cert_artifact_id'] ?? 0 ) );
+        if (
+            $artifact_id > 0 &&
+            get_post_type($artifact_id) === 'attachment' &&
+            get_post_mime_type($artifact_id) === 'application/pdf'
+        ) {
+            update_post_meta($post_id, '_opentrust_cert_artifact_id', $artifact_id);
+        } else {
+            delete_post_meta($post_id, '_opentrust_cert_artifact_id');
+        }
         update_post_meta($post_id, '_opentrust_cert_description', sanitize_textarea_field( wp_unslash( $_POST['opentrust_cert_description'] ?? '' ) ));
-        if ($attachment_id > 0 && get_post_type($attachment_id) === 'attachment') {
+        if (
+            $attachment_id > 0 &&
+            get_post_type($attachment_id) === 'attachment' &&
+            get_post_mime_type($attachment_id) === 'application/pdf'
+        ) {
             update_post_meta($post_id, '_opentrust_policy_attachment_id', $attachment_id);
         } else {
             delete_post_meta($post_id, '_opentrust_policy_attachment_id');
         }

Also applies to: 929-933

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@includes/class-opentrust-cpt.php` around lines 867 - 869, Validate and gate
the attachment IDs before calling update_post_meta: cast the posted IDs with
absint but then verify the attachment exists and is an attachment (use
get_post($id) and check $post->post_type === 'attachment') and only save if
valid; for the badge/artifact metas (_opentrust_cert_badge_id,
_opentrust_cert_artifact_id) additionally restrict mime types as appropriate
(e.g., badge -> image/* via wp_get_attachment_metadata or get_post_mime_type)
and for the policy PDF field (the metadata saved around lines 929-933) enforce
get_post_mime_type($id) === 'application/pdf' before updating; keep
sanitize_textarea_field for _opentrust_cert_description and do not call
update_post_meta if validation fails.

rename_postmeta_keys_v5() ran AFTER the v1→v2 UUID back-fill. On a v1.0.x
install upgrading straight to 1.1.1, backfill_uuids() saw no _opentrust_uuid
(the post still had the legacy _ot_uuid), stamped a fresh one, and then the
v5 rename renamed _ot_uuid → _opentrust_uuid — leaving two _opentrust_uuid
rows with different values on every pre-existing post.

Move the `if ($current < 5)` branch ahead of `if ($current < 2)` so legacy
_ot_uuid rows are renamed first; the back-fill then correctly sees the
existing _opentrust_uuid and skips. Corrects the misleading
"ordering-independent" comment.

Caught by CodeRabbit and an independent migration audit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@r00bbert r00bbert self-assigned this May 14, 2026
@r00bbert r00bbert added bug Something isn't working enhancement New feature or request labels May 14, 2026
@r00bbert
r00bbert self-requested a review May 14, 2026 14:39
@nolderoos
nolderoos merged commit 1e8f78d into main May 14, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants