<?php
/**
 * Robust SVG upload support & sanitization for Quicker.
 */

defined( 'ABSPATH' ) || exit;

// Capability required to upload SVG (change to 'upload_files' if broader access desired).
if ( ! defined( 'QUICKER_SVG_CAP' ) ) {
	define( 'QUICKER_SVG_CAP', 'manage_options' );
}

/**
 * Allow SVG mime for privileged users.
 */
add_filter( 'upload_mimes', function( $mimes ) {
	if ( current_user_can( QUICKER_SVG_CAP ) ) {
		$mimes['svg'] = 'image/svg+xml';
	}
	return $mimes;
}, 20 );

/**
 * Ensure WordPress recognizes SVG filetype (some hosts block without this).
 */
add_filter( 'wp_check_filetype_and_ext', function( $data, $file, $filename, $mimes ) {
	$ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
	if ( $ext === 'svg' && current_user_can( QUICKER_SVG_CAP ) ) {
		$data['ext']  = 'svg';
		$data['type'] = 'image/svg+xml';
		if ( empty( $data['proper_filename'] ) ) {
			$data['proper_filename'] = sanitize_file_name( $filename );
		}
	}
	return $data;
}, 20, 4 );

/**
 * Basic upload prefilter: size limit & strip script/foreignObject.
 */
add_filter( 'wp_handle_upload_prefilter', function( $file ) {
	$ext = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
	if ( $ext !== 'svg' ) { return $file; }
	if ( ! current_user_can( QUICKER_SVG_CAP ) ) {
		$file['error'] = __( 'You are not allowed to upload SVG files.', 'quicker' );
		return $file;
	}
	// Enforce 512KB limit
	if ( isset( $file['tmp_name'] ) && file_exists( $file['tmp_name'] ) && filesize( $file['tmp_name'] ) > 512 * 1024 ) {
		$file['error'] = __( 'SVG file too large (max 512KB).', 'quicker' );
		return $file;
	}
	if ( isset( $file['tmp_name'] ) && file_exists( $file['tmp_name'] ) ) {
		$raw = file_get_contents( $file['tmp_name'] );
		// Remove script & foreignObject blocks
		$raw = preg_replace( '/<script[\s\S]*?<\/script>/i', '', $raw );
		$raw = preg_replace( '/<foreignObject[\s\S]*?<\/foreignObject>/i', '', $raw );
		// Very defensive: remove onload= & javascript: URLs
		$raw = preg_replace( '/on[a-z]+="[^"]*"/i', '', $raw );
		$raw = preg_replace( '/xlink:href="javascript:[^"]*"/i', '', $raw );
		file_put_contents( $file['tmp_name'], $raw );
	}
	return $file;
}, 20 );

/**
 * Optional debug logging (enable by defining constant in wp-config.php):
 * define('QUICKER_SVG_DEBUG', true);
 */
if ( defined( 'QUICKER_SVG_DEBUG' ) && constant( 'QUICKER_SVG_DEBUG' ) ) {
	add_action( 'init', function() {
		if ( current_user_can( QUICKER_SVG_CAP ) ) {
			// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Debug logging only when QUICKER_SVG_DEBUG is enabled
			error_log( '[Quicker][SVG] Support loaded for user ' . get_current_user_id() );
		}
	} );
}

