| 1 |
<?php |
| 2 |
namespace FileBird\Classes; |
| 3 |
|
| 4 |
use enshrined\svgSanitize\Sanitizer; |
| 5 |
|
| 6 |
class Svg { |
| 7 |
public function __construct() { |
| 8 |
if( get_option( 'njt_fbv_allow_svg_upload' ) !== '1' ) { |
| 9 |
return; |
| 10 |
} |
| 11 |
add_filter( 'upload_mimes', array( $this, 'upload_mimes' ) ); |
| 12 |
add_filter( 'wp_check_filetype_and_ext', array( $this, 'wp_check_filetype_and_ext' ), 10, 4 ); |
| 13 |
add_filter( 'wp_handle_upload_prefilter', array( $this, 'wp_handle_upload_prefilter' ) ); |
| 14 |
} |
| 15 |
|
| 16 |
public function upload_mimes( $mimes ) { |
| 17 |
$mimes['svg'] = 'image/svg+xml'; |
| 18 |
$mimes['svgz'] = 'image/svg+xml'; |
| 19 |
|
| 20 |
return $mimes; |
| 21 |
} |
| 22 |
|
| 23 |
public function wp_check_filetype_and_ext( $data, $file, $filename, $mimes ) { |
| 24 |
global $wp_version; |
| 25 |
if ( $wp_version !== '4.7.1' ) { |
| 26 |
return $data; |
| 27 |
} |
| 28 |
|
| 29 |
$filetype = wp_check_filetype( $filename, $mimes ); |
| 30 |
|
| 31 |
return [ |
| 32 |
'ext' => $filetype['ext'], |
| 33 |
'type' => $filetype['type'], |
| 34 |
'proper_filename' => $data['proper_filename'] |
| 35 |
]; |
| 36 |
} |
| 37 |
public function wp_handle_upload_prefilter( $file ) { |
| 38 |
if ( ! isset( $file['tmp_name'] ) ) { |
| 39 |
return $file; |
| 40 |
} |
| 41 |
|
| 42 |
$file_name = isset( $file['name'] ) ? $file['name'] : ''; |
| 43 |
$wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file_name ); |
| 44 |
$type = ! empty( $wp_filetype['type'] ) ? $wp_filetype['type'] : ''; |
| 45 |
|
| 46 |
if( 'image/svg+xml' !== $type ) { |
| 47 |
return $file; |
| 48 |
} |
| 49 |
|
| 50 |
$sanitizer = new Sanitizer(); |
| 51 |
$dirtySVG = file_get_contents( $file['tmp_name'] ); |
| 52 |
$cleanSVG = $sanitizer->sanitize( $dirtySVG ); |
| 53 |
|
| 54 |
if ( $cleanSVG ) { |
| 55 |
file_put_contents( $file['tmp_name'], $cleanSVG ); |
| 56 |
} else { |
| 57 |
$file['error'] = __( 'This file couldn\'t be uploaded.', 'filebird' ); |
| 58 |
} |
| 59 |
|
| 60 |
return $file; |
| 61 |
} |
| 62 |
} |
| 63 |
|