<?php
/**
 * Class for the customizer importer.
 *
 * Code is mostly from the Customizer Export/Import plugin.
 *
 * @see https://wordpress.org/plugins/customizer-export-import/
 * @package Athemes Starter Sites
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit; // Exit if accessed directly.
}

/**
 * Customizer Importer
 */
class ATSS_Customizer_Importer {
	/**
	 * Import customizer.
	 *
	 * @param array $data The data.
	 */
	public static function import( $data ) {
		// Try to import the customizer settings.
		return self::import_customizer_options( $data );
	}

	/**
	 * Imports uploaded mods and calls WordPress core customize_save actions so
	 * themes that hook into them can act before mods are saved to the database.
	 *
	 * Update: WP core customize_save actions were removed, because of some errors.
	 *
	 * @param array $data The data.
	 * @return void|WP_Error
	 */
	public static function import_customizer_options( $data ) {
		// Setup global vars.
		global $wp_customize;

		// Setup internal vars.
		$template = get_template();
		$stylesheet = get_stylesheet();

		// Data checks.
		if ( ! is_array( $data ) && ( ! isset( $data['template'] ) || ! isset( $data['mods'] ) ) ) {
			return new WP_Error(
				'customizer_import_data_error',
				esc_html__( 'Error: The customizer import file is not in a correct format. Please make sure to use the correct customizer import file.', 'athemes-starter-sites' )
			);
		}

		// Allow import if the template matches either:
		// 1. The parent theme (template)
		// 2. The current theme/child theme (stylesheet)
		// 3. Apply filter to allow custom theme matching logic
		$theme_matches = ( $data['template'] === $template || $data['template'] === $stylesheet );
		$theme_matches = apply_filters( 'atss_customizer_import_theme_match', $theme_matches, $data['template'], $template, $stylesheet );

		if ( ! $theme_matches ) {
			return new WP_Error(
				'customizer_import_wrong_theme',
				sprintf(
					esc_html__( 'Error: The customizer import file is for "%s" theme but current theme is "%s". You can only import customizer settings for the same theme or a child theme.', 'athemes-starter-sites' ),
					$data['template'],
					$stylesheet
				)
			);
		}

		// Import images.
		if ( apply_filters( 'atss_customizer_import_images', true ) ) {
			$data['mods'] = self::import_customizer_images( $data['mods'] );
			$data = map_deep( $data, array( 'Athemes_Starter_Sites_Importer', 'replace_attachment_urls' ) );
		}

		// Import custom options.
		if ( isset( $data['options'] ) ) {

			// Require modified customizer options class.
			if ( ! class_exists( 'WP_Customize_Setting' ) ) {
				require_once ABSPATH . 'wp-includes/class-wp-customize-setting.php';
			}

			if ( ! class_exists( 'ATSS_Customizer_Option' ) ) {
				require_once ATSS_PATH . 'core/class-customizer-option.php';
			}

			foreach ( $data['options'] as $option_key => $option_value ) {

				$option = new ATSS_Customizer_Option( $wp_customize, $option_key, array(
					'default'    => '',
					'type'       => 'option',
					'capability' => 'edit_theme_options',
				) );

				$option->import( $option_value );

			}

		}

		// Should the customizer import use the WP customize_save* hooks?
		$use_wp_customize_save_hooks = apply_filters( 'atss_enable_wp_customize_save_hooks', false );

		if ( $use_wp_customize_save_hooks ) {
			do_action( 'customize_save', $wp_customize );
		}

		// Drop the stale custom CSS post pointer. The exported custom_css_post_id
		// refers to a post on the source site and can resolve to the wrong post on
		// the target site, hiding the imported Additional CSS. Removing it lets
		// WordPress fall back to locating the imported custom_css post by theme slug.
		unset( $data['mods']['custom_css_post_id'] );

		// Loop through the mods and save the mods.
		foreach ( $data['mods'] as $key => $val ) {

			if ( $use_wp_customize_save_hooks ) {
				do_action( 'customize_save_' . $key, $wp_customize );
			}

			set_theme_mod( $key, $val );

		}

		// Import Additional CSS for the active theme.
		if ( function_exists( 'wp_update_custom_css_post' ) && array_key_exists( 'wp_css', $data ) ) {
			$custom_css_post = wp_update_custom_css_post(
				(string) $data['wp_css'],
				array(
					'stylesheet' => $stylesheet,
				)
			);

			if ( is_wp_error( $custom_css_post ) ) {
				return $custom_css_post;
			}

			set_theme_mod(
				'custom_css_post_id',
				$custom_css_post->ID
			);

			$data['mods']['custom_css_post_id'] = $custom_css_post->ID;
		}

		if ( $use_wp_customize_save_hooks ) {
			do_action( 'customize_save_after', $wp_customize );
		}

		if ( ! empty( $data['mods'] ) ) {
			update_option( '_athemes_sites_imported_customizer_mods', $data['mods'] );
		}

		if ( ! empty( $data['options'] ) ) {
			update_option( '_athemes_sites_imported_customizer_options', $data['options'] );
		}

	}

	/**
	 * Helper function: Customizer import - imports images for settings saved as mods.
	 *
	 * @since 1.1.1
	 * @param array $mods An array of customizer mods.
	 * @return array The mods array with any new import data.
	 */
	private static function import_customizer_images( $mods ) {
		foreach ( $mods as $key => $val ) {
			if ( self::customizer_is_image_url( $val ) ) {
				$data = self::customizer_sideload_image( $val );

				if ( ! is_wp_error( $data ) ) {

					$mods[ $key ] = $data->url;

					update_post_meta( $data->attachment_id, '_athemes_sites_imported_post', true );

					// Handle header image controls.
					if ( isset( $mods[ $key . '_data' ] ) ) {
						$mods[ $key . '_data' ] = $data;
						update_post_meta( $data->attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() );
					}

				}
			}
		}

		return $mods;
	}

	/**
	 * Helper function: Customizer import
	 * Taken from the core media_sideload_image function and
	 * modified to return an array of data instead of html.
	 *
	 * @since 1.1.1.
	 * @param string $file The image file path.
	 * @return array An array of image data.
	 */
	private static function customizer_sideload_image( $file ) {

		$data = new stdClass();

		if ( ! function_exists( 'media_handle_sideload' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/media.php' );
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
		}

		if ( ! empty( $file ) ) {
			// Set variables for storage, fix file filename for query strings.
			preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
			$file_array = array();
			$file_array['name'] = basename( $matches[0] );

			preg_match('/https?:\/\/[^"]+\.(jpg|jpeg|jpe|png|gif)/', $matches[0], $matches2);
			$file_array['url'] = $matches2[0];

			// Download file to temp location.
			$file_array['tmp_name'] = download_url( $file_array['url'] );

			// If error storing temporarily, return the error.
			if ( is_wp_error( $file_array['tmp_name'] ) ) {
				return $file_array['tmp_name'];
			}

			// Do the validation and storage stuff.
			$id = media_handle_sideload( $file_array, 0 );

			// If error storing permanently, unlink.
			if ( is_wp_error( $id ) ) {
				unlink( $file_array['tmp_name'] );
				return $id;
			}

			if ( self::string_contains_html( $file ) ) {
				return new WP_Error(
					'customizer_import_data_error',
					esc_html__( 'Error: The customizer import file is not in a correct format. Please make sure to use the correct customizer import file.', 'athemes-starter-sites' )
				);
			}

			// Build the object to return.
			$meta                = wp_get_attachment_metadata( $id );
			$data->attachment_id = $id;
			$data->url           = wp_get_attachment_url( $id );
			$data->thumbnail_url = wp_get_attachment_thumb_url( $id );
			$data->height        = $meta['height'];
			$data->width         = $meta['width'];
		}

		return $data;

	}

	/**
	 * Checks to see whether a string is an image url or not.
	 *
	 * @since 1.1.1
	 * @param string $string The string to check.
	 * @return bool Whether the string is an image url or not.
	 */
	private static function customizer_is_image_url( $string = '' ) {

		if ( is_string( $string ) ) {
			if ( preg_match( '/\.(jpg|jpeg|png|gif)/i', $string ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Checks to see whether a string contains HTML or not.
	 *
	 * @since 1.1.1
	 * @param string $string The string to check.
	 * @return bool Whether the string contains HTML or not.
	 */
	private static function string_contains_html( $string ) {
		return preg_match( '/<[^>]+>/', $string );
	}
}
