get_charset_collate();
$proofs = self::table( 'proofs' );
if ( '' !== $proofs ) {
dbDelta(
"CREATE TABLE {$proofs} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
order_id bigint(20) unsigned NOT NULL DEFAULT 0,
order_item_id bigint(20) unsigned NOT NULL DEFAULT 0,
version smallint(5) unsigned NOT NULL DEFAULT 1,
file_path varchar(255) NOT NULL DEFAULT '',
file_name varchar(255) NOT NULL DEFAULT '',
mime varchar(100) NOT NULL DEFAULT '',
size_bytes bigint(20) unsigned NOT NULL DEFAULT 0,
sha256 char(64) NOT NULL DEFAULT '',
status varchar(20) NOT NULL DEFAULT 'draft',
created_by bigint(20) unsigned NOT NULL DEFAULT 0,
created_at datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
PRIMARY KEY (id),
UNIQUE KEY item_version (order_id,order_item_id,version),
KEY order_id (order_id),
KEY status (status),
KEY sha256 (sha256)
) {$charset};"
);
}
$events = self::table( 'events' );
if ( '' !== $events ) {
dbDelta(
"CREATE TABLE {$events} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
proof_id bigint(20) unsigned NOT NULL DEFAULT 0,
order_id bigint(20) unsigned NOT NULL DEFAULT 0,
event varchar(40) NOT NULL DEFAULT '',
actor varchar(20) NOT NULL DEFAULT 'system',
meta longtext,
created_at datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
PRIMARY KEY (id),
KEY proof_id (proof_id),
KEY order_id (order_id),
KEY event (event)
) {$charset};"
);
}
$tokens = self::table( 'tokens' );
if ( '' !== $tokens ) {
dbDelta(
"CREATE TABLE {$tokens} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
proof_id bigint(20) unsigned NOT NULL DEFAULT 0,
token_hash char(64) NOT NULL DEFAULT '',
scope varchar(20) NOT NULL DEFAULT 'view',
expires_at datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
used_at datetime DEFAULT NULL,
created_at datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
PRIMARY KEY (id),
UNIQUE KEY token_hash (token_hash),
KEY proof_id (proof_id)
) {$charset};"
);
}
update_option( 'proofkit_db_version', self::db_version() );
}
/**
* Returns a validated custom table name.
*
* @param string $name Short table name: proofs, events or tokens.
* @return string Empty string for unknown names.
*/
public static function table( string $name ): string {
global $wpdb;
if ( ! in_array( $name, self::TABLES, true ) ) {
return '';
}
return $wpdb->prefix . 'proofkit_' . $name;
}
/**
* Returns the private upload directory, with a trailing slash.
*
* @return string Empty string when the uploads directory is unavailable.
*/
public static function private_dir(): string {
$uploads = wp_upload_dir();
$basedir = isset( $uploads['basedir'] ) ? (string) $uploads['basedir'] : '';
if ( '' === $basedir ) {
return '';
}
return trailingslashit( $basedir ) . 'proofkit-private/';
}
/**
* Creates the directory and drops deny-all rules into it.
*
* @param string $dir Absolute directory path.
* @return void
*/
public static function protect_dir( string $dir ): void {
if ( '' === $dir || ! wp_mkdir_p( $dir ) ) {
return;
}
$htaccess = "\nRequire all denied\n\n\nOrder deny,allow\nDeny from all\n\n";
$nginx = "location ^~ /wp-content/uploads/proofkit-private/ {\n deny all;\n return 403;\n}\n";
self::write_file( $dir . '.htaccess', $htaccess );
self::write_file( $dir . 'index.php', "\n \n \n \n \n \n\n"
);
self::write_file( $dir . 'nginx.conf.example', $nginx );
if ( ! get_option( self::NGINX_LOGGED_OPTION ) ) {
Util::log( 'Add this Nginx rule once per server block to deny direct access to the ProofKit private directory:', array( 'rule' => $nginx ) );
update_option( self::NGINX_LOGGED_OPTION, 1, false );
}
}
/**
* Runs on plugin activation.
*
* @return void
*/
public static function activate(): void {
self::create_tables();
self::protect_dir( self::private_dir() );
update_option( 'proofkit_db_version', self::db_version() );
if ( false === wp_next_scheduled( 'proofkit_daily' ) ) {
$first_run = strtotime( 'tomorrow 03:00' );
if ( false !== $first_run ) {
wp_schedule_event( $first_run, 'daily', 'proofkit_daily' );
}
}
}
/**
* Runs on plugin deactivation. Data is kept.
*
* @return void
*/
public static function deactivate(): void {
wp_clear_scheduled_hook( 'proofkit_daily' );
}
/**
* Runs pending schema migrations once per version change.
*
* @return void
*/
public static function maybe_upgrade(): void {
$installed = (string) get_option( 'proofkit_db_version', '' );
if ( self::db_version() === $installed ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
self::create_tables();
self::protect_dir( self::private_dir() );
update_option( 'proofkit_db_version', self::db_version() );
}
/**
* Daily cron: expired tokens, abandoned uploads and retention purge.
*
* @return void
*/
public static function run_maintenance(): void {
self::maintenance_step(
'token purge',
static function (): void {
Token::purge_expired();
}
);
self::maintenance_step(
'abandoned uploads',
static function (): void {
Upload::purge_abandoned( 96 );
}
);
if ( ! function_exists( 'wc_get_orders' ) ) {
return;
}
$months = max( 1, (int) Settings::get( 'retention_months', 12 ) );
$cutoff = ( new \DateTimeImmutable( '-' . $months . ' months' ) )->format( 'Y-m-d' );
foreach ( self::retention_orders( $cutoff ) as $order ) {
if ( ! $order instanceof \WC_Order ) {
continue;
}
try {
self::purge_order_proofs( $order, $cutoff );
} catch ( \Throwable $e ) {
Util::log(
'Retention purge failed',
array(
'order_id' => $order->get_id(),
'error' => $e->getMessage(),
)
);
}
}
}
/**
* Runs one maintenance step so a failure cannot abort the next step.
*
* @param string $label Human label for the log.
* @param callable $step Work to run.
* @return void
*/
private static function maintenance_step( string $label, callable $step ): void {
try {
$step();
} catch ( \Throwable $e ) {
Util::log(
'Maintenance step failed: ' . $label,
array( 'error' => $e->getMessage() )
);
}
}
/**
* Oldest purgeable orders before the cutoff.
*
* @param string $cutoff Cutoff date in Y-m-d.
* @return \WC_Order[]
*/
private static function retention_orders( string $cutoff ): array {
$args = array(
'limit' => self::RETENTION_LIMIT,
'orderby' => 'date',
'order' => 'ASC',
'date_created' => '<' . $cutoff,
'status' => self::query_statuses(),
);
$orders = self::query_orders( $args );
// Some WC versions reject unregistered custom statuses. When the
// status-filtered query is short, supplement it with a date-only query
// and filter in PHP so wc-artwork/wc-proof orders are never skipped.
if ( count( $orders ) < self::RETENTION_LIMIT ) {
$known = array();
foreach ( $orders as $order ) {
if ( $order instanceof \WC_Order ) {
$known[ (int) $order->get_id() ] = true;
}
}
$fallback = self::query_orders(
array(
'limit' => self::RETENTION_LIMIT,
'orderby' => 'date',
'order' => 'ASC',
'date_created' => '<' . $cutoff,
)
);
foreach ( $fallback as $order ) {
if ( ! $order instanceof \WC_Order ) {
continue;
}
$id = (int) $order->get_id();
if ( isset( $known[ $id ] ) || ! self::is_purgeable_order( $order, $cutoff ) ) {
continue;
}
$orders[] = $order;
$known[ $id ] = true;
if ( count( $orders ) >= self::RETENTION_LIMIT ) {
break;
}
}
}
return is_array( $orders ) ? $orders : array();
}
/**
* Query orders defensively; WooCommerce can return a WP_Error.
*
* @param array $args Query args.
* @return \WC_Order[]
*/
private static function query_orders( array $args ): array {
try {
$orders = wc_get_orders( $args );
} catch ( \Throwable $e ) {
Util::log( 'Order query failed', array( 'error' => $e->getMessage() ) );
return array();
}
return is_array( $orders ) ? $orders : array();
}
/**
* Statuses to pass to wc_get_orders(), without the wc- prefix.
*
* @return string[]
*/
private static function query_statuses(): array {
return array_values(
array_unique(
array_map(
static fn( string $status ): string => self::normalize_status( $status ),
self::PURGEABLE_STATUSES
)
)
);
}
/**
* Strip the WooCommerce status prefix.
*/
private static function normalize_status( string $status ): string {
return str_starts_with( $status, 'wc-' ) ? substr( $status, 3 ) : $status;
}
/**
* Whether an order is old enough and in a purgeable status.
*/
private static function is_purgeable_order( \WC_Order $order, string $cutoff ): bool {
if ( ! in_array( self::normalize_status( $order->get_status() ), self::query_statuses(), true ) ) {
return false;
}
// Processing is deliberately absent from PURGEABLE_STATUSES: production
// or a gateway may still need the artwork, regardless of age.
$created = $order->get_date_created();
if ( ! $created ) {
return false;
}
return $created->getTimestamp() < (int) strtotime( $cutoff . ' 00:00:00' );
}
/**
* Removes every custom table, option and the private directory.
*
* @return void
*/
public static function drop_data(): void {
if ( ! is_multisite() ) {
self::drop_site_data();
return;
}
$sites = get_sites( array( 'number' => 0 ) );
$sites = is_array( $sites ) ? $sites : array();
foreach ( $sites as $site ) {
$blog_id = isset( $site->blog_id ) ? (int) $site->blog_id : 0;
if ( $blog_id <= 0 ) {
continue;
}
switch_to_blog( $blog_id );
try {
self::drop_site_data();
} catch ( \Throwable $e ) {
self::log_uninstall(
'Uninstall failed for site',
array(
'blog_id' => $blog_id,
'error' => $e->getMessage(),
)
);
} finally {
restore_current_blog();
}
}
}
/**
* Logs an uninstall failure without assuming the plugin runtime is loaded.
*
* @param string $message Log message.
* @param array $context Structured context.
* @return void
*/
private static function log_uninstall( string $message, array $context = array() ): void {
if ( class_exists( __NAMESPACE__ . '\\Util' ) ) {
Util::log( $message, $context );
return;
}
error_log( 'ProofKit: ' . $message . ' ' . wp_json_encode( $context ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
}
/**
* Removes this site's tables, options, cron, transients and private dir.
*
* @return void
*/
private static function drop_site_data(): void {
global $wpdb;
foreach ( self::TABLES as $name ) {
$table = self::table( $name );
if ( '' !== $table ) {
// Uninstall removes the plugin's own tables by design.
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
$wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $table ) );
}
}
foreach ( array( '_proofkit_enabled', '_proofkit_required', '_proofkit_instructions', '_proofkit_max_mb', '_proofkit_exts' ) as $meta_key ) {
delete_post_meta_by_key( $meta_key );
}
self::delete_order_meta();
delete_option( 'proofkit_settings' );
delete_option( 'proofkit_db_version' );
delete_option( 'proofkit_delete_data' );
delete_option( self::NGINX_LOGGED_OPTION );
wp_clear_scheduled_hook( 'proofkit_daily' );
self::clear_transients();
self::delete_private_dir();
}
/**
* Deletes ProofKit order and order-item meta, including HPOS orders.
*
* WooCommerce may be unavailable during uninstall; in that case the data
* cannot be addressed through the order API and this step is skipped.
*
* @return void
*/
private static function delete_order_meta(): void {
if ( ! function_exists( 'wc_get_orders' ) || ! function_exists( 'wc_get_order_statuses' ) ) {
return;
}
$statuses = array_keys( (array) wc_get_order_statuses() );
if ( array() === $statuses ) {
return;
}
// Trashed orders are not in wc_get_order_statuses(), but they can still
// carry ProofKit meta, so include them explicitly.
$statuses[] = 'trash';
try {
$ids = wc_get_orders(
array(
'limit' => -1,
'return' => 'ids',
'status' => $statuses,
)
);
} catch ( \Throwable $e ) {
self::log_uninstall( 'Order meta cleanup query failed', array( 'error' => $e->getMessage() ) );
return;
}
$ids = is_array( $ids ) ? array_values( array_filter( array_map( 'absint', $ids ) ) ) : array();
foreach ( array_chunk( $ids, 100 ) as $batch ) {
foreach ( $batch as $order_id ) {
try {
$order = wc_get_order( $order_id );
if ( ! $order instanceof \WC_Order ) {
continue;
}
$changed = false;
foreach ( $order->get_items() as $item ) {
if ( $item->meta_exists( '_proofkit_artwork' ) ) {
$item->delete_meta_data( '_proofkit_artwork' );
$item->save();
$changed = true;
}
}
foreach ( array( '_proofkit_proof_ids', '_proofkit_last_proof_status' ) as $meta_key ) {
if ( $order->meta_exists( $meta_key ) ) {
$order->delete_meta_data( $meta_key );
$changed = true;
}
}
if ( $changed ) {
$order->save();
}
} catch ( \Throwable $e ) {
self::log_uninstall(
'Order meta cleanup failed',
array(
'order_id' => $order_id,
'error' => $e->getMessage(),
)
);
}
}
}
}
/**
* Deletes rate-limit transients for the current site.
*
* A prepared LIKE delete is used instead of enumerating keys because the
* upload limiter creates unbounded hashed keys.
*
* @return void
*/
public static function clear_transients(): void {
global $wpdb;
// Every ProofKit transient is namespaced with proofkit_ (rate limits,
// per-user action notices, one-time install notices). Sweep them all so
// no option rows survive an uninstall.
$wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
$wpdb->esc_like( '_transient_proofkit_' ) . '%',
$wpdb->esc_like( '_transient_timeout_proofkit_' ) . '%'
)
);
}
/**
* Deletes proofs belonging to one purgeable order.
*
* @param \WC_Order $order Order to purge.
* @param string $cutoff Retention cutoff in Y-m-d.
* @return void
*/
private static function purge_order_proofs( \WC_Order $order, string $cutoff ): void {
$order_id = (int) $order->get_id();
if ( $order_id <= 0 || ! self::is_purgeable_order( $order, $cutoff ) ) {
return;
}
$proofs = Proof::get_for_order( $order_id );
if ( ! is_array( $proofs ) || array() === $proofs ) {
return;
}
$purged = 0;
foreach ( $proofs as $proof ) {
$proof_id = isset( $proof->id ) ? (int) $proof->id : 0;
if ( $proof_id <= 0 ) {
continue;
}
// Proofs are order-scoped, so an id can never belong to another order;
// this guard only protects against legacy or dirty rows.
if ( isset( $proof->order_id ) && (int) $proof->order_id !== $order_id ) {
continue;
}
$sha = isset( $proof->sha256 ) ? (string) $proof->sha256 : '';
$path = isset( $proof->file_path ) ? (string) $proof->file_path : '';
// Never remove rows without the audit trail: if the purged event
// cannot be written, leave this proof for the next run.
$logged = Proof::record_event(
$proof_id,
$order_id,
'purged',
'system',
array(
'reason' => 'retention',
'version' => isset( $proof->version ) ? (int) $proof->version : 0,
'sha256' => $sha,
'created_at' => isset( $proof->created_at ) ? (string) $proof->created_at : '',
)
);
if ( ! $logged ) {
Util::log( 'Retention purge skipped: event could not be written', array( 'proof_id' => $proof_id ) );
continue;
}
self::delete_proof_rows( 'tokens', $proof_id );
self::delete_proof_events( $proof_id );
self::delete_proof_row( $proof_id );
// Content addressing means several proofs may share one stored file.
// Check after row deletion so the count only covers surviving proofs.
if ( '' !== $path && ( '' === $sha || ! self::hash_referenced( $sha ) ) ) {
Upload::delete( $path );
}
$purged++;
}
Util::log(
'Retention purge completed',
array( 'order_id' => $order_id, 'proofs' => $purged )
);
}
/**
* Whether any surviving proof row references a file hash.
*/
private static function hash_referenced( string $sha256 ): bool {
global $wpdb;
$table = self::table( 'proofs' );
if ( '' === $table || '' === $sha256 ) {
return false;
}
$count = $wpdb->get_var(
$wpdb->prepare(
'SELECT COUNT(*) FROM %i WHERE sha256 = %s',
$table,
$sha256
)
);
return (int) $count > 0;
}
/**
* Deletes token rows for a proof.
*
* @param string $table Short table name: tokens or events.
* @param int $proof_id Proof id.
* @return void
*/
private static function delete_proof_rows( string $table, int $proof_id ): void {
global $wpdb;
$name = self::table( $table );
if ( '' === $name ) {
return;
}
$wpdb->delete( $name, array( 'proof_id' => $proof_id ), array( '%d' ) );
}
/**
* Deletes a proof's history but keeps the `purged` audit event.
*
* @param int $proof_id Proof id.
* @return void
*/
private static function delete_proof_events( int $proof_id ): void {
global $wpdb;
$table = self::table( 'events' );
if ( '' === $table ) {
return;
}
$wpdb->query(
$wpdb->prepare(
'DELETE FROM %i WHERE proof_id = %d AND event <> %s',
$table,
$proof_id,
'purged'
)
);
}
/**
* Deletes one proof row.
*
* @param int $proof_id Proof id.
* @return void
*/
private static function delete_proof_row( int $proof_id ): void {
global $wpdb;
$table = self::table( 'proofs' );
if ( '' === $table ) {
return;
}
$wpdb->delete( $table, array( 'id' => $proof_id ), array( '%d' ) );
}
/**
* Removes the private upload directory after validating its location.
*
* @return void
*/
private static function delete_private_dir(): void {
$dir = self::private_dir();
if ( '' === $dir || is_link( $dir ) || ! is_dir( $dir ) ) {
return;
}
$uploads = wp_upload_dir();
$basedir = isset( $uploads['basedir'] ) ? realpath( (string) $uploads['basedir'] ) : false;
$target = realpath( $dir );
if ( false === $basedir || false === $target ) {
return;
}
$basedir = trailingslashit( wp_normalize_path( $basedir ) );
$target = wp_normalize_path( $target );
if ( 0 !== strpos( $target . '/', $basedir ) ) {
return;
}
if ( 'proofkit-private' !== basename( $target ) ) {
return;
}
self::remove_tree( $target );
}
/**
* Recursively removes a directory without following symlinks.
*
* @param string $path Absolute path.
* @return void
*/
private static function remove_tree( string $path ): void {
if ( is_link( $path ) || ! is_dir( $path ) ) {
return;
}
$items = @scandir( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( false === $items ) {
return;
}
foreach ( $items as $item ) {
if ( '.' === $item || '..' === $item ) {
continue;
}
$child = $path . '/' . $item;
if ( is_link( $child ) ) {
wp_delete_file( $child );
continue;
}
if ( is_dir( $child ) ) {
self::remove_tree( $child );
continue;
}
wp_delete_file( $child );
}
$fs = self::fs();
if ( null !== $fs ) {
$fs->rmdir( $path );
}
}
/**
* Direct filesystem helper, loaded on demand for uninstall and cleanup.
*/
private static function fs(): ?\WP_Filesystem_Direct {
if ( ! class_exists( '\WP_Filesystem_Direct' ) ) {
$base = ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
$direct = ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
if ( ! is_readable( $base ) || ! is_readable( $direct ) ) {
return null;
}
require_once $base;
require_once $direct;
}
return new \WP_Filesystem_Direct( null );
}
/**
* Writes a file only when it is missing or its contents differ.
*
* @param string $path Absolute path.
* @param string $contents File contents.
* @return void
*/
private static function write_file( string $path, string $contents ): void {
if ( file_exists( $path ) ) {
$existing = @file_get_contents( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
if ( is_string( $existing ) && $existing === $contents ) {
return;
}
}
@file_put_contents( $path, $contents ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
}
/**
* Returns the schema version, with a safe fallback for standalone loads.
*
* @return string
*/
private static function db_version(): string {
return defined( 'PROOFKIT_DB_VERSION' ) ? (string) PROOFKIT_DB_VERSION : '1';
}
}