| 1 |
<?php |
| 2 |
/** |
| 3 |
* REST API: WP_REST_Edit_Site_Export_Controller class |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
* @subpackage REST_API |
| 7 |
*/ |
| 8 |
|
| 9 |
/** |
| 10 |
* Controller which provides REST endpoint for exporting current templates |
| 11 |
* and template parts. |
| 12 |
* |
| 13 |
* @since 5.9.0 |
| 14 |
* |
| 15 |
* @see WP_REST_Controller |
| 16 |
*/ |
| 17 |
class WP_REST_Edit_Site_Export_Controller extends WP_REST_Controller { |
| 18 |
|
| 19 |
/** |
| 20 |
* Constructs the controller. |
| 21 |
*/ |
| 22 |
public function __construct() { |
| 23 |
$this->namespace = 'wp-block-editor/v1'; |
| 24 |
$this->rest_base = 'export'; |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Registers the necessary REST API routes. |
| 29 |
*/ |
| 30 |
public function register_routes() { |
| 31 |
register_rest_route( |
| 32 |
$this->namespace, |
| 33 |
'/' . $this->rest_base, |
| 34 |
array( |
| 35 |
array( |
| 36 |
'methods' => WP_REST_Server::READABLE, |
| 37 |
'callback' => array( $this, 'export' ), |
| 38 |
'permission_callback' => array( $this, 'permissions_check' ), |
| 39 |
), |
| 40 |
) |
| 41 |
); |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Checks whether a given request has permission to export. |
| 46 |
* |
| 47 |
* @return WP_Error|bool True if the request has access, or WP_Error object. |
| 48 |
*/ |
| 49 |
public function permissions_check() { |
| 50 |
if ( current_user_can( 'edit_theme_options' ) ) { |
| 51 |
return true; |
| 52 |
} |
| 53 |
|
| 54 |
return new WP_Error( |
| 55 |
'rest_cannot_view_url_details', |
| 56 |
__( 'Sorry, you are not allowed to export templates and template parts.', 'gutenberg' ), |
| 57 |
array( 'status' => rest_authorization_required_code() ) |
| 58 |
); |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Output a ZIP file with an export of the current templates |
| 63 |
* and template parts from the site editor, and close the connection. |
| 64 |
* |
| 65 |
* @return WP_Error|void |
| 66 |
*/ |
| 67 |
public function export() { |
| 68 |
// Generate the export file. |
| 69 |
$filename = wp_generate_block_templates_export_file(); |
| 70 |
|
| 71 |
if ( is_wp_error( $filename ) ) { |
| 72 |
return $filename; |
| 73 |
} |
| 74 |
|
| 75 |
header( 'Content-Type: application/zip' ); |
| 76 |
header( 'Content-Disposition: attachment; filename=edit-site-export.zip' ); |
| 77 |
header( 'Content-Length: ' . filesize( $filename ) ); |
| 78 |
flush(); |
| 79 |
readfile( $filename ); |
| 80 |
unlink( $filename ); |
| 81 |
exit; |
| 82 |
} |
| 83 |
} |
| 84 |
|