Skip to content

fix: use wp_handle_upload for import-archive intake - #17

Merged
nolderoos merged 4 commits into
mainfrom
fix/wp-handle-upload
May 14, 2026
Merged

nolderoos merged 4 commits into
mainfrom
fix/wp-handle-upload

Conversation

@nolderoos

@nolderoos nolderoos commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #16

What

Replaces move_uploaded_file() in OpenTrust_Admin_Tools::handle_import_preview() with wp_handle_upload(). Drops the legacy opentrust-tmp/ quarantine directory; files now land in wp-content/uploads/YYYY/MM/ via the standard WP upload pipeline. Adds a one-shot legacy directory sweep to uninstall.php for sites upgrading from <1.1.0.

Why

wp.org review round 1, issue 5. Direct move_uploaded_file() bypasses WP's MIME validation (wp_check_filetype_and_ext), the upload_mimes filter chain, and any third-party security hooks. wp_handle_upload() is the canonical wrapper.

QA

  • wp plugin check opentrust --include-experimental — zero new errors or warnings on the changed files.
  • Cap, nonce, size cap, and is_uploaded_file() precheck all retained.
  • Downstream consumers (OpenTrust_IO::read_zip, transient stash, wp_delete_file in handle_import_apply) are path-agnostic — no change.

Summary by CodeRabbit

  • Refactor

    • Import-preview uploads now use the platform upload flow, store ZIPs in a private stash with deny-all protection, surface upload errors through the UI, and schedule stashed previews for deletion tied to the preview lifecycle.
  • Chores

    • Uninstall now performs a best-effort cleanup of legacy temporary import files.
  • Documentation

    • Updated translation template references and POT timestamp; one obsolete import-related message entry removed.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 909c1b53-fa50-4895-8c5c-e9b61a901aca

📥 Commits

Reviewing files that changed from the base of the PR and between 2122ed7 and 14f84c4.

📒 Files selected for processing (1)
  • languages/opentrust.pot
✅ Files skipped from review due to trivial changes (1)
  • languages/opentrust.pot

📝 Walkthrough

Walkthrough

ZIP import-preview now uses WordPress upload helpers (wp_handle_upload()); a private stash directory and cleanup hook were added and scheduled; uninstall now sweeps the legacy opentrust-tmp uploads folder; translation template (.pot) timestamp and source references were updated.

Changes

Upload stash refactoring

Layer / File(s) Summary
Stash helpers & cleanup hook
includes/class-opentrust-admin-tools.php
Adds stash_dir(), install_stash_upload_filter(), registers opentrust_io_preview_cleanup, and implements cleanup_preview_file() with canonical-path containment checks before deletion.
Import handler refactoring to wp_handle_upload
includes/class-opentrust-admin-tools.php
handle_import_preview() now loads WP file helpers and uses wp_handle_upload() with ZIP-only MIME constraints and test_form=false, reports upload errors via the existing bounce, removes the scoped upload filter after use, stores the returned file path as the stash, and schedules a single-event cleanup tied to the preview transient TTL.
Uninstall: legacy upload directory cleanup
uninstall.php
Uninstall now unschedules opentrust_io_preview_cleanup single-events and performs a best-effort recursive deletion of wp-content/uploads/opentrust-tmp, ignoring traversal errors and attempting to remove the top-level directory.
Translation template updates
languages/opentrust.pot
Updated POT-Creation-Date and adjusted source reference line numbers for several msgid entries; removed the obsolete Could not store uploaded file. entry.

Sequence Diagram

sequenceDiagram
  participant Admin as handle_import_preview
  participant FileHelpers as wp_admin_file_php
  participant Uploader as wp_handle_upload
  participant Scheduler as wp_schedule_single_event
  participant Cleaner as cleanup_preview_file
  Admin->>FileHelpers: require_once file.php
  Admin->>Uploader: call wp_handle_upload for zip
  Uploader-->>Admin: return file or error
  Admin->>Scheduler: schedule opentrust_io_preview_cleanup(stash_path,user_id)
  Scheduler->>Cleaner: call cleanup_preview_file(stash_path,user_id)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

bug

Poem

I’m a rabbit with a patch and rule,
I hopped the ZIP through WordPress’ tool,
The old stash cleared beneath my paw,
Translations ticked, timestamps in awe,
A tidy burrow—clean and cool. 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'fix: use wp_handle_upload for import-archive intake' clearly and concisely summarizes the main change: replacing move_uploaded_file() with wp_handle_upload() in the import-preview handler, which is the core objective of this pull request.
Linked Issues check ✅ Passed The PR fully addresses all coding requirements from issue #16: wp_handle_upload() replaces move_uploaded_file() with proper MIME validation, test_form=false parameter, error branching, file.php inclusion, legacy cleanup in uninstall.php, and downstream path-agnostic consumers remain unaffected.
Out of Scope Changes check ✅ Passed All changes directly support the core objective: wp_handle_upload integration (class-opentrust-admin-tools.php), legacy directory cleanup (uninstall.php), and language file updates reflecting the refactored import flow are all in-scope.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/wp-handle-upload

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-admin-tools.php (1)

329-367: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Preview ZIPs are orphaned in the public uploads directory.

wp_handle_upload() moves the file to wp-content/uploads/YYYY/MM/ and makes it publicly accessible. While the transient expires after 30 minutes, the ZIP file itself is never cleaned up—neither during normal expiry nor if the admin abandons the preview. Once the transient is gone, the file becomes an orphaned artifact accessible via direct URL indefinitely. For sensitive import archives, move the validated file to a non-public temp location with an unguessable name, or use an explicit cleanup mechanism (e.g., wp_scheduled_delete hook) that fires when the transient expires.

🤖 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-admin-tools.php` around lines 329 - 367, The
uploaded ZIP is left in the public uploads dir after wp_handle_upload() and
set_transient('opentrust_io_preview_' . get_current_user_id(), ...), so change
the flow to move the validated file ($stash_path after
OpenTrust_IO::read_zip/validate_manifest) out of the public uploads folder into
a non-public temp location (use wp_tempnam()/get_temp_dir() or similar to create
an unguessable filename) and update $stash_path used for preview; additionally
schedule a cleanup (use wp_schedule_single_event with a custom hook that unlinks
the temp file) to run when the transient would expire (or delete the file when
import completes/fails), and ensure the scheduled cleanup references the same
transient key (opentrust_io_preview_{user_id}) so orphaned files are removed.
🤖 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 `@uninstall.php`:
- Around line 72-79: The legacy stash cleanup currently only deletes files found
in $ot_legacy and then calls `@rmdir`($ot_stash), which will fail if nested
directories exist; update the uninstall block (the code that builds $ot_legacy
and calls wp_delete_file/@rmdir) to perform a recursive removal of $ot_stash
contents (e.g., walk the directory with a
RecursiveDirectoryIterator/RecursiveIteratorIterator or a small helper that
deletes files and directories depth-first) before removing $ot_stash, or
alternatively add an explicit check/assert that pre-1.1.0 layout was flat and
leave a comment documenting that guarantee.

---

Outside diff comments:
In `@includes/class-opentrust-admin-tools.php`:
- Around line 329-367: The uploaded ZIP is left in the public uploads dir after
wp_handle_upload() and set_transient('opentrust_io_preview_' .
get_current_user_id(), ...), so change the flow to move the validated file
($stash_path after OpenTrust_IO::read_zip/validate_manifest) out of the public
uploads folder into a non-public temp location (use wp_tempnam()/get_temp_dir()
or similar to create an unguessable filename) and update $stash_path used for
preview; additionally schedule a cleanup (use wp_schedule_single_event with a
custom hook that unlinks the temp file) to run when the transient would expire
(or delete the file when import completes/fails), and ensure the scheduled
cleanup references the same transient key (opentrust_io_preview_{user_id}) so
orphaned files are removed.
🪄 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: 1c718b29-4cfb-4473-851d-e26aaa7d8321

📥 Commits

Reviewing files that changed from the base of the PR and between 0a38992 and b84479d.

📒 Files selected for processing (2)
  • includes/class-opentrust-admin-tools.php
  • uninstall.php

Comment thread uninstall.php Resolved
@nolderoos

Copy link
Copy Markdown
Collaborator Author

Claude Code review

Verdict: Approve. The change cleanly routes the import-archive intake through wp_handle_upload() and the supporting changes are correct.

What I verified

  • move_uploaded_file() is gone from includes/class-opentrust-admin-tools.php and nothing else in the branch reintroduces it. The legacy opentrust-tmp/ stash dir, .htaccess write, and wp_generate_password() filename are all removed in favour of WP's wp-content/uploads/YYYY/MM/ + wp_unique_filename() path.
  • includes/class-opentrust-admin-tools.php:329-336 — wp_handle_upload($_FILES['ot_import_file'], ['test_form' => false, 'mimes' => ['zip' => 'application/zip']]). test_form => false is justified inline (this is an admin_post_opentrust_import_preview submission, not the wp_handle_upload token wp-admin expects). The single-entry mimes allowlist is correct: wp_check_filetype_and_ext() uses finfo to promote Safari's application/x-zip-compressed and raw application/octet-stream to application/zip based on the PK\x03\x04 signature, so one entry covers every browser without re-opening the global mime allowlist.
  • includes/class-opentrust-admin-tools.php:337-340 — return is checked via isset($upload['error']) (truthiness would have been wrong), success path takes $upload['file']. Matches the wp_handle_upload contract.
  • includes/class-opentrust-admin-tools.php:321 — require_once ABSPATH . 'wp-admin/includes/file.php' is added before the call, fixing the missing include called out in the analysis.
  • Capability + nonce: guard('opentrust_import_preview') at line 308 still runs current_user_can('manage_options') (line 439) and check_admin_referer('opentrust_import_preview') (line 442) before any $_FILES access. The is_uploaded_file() precheck (line 310) and the 50 MB cap (line 316) are retained as early exits — redundant with wp_handle_upload's internal checks but harmless and defensible UX.
  • Path safety: $stash_path comes from $upload['file'], which is an absolute path WP built via wp_unique_filename() inside the uploads tree. No concatenation from $_FILES['name'] or any raw input. Downstream OpenTrust_IO::read_zip(), the transient stash, and wp_delete_file($preview['zip_path']) in handle_import_apply() are path-agnostic — no rewrites needed.
  • The intake correctly uses wp_handle_upload (not media_handle_upload), so the ZIP is never registered as an attachment post — matches the import-flow lifecycle.
  • uninstall.php:67-82 — one-shot sweep of legacy wp-content/uploads/opentrust-tmp/ for upgrades from <1.1.0. Good migration hygiene.
  • languages/opentrust.pot — regenerated, drops the now-unreachable "Could not store uploaded file." string and updates the renumbered line refs in class-opentrust-admin-tools.php. Consistent with the code change.

Optional nit (non-blocking)

uninstall.php:71 — glob($ot_stash . '/{.,}*', GLOB_BRACE) will include . and .. in its results. They're filtered out by the is_file() check on line 73, so behaviour is correct, but glob($ot_stash . '/*', GLOB_BRACE) + glob($ot_stash . '/.*', GLOB_BRACE) (or a simple DirectoryIterator) reads slightly more obviously. Not worth a follow-up PR on its own.

— Claude (automated review on behalf of @nolderoos)

…stall cleanup

Address two CodeRabbit findings on PR #17:

- Stash import-preview ZIPs in a plugin-private wp-content/uploads/opentrust-tmp/
  via a scoped upload_dir filter around the wp_handle_upload() call, protected
  by an .htaccess deny-all and a blank index.html. Schedule a single-event
  cleanup keyed to the 30-min transient TTL with realpath-based containment
  guard and an active-preview check. Wires the cleanup hook from the class
  constructor; clears it on uninstall alongside the other scheduled events.
  Replaces the public-uploads exposure flagged in the PR review body without
  reverting wp_handle_upload (which the wporg reviewer required in 05-file-uploader).

- Replace the flat glob()+is_file() walk in uninstall.php with a depth-first
  RecursiveDirectoryIterator / RecursiveIteratorIterator(CHILD_FIRST) so any
  nested directories in the stash are torn down too. Wrapped in try/catch so
  uninstall is never fatal. Fixes the legacy-stash cleanup gap flagged at
  #17 (comment).

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

Copy link
Copy Markdown
Collaborator Author

Re: the outside-diff comment about preview ZIPs orphaned in public uploads — addressed in 2122ed7. The fix scopes an upload_dir filter around the wp_handle_upload() call so the archive lands in a plugin-private wp-content/uploads/opentrust-tmp/ with .htaccess deny-all + blank index.html, then schedules a single-event cleanup keyed to the 30-min transient TTL. The cleanup handler uses a realpath + str_starts_with(..., $canonical_stash . DIRECTORY_SEPARATOR) containment guard and bails if the user's preview transient still references that path (active import in flight). This is the documented escalation path from wporg-review/05-file-uploader/analysis.md — keeps wp_handle_upload() (per the wporg reviewer's requirement) without leaving the file in a publicly enumerable directory.

New methods added in 2122ed7 (stash_dir, install_stash_upload_filter,
cleanup_preview_file) shifted line numbers below in
includes/class-opentrust-admin-tools.php. No translatable strings were
added or changed — only `#:` source-reference lines updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@nolderoos
nolderoos merged commit eb44fc8 into main May 14, 2026
10 checks passed
@nolderoos
nolderoos deleted the fix/wp-handle-upload branch May 14, 2026 12:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace move_uploaded_file with wp_handle_upload in import-preview handler

1 participant