| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets; |
| 4 |
|
| 5 |
/** |
| 6 |
* Handles exporting snippets from the site to a downloadable file over HTTP. |
| 7 |
* |
| 8 |
* @package Code_Snippets |
| 9 |
*/ |
| 10 |
class Export_Attachment extends Export { |
| 11 |
|
| 12 |
/** |
| 13 |
* Set up the current page to act like a downloadable file instead of being shown in the browser |
| 14 |
* |
| 15 |
* @param string $language File format. Used for file extension. |
| 16 |
* @param string $mime_type File MIME type. Used for Content-Type header. |
| 17 |
*/ |
| 18 |
private function do_headers( string $language, string $mime_type = 'text/plain' ) { |
| 19 |
header( 'Content-Disposition: attachment; filename=' . sanitize_file_name( $this->build_filename( $language ) ) ); |
| 20 |
header( sprintf( 'Content-Type: %s; charset=%s', sanitize_mime_type( $mime_type ), get_bloginfo( 'charset' ) ) ); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Export snippets in JSON format as a downloadable file. |
| 25 |
*/ |
| 26 |
public function download_snippets_json() { |
| 27 |
$this->do_headers( 'json', 'application/json' ); |
| 28 |
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped |
| 29 |
echo wp_json_encode( |
| 30 |
$this->create_export_object(), |
| 31 |
apply_filters( 'code_snippets/export/json_encode_options', 0 ) |
| 32 |
); |
| 33 |
exit; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Export snippets in their code file format. |
| 38 |
*/ |
| 39 |
public function download_snippets_code() { |
| 40 |
$lang = $this->snippets_list[0]->lang; |
| 41 |
|
| 42 |
$mime_types = [ |
| 43 |
'php' => 'text/php', |
| 44 |
'css' => 'text/css', |
| 45 |
'js' => 'text/javascript', |
| 46 |
'json' => 'application/json', |
| 47 |
]; |
| 48 |
|
| 49 |
$this->do_headers( $lang, $mime_types[ $lang ] ?? 'text/plain' ); |
| 50 |
|
| 51 |
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped |
| 52 |
echo $this->export_snippets_code( $this->snippets_list[0]->type ); |
| 53 |
exit; |
| 54 |
} |
| 55 |
} |
| 56 |
|