prefix . 'ToDownload_license_keys' ); $now = current_time('mysql'); // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Internal plugin table. $download_ids = []; foreach ($items as $it) { $download_id = (int) ($it['download_id'] ?? 0); if ($download_id) { $download_ids[$download_id] = true; } } foreach (array_keys($download_ids) as $download_id) { $existing = (string) $wpdb->get_var( $wpdb->prepare( "SELECT license_key FROM " . $table . " WHERE order_id = %d AND download_id = %d LIMIT 1", $order_id, $download_id ) ); if ($existing !== '') { continue; } $key = self::generate_key($order_id, $download_id); $wpdb->insert($table, [ 'order_id' => $order_id, 'download_id' => $download_id, 'license_key' => $key, 'created_at' => $now, ]); } } public static function get_for_order(int $order_id): array { global $wpdb; $table = esc_sql( $wpdb->prefix . 'ToDownload_license_keys' ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT download_id, license_key FROM " . $table . " WHERE order_id = %d ORDER BY download_id ASC", $order_id ), ARRAY_A ); return is_array($rows) ? $rows : []; } public static function get_for_item(int $order_id, int $download_id): string { global $wpdb; $table = esc_sql( $wpdb->prefix . 'ToDownload_license_keys' ); $val = $wpdb->get_var( $wpdb->prepare( "SELECT license_key FROM " . $table . " WHERE order_id = %d AND download_id = %d LIMIT 1", $order_id, $download_id ) ); // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching return is_string($val) ? $val : ''; } private static function generate_key(int $order_id, int $download_id): string { // Format: XXXX-XXXX-XXXX-XXXX (no PII) $bytes = random_bytes(16); $hex = strtoupper(bin2hex($bytes)); $hex = substr($hex, 0, 16) . substr($hex, 16, 16); $parts = str_split(substr($hex, 0, 16), 4); return implode('-', $parts); } }