<?php
/**
 * File system manipulations
 *
 * @package WordPress
 * @subpackage ThemeREX Addons
 * @since v1.0
 */

// Don't load directly
if ( ! defined( 'TRX_ADDONS_VERSION' ) ) {
	die( '-1' );
}

/* Enqueue scripts and styles
------------------------------------------------------------------------------------- */

//  Enqueue slider scripts and styles
if ( !function_exists( 'trx_addons_enqueue_slider' ) ) {
    function trx_addons_enqueue_slider($engine='swiper') {
        static $loaded = array( 'swiper' => false, 'elastistack' => false );
        if ( ! $loaded[$engine] ) {
            $loaded[$engine] = true;
            if ($engine=='swiper') {
				$v8 = trx_addons_exists_elementor() && trx_addons_elm_use_swiper_latest() ? 'v8/' : '';
				wp_enqueue_style(  'swiper', trx_addons_get_file_url('js/swiper/' . $v8 . 'swiper.min.css'), array(), null );
				wp_enqueue_script( 'swiper', trx_addons_get_file_url('js/swiper/' . $v8 . 'swiper.min.js'), array(), null, true );
            } else if ($engine=='elastistack') {
                wp_enqueue_script( 'modernizr', trx_addons_get_file_url('js/elastistack/modernizr.custom.js'), array(), null, true );
                wp_enqueue_script( 'draggabilly', trx_addons_get_file_url('js/elastistack/draggabilly.pkgd.min.js'), array(), null, true );
                wp_enqueue_script( 'elastistack', trx_addons_get_file_url('js/elastistack/elastistack.js'), array(), null, true );
            }
        }
    }
}


// Enqueue popup scripts and styles
// Link must have attribute: data-rel="popupEngine" or data-rel="popupEngine[gallery]"
if ( !function_exists( 'trx_addons_enqueue_popup' ) ) {
	function trx_addons_enqueue_popup($engine='') {
		if ($engine=='pretty') {
			wp_enqueue_style(  'prettyphoto',	trx_addons_get_file_url('js/prettyphoto/css/prettyPhoto.css'), array(), null );
			wp_enqueue_script( 'prettyphoto',	trx_addons_get_file_url('js/prettyphoto/jquery.prettyPhoto.min.js'), array('jquery'), 'no-compose', true );
		} else {
			wp_enqueue_style(  'magnific-popup',trx_addons_get_file_url('js/magnific/magnific-popup.min.css'), array(), null );
			wp_enqueue_script( 'magnific-popup',trx_addons_get_file_url('js/magnific/jquery.magnific-popup.min.js'), array('jquery'), null, true );
		}
	}
}

//  Enqueue Google map script
if ( !function_exists( 'trx_addons_enqueue_googlemap' ) ) {
	function trx_addons_enqueue_googlemap() {
		if (trx_addons_is_on(trx_addons_get_option('api_google_load'))) {
			$api_key = trx_addons_get_option('api_google');
			wp_enqueue_script( 'google-maps', trx_addons_get_protocol().'://maps.googleapis.com/maps/api/js'.($api_key ? '?key='.$api_key : ''), array(), null, true );
		}
	}
}

//  Enqueue Select2 scripts and styles
if ( !function_exists( 'trx_addons_enqueue_select2' ) ) {
	function trx_addons_enqueue_select2() {
		wp_enqueue_style(  'select2', trx_addons_get_file_url('js/select2/select2.min.css'), array(), null );
		wp_enqueue_script( 'select2', trx_addons_get_file_url('js/select2/select2.min.js'), array('jquery'), null, true );
	}
}

/* Check if file/folder present in the child theme and return path (url) to it. 
   Else - path (url) to file in the main theme dir
------------------------------------------------------------------------------------- */
if (!function_exists('trx_addons_get_file_dir')) {	
	function trx_addons_get_file_dir($file, $return_url=false) {
		if ($file[0]=='/') $file = substr($file, 1);
		$theme_dir = get_template_directory().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$theme_url = get_template_directory_uri().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$child_dir = get_stylesheet_directory().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$child_url = get_stylesheet_directory_uri().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$dir = '';
		if (file_exists(($child_dir).($file)))
			$dir = ($return_url ? $child_url : $child_dir) . trx_addons_check_min_file($file, $child_dir);
		else if (file_exists(($theme_dir).($file)))
			$dir = ($return_url ? $theme_url : $theme_dir) . trx_addons_check_min_file($file, $theme_dir);
		else if (file_exists(TRX_ADDONS_PLUGIN_DIR . ($file)))
			$dir = ($return_url ? TRX_ADDONS_PLUGIN_URL : TRX_ADDONS_PLUGIN_DIR) . trx_addons_check_min_file($file, TRX_ADDONS_PLUGIN_DIR);
		return apply_filters( $return_url ? 'trx_addons_get_file_url' : 'trx_addons_get_file_dir', $dir, $file );
	}
}

if (!function_exists('trx_addons_get_file_url')) {	
	function trx_addons_get_file_url($file) {
		return trx_addons_get_file_dir($file, true);
	}
}

// Return file extension from full name/path
if (!function_exists('trx_addons_get_file_ext')) {	
	function trx_addons_get_file_ext($file) {
		$parts = pathinfo($file);
		return $parts['extension'];
	}
}

// Return file name from full name/path
if (!function_exists('trx_addons_get_file_name')) {	
	function trx_addons_get_file_name($file, $without_ext=true) {
		$parts = pathinfo($file);
		return !empty($parts['filename']) && $without_ext ? $parts['filename'] : $parts['basename'];
	}
}

// Detect folder location (in the child theme or in the main theme)
if (!function_exists('trx_addons_get_folder_dir')) {	
	function trx_addons_get_folder_dir($folder, $return_url=false) {
		if ($folder[0]=='/') $folder = substr($folder, 1);
		$theme_dir = get_template_directory().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$theme_url = get_template_directory_uri().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$child_dir = get_stylesheet_directory().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$child_url = get_stylesheet_directory_uri().'/'.TRX_ADDONS_PLUGIN_BASE.'/';
		$dir = '';
		if (is_dir(($child_dir).($folder)))
			$dir = ($return_url ? $child_url : $child_dir).($folder);
		else if (is_dir(($theme_dir).($folder)))
			$dir = ($return_url ? $theme_url : $theme_dir).($folder);
		else if (is_dir((TRX_ADDONS_PLUGIN_DIR).($folder)))
			$dir = ($return_url ? TRX_ADDONS_PLUGIN_URL : TRX_ADDONS_PLUGIN_DIR).($folder);
		return $dir;
	}
}

if (!function_exists('trx_addons_get_folder_url')) {	
	function trx_addons_get_folder_url($folder) {
		return trx_addons_get_folder_dir($folder, true);
	}
}

// Get domain part from URL
if (!function_exists('trx_addons_get_domain_from_url')) {
	function trx_addons_get_domain_from_url($url) {
		if (($pos=strpos($url, '://'))!==false) $url = substr($url, $pos+3);
		if (($pos=strpos($url, '/'))!==false) $url = substr($url, 0, $pos);
		return $url;
	}
}


// Return .min version (if exists and filetime .min > filetime original) instead original
if (!function_exists('trx_addons_check_min_file')) {	
	function trx_addons_check_min_file($file, $dir) {
		if (substr($file, -3)=='.js') {
			if (substr($file, -7)!='.min.js' && trx_addons_is_off(trx_addons_get_option('debug_mode', false, false))) {
				$dir = trailingslashit($dir);
				$file_min = substr($file, 0, strlen($file)-3).'.min.js';
				if (file_exists($dir . $file_min) && filemtime($dir . $file) <= filemtime($dir . $file_min)) $file = $file_min;
			}
		} else if (substr($file, -4)=='.css') {
			if (substr($file, -8)!='.min.css'  && trx_addons_is_off(trx_addons_get_option('debug_mode', false, false))) {
				$dir = trailingslashit($dir);
				$file_min = substr($file, 0, strlen($file)-4).'.min.css';
				if (file_exists($dir . $file_min) && filemtime($dir . $file) <= filemtime($dir . $file_min)) $file = $file_min;
			}
		}
		return $file;
	}
}



/* Init WP Filesystem before the plugins and theme init
------------------------------------------------------------------- */
if (!function_exists('trx_addons_init_filesystem')) {
	add_action( 'after_setup_theme', 'trx_addons_init_filesystem', 0);
	function trx_addons_init_filesystem() {
        if( !function_exists('WP_Filesystem') ) {
            require_once trailingslashit(ABSPATH) . 'wp-admin/includes/file.php';
        }
		if (is_admin()) {
			$url = admin_url();
			$creds = false;
			// First attempt to get credentials.
			if ( function_exists('request_filesystem_credentials') && false === ( $creds = request_filesystem_credentials( $url, '', false, false, array() ) ) ) {
				// If we comes here - we don't have credentials
				// so the request for them is displaying no need for further processing
				return false;
			}
	
			// Now we got some credentials - try to use them.
			if ( !WP_Filesystem( $creds ) ) {
				// Incorrect connection data - ask for credentials again, now with error message.
				if ( function_exists('request_filesystem_credentials') ) request_filesystem_credentials( $url, '', true, false );
				return false;
			}
			
			return true; // Filesystem object successfully initiated.
		} else {
            WP_Filesystem();
		}
		return true;
	}
}

if ( ! function_exists('trx_addons_prepare_path')) {	
	/**
	 * Replace '\' with '/' in the file/folder path
	 * 
	 * @param string $name		File/folder path
	 * 
	 * @return string			Safe path
	 */
	function trx_addons_prepare_path( $name ) {
		return str_replace( '\\', defined( 'DIRECTORY_SEPARATOR' ) ? DIRECTORY_SEPARATOR : '/', trim( $name ) );
	}
}

if ( ! function_exists( 'trx_addons_unzip_file' ) ) {
	/**
	 * Init a $wp_filesystem ( if need ) and unzip file
	 * 
	 * @param string $zip  path to zip file
	 * @param string $dest path to destination folder
	 * 
	 * @return bool  	true if success
	 */
	function trx_addons_unzip_file( $zip, $dest ) {
		global $wp_filesystem;
		if ( empty( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
			trx_addons_init_filesystem( true );
		}
		return unzip_file( $zip, $dest );
	}
}


if ( ! function_exists( 'trx_addons_fpc' ) ) {	
	/**
	 * Put data to the specified file
	 *
	 * @param string $file		File name (or path relative to the theme folder)
	 * @param string $data		Data to put into the file
	 * @param int $flag			Flag to modify the behavior of the function
	 * 
	 * @return int				Number of bytes that were written to the file, or false on failure.
	 */
	function trx_addons_fpc( $file, $data, $flag = 0 ) {
		if ( ! empty( $file ) ) {
			$file = trx_addons_prepare_path( $file );
			return file_put_contents( $file, $data, $flag );
		}		
		return false;
	}
}

if ( ! function_exists( 'trx_addons_fgc' ) ) {
	/**
	 * Get content of the specified file
	 *
	 * @param string $file		File name (or path relative to the theme folder)
	 * @param bool $unpack		Unpack data after get it from file
	 * 
	 * @return string			Content of the file
	 */
	function trx_addons_fgc( $file, $unpack = false ) {
		$tmp_cont = '';
		if ( ! empty( $file ) ) {
			if ( trx_addons_is_url( $file ) ) { //&& ! $allow_url_fopen 
				$tmp_cont = trx_addons_remote_get( $file );
			} else {
				$file = trx_addons_prepare_path( $file );
				if ( file_exists( $file ) ) {
					$tmp_cont = file_get_contents( $file );
				}
			}
		}
		if ( ! empty( $tmp_cont ) && $unpack && trx_addons_get_file_ext( $file ) == 'zip' ) {
			$tmp_name = 'tmp-'.rand().'.zip';
			$tmp = wp_upload_bits( $tmp_name, null, $tmp_cont );
			if ( $tmp['error'] ) {
				$tmp_cont = '';
			} else {
				trx_addons_unzip_file( $tmp['file'], dirname( $tmp['file'] ) );
				$file_name = trailingslashit( dirname( $tmp['file'] ) ) . basename( $file, '.zip' ) . '.txt';
				$tmp_cont = trx_addons_fgc( $file_name );
				unlink( $tmp['file'] );
				unlink( $file_name );
			}
		}
		return $tmp_cont;
	}
}

if ( ! function_exists( 'trx_addons_fga' ) ) {
	/**
	 * Get array with rows from specified file
	 *
	 * @param string $file		File name (or path relative to the theme folder)
	 * 
	 * @return array			Array with rows from the file
	 */
	function trx_addons_fga( $file ) {
		if ( ! empty( $file ) ) {
			$file = trx_addons_prepare_path( $file );
			if ( file_exists( $file ) ) {
				return file( $file );
			}			
		}
		return array();
	}
}



// Get text from specified file via HTTP (cURL)
if (!function_exists('trx_addons_remote_get')) {	
	function trx_addons_remote_get($file, $timeout=-1) {
		// Set timeout as half of the PHP execution time
		if ($timeout < 1) $timeout = round( 0.5 * max(30, ini_get('max_execution_time')));
		$response = wp_remote_get($file, array(
									'timeout'     => $timeout
									)
								);
		//return wp_remote_retrieve_response_code( $response ) == 200 ? wp_remote_retrieve_body( $response ) : '';
		return isset($response['response']['code']) && $response['response']['code']==200 ? $response['body'] : '';
	}
}


// Remove unsafe characters from file/folder path
if (!function_exists('trx_addons_esc')) {	
	function trx_addons_esc( $name, $local = false ) {
		return str_replace(
					array_merge( array( '\\', '~', '$', ';', '+', '>', '<', '|', '"', "'", '`', "\xFF", "\x0A", "\x0D", '*', '?', '^' ), ! $local ? array( ':' ) : array() ),
					defined( 'DIRECTORY_SEPARATOR' ) ? DIRECTORY_SEPARATOR : '/',
					trim( $name )
				);
	}
}

if ( ! function_exists( 'trx_addons_sanitize_file_name' ) ) {	

	function trx_addons_sanitize_file_name( $name ) {
		return sanitize_file_name( (string)$name );
	}
}

if ( ! function_exists( 'trx_addons_url_to_local_path' ) ) {	
	/**
	 * Convert URL to local path
	 * 
	 * @param string $url		URL to convert
	 * 
	 * @return string			Local path
	 */
	function trx_addons_url_to_local_path( $url ) {
		$path = '';
		// Remove scheme from url
		$url = trx_addons_remove_protocol( $url );
		// Get upload path & dir
		$upload_info = wp_upload_dir();
		// Where check file
		$locations = array(
			'uploads' => array(
				'dir' => $upload_info['basedir'],
				'url' => trx_addons_remove_protocol($upload_info['baseurl'])
				),
			'child' => array(
				'dir' => get_stylesheet_directory(),
				'url' => trx_addons_remove_protocol(get_stylesheet_directory_uri())
				),
			'theme' => array(
				'dir' => get_template_directory(),
				'url' => trx_addons_remove_protocol(get_template_directory_uri())
				)
			);
		// Find a file in locations
		foreach( $locations as $key => $loc ) {
			// Check if $url is in location
			if ( false === strpos( $url, $loc['url'] ) ) continue;
			// Get a path from the URL
			$path = str_replace( $loc['url'], $loc['dir'], $url );
			// Check if a file exists
			if ( file_exists( $path ) ) {
				break;
			}
			$path = '';
		}
		return $path;
	}
}
?>