class-wp-rest-edit-site-export-controller.php 2.1 KB

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