-
Notifications
You must be signed in to change notification settings - Fork 31
/
safe-svg.php
802 lines (695 loc) · 24.8 KB
/
safe-svg.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
<?php
/**
* Plugin Name: Safe SVG
* Plugin URI: https://wordpress.org/plugins/safe-svg/
* Description: Enable SVG uploads and sanitize them to stop XML/SVG vulnerabilities in your WordPress website
* Version: 2.2.6
* Requires at least: 6.5
* Requires PHP: 7.4
* Author: 10up
* Author URI: https://10up.com
* License: GPL-2.0-or-later
* License URI: https://spdx.org/licenses/GPL-2.0-or-later.html
* Text Domain: safe-svg
* Domain Path: /languages
*
* @package safe-svg
*/
namespace SafeSvg;
use enshrined\svgSanitize\Sanitizer;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
define( 'SAFE_SVG_VERSION', '2.2.6' );
define( 'SAFE_SVG_PLUGIN_DIR', __DIR__ );
define( 'SAFE_SVG_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
/**
* Get the minimum version of PHP required by this plugin.
*
* @since 2.1.1
*
* @return string Minimum version required.
*/
function minimum_php_requirement() {
return '7.4';
}
/**
* Whether PHP installation meets the minimum requirements
*
* @since 2.1.1
*
* @return bool True if meets minimum requirements, false otherwise.
*/
function site_meets_php_requirements() {
return version_compare( phpversion(), minimum_php_requirement(), '>=' );
}
// Try and include our autoloader, ensuring our PHP version is met first.
if ( ! site_meets_php_requirements() ) {
add_action(
'admin_notices',
function() {
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses_post(
sprintf(
/* translators: %s: Minimum required PHP version */
__( 'Safe SVG requires PHP version %s or later. Please upgrade PHP or disable the plugin.', 'safe-svg' ),
esc_html( minimum_php_requirement() )
)
);
?>
</p>
</div>
<?php
}
);
return;
} elseif ( is_readable( __DIR__ . '/vendor/autoload.php' ) ) {
require __DIR__ . '/vendor/autoload.php';
} elseif ( ! class_exists( Sanitizer::class ) ) {
add_action(
'admin_notices',
function() {
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses_post(
sprintf(
/* translators: %1$s is the command that needs to be run. */
__( 'You appear to be running a development version of Safe SVG. Please run %1$s in order for things to work properly.', 'safe-svg' ),
'<code>composer install</code>'
)
);
?>
</p>
</div>
<?php
}
);
return;
}
require __DIR__ . '/includes/safe-svg-tags.php';
require __DIR__ . '/includes/safe-svg-attributes.php';
require __DIR__ . '/includes/safe-svg-settings.php';
require __DIR__ . '/includes/blocks.php';
require __DIR__ . '/includes/optimizer.php';
new \SafeSVG\Optimizer();
if ( ! class_exists( 'SafeSvg\\safe_svg' ) ) {
/**
* Class safe_svg
*/
class safe_svg {
/**
* The sanitizer
*
* @var \enshrined\svgSanitize\Sanitizer
*/
protected $sanitizer;
/**
* Set up the class
*/
public function __construct() {
$this->sanitizer = new Sanitizer();
$this->sanitizer->minify( true );
// Allow SVG uploads from specific contexts.
add_action( 'load-upload.php', array( $this, 'allow_svg_from_upload' ) );
add_action( 'load-post-new.php', array( $this, 'allow_svg_from_upload' ) );
add_action( 'load-post.php', array( $this, 'allow_svg_from_upload' ) );
add_action( 'load-site-editor.php', array( $this, 'allow_svg_from_upload' ) );
// Init all the things.
add_action( 'init', array( $this, 'setup_blocks' ) );
add_filter( 'wp_handle_sideload_prefilter', array( $this, 'check_for_svg' ) );
add_filter( 'wp_handle_upload_prefilter', array( $this, 'check_for_svg' ) );
add_filter( 'wp_prepare_attachment_for_js', array( $this, 'fix_admin_preview' ), 10, 3 );
add_filter( 'wp_get_attachment_image_src', array( $this, 'one_pixel_fix' ), 10, 4 );
add_filter( 'admin_post_thumbnail_html', array( $this, 'featured_image_fix' ), 10, 3 );
add_action( 'admin_enqueue_scripts', array( $this, 'load_custom_admin_style' ) );
add_action( 'get_image_tag', array( $this, 'get_image_tag_override' ), 10, 6 );
add_filter( 'wp_generate_attachment_metadata', array( $this, 'skip_svg_regeneration' ), 10, 2 );
add_filter( 'wp_get_attachment_metadata', array( $this, 'metadata_error_fix' ), 10, 2 );
add_filter( 'wp_calculate_image_srcset_meta', array( $this, 'disable_srcset' ), 10, 4 );
new safe_svg_settings();
}
/**
* Allow SVG uploads from the wp-admin/upload.php screen. Without this, you cannot upload SVGs from the media grid view.
*
* @return void
*/
public function allow_svg_from_upload() {
add_filter( 'upload_mimes', array( $this, 'allow_svg' ) );
add_filter( 'wp_check_filetype_and_ext', array( $this, 'fix_mime_type_svg' ), 75, 4 );
}
/**
* Custom function to check if user can upload svg.
*
* Use core caps if setting hasn't every been updated.
*
* @return bool
*/
public function current_user_can_upload_svg() {
$upload_roles = get_option( 'safe_svg_upload_roles', [] );
$can_upload = false;
if ( empty( $upload_roles ) ) {
// Fallback to upload_files check for backwards compatibility.
$can_upload = current_user_can( 'upload_files' );
} else {
// Use our custom capability if some upload roles are set.
$can_upload = current_user_can( 'safe_svg_upload_svg' );
}
/**
* Determine if the current user can upload an svg.
*
* @param bool $can_upload Can the current user upload an svg?
*
* @return bool
*/
return (bool) apply_filters( 'safe_svg_current_user_can_upload', $can_upload );
}
/**
* Setup the blocks.
*/
public function setup_blocks() {
// Setup blocks.
Blocks\setup();
}
/**
* Allow SVG Uploads
*
* @param array $mimes Mime types keyed by the file extension regex corresponding to those types.
*
* @return mixed
*/
public function allow_svg( $mimes ) {
if ( $this->current_user_can_upload_svg() ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['svgz'] = 'image/svg+xml';
}
return $mimes;
}
/**
* Fixes the issue in WordPress 4.7.1 being unable to correctly identify SVGs
*
* @thanks @lewiscowles
*
* @param array $data Values for the extension, mime type, and corrected filename.
* @param string $file Full path to the file.
* @param string $filename The name of the file.
* @param string[] $mimes Array of mime types keyed by their file extension regex.
*
* @return null
*/
public function fix_mime_type_svg( $data = null, $file = null, $filename = null, $mimes = null ) {
$ext = isset( $data['ext'] ) ? $data['ext'] : '';
if ( strlen( $ext ) < 1 ) {
$exploded = explode( '.', $filename );
$ext = strtolower( end( $exploded ) );
}
if ( 'svg' === $ext ) {
$data['type'] = 'image/svg+xml';
$data['ext'] = 'svg';
} elseif ( 'svgz' === $ext ) {
$data['type'] = 'image/svg+xml';
$data['ext'] = 'svgz';
}
return $data;
}
/**
* Check if the file is an SVG, if so handle appropriately
*
* @param array $file An array of data for a single file.
*
* @return mixed
*/
public function check_for_svg( $file ) {
// Ensure we have a proper file path before processing
if ( ! isset( $file['tmp_name'] ) ) {
return $file;
}
$file_name = isset( $file['name'] ) ? $file['name'] : '';
// Allow SVGs to be uploaded when this function runs.
add_filter( 'upload_mimes', array( $this, 'allow_svg' ) );
add_filter( 'wp_check_filetype_and_ext', array( $this, 'fix_mime_type_svg' ), 75, 4 );
$wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file_name );
// Remove the SVG mime type after we've sanitized the file.
// We need to utilize the pre_move_uploaded_file filter to ensure we can remove the filters after the file has been full-processed.
// This is because wp_check_filetype_and_ext() is called multiple times during the upload process.
add_filter( 'pre_move_uploaded_file', array( $this, 'pre_move_uploaded_file' ) );
$type = ! empty( $wp_filetype['type'] ) ? $wp_filetype['type'] : '';
if ( 'image/svg+xml' === $type ) {
if ( ! $this->current_user_can_upload_svg() ) {
$file['error'] = __(
'Sorry, you are not allowed to upload SVG files.',
'safe-svg'
);
return $file;
}
if ( ! $this->sanitize( $file['tmp_name'] ) ) {
$file['error'] = __(
"Sorry, this file couldn't be sanitized so for security reasons wasn't uploaded",
'safe-svg'
);
}
}
return $file;
}
/**
* Remove the filters after the file has been processed.
*
* We need to utilize the pre_move_uploaded_file filter to ensure we can remove the filters after the file has been full-processed.
* This is because wp_check_filetype_and_ext() is called multiple times during the upload process.
*
* @param string $move_new_file The new file path. We don't touch this, just return it.
*
* @return string
*/
public function pre_move_uploaded_file( $move_new_file ) {
remove_filter( 'wp_check_filetype_and_ext', array( $this, 'fix_mime_type_svg' ), 75 );
remove_filter( 'upload_mimes', array( $this, 'allow_svg' ) );
return $move_new_file;
}
/**
* Sanitize the SVG
*
* @param string $file Temp file path.
*
* @return bool|int
*/
protected function sanitize( $file ) {
$dirty = file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
// Is the SVG gzipped? If so we try and decode the string
$is_zipped = $this->is_gzipped( $dirty );
if ( $is_zipped ) {
$dirty = gzdecode( $dirty );
// If decoding fails, bail as we're not secure
if ( false === $dirty ) {
return false;
}
}
// Allow large SVGs if the setting is on.
if ( get_option( 'safe_svg_large_svg' ) ) {
$this->sanitizer->setAllowHugeFiles( true );
}
/**
* Load extra filters to allow devs to access the safe tags and attrs by themselves.
*/
$this->sanitizer->setAllowedTags( new SafeSvgTags\safe_svg_tags() );
$this->sanitizer->setAllowedAttrs( new SafeSvgAttr\safe_svg_attributes() );
$clean = $this->sanitizer->sanitize( $dirty );
if ( false === $clean ) {
return false;
}
// If we were gzipped, we need to re-zip
if ( $is_zipped ) {
$clean = gzencode( $clean );
}
file_put_contents( $file, $clean ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
return true;
}
/**
* Check if the contents are gzipped
*
* @see http://www.gzip.org/zlib/rfc-gzip.html#member-format
*
* @param string $contents Content to check.
*
* @return bool
*/
protected function is_gzipped( $contents ) {
// phpcs:disable Generic.Strings.UnnecessaryStringConcat.Found
if ( function_exists( 'mb_strpos' ) ) {
return 0 === mb_strpos( $contents, "\x1f" . "\x8b" . "\x08" );
} else {
return 0 === strpos( $contents, "\x1f" . "\x8b" . "\x08" );
}
// phpcs:enable
}
/**
* Filters the attachment data prepared for JavaScript to add the sizes array to the response
*
* @param array $response Array of prepared attachment data.
* @param int|object $attachment Attachment ID or object.
* @param array $meta Array of attachment meta data.
*
* @return array
*/
public function fix_admin_preview( $response, $attachment, $meta ) {
if ( 'image/svg+xml' === $response['mime'] ) {
$dimensions = $this->svg_dimensions( $attachment->ID );
if ( $dimensions ) {
$response = array_merge( $response, $dimensions );
}
$possible_sizes = apply_filters(
'image_size_names_choose',
array(
'full' => __( 'Full Size' ),
'thumbnail' => __( 'Thumbnail' ),
'medium' => __( 'Medium' ),
'large' => __( 'Large' ),
)
);
$sizes = array();
foreach ( $possible_sizes as $size => $label ) {
$default_height = 2000;
$default_width = 2000;
if ( 'full' === $size && $dimensions ) {
$default_height = $dimensions['height'];
$default_width = $dimensions['width'];
}
$sizes[ $size ] = array(
'height' => get_option( "{$size}_size_w", $default_height ),
'width' => get_option( "{$size}_size_h", $default_width ),
'url' => $response['url'],
'orientation' => 'portrait',
);
}
$response['sizes'] = $sizes;
$response['icon'] = $response['url'];
}
return $response;
}
/**
* Filters the image src result.
* If the image size doesn't exist, set a default size of 100 for width and height
*
* @param array|false $image Either array with src, width & height, icon src, or false.
* @param int $attachment_id Image attachment ID.
* @param string|array $size Size of image. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
* @param bool $icon Whether the image should be treated as an icon. Default false.
*
* @return array
*/
public function one_pixel_fix( $image, $attachment_id, $size, $icon ) {
if ( get_post_mime_type( $attachment_id ) === 'image/svg+xml' ) {
$dimensions = $this->get_svg_dimensions( $attachment_id, $size );
if ( is_array( $dimensions ) && isset( $dimensions['height'], $dimensions['width'] ) ) {
$image[1] = $dimensions['width'];
$image[2] = $dimensions['height'];
} else {
$image[1] = 100;
$image[2] = 100;
}
}
return $image;
}
/**
* If the featured image is an SVG we wrap it in an SVG class so we can apply our CSS fix.
*
* @param string $content Admin post thumbnail HTML markup.
* @param int $post_id Post ID.
* @param int|null $thumbnail_id Thumbnail attachment ID, or null if there isn't one.
*
* @return string
*/
public function featured_image_fix( $content, $post_id, $thumbnail_id = null ) {
$mime = get_post_mime_type( $thumbnail_id );
if ( 'image/svg+xml' === $mime ) {
$content = sprintf( '<span class="svg">%s</span>', $content );
}
return $content;
}
/**
* Load our custom CSS sheet.
*/
public function load_custom_admin_style() {
wp_enqueue_style( 'safe-svg-css', plugins_url( 'assets/safe-svg.css', __FILE__ ), array(), SAFE_SVG_VERSION );
}
/**
* Override the default height and width string on an SVG
*
* @param string $html HTML content for the image.
* @param int $id Attachment ID.
* @param string $alt Alternate text.
* @param string $title Attachment title.
* @param string $align Part of the class name for aligning the image.
* @param string|array $size Size of image. Image size or array of width and height values (in that order).
* Default 'medium'.
*
* @return mixed
*/
public function get_image_tag_override( $html, $id, $alt, $title, $align, $size ) {
$mime = get_post_mime_type( $id );
if ( 'image/svg+xml' === $mime ) {
$dimensions = $this->get_svg_dimensions( $id, $size );
if ( is_array( $dimensions ) && isset( $dimensions['height'], $dimensions['width'] ) ) {
$html = str_replace( 'width="1" ', sprintf( 'width="%s" ', $dimensions['width'] ), $html );
$html = str_replace( 'height="1" ', sprintf( 'height="%s" ', $dimensions['height'] ), $html );
} else {
$html = str_replace( 'width="1" ', '', $html );
$html = str_replace( 'height="1" ', '', $html );
}
$html = str_replace( '/>', ' role="img" />', $html );
}
return $html;
}
/**
* Skip regenerating SVGs
*
* @param array $metadata An array of attachment meta data.
* @param int $attachment_id Attachment Id to process.
*
* @return mixed Metadata for attachment.
*/
public function skip_svg_regeneration( $metadata, $attachment_id ) {
$mime = get_post_mime_type( $attachment_id );
if ( 'image/svg+xml' === $mime ) {
$additional_image_sizes = wp_get_additional_image_sizes();
$svg_path = get_attached_file( $attachment_id );
$upload_dir = wp_upload_dir();
// get the path relative to /uploads/ - found no better way:
$relative_path = str_replace( trailingslashit( $upload_dir['basedir'] ), '', $svg_path );
$filename = basename( $svg_path );
$dimensions = $this->svg_dimensions( $attachment_id );
if ( ! $dimensions ) {
return $metadata;
}
$metadata = array(
'width' => intval( $dimensions['width'] ),
'height' => intval( $dimensions['height'] ),
'file' => $relative_path,
);
// Might come handy to create the sizes array too - But it's not needed for this workaround! Always links to original svg-file => Hey, it's a vector graphic! ;)
$sizes = array();
foreach ( get_intermediate_image_sizes() as $s ) {
$sizes[ $s ] = array(
'width' => '',
'height' => '',
'crop' => false,
);
if ( isset( $additional_image_sizes[ $s ]['width'] ) ) {
// For theme-added sizes
$sizes[ $s ]['width'] = intval( $additional_image_sizes[ $s ]['width'] );
} else {
// For default sizes set in options
$sizes[ $s ]['width'] = get_option( "{$s}_size_w" );
}
if ( isset( $additional_image_sizes[ $s ]['height'] ) ) {
// For theme-added sizes
$sizes[ $s ]['height'] = intval( $additional_image_sizes[ $s ]['height'] );
} else {
// For default sizes set in options
$sizes[ $s ]['height'] = get_option( "{$s}_size_h" );
}
if ( isset( $additional_image_sizes[ $s ]['crop'] ) ) {
// For theme-added sizes
$sizes[ $s ]['crop'] = intval( $additional_image_sizes[ $s ]['crop'] );
} else {
// For default sizes set in options
$sizes[ $s ]['crop'] = get_option( "{$s}_crop" );
}
$sizes[ $s ]['file'] = $filename;
$sizes[ $s ]['mime-type'] = $mime;
}
$metadata['sizes'] = $sizes;
}
return $metadata;
}
/**
* Filters the attachment meta data.
*
* @param array|bool $data Array of meta data for the given attachment, or false
* if the object does not exist.
* @param int $post_id Attachment ID.
*/
public function metadata_error_fix( $data, $post_id ) {
// If it's a WP_Error regenerate metadata and save it
if ( is_wp_error( $data ) ) {
$data = wp_generate_attachment_metadata( $post_id, get_attached_file( $post_id ) );
wp_update_attachment_metadata( $post_id, $data );
}
return $data;
}
/**
* Get SVG size from the width/height or viewport.
*
* @param integer $attachment_id The attachment ID of the SVG being processed.
*
* @return array|bool
*/
protected function svg_dimensions( $attachment_id ) {
/**
* Calculate SVG dimensions and orientation.
*
* This filter allows you to implement your own sizing. By returning a non-false
* value, it will short-circuit this function and return your set value.
*
* @param boolean Default value of the filter.
* @param integer $attachment_id The attachment ID of the SVG being processed.
*
* @return array|false An array of SVG dimensions and orientation or false.
*/
$short_circuit = apply_filters( 'safe_svg_pre_dimensions', false, $attachment_id );
if ( false !== $short_circuit ) {
return $short_circuit;
}
if ( ! function_exists( 'simplexml_load_file' ) ) {
return false;
}
$svg = get_attached_file( $attachment_id );
$metadata = wp_get_attachment_metadata( $attachment_id );
$width = 0;
$height = 0;
if ( $svg && ! empty( $metadata['width'] ) && ! empty( $metadata['height'] ) ) {
$width = floatval( $metadata['width'] );
$height = floatval( $metadata['height'] );
} elseif ( $svg ) {
$svg = @simplexml_load_file( $svg ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
// Ensure the svg could be loaded.
if ( ! $svg ) {
return false;
}
$attributes = $svg->attributes();
if ( isset( $attributes->viewBox ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$sizes = explode( ' ', $attributes->viewBox ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( isset( $sizes[2], $sizes[3] ) ) {
$viewbox_width = floatval( $sizes[2] );
$viewbox_height = floatval( $sizes[3] );
}
}
if ( isset( $attributes->width, $attributes->height ) && is_numeric( (float) $attributes->width ) && is_numeric( (float) $attributes->height ) && ! $this->str_ends_with( (string) $attributes->width, '%' ) && ! $this->str_ends_with( (string) $attributes->height, '%' ) ) {
$attr_width = floatval( $attributes->width );
$attr_height = floatval( $attributes->height );
}
/**
* Decide which attributes of the SVG we use first for image tag dimensions.
*
* We default to using the parameters in the viewbox attribute but
* that can be overridden using this filter if you'd prefer to use
* the width and height attributes.
*
* @hook safe_svg_use_width_height_attributes
*
* @param bool $use_width_height_attributes If the width & height attributes should be used first. Default false.
* @param string $svg The file path to the SVG.
*
* @return bool If we should use the width & height attributes first or not.
*/
$use_width_height = (bool) apply_filters( 'safe_svg_use_width_height_attributes', false, $svg );
if ( $use_width_height ) {
if ( isset( $attr_width, $attr_height ) ) {
$width = $attr_width;
$height = $attr_height;
} elseif ( isset( $viewbox_width, $viewbox_height ) ) {
$width = $viewbox_width;
$height = $viewbox_height;
}
} else {
if ( isset( $viewbox_width, $viewbox_height ) ) {
$width = $viewbox_width;
$height = $viewbox_height;
} elseif ( isset( $attr_width, $attr_height ) ) {
$width = $attr_width;
$height = $attr_height;
}
}
if ( ! $width && ! $height ) {
return false;
}
}
$dimensions = array(
'width' => $width,
'height' => $height,
'orientation' => ( $width > $height ) ? 'landscape' : 'portrait',
);
/**
* Calculate SVG dimensions and orientation.
*
* @param array $dimensions An array containing width, height, and orientation.
* @param string $svg The file path to the SVG.
*
* @return array An array of SVG dimensions and orientation.
*/
return apply_filters( 'safe_svg_dimensions', $dimensions, $svg );
}
/**
* Disable the creation of srcset on SVG images.
*
* @param array $image_meta The image meta data.
* @param int[] $size_array {
* An array of requested width and height values.
*
* @type int $0 The width in pixels.
* @type int $1 The height in pixels.
* }
* @param string $image_src The 'src' of the image.
* @param int $attachment_id The image attachment ID.
*/
public function disable_srcset( $image_meta, $size_array, $image_src, $attachment_id ) {
if ( $attachment_id && 'image/svg+xml' === get_post_mime_type( $attachment_id ) && is_array( $image_meta ) ) {
$image_meta['sizes'] = array();
}
return $image_meta;
}
/**
* Polyfill for `str_ends_with()` function added in PHP 8.0.
*
* Performs a case-sensitive check indicating if
* the haystack ends with needle.
*
* @param string $haystack The string to search in.
* @param string $needle The substring to search for in the `$haystack`.
* @return bool True if `$haystack` ends with `$needle`, otherwise false.
*/
protected function str_ends_with( $haystack, $needle ) {
if ( function_exists( 'str_ends_with' ) ) {
return str_ends_with( $haystack, $needle );
}
if ( '' === $haystack && '' !== $needle ) {
return false;
}
$len = strlen( $needle );
return 0 === substr_compare( $haystack, $needle, -$len, $len );
}
/**
* Return custom width or height of the SVG image.
*
* @param int $id Image attachment ID.
* @param string|array $size Size of image. Image size or array of width and height values
* (in that order). Default 'thumbnail'.
*
* @return array|bool Width or height of the SVG image, or false if not found.
*/
protected function get_svg_dimensions( $id, $size ) {
$dimensions = $this->svg_dimensions( $id );
if ( is_array( $size ) ) {
$width = $size[0];
$height = $size[1];
} elseif ( 'full' === $size && is_array( $dimensions ) && isset( $dimensions['width'], $dimensions['height'] ) ) {
$width = $dimensions['width'];
$height = $dimensions['height'];
} else {
$width = get_option( "{$size}_size_w", false );
$height = get_option( "{$size}_size_h", false );
}
if ( $dimensions ) {
$dimensions['width'] = $width;
$dimensions['height'] = $height;
}
return $dimensions;
}
}
}
new safe_svg();