PluginProbe
Gutenberg / 23.0.1
Gutenberg v23.0.1
24.0.0 23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 All 403 releases
gutenberg / lib / media / load.php

load.php in Gutenberg 23.0.1, at lib/media/load.php

432 lines 12.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Adds media-related functionality for client-side media processing.
4 *
5 * @package gutenberg
6 */
7
8 // Client-side media processing is currently plugin-only while the feature matures.
9 if ( ! defined( 'IS_GUTENBERG_PLUGIN' ) || ! IS_GUTENBERG_PLUGIN ) {
10 return;
11 }
12
13 if ( ! gutenberg_is_client_side_media_processing_enabled() ) {
14 return;
15 }
16
17 /**
18 * Sets a global JS variable to indicate that client-side media processing is enabled.
19 */
20 function gutenberg_set_client_side_media_processing_flag() {
21 if ( ! gutenberg_is_client_side_media_processing_enabled() ) {
22 return;
23 }
24 wp_add_inline_script( 'wp-block-editor', 'window.__clientSideMediaProcessing = true', 'before' );
25 }
26 add_action( 'admin_init', 'gutenberg_set_client_side_media_processing_flag' );
27
28 /**
29 * Returns a list of all available image sizes.
30 *
31 * @return array Existing image sizes.
32 */
33 function gutenberg_get_all_image_sizes(): array {
34 $sizes = wp_get_registered_image_subsizes();
35
36 foreach ( $sizes as $name => &$size ) {
37 $size['height'] = (int) $size['height'];
38 $size['width'] = (int) $size['width'];
39 $size['name'] = $name;
40 }
41 unset( $size );
42
43 return $sizes;
44 }
45
46 /**
47 * Returns the default output format mapping for the supported image formats.
48 *
49 * @return array<string,string> Map of input formats to output formats.
50 */
51 function gutenberg_get_default_image_output_formats() {
52 $input_formats = array(
53 'image/jpeg',
54 'image/png',
55 'image/gif',
56 'image/webp',
57 'image/avif',
58 'image/heic',
59 );
60
61 $output_formats = array();
62
63 foreach ( $input_formats as $mime_type ) {
64 /** This filter is documented in wp-includes/media.php */
65 $output_formats = apply_filters(
66 'image_editor_output_format', // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
67 $output_formats,
68 '',
69 $mime_type
70 );
71 }
72
73 return $output_formats;
74 }
75
76 /**
77 * Filters the REST API root index data to add custom settings.
78 *
79 * @param WP_REST_Response $response Response data.
80 */
81 function gutenberg_media_processing_filter_rest_index( WP_REST_Response $response ) {
82 /** This filter is documented in wp-admin/includes/images.php */
83 $image_size_threshold = (int) apply_filters( 'big_image_size_threshold', 2560, array( 0, 0 ), '', 0 ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
84
85 $default_image_output_formats = gutenberg_get_default_image_output_formats();
86
87 /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
88 $jpeg_interlaced = (bool) apply_filters( 'image_save_progressive', false, 'image/jpeg' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
89 /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
90 $png_interlaced = (bool) apply_filters( 'image_save_progressive', false, 'image/png' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
91 /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
92 $gif_interlaced = (bool) apply_filters( 'image_save_progressive', false, 'image/gif' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
93
94 if ( current_user_can( 'upload_files' ) ) {
95 $response->data['image_sizes'] = gutenberg_get_all_image_sizes();
96 $response->data['image_size_threshold'] = $image_size_threshold;
97 $response->data['image_output_formats'] = (object) $default_image_output_formats;
98 $response->data['jpeg_interlaced'] = $jpeg_interlaced;
99 $response->data['png_interlaced'] = $png_interlaced;
100 $response->data['gif_interlaced'] = $gif_interlaced;
101 }
102
103 return $response;
104 }
105
106 add_filter( 'rest_index', 'gutenberg_media_processing_filter_rest_index' );
107
108
109 /**
110 * Overrides the REST controller for the attachment post type.
111 *
112 * @param array $args Array of arguments for registering a post type.
113 * See the register_post_type() function for accepted arguments.
114 * @param string $post_type Post type key.
115 */
116 function gutenberg_filter_attachment_post_type_args( array $args, string $post_type ): array {
117 if ( 'attachment' === $post_type ) {
118 require_once __DIR__ . '/class-gutenberg-rest-attachments-controller.php';
119
120 $args['rest_controller_class'] = Gutenberg_REST_Attachments_Controller::class;
121 }
122
123 return $args;
124 }
125
126 add_filter( 'register_post_type_args', 'gutenberg_filter_attachment_post_type_args', 10, 2 );
127
128
129 /**
130 * Registers additional REST fields for attachments.
131 */
132 function gutenberg_media_processing_register_rest_fields(): void {
133 register_rest_field(
134 'attachment',
135 'filename',
136 array(
137 'schema' => array(
138 'description' => __( 'Original attachment file name', 'gutenberg' ),
139 'type' => 'string',
140 'context' => array( 'view', 'edit' ),
141 ),
142 'get_callback' => 'gutenberg_rest_get_attachment_filename',
143 )
144 );
145
146 register_rest_field(
147 'attachment',
148 'filesize',
149 array(
150 'schema' => array(
151 'description' => __( 'Attachment file size', 'gutenberg' ),
152 'type' => 'number',
153 'context' => array( 'view', 'edit' ),
154 ),
155 'get_callback' => 'gutenberg_rest_get_attachment_filesize',
156 )
157 );
158 }
159
160 add_action( 'rest_api_init', 'gutenberg_media_processing_register_rest_fields' );
161
162 /**
163 * Returns the attachment's original file name.
164 *
165 * @param array $post Post data.
166 * @return string|null Attachment file name.
167 */
168 function gutenberg_rest_get_attachment_filename( array $post ): ?string {
169 $path = wp_get_original_image_path( $post['id'] );
170
171 if ( $path ) {
172 return basename( $path );
173 }
174
175 $path = get_attached_file( $post['id'] );
176
177 if ( $path ) {
178 return basename( $path );
179 }
180
181 return null;
182 }
183
184 /**
185 * Returns the attachment's file size in bytes.
186 *
187 * @param array $post Post data.
188 * @return int|null Attachment file size.
189 */
190 function gutenberg_rest_get_attachment_filesize( array $post ): ?int {
191 $attachment_id = $post['id'];
192
193 $meta = wp_get_attachment_metadata( $attachment_id );
194
195 if ( isset( $meta['filesize'] ) ) {
196 return $meta['filesize'];
197 }
198
199 $original_path = wp_get_original_image_path( $attachment_id );
200 $attached_file = $original_path ? $original_path : get_attached_file( $attachment_id );
201
202 if ( is_string( $attached_file ) && file_exists( $attached_file ) ) {
203 return wp_filesize( $attached_file );
204 }
205
206 return null;
207 }
208
209 /**
210 * Filters the list of rewrite rules formatted for output to an .htaccess file.
211 *
212 * Adds support for serving wasm-vips locally.
213 *
214 * @param string $rules mod_rewrite Rewrite rules formatted for .htaccess.
215 * @return string Filtered rewrite rules.
216 */
217 function gutenberg_filter_mod_rewrite_rules( string $rules ): string {
218 $rules .= "\n# BEGIN Gutenberg client-side media processing\n" .
219 "AddType application/wasm wasm\n" .
220 "# END Gutenberg client-side media processing\n";
221
222 return $rules;
223 }
224
225 add_filter( 'mod_rewrite_rules', 'gutenberg_filter_mod_rewrite_rules' );
226
227 /**
228 * Returns the major Chromium version from the current request's User-Agent.
229 *
230 * Matches all Chromium-based browsers (Chrome, Edge, Opera, Brave).
231 *
232 * @return int|null The major Chromium version, or null if not a Chromium browser.
233 */
234 function gutenberg_get_chromium_major_version(): ?int {
235 if ( empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
236 return null;
237 }
238 if ( preg_match( '/Chrome\/(\d+)/', $_SERVER['HTTP_USER_AGENT'], $matches ) ) {
239 return (int) $matches[1];
240 }
241 return null;
242 }
243
244 /**
245 * Enables cross-origin isolation in the block editor.
246 *
247 * Required for enabling SharedArrayBuffer for WebAssembly-based
248 * media processing in the editor. Uses Document-Isolation-Policy
249 * on supported browsers (Chromium 137+).
250 */
251 function gutenberg_set_up_cross_origin_isolation() {
252 // Re-check the filter at action time, since other plugins (loaded after Gutenberg)
253 // may have added a filter to disable client-side media processing.
254 if ( ! gutenberg_is_client_side_media_processing_enabled() ) {
255 return;
256 }
257
258 $screen = get_current_screen();
259
260 if ( ! $screen ) {
261 return;
262 }
263
264 if ( ! $screen->is_block_editor() && 'site-editor' !== $screen->id && ! ( 'widgets' === $screen->id && wp_use_widgets_block_editor() ) ) {
265 return;
266 }
267
268 // Skip when a third-party page builder overrides the block editor.
269 // DIP isolates the document into its own agent cluster,
270 // which blocks same-origin iframe access that these editors rely on.
271 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
272 if ( isset( $_GET['action'] ) && 'edit' !== $_GET['action'] ) {
273 return;
274 }
275
276 $user_id = get_current_user_id();
277 if ( ! $user_id ) {
278 return;
279 }
280
281 // Cross-origin isolation is not needed if users can't upload files anyway.
282 if ( ! user_can( $user_id, 'upload_files' ) ) {
283 return;
284 }
285
286 gutenberg_start_cross_origin_isolation_output_buffer();
287 }
288
289 add_action( 'load-post.php', 'gutenberg_set_up_cross_origin_isolation' );
290 add_action( 'load-post-new.php', 'gutenberg_set_up_cross_origin_isolation' );
291 add_action( 'load-site-editor.php', 'gutenberg_set_up_cross_origin_isolation' );
292 add_action( 'load-widgets.php', 'gutenberg_set_up_cross_origin_isolation' );
293
294 // Remove core's COEP/COOP-based cross-origin isolation in favor of
295 // Gutenberg's DIP-based approach, which also skips third-party editors.
296 remove_action( 'load-post.php', 'wp_set_up_cross_origin_isolation' );
297 remove_action( 'load-post-new.php', 'wp_set_up_cross_origin_isolation' );
298 remove_action( 'load-site-editor.php', 'wp_set_up_cross_origin_isolation' );
299 remove_action( 'load-widgets.php', 'wp_set_up_cross_origin_isolation' );
300
301 /**
302 * Sends the Document-Isolation-Policy header for cross-origin isolation.
303 *
304 * Uses an output buffer to add crossorigin="anonymous" where needed.
305 */
306 function gutenberg_start_cross_origin_isolation_output_buffer(): void {
307 $chromium_version = gutenberg_get_chromium_major_version();
308
309 /**
310 * Filters whether to use Document-Isolation-Policy for cross-origin isolation.
311 *
312 * Document-Isolation-Policy provides per-document cross-origin isolation
313 * without affecting other iframes on the page, avoiding breakage of plugins
314 * whose iframes lose credentials/DOM access.
315 *
316 * @since 21.8.0
317 *
318 * @param bool $use_dip Whether DIP is supported and should be used.
319 */
320 $use_dip = apply_filters(
321 'gutenberg_use_document_isolation_policy',
322 null !== $chromium_version && $chromium_version >= 137
323 );
324
325 if ( ! $use_dip ) {
326 return;
327 }
328
329 ob_start(
330 function ( string $output ): string {
331 header( 'Document-Isolation-Policy: isolate-and-credentialless' );
332
333 return gutenberg_add_crossorigin_attributes( $output );
334 }
335 );
336 }
337
338 /**
339 * Adds crossorigin="anonymous" to relevant tags in the given HTML string.
340 *
341 * @param string $html HTML input.
342 *
343 * @return string Modified HTML.
344 */
345 function gutenberg_add_crossorigin_attributes( string $html ): string {
346 $site_url = site_url();
347
348 $processor = new WP_HTML_Tag_Processor( $html );
349
350 // See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin.
351 $tags = array(
352 'AUDIO' => 'src',
353 'LINK' => 'href',
354 'SCRIPT' => 'src',
355 'VIDEO' => 'src',
356 'SOURCE' => 'src',
357 );
358
359 $tag_names = array_keys( $tags );
360
361 while ( $processor->next_tag() ) {
362 $tag = $processor->get_tag();
363
364 if ( ! in_array( $tag, $tag_names, true ) ) {
365 continue;
366 }
367
368 if ( 'AUDIO' === $tag || 'VIDEO' === $tag ) {
369 $processor->set_bookmark( 'audio-video-parent' );
370 }
371
372 $processor->set_bookmark( 'resume' );
373
374 $sought = false;
375
376 $crossorigin = $processor->get_attribute( 'crossorigin' );
377
378 $url = $processor->get_attribute( $tags[ $tag ] );
379
380 if ( is_string( $url ) && ! str_starts_with( $url, $site_url ) && ! str_starts_with( $url, '/' ) && ! is_string( $crossorigin ) ) {
381 if ( 'SOURCE' === $tag ) {
382 $sought = $processor->seek( 'audio-video-parent' );
383
384 if ( $sought ) {
385 $processor->set_attribute( 'crossorigin', 'anonymous' );
386 }
387 } else {
388 $processor->set_attribute( 'crossorigin', 'anonymous' );
389 }
390
391 if ( $sought ) {
392 $processor->seek( 'resume' );
393 $processor->release_bookmark( 'audio-video-parent' );
394 }
395 }
396 }
397
398 return $processor->get_updated_html();
399 }
400
401 /**
402 * Overrides templates from wp_print_media_templates with custom ones.
403 *
404 * Adds `crossorigin` attribute to all tags that
405 * could have assets loaded from a different domain.
406 */
407 function gutenberg_override_media_templates(): void {
408 remove_action( 'admin_footer', 'wp_print_media_templates' );
409 add_action(
410 'admin_footer',
411 static function (): void {
412 ob_start();
413 wp_print_media_templates();
414 $html = (string) ob_get_clean();
415
416 $tags = array(
417 'audio',
418 'img',
419 'video',
420 );
421
422 foreach ( $tags as $tag ) {
423 $html = (string) str_replace( "<$tag", "<$tag crossorigin=\"anonymous\"", $html );
424 }
425
426 echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
427 }
428 );
429 }
430
431 add_action( 'wp_enqueue_media', 'gutenberg_override_media_templates' );
432