prefix . 'adpresso_import_log'; return $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY imported_at DESC LIMIT 20', $log_table ) ); } /** * Hook for admin_post to handle the rollback action. */ #[NoReturn] public static function handle_rollback_action(): void { $session_key = Params::get()->getString( 'session_key' ); $nonce = Params::get()->getString( '_wpnonce' ); if ( ! $session_key || ! wp_verify_nonce( $nonce, 'adpresso_rollback_' . $session_key ) ) { wp_die( 'Security check failed.' ); } if ( ! current_user_can( adpresso_get_capability( 'use_tools' ) ) ) { wp_die( esc_html__( 'You do not have permission to perform this action.', 'adpresso' ), 403 ); } $success = self::execute_rollback( $session_key ); if ( $success ) { self::mark_import_as_rolled_back( $session_key ); wp_safe_redirect( admin_url( 'admin.php?page=adpresso-tools&tab=history&message=rollback_success' ) ); } else { wp_safe_redirect( admin_url( 'admin.php?page=adpresso-tools&tab=history&message=rollback_failed' ) ); } exit; } /** * Deletes all AdPresso entities (ads, groups, placements) associated with a specific import session key. * * @param string $session_key * @return bool */ private static function execute_rollback( string $session_key ): bool { global $wpdb; $meta_key = \AdPresso\Constants::META_PREFIX . 'import_session_key'; // Imports only tag the entities they create; never delete other post types carrying the key. $post_types = [ Constants::POST_TYPE_AD, Constants::POST_TYPE_GROUP, Constants::POST_TYPE_PLACEMENT ]; $post_ids_to_delete = $wpdb->get_col( $wpdb->prepare( "SELECT pm.post_id FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND pm.meta_value = %s AND p.post_type IN (%s, %s, %s)", $meta_key, $session_key, ...$post_types ) ); if ( empty( $post_ids_to_delete ) ) { return true; } $deleted_count = 0; foreach ( $post_ids_to_delete as $post_id ) { if ( wp_delete_post( (int) $post_id, true ) ) { $deleted_count++; } } return $deleted_count === count( $post_ids_to_delete ); } /** * Mark an import as rolled back. * * @param string $session_key * * @return void */ private static function mark_import_as_rolled_back( string $session_key ): void { global $wpdb; $log_table = $wpdb->prefix . 'adpresso_import_log'; $wpdb->update( $log_table, [ 'status' => 'rolled_back' ], [ 'session_key' => $session_key ] ); } }