<?php

/**
 * Framework Name: Themify Builder
 * Framework URI: https://themify.me/
 * Description: Page Builder with interactive drag and drop features
 * Version: 1.0
 * Author: Themify
 * Author URI: https://themify.me
 *
 *
 * @package ThemifyBuilder
 * @category Core
 * @author Themify
 */
if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

/**
 * Define builder constant
 */
define('THEMIFY_BUILDER_DIR', dirname(__FILE__));
define('THEMIFY_BUILDER_MODULES_DIR', THEMIFY_BUILDER_DIR . '/modules');
define('THEMIFY_BUILDER_TEMPLATES_DIR', THEMIFY_BUILDER_DIR . '/templates');
define('THEMIFY_BUILDER_CLASSES_DIR', THEMIFY_BUILDER_DIR . '/classes');
define('THEMIFY_BUILDER_INCLUDES_DIR', THEMIFY_BUILDER_DIR . '/includes');
define('THEMIFY_BUILDER_LIBRARIES_DIR', THEMIFY_BUILDER_INCLUDES_DIR . '/libraries');


// URI Constant
define('THEMIFY_BUILDER_URI', THEMIFY_URI . '/themify-builder');

/**
 * Include builder class
 */
require_once( THEMIFY_BUILDER_CLASSES_DIR . '/class-themify-builder-model.php' );
require_once( THEMIFY_BUILDER_CLASSES_DIR . '/class-themify-builder-layouts.php' );
require_once( THEMIFY_BUILDER_CLASSES_DIR . '/class-themify-builder.php' );
///////////////////////////////////////////
// Version Getter
///////////////////////////////////////////
if (!function_exists('themify_builder_get')) {

    function themify_builder_get($theme_var, $builder_var = false) {
        if (Themify_Builder_Model::is_themify_theme()) {
            return themify_get($theme_var);
        }
        if ($builder_var === false) {
            return false;
        }
        global $post;
        $data = Themify_Builder_Model::get_builder_settings();
        if (isset($data[$builder_var]) && $data[$builder_var] !== '') {
            return $data[$builder_var];
        } else if (is_object($post) && ($val = get_post_meta($post->ID, $builder_var, true)) !== '') {
            return $val;
        }
        return null;
    }

}
/**
 * Init themify builder class
 */
add_action('after_setup_theme', 'themify_builder_init', 15);

function themify_builder_init() {
    if (class_exists('Themify_Builder')) {
        global $ThemifyBuilder, $Themify_Builder_Layouts;
        do_action('themify_builder_before_init');

        if (Themify_Builder_Model::builder_check()) {
            $Themify_Builder_Layouts = new Themify_Builder_Layouts();

            $ThemifyBuilder = new Themify_Builder();
            $ThemifyBuilder->init();
        }
    }
}

if (!function_exists('themify_manage_builder')) {

    /**
     * Builder Settings
     * @param array $data
     * @return string
     * @since 1.2.7
     */
    function themify_manage_builder($data = array()) {
        $data = themify_get_data();
        $pre = 'setting-page_builder_';

        $output = '';
        $modules = Themify_Builder_Model::get_modules('all');
        foreach ($modules as $k=>$m) {
		$exclude = $pre . 'exc_' . $k;
		$checked = !empty($data[$exclude]) ? 'checked="checked"' : '';
		$output .= '<p><span><input id="builder_module_' . $k. '" type="checkbox" name="' . $exclude . '" value="1" ' . $checked . '/> <label for="builder_module_' . $k . '">' . wp_kses_post(sprintf(__('Disable "%s" module', 'themify'), $m['name'])) . '</label></span></p>';
	   
        }

        return $output;
    }

}

if (!function_exists('tb_tools_options')) {

    /**
     * Call and return all tools options HTML
     * @return array posts id
     * @since 4.1.2
     */
    function tb_tools_options() {
        $output = '';
        $output .= tb_find_and_replace();
		$output .= themify_regenerate_css_files();
        return $output;
    }

}

if (!function_exists('themify_regenerate_css_files')) {

    /**
     * Builder Settings
     * @param array $data
     * @return string
     * @since 1.2.7
     */
    function themify_regenerate_css_files($data = array()) {
        $output = '<hr><h4>'.__('Regenerate CSS Files','themify').'</h4>';
        $output .= '<p><label class="label" for="builder-regenerate-css-files">' . __('Regenerate Files', 'themify'). '</label><input id="builder-regenerate-css-files" type="button" value="'.__('Regenerate CSS Files','themify').'" class="themify_button"/></p>';
        $output .= sprintf('<span class="pushlabel regenerate-css-file-pushlabel"><small>%s</small></span>', esc_html__('Builder styling are output to the generated CSS files stored in \'wp-content/uploads\' folder. Regenerate files will update all data in the generated files (eg. correct background image paths, etc.).', 'themify')
        );
        return $output;
    }

}

if (!function_exists('tb_find_and_replace')) {

    /**
     * Add find and replace string tool to builder setting
     * @param array $data
     * @return string
     * @since 4.1.2
     */
    function tb_find_and_replace($data = array()) {
        $in_progress = (true === get_transient( 'themify_find_and_replace_in_progress' )) ? true : false;
        $disabled = $in_progress ? 'disabled="disabled"' : '';
        $value = $in_progress ? __('Replacing ...','themify') : __('Replace','themify');
        $output = '<h4>'.__('Find & Replace','themify').'</h4>';
        $output .= '<p><span class="label">' . __( 'Search for', 'themify' ) . '</span> <input type="text" class="width10" id="original_string" name="original_string" /></p>';
        $output .= '<p><span class="label">' . __( 'Replace to', 'themify' ) . '</span> <input type="text" class="width10" id="replace_string" name="replace_string" /></p>';
        $output .= '<p><span class="pushlabel"><input id="builder-find-and-replace-btn" type="button" name="builder-find-and-replace-btn" '.$disabled.' value="'.$value.'" class="themify_button"/> </span></p>';
        $output .= sprintf('<span class="pushlabel replace-strings-pushlabel"><small>%s</small></span>', esc_html__('Use this tool to replace the strings in the Builder data. Warning: Please backup your database before replacing strings, this can not be undone.', 'themify')
        );
        return $output;
    }

}

if (!function_exists('themify_manage_builder_active')) {

    /**
     * Builder Settings
     * @param array $data
     * @return string
     * @since 1.2.7
     */
    function themify_manage_builder_active($data = array()) {
        $pre = 'setting-page_builder_';
        $options = array(
            array('name' => __('Enable', 'themify'), 'value' => 'enable'),
            array('name' => __('Disable', 'themify'), 'value' => 'disable')
        );

        $output = sprintf('<p><span class="label">%s</span><select id="%s" name="%s">%s</select>%s</p>', esc_html__('Themify Builder:', 'themify'), $pre . 'is_active', $pre . 'is_active', themify_options_module($options, $pre . 'is_active'), sprintf('<small class="pushlabel" data-show-if-element="[name=setting-page_builder_is_active]" data-show-if-value="disable">%s</small>'
                        , esc_html__('WARNING: When Builder is disabled, all Builder content/layout will not appear. They will re-appear once Builder is enabled.', 'themify'))
        );

        if ('disable' !== themify_builder_get($pre . 'is_active')) {

            $output .= sprintf('<p><label for="%s"><input type="checkbox" id="%s" name="%s"%s> %s</label></p>', $pre . 'disable_shortcuts', $pre . 'disable_shortcuts', $pre . 'disable_shortcuts', checked('on', themify_builder_get($pre . 'disable_shortcuts', 'builder_disable_shortcuts'), false), wp_kses_post(__('Disable Builder shortcuts (eg. disable shortcut like Cmd+S = save)', 'themify'))
            );

			// Disable WP editor
			$output .= sprintf('<p><label for="%s"><input type="checkbox" id="%s" name="%s"%s> %s</label></p>', $pre . 'disable_wp_editor', $pre . 'disable_wp_editor', $pre . 'disable_wp_editor', checked('on', themify_builder_get($pre . 'disable_wp_editor', 'builder_disable_wp_editor'), false), wp_kses_post(__('Disable WordPress editor when Builder is in use', 'themify'))
            );
        }

        return $output;
    }

}

if (!function_exists('themify_manage_builder_animation')) {

    /**
     * Builder Setting Animations
     * @param array $data
     * @return string
     * @since 2.0.0
     */
    function themify_manage_builder_animation($data = array()) {
        $opt_data = themify_get_data();
        $pre = 'setting-page_builder_animation_';
        $options = array(
            array('name' => '', 'value' => 'none'),
            array('name' => esc_html__('Disable on mobile & tablet', 'themify'), 'value' => 'mobile'),
            array('name' => esc_html__('Disable on all devices', 'themify'), 'value' => 'all')
        );

        $output = sprintf('<p><label for="%s" class="label">%s</label><select id="%s" name="%s">%s</select></p>', $pre . 'appearance', esc_html__('Appearance Animation', 'themify'), $pre . 'appearance', $pre . 'appearance', themify_options_module($options, $pre . 'appearance')
        );
        $output .= sprintf('<p><label for="%s" class="label">%s</label><select id="%s" name="%s">%s</select></p>', $pre . 'parallax_bg', esc_html__('Parallax Background', 'themify'), $pre . 'parallax_bg', $pre . 'parallax_bg', themify_options_module($options, $pre . 'parallax_bg')
        );
        $output .= sprintf('<p><label for="%s" class="label">%s</label><select id="%s" name="%s">%s</select></p>', $pre . 'parallax_scroll', esc_html__('Float Scrolling', 'themify'), $pre . 'parallax_scroll', $pre . 'parallax_scroll', themify_options_module($options, $pre . 'parallax_scroll', true, 'mobile')
        );
        $output .= sprintf('<p><label for="%s" class="label">%s</label><select id="%s" name="%s">%s</select></p>', $pre . 'sticky_scroll', esc_html__('Sticky Scrolling', 'themify'), $pre . 'sticky_scroll', $pre . 'sticky_scroll', themify_options_module($options, $pre . 'sticky_scroll')
        );

        return $output;
    }

}

if(!function_exists('getSavedGradients')){
	function getSavedGradients(){
		$data =get_option('saved_gradient_on_clients',serialize(array('result' => 1, 'stamp' => 0,'records'=>array())));
		$data = unserialize($data);
		$stamp = isset($_GET['stamp']) ? $_GET['stamp'] : -1;
		if($data['stamp'] > $stamp){
			if(! $data['records']) $data['records'] = array();
			wp_send_json_success($data);
		}else{
			wp_send_json_success(array('result' => 0, 'stamp' => 0,'records'=>array()));
		}
		wp_die();
	}
	if(isset($_GET['action']) && $_GET['action'] === 'getSavedGradients'){
		if(is_user_logged_in())
			getSavedGradients();
		wp_send_json_error();
	}
}
if(!function_exists('setSavedGradients')){
	function setSavedGradients(){
		$data =get_option('saved_gradient_on_clients',serialize(array('result' => 1, 'stamp' => 0,'records'=>array())));
		$data = unserialize($data);
		$gradients = isset($_POST['gradients']) ? $_POST['gradients'] : array('result' => 1, 'stamp' => 0,'records'=>array());
		if($gradients['stamp'] > $data['stamp']){
			$data['stamp'] = $gradients['stamp'];
			$data['records'] = $gradients['records'];
			if(! $data['records']) $data['records'] = array();
			update_option( 'saved_gradient_on_clients', serialize($data));
			wp_send_json_success($data);
		}else{
			wp_send_json_success(array('result' => 0, 'stamp' => 0,'data'=>$gradients));
		}
		wp_die();
	}
	if(isset($_POST['action']) && $_POST['action'] === 'setSavedGradients'){
		if(is_user_logged_in())
			setSavedGradients();
		wp_send_json_error();
	}
}
if(!function_exists('getGradientsExport')){
	function getGradientsExport(){
		$data =get_option('saved_gradient_on_clients',serialize(array('result' => 1, 'stamp' => 0,'records'=>array())));
		header('Content-Type:text/plan');
		header("Content-Disposition: attachment; filename=export-gradient-".date("Y-m-d_H").'.txt');
		echo $data;
		exit;
	}
	if(isset($_GET['action']) && $_GET['action'] === 'getGradientsExport'){
		if(is_user_logged_in())
			getGradientsExport();
		wp_send_json_error();
	}
}
if(!function_exists('setGradientsImport')){
	function setGradientsImport(){
		if(isset($_FILES['exported_file'])){
			$fileContent = file_get_contents($_FILES['exported_file']['tmp_name']);
			$new_data = unserialize($fileContent);
			if($new_data !== null){
				update_option( 'saved_gradient_on_clients', serialize($new_data));
				wp_send_json_success(array('result' => 1, 'new_data'=>$new_data));
				wp_die();
			}
		}
		wp_send_json_error();
		wp_die();
	}
	if(isset($_POST['action']) && $_POST['action'] === 'setGradientsImport'){
		if(is_user_logged_in())
			setGradientsImport();
	}
}
if(!function_exists('getMiniColorExport')){
	function getMiniColorExport(){
		$data =get_option('saved_colors_on_clients',serialize(array()));
		header('Content-Type:text/plan');
		header("Content-Disposition: attachment; filename=export-colors-".date("Y-m-d_H").'.txt');
		echo $data;
		exit;
	}
	if(isset($_GET['action']) && $_GET['action'] === 'getMiniColorExport'){
		if(is_user_logged_in())
			getMiniColorExport();
		wp_send_json_error();
	}
}
if(!function_exists('setMiniColorImport')){
	function setMiniColorImport(){
		if(isset($_FILES['exported_file'])){
			$fileContent = file_get_contents($_FILES['exported_file']['tmp_name']);
			$new_data = unserialize($fileContent);
			if($new_data !== null){
				update_option( 'saved_colors_on_clients', serialize($new_data));
				wp_send_json_success($new_data);
				wp_die();
			}
		}
		wp_send_json_error();
		wp_die();
	}
	if(isset($_POST['action']) && $_POST['action'] === 'setMiniColorImport'){
		if(is_user_logged_in())
			setMiniColorImport();
	}
}
if(!function_exists('getSavedColors')){
	function getSavedColors(){
		$data =get_option('saved_colors_on_clients',serialize(array()));
		wp_send_json_success(unserialize($data));
		wp_die();
	}
	if(isset($_GET['action']) && $_GET['action'] === 'getSavedColors'){
		if(is_user_logged_in())
			getSavedColors();
		wp_send_json_error();
	}
}
if(!function_exists('saveColorsOnServer')){
	function saveColorsOnServer(){
		if(!isset($_POST['colors'])){
			wp_send_json_error();
		}elseif(is_array($_POST['colors'])){
			update_option( 'saved_colors_on_clients', serialize($_POST['colors']));
			wp_send_json_success();
		}else{
			wp_send_json_error();
		}
		wp_die();
	}
	if(isset($_POST['action']) && $_POST['action'] === 'saveColorsOnServer'){
		if(is_user_logged_in())
			saveColorsOnServer();
		wp_send_json_error();
	}
}

/**
 * Add Builder to all themes using the themify_theme_config_setup filter.
 * @param $themify_theme_config
 * @return mixed
 * @since 1.4.2
 */
function themify_framework_theme_config_add_builder($themify_theme_config) {
    $themify_theme_config['panel']['settings']['tab']['page_builder'] = array(
        'title' => __('Themify Builder', 'themify'),
        'id' => 'themify-builder',
        'custom-module' => array(
            array(
                'title' => __('Themify Builder Options', 'themify'),
                'function' => 'themify_manage_builder_active'
            )
        )
    );
    $themify_theme_config['panel']['settings']['tab']['integration-api']['custom-module'][] = array(
		'title' => __('Optin', 'themify'),
		'function' => 'themify_setting_optin',
	);

    if ('disable' !== apply_filters('themify_enable_builder', themify_get('setting-page_builder_is_active'))) {
        $themify_theme_config['panel']['settings']['tab']['page_builder']['custom-module'][] = array(
            'title' => __('Animation Effects', 'themify'),
            'function' => 'themify_manage_builder_animation'
        );

        $themify_theme_config['panel']['settings']['tab']['page_builder']['custom-module'][] = array(
            'title' => __('Builder Modules', 'themify'),
            'function' => 'themify_manage_builder'
        );

		$themify_theme_config['panel']['settings']['tab']['page_builder']['custom-module'][] = array(
			'title' => __('Tools', 'themify'),
			'function' => 'tb_tools_options'
		);
    }
    return $themify_theme_config;
}

add_filter( 'themify_theme_config_setup', 'themify_framework_theme_config_add_builder', 11 );

function themify_setting_optin() {
	if ( isset( $_GET['tb_option_flush_cache'] ) ) {
		$services = Builder_Optin_Services_Container::get_instance()->get_providers();
		foreach ( $services as $id => $instance ) {
			$instance->clear_cache();
		}
	}

	ob_start();
	$providers = Builder_Optin_Services_Container::get_instance()->get_providers();
	foreach ( $providers as $id => $instance ) {
		if ( $options = $instance->get_global_options() ) {
			?>
			<fieldset id="themify_setting_<?php echo $id; ?>">
				<legend>
					<span><?php echo $instance->get_label(); ?></span>
					<i class="ti-plus"></i>
				</legend>
				<div class="themify_panel_fieldset_wrap" style="display: block !important;">
					<?php foreach ( $options as $field ) : ?>
						<p>
							<label class="label" for="setting-<?php echo $field['id']; ?>"><?php echo $field['label'] ?></label>
							<input type="text" name="setting-<?php echo $field['id']; ?>" id="setting-<?php echo $field['id']; ?>" value="<?php echo esc_attr( themify_builder_get( "setting-{$field['id']}" ) ); ?>" class="width10">
							<?php if ( isset( $field['description'] ) ) : ?>
								<small class="pushlabel"><?php echo $field['description'] ?></small>
							<?php endif; ?>
						</p>
					<?php endforeach; ?>
				</div><!-- .themify_panel_fieldset_wrap -->
			</fieldset>
		<?php } ?>
	<?php } ?>

	<br>
	<p>
		<a href="<?php echo add_query_arg( 'tb_option_flush_cache', 1 ); ?>" class="tb_option_flush_cache themify_button"><span><?php _e( 'Clear Cache', 'themify' ); ?></span> </a>
	</p>

	<?php
	return ob_get_clean();
}
