sprintf( /* translators: 1: file format, 2: number of rows. */ __( 'Exported the activity journal as %1$s (%2$d rows).', 'admintrace-activity-logger' ), strtoupper( $format ), count( $rows ) ), 'category' => 'privacy', 'action' => 'privacy.export', 'severity' => 'notice', 'logger' => 'export', 'initiator' => 'user', ) ); nocache_headers(); header( 'X-Content-Type-Options: nosniff' ); $filename = 'admintrace-activity-logger-' . gmdate( 'Ymd-His' ) . '.' . $format; if ( 'json' === $format ) { header( 'Content-Type: application/json; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); echo self::json( $rows ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- a JSON download; json() escapes tags, ampersands, and quotes. exit; } header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); echo "\xEF\xBB\xBF"; self::write_csv( fopen( 'php://output', 'w' ), $rows ); exit; } /** * JSON body of an export. * * @param array $rows Rows from collect(). * @return string */ public static function json( array $rows ) { return (string) wp_json_encode( $rows, JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); } /** * Write the CSV header and rows to a stream. * * @param resource $out Writable stream. * @param array $rows Rows from collect(). */ public static function write_csv( $out, array $rows ) { $headers = array( 'id', 'created_gmt', 'created_ms', 'user_login', 'user_display', 'user_role', 'initiator', 'ip_masked', 'severity', 'category', 'action', 'object_type', 'object_id', 'object_title', 'summary', 'context' ); fputcsv( $out, $headers, ',', '"', '\\' ); foreach ( $rows as $row ) { $context = isset( $row['context'] ) ? wp_json_encode( $row['context'] ) : ''; $line = array( isset( $row['id'] ) ? $row['id'] : '', isset( $row['created_gmt'] ) ? $row['created_gmt'] : '', isset( $row['created_ms'] ) ? $row['created_ms'] : 0, isset( $row['user_login'] ) ? $row['user_login'] : '', isset( $row['user_display'] ) ? $row['user_display'] : '', isset( $row['user_role'] ) ? $row['user_role'] : '', isset( $row['initiator'] ) ? $row['initiator'] : '', isset( $row['ip_masked'] ) ? $row['ip_masked'] : '', isset( $row['severity'] ) ? $row['severity'] : '', isset( $row['category'] ) ? $row['category'] : '', isset( $row['action'] ) ? $row['action'] : '', isset( $row['object_type'] ) ? $row['object_type'] : '', isset( $row['object_id'] ) ? $row['object_id'] : '', isset( $row['object_title'] ) ? $row['object_title'] : '', isset( $row['summary'] ) ? $row['summary'] : '', $context, ); fputcsv( $out, array_map( array( Csv::class, 'cell' ), $line ), ',', '"', '\\' ); } } }