self::ACTION, 'export' => (int) $export_id, '_wpnonce' => wp_create_nonce( self::ACTION . '_' . (int) $export_id ), ), admin_url( 'admin-post.php' ) ); } /** * Handles the request. * * @return void */ public static function handle() { $export_id = isset( $_GET['export'] ) ? (int) $_GET['export'] : 0; if ( ! current_user_can( Auth::read_capability() ) || ! check_admin_referer( self::ACTION . '_' . $export_id ) ) { wp_die( esc_html__( 'You do not have permission to download this export.', 'recast-subscriptions' ), 403 ); } $repo = new ExportRepository(); $export = $repo->get( $export_id ); if ( ! $export || ! ExportRepository::viewable( $export ) ) { wp_die( esc_html__( 'Export not found.', 'recast-subscriptions' ), 404 ); } $download_name = sprintf( 'subscriptions-%s.csv', gmdate( 'Ymd-His', strtotime( $export['created_at'] . ' UTC' ) ) ); if ( 'stream' === $export['mode'] ) { try { $spec = CohortSpec::from_array( $export['spec'] ); } catch ( InvalidSpecException $e ) { wp_die( esc_html( $e->getMessage() ), 400 ); } $repo->update( $export_id, array( 'status' => ExportRepository::STATUS_RUNNING ) ); StreamExporter::send( $spec, $download_name ); $repo->update( $export_id, array( 'status' => ExportRepository::STATUS_READY, 'finished_at' => current_time( 'mysql', true ), ) ); exit; } if ( ExportRepository::STATUS_READY !== $export['status'] || ! $export['file_name'] ) { wp_die( esc_html__( 'This export is not ready yet.', 'recast-subscriptions' ), 409 ); } $path = Storage::path( $export['file_name'] ); if ( ! file_exists( $path ) ) { wp_die( esc_html__( 'The export file was deleted.', 'recast-subscriptions' ), 410 ); } nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . sanitize_file_name( $download_name ) . '"' ); header( 'Content-Length: ' . (string) filesize( $path ) ); header( 'X-Content-Type-Options: nosniff' ); $handle = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions while ( $handle && ! feof( $handle ) ) { echo fread( $handle, 8192 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped, WordPress.WP.AlternativeFunctions flush(); } if ( $handle ) { fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions } exit; } }