<?php
/**
 * Loader for the ThemeIsleSDK
 *
 * Logic for loading always the latest SDK from the installed themes/plugins.
 *
 * @package     ThemeIsleSDK
 * @copyright   Copyright (c) 2017, Marius Cristea
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.1.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	return;
}
// Current SDK version and path.
$themeisle_sdk_version = '3.3.57';
$themeisle_sdk_path    = dirname( __FILE__ );

global $themeisle_sdk_max_version;
global $themeisle_sdk_max_path;

// If this is the latest SDK and it comes from a theme, we should load licenser separately.
$themeisle_sdk_relative_licenser_path = '/src/Modules/Licenser.php';

global $themeisle_sdk_abs_licenser_path;
if ( ! is_file( $themeisle_sdk_path . $themeisle_sdk_relative_licenser_path ) && ! empty( $themeisle_sdk_max_path ) && is_file( $themeisle_sdk_max_path . $themeisle_sdk_relative_licenser_path ) ) {
	$themeisle_sdk_abs_licenser_path = $themeisle_sdk_max_path . $themeisle_sdk_relative_licenser_path;
	add_filter( 'themeisle_sdk_required_files', 'themeisle_sdk_load_licenser_if_present' );
}

if ( ( is_null( $themeisle_sdk_max_path ) || version_compare( $themeisle_sdk_version, $themeisle_sdk_max_version ) == 0 ) &&
	apply_filters( 'themeisle_sdk_should_overwrite_path', false, $themeisle_sdk_path, $themeisle_sdk_max_path ) ) {
	$themeisle_sdk_max_path = $themeisle_sdk_path;
}

if ( is_null( $themeisle_sdk_max_version ) || version_compare( $themeisle_sdk_version, $themeisle_sdk_max_version ) > 0 ) {
	$themeisle_sdk_max_version = $themeisle_sdk_version;
	$themeisle_sdk_max_path    = $themeisle_sdk_path;
}

// load the latest sdk version from the active Themeisle products.
if ( ! function_exists( 'themeisle_sdk_load_licenser_if_present' ) ) :
	/**
	 * Always load the licenser, if present.
	 *
	 * @param array $to_load Previously files to load.
	 */
	function themeisle_sdk_load_licenser_if_present( $to_load ) {
		global $themeisle_sdk_abs_licenser_path;
		$to_load[] = $themeisle_sdk_abs_licenser_path;

		return $to_load;
	}
endif;

// load the latest sdk version from the active Themeisle products.
if ( ! function_exists( 'themeisle_sdk_load_latest' ) ) :
	/**
	 * Always load the latest sdk version.
	 */
	function themeisle_sdk_load_latest() {
		/**
		 * Don't load the library if we are on < 5.4.
		 */
		if ( version_compare( PHP_VERSION, '5.4.32', '<' ) ) {
			return;
		}
		global $themeisle_sdk_max_path;
		require_once $themeisle_sdk_max_path . '/start.php';
	}
endif;
add_action( 'init', 'themeisle_sdk_load_latest' );

if ( ! function_exists( 'themeisle_sdk_crash_sentinel' ) ) :
	/**
	 * Early crash sentinel: minimal shutdown-time capture of fatal errors
	 * originating from a registered ThemeIsle product directory.
	 *
	 * Runs only when the full crash reporter module never registered (e.g. the
	 * fatal happened during plugin bootstrap, before the SDK loaded on init).
	 * Stores one raw record locally; the module sanitizes and adopts it on the
	 * next normal load. Never outputs, never exits, fails silently.
	 *
	 * Must stay parseable on PHP 5.4, like the rest of this file.
	 */
	function themeisle_sdk_crash_sentinel() {
		if ( defined( 'THEMEISLE_SDK_CRASH_HANDLER' ) ) {
			return;
		}
		if ( defined( 'WP_SANDBOX_SCRAPING' ) && WP_SANDBOX_SCRAPING ) {
			return;
		}
		if ( ! function_exists( 'apply_filters' ) || ! function_exists( 'get_option' ) || ! function_exists( 'update_option' ) || ! function_exists( 'add_option' ) ) {
			return;
		}
		$error = error_get_last();
		if ( empty( $error ) || ! isset( $error['type'] ) || ! in_array( (int) $error['type'], array( E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR ), true ) ) {
			return;
		}
		$error_file = isset( $error['file'] ) ? str_replace( '\\', '/', (string) $error['file'] ) : '';
		if ( '' === $error_file ) {
			return;
		}
		$products = apply_filters( 'themeisle_sdk_products', array() );
		if ( empty( $products ) || ! is_array( $products ) ) {
			return;
		}
		foreach ( $products as $basefile ) {
			$product_dir = rtrim( str_replace( '\\', '/', dirname( (string) $basefile ) ), '/' ) . '/';
			if ( '/' === $product_dir || 0 !== strpos( $error_file, $product_dir ) ) {
				continue;
			}
			$key    = str_replace( '-', '_', strtolower( trim( basename( $product_dir ) ) ) );
			$option = $key . '_crash_data';
			$data   = get_option( $option, array() );
			if ( ! is_array( $data ) ) {
				$data = array();
			}
			if ( ! isset( $data['raw'] ) || ! is_array( $data['raw'] ) ) {
				$data['raw'] = array();
			}
			if ( count( $data['raw'] ) >= 3 ) {
				return;
			}
			foreach ( $data['raw'] as $record ) {
				if ( isset( $record['file'] ) && isset( $record['line'] ) && $record['file'] === $error_file && (int) $record['line'] === (int) $error['line'] ) {
					return;
				}
			}
			$data['raw'][] = array(
				'type'    => (int) $error['type'],
				'message' => substr( isset( $error['message'] ) ? (string) $error['message'] : '', 0, 2000 ),
				'file'    => $error_file,
				'line'    => isset( $error['line'] ) ? (int) $error['line'] : 0,
				'time'    => time(),
			);
			if ( false === get_option( $option, false ) ) {
				add_option( $option, $data, '', 'no' );
			} else {
				update_option( $option, $data );
			}

			return;
		}
	}
endif;

if ( empty( $GLOBALS['themeisle_sdk_crash_sentinel'] ) ) {
	$GLOBALS['themeisle_sdk_crash_sentinel'] = true;
	register_shutdown_function( 'themeisle_sdk_crash_sentinel' );
}

if ( ! function_exists( 'tsdk_utmify' ) ) {
	/**
	 * Utmify a link.
	 *
	 * @param string $url URL to add utms.
	 * @param string $area Area in page where this is used ( CTA, image, section name).
	 * @param string $location Location, such as customizer, about page.
	 *
	 * @return string
	 */
	function tsdk_utmify( $url, $area, $location = null ) {
		static $current_page = null;
		if ( $location === null && $current_page === null ) {
			global $pagenow;
			$screen       = function_exists( 'get_current_screen' ) ? get_current_screen() : $pagenow;
			$current_page = isset( $screen->id ) ? $screen->id : ( ( $screen === null ) ? 'non-admin' : $screen );
			$current_page = sanitize_key( str_replace( '.php', '', $current_page ) );
		}
		$location        = $location === null ? $current_page : $location;
		$is_upgrade_url  = strpos( $url, '/upgrade' ) !== false;
		$content         = sanitize_key(
			trim(
				str_replace(
					[
						'https://',
						'themeisle.com',
						'/themes/',
						'/plugins/',
						'/upgrade',
					],
					'',
					$url
				),
				'/'
			)
		);
		$filter_key      = sanitize_key( $content );
		$url_args        = [
			'utm_source'   => 'wpadmin',
			'utm_medium'   => $location,
			'utm_campaign' => $area,
			'utm_content'  => $content,
		];
		$query_arguments = apply_filters( 'tsdk_utmify_' . $filter_key, $url_args, $url );
		$utmify_url      = esc_url_raw(
			add_query_arg(
				$query_arguments,
				$url
			)
		);

		/**
		 * Check if there is an affiliate URL for this upgrade link, if so use it.
		 */
		if ( $is_upgrade_url ) {
			$option_content_key         = str_replace( '-', '_', $filter_key );
			$theme_upgrade_option_name  = 'themeisle_af_' . $option_content_key . '_themes_upgrade';
			$plugin_upgrade_option_name = 'themeisle_af_' . $option_content_key . '_plugins_upgrade';

			$theme_option_url = get_option( $theme_upgrade_option_name, false );
			if ( ! empty( $theme_option_url ) ) {
				$utmify_url = esc_url_raw( $theme_option_url );
			}
			$plugin_option_url = get_option( $plugin_upgrade_option_name, false );
			if ( ! empty( $plugin_option_url ) ) {
				$utmify_url = esc_url_raw( $plugin_option_url );
			}
		}



		return apply_filters( 'tsdk_utmify_url_' . $filter_key, $utmify_url, $url );
	}

	add_filter( 'tsdk_utmify', 'tsdk_utmify', 10, 3 );
}


if ( ! function_exists( 'tsdk_lstatus' ) ) {
	/**
	 * Check license status.
	 *
	 * @param string $file Product basefile.
	 *
	 * @return string Status.
	 */
	function tsdk_lstatus( $file ) {
		return \ThemeisleSDK\Modules\Licenser::status( $file );
	}
}
if ( ! function_exists( 'tsdk_lis_valid' ) ) {
	/**
	 * Check if license is valid.
	 *
	 * @param string $file Product basefile.
	 *
	 * @return bool Validness.
	 */
	function tsdk_lis_valid( $file ) {
		return \ThemeisleSDK\Modules\Licenser::is_valid( $file );
	}
}
if ( ! function_exists( 'tsdk_lplan' ) ) {
	/**
	 * Get license plan.
	 *
	 * @param string $file Product basefile.
	 *
	 * @return string Plan.
	 */
	function tsdk_lplan( $file ) {
		return \ThemeisleSDK\Modules\Licenser::plan( $file );
	}
}

if ( ! function_exists( 'tsdk_lkey' ) ) {
	/**
	 * Get license key.
	 *
	 * @param string $file Product basefile.
	 *
	 * @return string Key.
	 */
	function tsdk_lkey( $file ) {
		return \ThemeisleSDK\Modules\Licenser::key( $file );
	}
}

if ( ! function_exists( 'tsdk_translate_link' ) ) {

	/**
	 * Function to translate a link based on the current language.
	 *
	 * @param string                          $url URL to translate.
	 * @param string{'path'|'query'|'domain'} $type Type of localization. Supports path, query and domain.
	 * @param array                           $available_languages Available language to choose from.
	 *
	 * @return string
	 */
	function tsdk_translate_link(
		$url, $type = 'path', $available_languages = [
			'de_DE'        => 'de',
			'de_DE_formal' => 'de',
			'es_ES'        => 'es',
			'fr_FR'        => 'fr',
			'it_IT'        => 'it',
			'ja'           => 'ja',
			'nl_NL'        => 'nl',
			'nl_NL_formal' => 'nl',
			'ro_RO'        => 'ro',
		]
	) {
		$language = get_user_locale();
		if ( ! isset( $available_languages[ $language ] ) ) {
			return $url;
		}
		$code = $available_languages[ $language ];
		// We asume that false is based on query and add the code via query arg.
		if ( $type === 'query' ) {
			return add_query_arg( 'lang', $code, $url );
		}

		$parsed_url = wp_parse_url( $url );
		// we replace the domain here based on the localized one.
		if ( $type === 'domain' ) {
			return $parsed_url['scheme'] . '://' . $code . ( isset( $parsed_url['path'] ) ? $parsed_url['path'] : '' ) . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' ) . ( isset( $parsed_url['fragment'] ) ? '#' . $parsed_url['fragment'] : '' );
		}
		// default is the path based approach.
		$new_path = isset( $parsed_url['path'] ) ? "/$code" . $parsed_url['path'] : "/$code";

		return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $new_path . ( isset( $parsed_url['query'] ) ? '?' . $parsed_url['query'] : '' ) . ( isset( $parsed_url['fragment'] ) ? '#' . $parsed_url['fragment'] : '' );

	}
}
if ( ! function_exists( 'tsdk_support_link' ) ) {

	/**
	 * Get Themeisle Support URL.
	 *
	 * @param string $file Product basefile.
	 *
	 * @return false|string Return support URL or false if no license is active.
	 */
	function tsdk_support_link( $file ) {

		if ( ! did_action( 'init' ) ) {
			_doing_it_wrong( __FUNCTION__, 'tsdk_support_link() should not be called before the init action.', '3.2.39' );
		}
		$params = [];
		if ( ! tsdk_lis_valid( $file ) ) {
			return false;
		}
		$product = \ThemeisleSDK\Product::get( $file );
		if ( ! $product->requires_license() ) {
			return false;
		}
		static $site_params = null;
		if ( $site_params === null ) {
			if ( is_user_logged_in() && function_exists( 'wp_get_current_user' ) ) {
				$current_user          = wp_get_current_user();
				$site_params['semail'] = urlencode( $current_user->user_email );
			}
			$site_params['swb'] = urlencode( home_url() );
			global $wp_version;
			$site_params['snv'] = urlencode( sprintf( 'WP-%s-PHP-%s', $wp_version, ( PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION ) ) );
		}
		$params['slkey'] = tsdk_lkey( $file );
		$params['sprd']  = urlencode( $product->get_name() );
		$params['svrs']  = urlencode( $product->get_version() );


		return add_query_arg(
			array_merge( $site_params, $params ),
			'https://store.themeisle.com/direct-support/'
		);
	}
}
