<?php
namespace FileBird\Classes\Modules;

use enshrined\svgSanitize\Sanitizer;
use FileBird\Model\SettingModel;

class ModuleSvg {
    public function __construct() {
        if ( SettingModel::getInstance()->get( 'svg_support' ) !== '1' ) {
            return;
        }
        add_filter( 'upload_mimes', array( $this, 'upload_mimes' ) );
        add_filter( 'wp_check_filetype_and_ext', array( $this, 'wp_check_filetype_and_ext' ), 10, 4 );
        add_filter( 'wp_handle_upload_prefilter', array( $this, 'wp_handle_upload_prefilter' ) );
    }

    public function upload_mimes( $mimes ) {
        $mimes['svg']  = 'image/svg+xml';
        $mimes['svgz'] = 'image/svg+xml';

        return $mimes;
    }

    public function wp_check_filetype_and_ext( $data, $file, $filename, $mimes ) {
        global $wp_version;
        if ( $wp_version !== '4.7.1' ) {
            return $data;
        }

        $filetype = wp_check_filetype( $filename, $mimes );

        return array(
            'ext'             => $filetype['ext'],
            'type'            => $filetype['type'],
            'proper_filename' => $data['proper_filename'],
        );
    }
    public function wp_handle_upload_prefilter( $file ) {
        if ( ! isset( $file['tmp_name'] ) ) {
            return $file;
        }

        $file_name   = isset( $file['name'] ) ? $file['name'] : '';
        $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file_name );
        $type        = ! empty( $wp_filetype['type'] ) ? $wp_filetype['type'] : '';

        $type = ! empty( $wp_filetype['type'] ) ? strtolower( trim( (string) $wp_filetype['type'] ) ) : '';

        // Remove optional MIME parameters like:
        // image/svg+xml; charset=utf-8
        $type = explode( ';', $type )[0];
        $ext = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );

        // Only continue for SVG uploads.
        if ( 'image/svg+xml' !== $type && 'svg' !== $ext ) {
            return $file;
        }

        $sanitizer = new Sanitizer();
        $dirtySVG  = file_get_contents( $file['tmp_name'] );
        $cleanSVG  = $sanitizer->sanitize( $dirtySVG );

        if ( $cleanSVG ) {
            file_put_contents( $file['tmp_name'], $cleanSVG );
        } else {
            $file['error'] = __( 'This file couldn\'t be uploaded.', 'filebird' );
        }

        return $file;
    }
}
