| 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 $format 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( $format, $mime_type = 'text/plain' ) { |
| 19 |
header( 'Content-Disposition: attachment; filename=' . sanitize_file_name( $this->build_filename( $format ) ) ); |
| 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 $this->export_snippets_json(); |
| 30 |
exit; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Export snippets in their code file format. |
| 35 |
*/ |
| 36 |
public function download_snippets_code() { |
| 37 |
$mime_types = [ |
| 38 |
'php' => 'text/php', |
| 39 |
'css' => 'text/css', |
| 40 |
'js' => 'text/javascript', |
| 41 |
]; |
| 42 |
|
| 43 |
$type = isset( $mime_types[ $this->snippets_list[0]->type ] ) ? $this->snippets_list[0]->type : 'php'; |
| 44 |
$this->do_headers( $type, $mime_types[ $type ] ); |
| 45 |
|
| 46 |
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped |
| 47 |
echo ( 'php' === $type || 'html' === $type ) ? |
| 48 |
$this->export_snippets_php() : |
| 49 |
$this->export_snippets_code( $type ); |
| 50 |
|
| 51 |
exit; |
| 52 |
} |
| 53 |
} |
| 54 |
|