get_results( $wpdb->prepare( 'SELECT id, status FROM %i WHERE order_id = %d AND order_item_id = %d AND status IN (%s, %s, %s) FOR UPDATE', $table, $order_id, $order_item_id, 'draft', 'sent', 'changes_requested' ) ); if ( null === $old_rows ) { if ( $transaction ) { self::rollback(); } return self::db_error(); } if ( ! is_array( $old_rows ) ) { $old_rows = []; } $version = $transaction ? self::next_version_locked( $order_id, $order_item_id ) : self::next_version( $order_id, $order_item_id ); $created_at = Util::now(); $data = [ 'order_id' => $order_id, 'order_item_id' => $order_item_id, 'version' => $version, 'file_path' => $path, 'file_name' => $name, 'mime' => substr( $mime, 0, 100 ), 'size_bytes' => $size, 'sha256' => $sha, 'status' => 'draft', 'created_by' => $created_by, 'created_at' => $created_at, ]; $formats = [ '%d', '%d', '%d', '%s', '%s', '%s', '%d', '%s', '%s', '%d', '%s' ]; $inserted = $wpdb->insert( $table, $data, $formats ); if ( false === $inserted && self::is_duplicate_error() ) { // Two uploads raced for the same version: recompute once. $data['version'] = $transaction ? self::next_version_locked( $order_id, $order_item_id ) : self::next_version( $order_id, $order_item_id ); $inserted = $wpdb->insert( $table, $data, $formats ); if ( false === $inserted ) { if ( $transaction ) { self::rollback(); } return new \WP_Error( 'proofkit_duplicate_version', __( 'Another proof version was created at the same time. Please retry.', 'proofkit' ) ); } } if ( false === $inserted ) { if ( $transaction ) { self::rollback(); } return self::db_error(); } $id = (int) $wpdb->insert_id; if ( $id <= 0 ) { if ( $transaction ) { self::rollback(); } return self::db_error(); } $version = (int) $data['version']; // Voids every earlier actionable version and its links in the same // transaction as the new row. foreach ( $old_rows as $old ) { $old_id = (int) $old->id; $old_status = (string) $old->status; if ( $old_id === $id ) { continue; } $changed = $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status = %s WHERE id = %d AND status = %s', $table, 'superseded', $old_id, $old_status ) ); if ( false === $changed ) { self::abort_create( $transaction, $id, $old_rows ); return self::db_error(); } Token::revoke( $old_id ); if ( ! self::record_event( $old_id, $order_id, 'superseded', 'system', [ 'replaced_by_version' => $version, 'replaced_by_id' => $id, ] ) ) { self::abort_create( $transaction, $id, $old_rows ); return self::event_failed_error(); } } $actor = current_user_can( 'manage_woocommerce' ) ? 'admin' : 'customer'; if ( ! self::record_event( $id, $order_id, 'uploaded', $actor, [ 'file_name' => $name, 'size' => $size, 'sha256' => $sha, 'created_by' => $created_by, ] ) ) { self::abort_create( $transaction, $id, $old_rows ); return self::event_failed_error(); } if ( $transaction ) { self::commit(); } self::append_order_proof_id( $order_id, $id ); return $id; } /** * Fetch one proof. */ public static function get( int $id ): ?object { global $wpdb; $id = absint( $id ); if ( $id <= 0 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d LIMIT 1', Install::table( 'proofs' ), $id ) ); return $row ? self::cast( $row ) : null; } /** * All proofs for an order, grouped by item then version. * * @return object[] */ public static function get_for_order( int $order_id ): array { global $wpdb; $order_id = absint( $order_id ); if ( $order_id <= 0 ) { return []; } $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE order_id = %d ORDER BY order_item_id ASC, version ASC', Install::table( 'proofs' ), $order_id ) ); if ( ! is_array( $rows ) ) { return []; } foreach ( $rows as $row ) { self::cast( $row ); } return $rows; } /** * All proofs for one order line item, oldest first. * * @return object[] */ public static function get_for_item( int $order_id, int $order_item_id ): array { global $wpdb; $order_id = absint( $order_id ); $order_item_id = absint( $order_item_id ); if ( $order_id <= 0 ) { return []; } $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE order_id = %d AND order_item_id = %d ORDER BY version ASC', Install::table( 'proofs' ), $order_id, $order_item_id ) ); if ( ! is_array( $rows ) ) { return []; } foreach ( $rows as $row ) { self::cast( $row ); } return $rows; } /** * Most recent proof for one order line item. */ public static function latest_for_item( int $order_id, int $order_item_id ): ?object { global $wpdb; $order_id = absint( $order_id ); $order_item_id = absint( $order_item_id ); if ( $order_id <= 0 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE order_id = %d AND order_item_id = %d ORDER BY version DESC LIMIT 1', Install::table( 'proofs' ), $order_id, $order_item_id ) ); return $row ? self::cast( $row ) : null; } /** * Next version number for an order line item. */ public static function next_version( int $order_id, int $order_item_id ): int { global $wpdb; $max = $wpdb->get_var( $wpdb->prepare( 'SELECT MAX(version) FROM %i WHERE order_id = %d AND order_item_id = %d', Install::table( 'proofs' ), absint( $order_id ), absint( $order_item_id ) ) ); return (int) $max + 1; } /** * Send a draft proof to the customer. * * @return bool|\WP_Error */ public static function send( int $id ): bool|\WP_Error { global $wpdb; $proof = self::get( $id ); if ( ! $proof ) { return self::not_found_error(); } if ( 'draft' !== $proof->status ) { return self::wrong_status_error(); } if ( ! Upload::exists( $proof->file_path ) || ! Upload::verify( $proof->file_path, $proof->sha256 ) ) { return self::file_missing_error(); } $order = function_exists( 'wc_get_order' ) ? wc_get_order( (int) $proof->order_id ) : false; if ( ! $order instanceof \WC_Order ) { return new \WP_Error( 'proofkit_order_missing', __( 'The order for this proof no longer exists.', 'proofkit' ) ); } $table = Install::table( 'proofs' ); $transaction = self::begin(); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d FOR UPDATE', $table, (int) $proof->id ) ); if ( ! $row ) { if ( $transaction ) { self::rollback(); } return self::not_found_error(); } $proof = self::cast( $row ); if ( 'draft' !== $proof->status || ! self::is_latest( $proof ) ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } // Claim the transition before minting a link. If two requests raced, // only the winner may issue or revoke tokens; otherwise the loser // could delete the link that was just emailed to the customer. $updated = $wpdb->update( $table, [ 'status' => 'sent' ], [ 'id' => (int) $proof->id, 'status' => 'draft', ], [ '%s' ], [ '%d', '%s' ] ); if ( 1 !== $updated ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } // Drop stale links, then issue exactly one fresh respond token // through Frontend::proof_url(). Token::revoke( (int) $proof->id, 'respond' ); $url = Frontend::proof_url( (int) $proof->id, (int) $proof->order_id, 'respond' ); if ( is_wp_error( $url ) ) { // Roll back so the admin can retry; no link was minted. if ( $transaction ) { self::rollback(); } else { $wpdb->update( $table, [ 'status' => 'draft' ], [ 'id' => (int) $proof->id, 'status' => 'sent', ], [ '%s' ], [ '%d', '%s' ] ); Token::revoke( (int) $proof->id, 'respond' ); } return $url; } $proof->status = 'sent'; $days = max( 1, min( 365, (int) Settings::get( 'link_expiry_days', 30 ) ) ); $email_failed = false; $sent = false; try { $sent = Plugin::send_proof_email( $order, $proof, (string) $url ); } catch ( \Throwable ) { $sent = false; } $email_failed = ! $sent; $meta = [ 'expires_in_days' => $days ]; if ( $email_failed ) { $meta['email_failed'] = true; } if ( ! self::record_event( (int) $proof->id, (int) $proof->order_id, 'proof_sent', 'admin', $meta ) ) { if ( $transaction ) { self::rollback(); } else { $wpdb->update( $table, [ 'status' => 'draft' ], [ 'id' => (int) $proof->id, 'status' => 'sent', ], [ '%s' ], [ '%d', '%s' ] ); Token::revoke( (int) $proof->id, 'respond' ); } return self::event_failed_error(); } if ( $transaction ) { self::commit(); } Order::sync( (int) $proof->order_id, 'sent' ); if ( $email_failed ) { self::log( 'Proof ready email was not accepted by the mailer.', [ 'proof_id' => (int) $proof->id ] ); return self::email_failed_error( (int) $proof->id ); } return true; } /** * Reissue the respond link and email a sent proof again. * * @return bool|\WP_Error */ public static function resend( int $id ): bool|\WP_Error { global $wpdb; $proof = self::get( $id ); if ( ! $proof ) { return self::not_found_error(); } if ( 'sent' !== $proof->status ) { return self::wrong_status_error(); } if ( ! Upload::exists( $proof->file_path ) || ! Upload::verify( $proof->file_path, $proof->sha256 ) ) { return self::file_missing_error(); } $order = function_exists( 'wc_get_order' ) ? wc_get_order( (int) $proof->order_id ) : false; if ( ! $order instanceof \WC_Order ) { return new \WP_Error( 'proofkit_order_missing', __( 'The order for this proof no longer exists.', 'proofkit' ) ); } $table = Install::table( 'proofs' ); $transaction = self::begin(); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d FOR UPDATE', $table, (int) $proof->id ) ); if ( ! $row ) { if ( $transaction ) { self::rollback(); } return self::not_found_error(); } $proof = self::cast( $row ); if ( 'sent' !== $proof->status || ! self::is_latest( $proof ) ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } Token::revoke( (int) $proof->id, 'respond' ); $url = Frontend::proof_url( (int) $proof->id, (int) $proof->order_id, 'respond' ); if ( is_wp_error( $url ) ) { if ( $transaction ) { self::rollback(); } else { Token::revoke( (int) $proof->id, 'respond' ); } return $url; } $email_failed = false; $sent = false; try { $sent = Plugin::send_proof_email( $order, $proof, (string) $url ); } catch ( \Throwable ) { $sent = false; } $email_failed = ! $sent; $meta = [ 'resend' => true ]; if ( $email_failed ) { $meta['email_failed'] = true; } if ( ! self::record_event( (int) $proof->id, (int) $proof->order_id, 'proof_sent', 'admin', $meta ) ) { if ( $transaction ) { self::rollback(); } else { Token::revoke( (int) $proof->id, 'respond' ); } return self::event_failed_error(); } if ( $transaction ) { self::commit(); } if ( $email_failed ) { self::log( 'Proof ready email was not accepted by the mailer on resend.', [ 'proof_id' => (int) $proof->id ] ); return self::email_failed_error( (int) $proof->id ); } return true; } /** * Record customer approval of a sent proof. * * @return bool|\WP_Error */ public static function approve( int $id, string $note = '' ): bool|\WP_Error { global $wpdb; $proof = self::get( $id ); if ( ! $proof ) { return self::not_found_error(); } if ( 'sent' !== $proof->status ) { return self::wrong_status_error(); } $order = function_exists( 'wc_get_order' ) ? wc_get_order( (int) $proof->order_id ) : false; if ( $order instanceof \WC_Order ) { if ( in_array( $order->get_status(), [ 'cancelled', 'refunded', 'failed' ], true ) ) { return self::order_closed_error(); } } else { self::log( 'Could not load the order while checking whether the proof may be approved.', [ 'proof_id' => (int) $proof->id ] ); } $table = Install::table( 'proofs' ); $transaction = self::begin(); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d FOR UPDATE', $table, (int) $proof->id ) ); if ( ! $row ) { if ( $transaction ) { self::rollback(); } return self::not_found_error(); } $proof = self::cast( $row ); if ( 'sent' !== $proof->status || ! self::is_latest( $proof ) ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } $updated = $wpdb->update( $table, [ 'status' => 'approved' ], [ 'id' => (int) $proof->id, 'status' => 'sent', ], [ '%s' ], [ '%d', '%s' ] ); if ( 1 !== $updated ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } Token::revoke( (int) $proof->id ); if ( ! self::record_event( (int) $proof->id, (int) $proof->order_id, 'approved', 'customer', [ 'note' => self::sanitize_note( $note ), 'ip_hash' => Util::hash_ip( Util::client_ip() ), 'version' => (int) $proof->version, 'sha256' => (string) $proof->sha256, ] ) ) { if ( $transaction ) { self::rollback(); } else { $wpdb->update( $table, [ 'status' => 'sent' ], [ 'id' => (int) $proof->id, 'status' => 'approved', ], [ '%s' ], [ '%d', '%s' ] ); } return self::event_failed_error(); } if ( $transaction ) { self::commit(); } Order::sync( (int) $proof->order_id, 'approved' ); return true; } /** * Record a customer change request. A note is mandatory. * * @return bool|\WP_Error */ public static function request_changes( int $id, string $note ): bool|\WP_Error { global $wpdb; $proof = self::get( $id ); if ( ! $proof ) { return self::not_found_error(); } if ( 'sent' !== $proof->status ) { return self::wrong_status_error(); } $note = trim( $note ); if ( '' === $note ) { return new \WP_Error( 'proofkit_note_required', __( 'Please describe the changes you need.', 'proofkit' ) ); } if ( self::text_length( $note ) > 2000 ) { return new \WP_Error( 'proofkit_note_too_long', __( 'The change request must be 2000 characters or fewer.', 'proofkit' ) ); } $order = function_exists( 'wc_get_order' ) ? wc_get_order( (int) $proof->order_id ) : false; if ( $order instanceof \WC_Order ) { if ( in_array( $order->get_status(), [ 'cancelled', 'refunded', 'failed' ], true ) ) { return self::order_closed_error(); } } else { self::log( 'Could not load the order while checking whether a change request may be recorded.', [ 'proof_id' => (int) $proof->id ] ); } $table = Install::table( 'proofs' ); $transaction = self::begin(); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d FOR UPDATE', $table, (int) $proof->id ) ); if ( ! $row ) { if ( $transaction ) { self::rollback(); } return self::not_found_error(); } $proof = self::cast( $row ); if ( 'sent' !== $proof->status || ! self::is_latest( $proof ) ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } $updated = $wpdb->update( $table, [ 'status' => 'changes_requested' ], [ 'id' => (int) $proof->id, 'status' => 'sent', ], [ '%s' ], [ '%d', '%s' ] ); if ( 1 !== $updated ) { if ( $transaction ) { self::rollback(); } return self::wrong_status_error(); } Token::revoke( (int) $proof->id ); if ( ! self::record_event( (int) $proof->id, (int) $proof->order_id, 'changes_requested', 'customer', [ 'note' => self::sanitize_note( $note ), 'ip_hash' => Util::hash_ip( Util::client_ip() ), 'version' => (int) $proof->version, 'sha256' => (string) $proof->sha256, ] ) ) { if ( $transaction ) { self::rollback(); } else { $wpdb->update( $table, [ 'status' => 'sent' ], [ 'id' => (int) $proof->id, 'status' => 'changes_requested', ], [ '%s' ], [ '%d', '%s' ] ); } return self::event_failed_error(); } if ( $transaction ) { self::commit(); } Order::sync( (int) $proof->order_id, 'changes_requested' ); return true; } /** * Log at most one view per token, or per proof, per hour. Never changes status. */ public static function mark_viewed( int $id, string $token_hash = '' ): void { global $wpdb; $proof = self::get( $id ); if ( ! $proof ) { return; } $hash = strtolower( trim( $token_hash ) ); if ( '' !== $hash ) { $hash = preg_match( '/^[a-f0-9]{64}$/', $hash ) ? $hash : hash( 'sha256', $hash ); } $cutoff = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS ); $events = Install::table( 'events' ); if ( '' !== $hash ) { $recent = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE proof_id = %d AND event = %s AND created_at > %s AND meta LIKE %s LIMIT 1', $events, (int) $proof->id, 'viewed', $cutoff, '%"token_hash":"' . $wpdb->esc_like( $hash ) . '"%' ) ); } else { $recent = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE proof_id = %d AND event = %s AND created_at > %s LIMIT 1', $events, (int) $proof->id, 'viewed', $cutoff ) ); } if ( null !== $recent ) { return; } $meta = [ 'ip_hash' => Util::hash_ip( Util::client_ip() ) ]; if ( '' !== $hash ) { $meta['token_hash'] = $hash; } if ( ! self::record_event( (int) $proof->id, (int) $proof->order_id, 'viewed', 'customer', $meta ) ) { self::log( 'Could not record a proof view event.', [ 'proof_id' => (int) $proof->id ] ); } } /** * Append an immutable audit event. * * @return bool True only when the event row was written. */ public static function record_event( int $proof_id, int $order_id, string $event, string $actor, array $meta = [] ): bool { global $wpdb; $event = substr( sanitize_key( $event ), 0, 40 ); $actor = sanitize_key( $actor ); if ( '' === $event ) { return false; } if ( ! in_array( $actor, [ 'admin', 'customer', 'system' ], true ) ) { $actor = 'system'; } $json = json_encode( $meta, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE ); if ( false === $json ) { $json = '{}'; } $inserted = $wpdb->insert( Install::table( 'events' ), [ 'proof_id' => absint( $proof_id ), 'order_id' => absint( $order_id ), 'event' => $event, 'actor' => $actor, 'meta' => $json, 'created_at' => Util::now(), ], [ '%d', '%d', '%s', '%s', '%s', '%s' ] ); return (bool) $inserted; } /** * Event log for a proof, oldest first. * * @return object[] */ public static function events( int $proof_id ): array { global $wpdb; $proof_id = absint( $proof_id ); if ( $proof_id <= 0 ) { return []; } $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE proof_id = %d ORDER BY created_at ASC, id ASC', Install::table( 'events' ), $proof_id ) ); if ( ! is_array( $rows ) ) { return []; } foreach ( $rows as $row ) { $row->id = (int) $row->id; $row->proof_id = (int) $row->proof_id; $row->order_id = (int) $row->order_id; } return $rows; } /** * Translated status label. */ public static function status_label( string $status ): string { switch ( $status ) { case 'draft': return __( 'Draft — not sent', 'proofkit' ); case 'sent': return __( 'Sent — awaiting customer', 'proofkit' ); case 'approved': return __( 'Approved', 'proofkit' ); case 'changes_requested': return __( 'Changes requested', 'proofkit' ); case 'superseded': return __( 'Superseded — a newer version exists', 'proofkit' ); default: return ucfirst( $status ); } } /** * WooCommerce order status that corresponds to a proof status. */ public static function order_status_for( string $proof_status ): string { switch ( $proof_status ) { case 'sent': return Order::STATUS_PROOF; case 'approved': return 'processing'; case 'draft': case 'changes_requested': case 'superseded': default: return Order::STATUS_ARTWORK; } } /** * Delete every proof, event and token for an order, and any files that * are no longer referenced by another proof row. */ public static function delete_for_order( int $order_id ): void { global $wpdb; $order_id = absint( $order_id ); if ( $order_id <= 0 ) { return; } $proofs = self::get_for_order( $order_id ); if ( [] === $proofs ) { return; } $files = []; foreach ( $proofs as $proof ) { $files[ (string) $proof->sha256 ][] = (string) $proof->file_path; $wpdb->delete( Install::table( 'tokens' ), [ 'proof_id' => (int) $proof->id ], [ '%d' ] ); $wpdb->delete( Install::table( 'events' ), [ 'proof_id' => (int) $proof->id ], [ '%d' ] ); $wpdb->delete( Install::table( 'proofs' ), [ 'id' => (int) $proof->id ], [ '%d' ] ); } // Catch any event rows that lost their proof row. $wpdb->delete( Install::table( 'events' ), [ 'order_id' => $order_id ], [ '%d' ] ); foreach ( $files as $sha => $paths ) { foreach ( array_unique( $paths ) as $path ) { $remaining = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE file_path = %s OR sha256 = %s', Install::table( 'proofs' ), $path, $sha ) ); // Fail closed: a query error must never trigger file deletion. if ( null === $remaining && '' !== $wpdb->last_error ) { continue; } if ( (int) $remaining > 0 ) { continue; } Upload::delete( $path ); } } } /** * Cast numeric columns to int. */ private static function cast( object $row ): object { foreach ( [ 'id', 'order_id', 'order_item_id', 'version', 'size_bytes', 'created_by' ] as $key ) { if ( isset( $row->$key ) ) { $row->$key = (int) $row->$key; } } return $row; } /** * Whether a proof is the latest version for its order line item. */ private static function is_latest( object $proof ): bool { return self::latest_id( (int) $proof->order_id, (int) $proof->order_item_id ) === (int) $proof->id; } /** * Latest proof id for a line item, locked when a transaction is open. */ private static function latest_id( int $order_id, int $order_item_id ): int { global $wpdb; $id = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE order_id = %d AND order_item_id = %d ORDER BY version DESC LIMIT 1 FOR UPDATE', Install::table( 'proofs' ), absint( $order_id ), absint( $order_item_id ) ) ); return (int) $id; } /** * Next version inside a transaction, using a locking read. */ private static function next_version_locked( int $order_id, int $order_item_id ): int { global $wpdb; $max = $wpdb->get_var( $wpdb->prepare( 'SELECT version FROM %i WHERE order_id = %d AND order_item_id = %d ORDER BY version DESC LIMIT 1 FOR UPDATE', Install::table( 'proofs' ), absint( $order_id ), absint( $order_item_id ) ) ); return (int) $max + 1; } /** * Roll back, or compensate when transactions are unavailable. * * @param bool $transaction Whether a transaction was opened. * @param int $new_id Newly inserted proof id. * @param array $old_rows Earlier rows selected before the insert. */ private static function abort_create( bool $transaction, int $new_id, array $old_rows ): void { global $wpdb; if ( $transaction ) { self::rollback(); return; } // Without transactions, restore the earlier rows and remove the // half-created proof plus the events written by this attempt. $proofs = Install::table( 'proofs' ); $events = Install::table( 'events' ); $needle = '%"replaced_by_id":' . $new_id . '%'; foreach ( $old_rows as $old ) { $old_id = (int) $old->id; if ( $old_id === $new_id ) { continue; } $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status = %s WHERE id = %d AND status = %s', $proofs, (string) $old->status, $old_id, 'superseded' ) ); $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE proof_id = %d AND event = %s AND meta LIKE %s', $events, $old_id, 'superseded', $needle ) ); } Token::revoke( $new_id ); $wpdb->delete( $events, [ 'proof_id' => $new_id ], [ '%d' ] ); $wpdb->delete( $proofs, [ 'id' => $new_id ], [ '%d' ] ); } /** * Open a transaction when the database supports one. */ private static function begin(): bool { global $wpdb; if ( false === self::$transaction_support ) { return false; } $started = $wpdb->query( 'START TRANSACTION' ); if ( false === $started ) { self::$transaction_support = false; self::$in_transaction = false; return false; } self::$transaction_support = true; self::$in_transaction = true; return true; } /** * Commit the current transaction, if one is open. */ private static function commit(): void { global $wpdb; if ( ! self::$in_transaction ) { return; } $wpdb->query( 'COMMIT' ); self::$in_transaction = false; } /** * Roll back the current transaction, if one is open. */ private static function rollback(): void { global $wpdb; if ( ! self::$in_transaction ) { return; } $wpdb->query( 'ROLLBACK' ); self::$in_transaction = false; } /** * Append the proof id to the order's `_proofkit_proof_ids` meta. */ private static function append_order_proof_id( int $order_id, int $proof_id ): void { if ( ! function_exists( 'wc_get_order' ) ) { return; } $order = wc_get_order( $order_id ); if ( ! $order instanceof \WC_Order ) { return; } $ids = $order->get_meta( '_proofkit_proof_ids', true ); if ( ! is_array( $ids ) ) { $ids = []; } $ids[] = $proof_id; $ids = array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ); $order->update_meta_data( '_proofkit_proof_ids', $ids ); $order->save(); } /** * Whether the last database error was a duplicate-key violation. */ private static function is_duplicate_error(): bool { global $wpdb; return str_contains( strtolower( (string) $wpdb->last_error ), 'duplicate' ); } /** * Sanitise a customer note to plain text. */ private static function sanitize_note( string $note, int $limit = 2000 ): string { $note = wp_kses_post( $note ); $note = wp_strip_all_tags( $note ); $note = trim( $note ); if ( self::text_length( $note ) > $limit ) { $note = function_exists( 'mb_substr' ) ? mb_substr( $note, 0, $limit, 'UTF-8' ) : substr( $note, 0, $limit ); } return $note; } /** * Character length, falling back to bytes without mbstring. */ private static function text_length( string $text ): int { return function_exists( 'mb_strlen' ) ? mb_strlen( $text, 'UTF-8' ) : strlen( $text ); } /** * Invalid or mismatched file descriptor. */ private static function invalid_file_error(): \WP_Error { return new \WP_Error( 'proofkit_invalid_file', __( 'The artwork descriptor is invalid.', 'proofkit' ) ); } /** * Stored file missing or tampered with. */ private static function file_missing_error(): \WP_Error { return new \WP_Error( 'proofkit_file_missing', __( 'The stored artwork file is missing or does not match its record.', 'proofkit' ) ); } /** * Proof id does not exist. */ private static function not_found_error(): \WP_Error { return new \WP_Error( 'proofkit_not_found', __( 'The proof could not be found.', 'proofkit' ) ); } /** * Transition attempted from the wrong state. */ private static function wrong_status_error(): \WP_Error { return new \WP_Error( 'proofkit_wrong_status', __( 'This proof has already changed state. Reload the order and try again.', 'proofkit' ) ); } /** * The audit event could not be written. */ private static function event_failed_error(): \WP_Error { return new \WP_Error( 'proofkit_event_failed', __( 'Could not write the audit event.', 'proofkit' ) ); } /** * The proof link is live but the email could not be sent. */ private static function email_failed_error( int $proof_id ): \WP_Error { return new \WP_Error( 'proofkit_email_failed', __( 'The proof link is live but the email could not be sent.', 'proofkit' ), [ 'proof_id' => $proof_id, 'resend' => true, ] ); } /** * The order is in a terminal state. */ private static function order_closed_error(): \WP_Error { return new \WP_Error( 'proofkit_order_closed', __( 'This order is closed. No approval can be recorded.', 'proofkit' ) ); } /** * Generic database write failure. */ private static function db_error(): \WP_Error { return new \WP_Error( 'proofkit_db_error', __( 'The proof could not be saved. Please try again.', 'proofkit' ) ); } /** * Log operational failures at error level, regardless of WP_DEBUG. */ private static function log( string $message, array $context = [] ): void { try { if ( function_exists( 'wc_get_logger' ) ) { $logger = wc_get_logger(); if ( is_object( $logger ) && method_exists( $logger, 'error' ) ) { $logger->error( $message, [ 'source' => 'proofkit', 'context' => $context, ] ); return; } } $line = 'ProofKit: ' . $message; if ( [] !== $context ) { $encoded = function_exists( 'wp_json_encode' ) ? wp_json_encode( $context ) : json_encode( $context ); if ( is_string( $encoded ) ) { $line .= ' ' . $encoded; } } error_log( $line ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } catch ( \Throwable ) { // Logging is best-effort only. } } }