Server : LiteSpeed
System : Linux quebec.us.hostns.io 5.14.0-687.42.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Aug 27 11:55:12 EDT 2026 x86_64
User : gazetufm ( 1431)
PHP Version : 8.1.35
Disable Function : NONE
Directory :  /home2/gazetufm/dumoshi.com/wp-content/plugins/ultimate-post-kit/includes/setup-wizard/

📁 Create New:
⬆️ Upload File:
Current Dir [ Writable ] Root [ Writable ]


OR Upload from URL:
URL: Save as:

📄 File: init.php

Path: //home2/gazetufm/dumoshi.com/wp-content/plugins/ultimate-post-kit/includes/setup-wizard/init.php

Size: 28.9 KB

Permissions: 0644

<?php

namespace UltimatePostKit\Includes;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Load the Remote Data Handler
require_once __DIR__ . '/class-remote-data-handler.php';

use UltimatePostKit\Admin\ModuleService;
use Elementor\Plugin;
/**
 * Overwrite the feedback method in the WP_Upgrader_Skin
 * to suppress the normal feedback.
 */

require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

class Quiet_Upgrader_Skin extends \WP_Upgrader_Skin {
	/*
	 * Suppress normal upgrader feedback / output
	 */
	public function feedback( $string, ...$args ) {
		/* no output */
	}
}


class Setup_Wizard {

	// Singleton instance
	private static $instance = null;

	/**
	 * Whether this request renders the wizard. Set on admin_init, read when
	 * the assets are enqueued.
	 *
	 * @var bool
	 */
	private $is_wizard_request = false;

	// Constructor
	private function __construct() {
		$this->init_hooks();
	}

	// Get instance
	public static function get_instance() {
		if ( self::$instance == null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Newsletter list endpoint the welcome step's opt-in posts to.
	 */
	const SUBSCRIBE_ENDPOINT = 'https://marketing.sigmative.com/newsletter/rui/lists/6a9943aacbe70/embedded-form-subscribe';

	/**
	 * Customer identifier required by the newsletter endpoint.
	 */
	const SUBSCRIBE_CUSTOMER_UID = '6a93d39ce0ebd';

	// Initialize hooks
	private function init_hooks() {
		add_action( 'wp_ajax_ultimate_post_kit_setup_wizard_install_plugins', array( $this, 'install_plugins' ) );
		add_action( 'wp_ajax_ultimate_post_kit_setup_wizard_subscribe', array( $this, 'ajax_subscribe' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'dequeue_sibling_wizards' ), 100 );
		add_action( 'admin_init', array( $this, 'activate_default_widgets' ) );
		add_action( 'admin_init', array( $this, 'maybe_display_setup_wizard' ) );
		add_action( 'admin_init', array( $this, 'check_manual_wizard_request' ) );

		// NOTE: WordPress manages plugin/translation updates. Do not add filters
		// that interfere with the built-in update pipeline (wp.org Guideline).
	}

	// Check for manual wizard requests
	public function check_manual_wizard_request() {
		// This runs on admin_init, which also fires on admin-ajax.php before any
		// authentication, and on every admin screen for every logged-in role. The setup
		// wizard is an administrator-only flow, so gate it explicitly.
		if ( wp_doing_ajax() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only check of a GET flag to decide whether to render the setup wizard screen, no form data processed.
		$is_setup_wizard_request = isset($_GET['upk_setup_wizard']) && $_GET['upk_setup_wizard'] === 'show';
		
		if ( $is_setup_wizard_request ) {
			$this->is_wizard_request = true;

			// Use the same approach as first activation - completely override the page
			add_action('admin_head', function() {
				?>
				<style>
					html, body {
						height: 100%;
						margin: 0;
						padding: 0;
						overflow: hidden;
					}
					#wpwrap, #wpcontent, #wpbody, #wpbody-content {
						height: 100%;
						padding: 0;
						margin: 0;
					}
					#adminmenumain, #wpadminbar {
						display: none;
					}
				</style>
				<script>
					jQuery(document).ready(function($) {
						$('body').addClass('bdt-setup-wizard-active');
					});
				</script>
				<?php
				
				// Display setup wizard using the same method as first activation
				$this->display_page();
			});
		}
	}

	// Display wizard in fullscreen mode
	public function display_wizard_fullscreen() {
		?>
		<style>
			html, body {
				height: 100%;
				margin: 0;
				padding: 0;
				overflow: hidden;
			}
			#wpwrap, #wpcontent, #wpbody, #wpbody-content {
				height: 100%;
				padding: 0;
				margin: 0;
			}
			#adminmenumain, #wpadminbar {
				display: none;
			}
		</style>
		<?php
		// Directly output the wizard content
		add_action('admin_footer', function() {
			echo '<div id="upk-setup-wizard-container">';
			$this->display_page();
			echo '</div>';
			?>
			<script>
				jQuery(document).ready(function($) {
					$('body').addClass('bdt-setup-wizard-active');
					// Hide all other content and show only our wizard
					$('#wpbody-content').html($('#upk-setup-wizard-container').html());
					$('#upk-setup-wizard-container').remove();
				});
			</script>
			<?php
		}, 999);
	}

	// Get wizard HTML content
	public function get_wizard_html() {
		ob_start();
		?>
		<div class="bdt-setup-wizard-overlay upk-setup-wizard ">
			<div class="bdt-setup-wizard content-loaded">
				<?php
				require_once plugin_dir_path( BDTUPK__FILE__ ) . 'includes/setup-wizard/views/render.php';
				?>
			</div>
		</div>
		<?php
		return ob_get_clean();
	}

	// Check if this is first activation and display setup wizard if needed
	public function maybe_display_setup_wizard() {
		// This runs on admin_init, which also fires on admin-ajax.php before any
		// authentication, and on every admin screen for every logged-in role. The setup
		// wizard is an administrator-only flow, so gate it explicitly.
		if ( wp_doing_ajax() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Only check for first activation here
		if ( get_option( 'bdtupk_setup_wizard_completed' ) === false ) {
			// Set the flag so it doesn't run again
			update_option( 'bdtupk_setup_wizard_completed', true );

			$this->is_wizard_request = true;
			
			// Add a header to ensure proper full-page display
			add_action('admin_head', function() {
				?>
				<style>
					html, body {
						height: 100%;
						margin: 0;
						padding: 0;
						overflow: hidden;
					}
					#wpwrap, #wpcontent, #wpbody, #wpbody-content {
						height: 100%;
						padding: 0;
						margin: 0;
					}
					#adminmenumain, #wpadminbar {
						display: none;
					}
				</style>
				<script>
					jQuery(document).ready(function($) {
						$('body').addClass('bdt-setup-wizard-active');
					});
				</script>
				<?php
				
				// Display setup wizard
				$this->display_page();
			});
		}
	}

	// Keep the admin_menu method for reference but not hooked
	public function admin_menu() {
		add_submenu_page(
			'ultimate_post_kit_options',
			esc_html__( 'Setup Wizard', 'ultimate-post-kit' ),
			esc_html__( 'Setup Wizard', 'ultimate-post-kit' ),
			'manage_options',
			'ultimate-post-kit-setup-wizard',
			array( $this, 'display_page' )
		);
	}

	public function display_page() {
		?>
		<div class="bdt-setup-wizard-overlay upk-setup-wizard">
			<div class="bdt-setup-wizard content-loaded">
				<?php
				require_once plugin_dir_path( BDTUPK__FILE__ ) . 'includes/setup-wizard/views/render.php';
				?>
			</div>
		</div>
		<?php
	}

	// Enqueue necessary scripts
	public function enqueue_scripts() {

		// Loaded on admin_enqueue_scripts for every admin screen and every role. The
		// wizard's assets and its nonce have no business outside an administrator's
		// wizard/settings screen.
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Only the request that renders the wizard needs its assets. Loaded on
		// every admin screen, the script also attached itself to the other
		// BdThemes plugins' wizards, which share the .bdt-setup-wizard markup.
		if ( ! $this->is_wizard_request ) {
			return;
		}

		$direction_suffix = is_rtl() ? '.rtl' : '';

		wp_enqueue_style('bdt-uikit', BDTUPK_ADMIN_ASSETS_URL . 'css/bdt-uikit' . $direction_suffix . '.css', [], '3.17.0');
		wp_enqueue_script('bdt-uikit', BDTUPK_ADMIN_ASSETS_URL . 'js/bdt-uikit.min.js', ['jquery'], '3.17.0', true);

		wp_register_script( 'upk-setup-wizard', plugins_url( 'assets/js/setup-wizard.js', __FILE__ ), array( 'jquery' ), BDTUPK_VER, true );
		wp_register_style( 'upk-setup-wizard', plugins_url( 'assets/css/setup-wizard.css', __FILE__ ), array(), BDTUPK_VER );

		wp_enqueue_script( 'upk-setup-wizard' );
		wp_enqueue_style( 'upk-setup-wizard' );

		wp_localize_script(
			'upk-setup-wizard',
			'UPK_SetupWizard',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'ultimate_post_kit_setup_wizard_nonce' ),
				'is_fullscreen' => true
			)
		);
	}

	/**
	 * Keep the other BdThemes plugins' setup wizards off this one.
	 *
	 * Those plugins enqueue their wizard script and stylesheet on every admin
	 * screen and select the same .bdt-setup-wizard markup, so on this page
	 * their handlers ran as well. Only handles loaded from another plugin's
	 * includes/setup-wizard/ folder are removed.
	 */
	public function dequeue_sibling_wizards() {
		if ( ! $this->is_wizard_request ) {
			return;
		}

		$own_folder = '/' . basename( dirname( BDTUPK__FILE__ ) ) . '/';

		foreach ( array( wp_scripts(), wp_styles() ) as $deps ) {
			foreach ( (array) $deps->queue as $handle ) {
				if ( 'upk-setup-wizard' === $handle || ! isset( $deps->registered[ $handle ] ) ) {
					continue;
				}

				$src = (string) $deps->registered[ $handle ]->src;

				if ( false !== strpos( $src, '/includes/setup-wizard/' ) && false === strpos( $src, $own_folder ) ) {
					$deps instanceof \WP_Scripts ? wp_dequeue_script( $handle ) : wp_dequeue_style( $handle );
				}
			}
		}
	}

	public static function get_widget_map() {
		$arr_obj = ModuleService::get_widget_settings(
			function ( $settings ) {
				$core_widgets = $settings['settings_fields']['ultimate_post_kit_active_modules'];
				return $core_widgets;
			}
		);
		return $arr_obj;
	}

	/**
	 * Handle the newsletter opt-in on the welcome step.
	 *
	 * Opt-in only: nothing is sent unless the administrator ticked the box,
	 * which is unticked by default. The choice is recorded either way so the
	 * wizard can show it again on a re-run. Runs server side so the
	 * cross-origin POST is not subject to CORS.
	 */
	public function ajax_subscribe() {
		check_ajax_referer( 'ultimate_post_kit_setup_wizard_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'ultimate-post-kit' ) ) );
		}

		// Record the choice first, whichever way it went.
		$consent = isset( $_POST['consent'] ) && 'yes' === sanitize_text_field( wp_unslash( $_POST['consent'] ) );

		update_option( 'bdtupk_subscribe_optin', $consent ? 'yes' : 'no' );

		if ( ! $consent ) {
			// No opt-in: the choice is stored and nothing leaves the site.
			wp_send_json_success(
				array(
					'subscribed' => false,
					'message'    => esc_html__( 'Preferences saved.', 'ultimate-post-kit' ),
				)
			);
		}

		// Keep the raw value: sanitize_email() flattens anything malformed to an
		// empty string, which would otherwise be indistinguishable from "left blank".
		$raw_email = isset( $_POST['email'] ) ? sanitize_text_field( wp_unslash( $_POST['email'] ) ) : '';
		$email     = sanitize_email( $raw_email );

		if ( '' === trim( $raw_email ) ) {
			wp_send_json_success(
				array(
					'subscribed' => false,
					'message'    => esc_html__( 'Preferences saved.', 'ultimate-post-kit' ),
				)
			);
		}

		if ( ! is_email( $email ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Please enter a valid email address.', 'ultimate-post-kit' ) ) );
		}

		// Never subscribe the same address twice from this site.
		if ( get_option( 'bdtupk_subscribed_email' ) === $email ) {
			wp_send_json_success(
				array(
					'subscribed' => true,
					'message'    => esc_html__( 'You are already subscribed.', 'ultimate-post-kit' ),
				)
			);
		}

		$current_user = wp_get_current_user();

		$body = array(
			'customer_uid' => apply_filters( 'bdtupk/setup_wizard/subscribe_customer_uid', self::SUBSCRIBE_CUSTOMER_UID ),
			'EMAIL'        => $email,
			'FIRST_NAME'   => $current_user ? $current_user->first_name : '',
			'LAST_NAME'    => $current_user ? $current_user->last_name : '',
		);

		$response = wp_safe_remote_post(
			apply_filters( 'bdtupk/setup_wizard/subscribe_url', self::SUBSCRIBE_ENDPOINT ),
			array(
				'timeout'   => 15,
				'body'      => apply_filters( 'bdtupk/setup_wizard/subscribe_body', $body, $email ),
				'headers'   => array( 'Accept' => '*/*' ),
				'sslverify' => true,
			)
		);

		if ( is_wp_error( $response ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Could not reach the subscription service. Please try again later.', 'ultimate-post-kit' ) ) );
		}

		$code = wp_remote_retrieve_response_code( $response );

		if ( $code < 200 || $code >= 400 ) {
			wp_send_json_error( array( 'message' => esc_html__( 'The subscription service rejected the request.', 'ultimate-post-kit' ) ) );
		}

		update_option( 'bdtupk_subscribed_email', $email );

		wp_send_json_success(
			array(
				'subscribed' => true,
				'message'    => esc_html__( 'Thanks for subscribing!', 'ultimate-post-kit' ),
			)
		);
	}

	// Install plugins
	public function install_plugins() {
		check_ajax_referer( 'ultimate_post_kit_setup_wizard_nonce', 'nonce' );

		$plugin_slugs = isset( $_POST['plugins'] ) ? map_deep( wp_unslash( $_POST['plugins'] ), 'sanitize_text_field' ) : array();

		if ( empty( $plugin_slugs ) || ! is_array( $plugin_slugs ) ) {
			wp_send_json_error( array( 'message' => 'Invalid plugins array' ) );
		}

		if ( ! current_user_can( 'install_plugins' ) ) {
			wp_send_json_error( array( 'message' => 'Unauthorized' ) );
		}

		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
		include_once ABSPATH . 'wp-admin/includes/plugin.php';

		$upgrader = new \Plugin_Upgrader( new Quiet_Upgrader_Skin() );
		$results  = array();

		foreach ( $plugin_slugs as $plugin_slug ) {
			// The wizard sends wordpress.org slugs ("live-copy-paste") and, for
			// some entries, a main file path ("bdthemes-prime-slider-lite/
			// bdthemes-prime-slider.php"). activate_plugin() needs the main file,
			// so both are reduced to the folder and looked up.
			$slug        = sanitize_key( strtok( (string) $plugin_slug, '/' ) );
			$plugin_file = $slug ? $this->get_plugin_file( $slug ) : false;

			if ( ! $slug ) {
				continue;
			}

			if ( $plugin_file && is_plugin_active( $plugin_file ) ) {
				$results[] = array(
					'slug'    => $slug,
					'success' => true,
					'message' => esc_html__( 'Already active.', 'ultimate-post-kit' ),
				);
				continue;
			}

			// Download only what is not installed yet. Installing over an
			// existing folder fails with "Destination folder already exists".
			if ( ! $plugin_file ) {
				$api = plugins_api( 'plugin_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ) ) );

				if ( is_wp_error( $api ) ) {
					$results[] = array(
						'slug'    => $slug,
						'success' => false,
						'message' => $api->get_error_message(),
					);
					continue;
				}

				$installed = $upgrader->install( $api->download_link );

				if ( is_wp_error( $installed ) || ! $installed ) {
					$results[] = array(
						'slug'    => $slug,
						'success' => false,
						'message' => is_wp_error( $installed ) ? $installed->get_error_message() : esc_html__( 'Installation failed.', 'ultimate-post-kit' ),
					);
					continue;
				}

				wp_clean_plugins_cache();
				$plugin_file = $upgrader->plugin_info() ? $upgrader->plugin_info() : $this->get_plugin_file( $slug );
			}

			if ( ! $plugin_file ) {
				$results[] = array(
					'slug'    => $slug,
					'success' => false,
					'message' => esc_html__( 'The plugin was installed, but its main file could not be found.', 'ultimate-post-kit' ),
				);
				continue;
			}

			// Activating a plugin is a separate capability from installing one, so it is
			// checked on its own rather than being implied by 'install_plugins' above.
			if ( ! current_user_can( 'activate_plugin', $plugin_file ) ) {
				$results[] = array(
					'slug'    => $slug,
					'success' => false,
					'message' => esc_html__( 'You do not have permission to activate plugins on this site.', 'ultimate-post-kit' ),
				);
				continue;
			}

			$activated = activate_plugin( $plugin_file );

			$results[] = array(
				'slug'    => $slug,
				'success' => ! is_wp_error( $activated ),
				'message' => is_wp_error( $activated ) ? $activated->get_error_message() : esc_html__( 'Installed and activated successfully.', 'ultimate-post-kit' ),
			);
		}

		// Discard anything an activated plugin printed into an open buffer, so
		// the response stays valid JSON. ob_clean() without a buffer raises a
		// notice, which is what the unconditional call here used to do.
		if ( ob_get_level() > 0 && ob_get_length() ) {
			ob_clean();
		}

		// The wizard sends one plugin per request and reads the envelope's
		// success flag, so a failed install or activation has to answer with an
		// error; it used to be reported as a success.
		$failed = array_filter(
			$results,
			function ( $result ) {
				return empty( $result['success'] );
			}
		);

		if ( $failed ) {
			wp_send_json_error(
				array(
					'results' => $results,
					'message' => implode( ' ', wp_list_pluck( $failed, 'message' ) ),
				)
			);
		}

		wp_send_json_success( array( 'results' => $results ) );
	}

	/**
	 * Get the main plugin file path for a given slug.
	 *
	 * @param string $slug Plugin slug.
	 * @return string|false Plugin file path or false if not found.
	 */
	private function get_plugin_file( $slug ) {
		$plugins = get_plugins();

		foreach ( array_keys( $plugins ) as $file ) {
			// Match the folder exactly: a substring test would match
			// "ultimate-post-kit-pro/…" for "ultimate-post-kit".
			if ( dirname( $file ) === $slug ) {
				return $file;
			}
		}

		return false;
	}
    
    /**
     * Activate default widgets in setup wizard
     */
    public function activate_default_widgets() {

        // Also reached anonymously via admin-ajax.php, which fires admin_init before
        // authentication. Enabling widget modules is an administrator action.
        if ( wp_doing_ajax() || ! current_user_can( 'manage_options' ) ) {
            return;
        }

        // List of widgets to activate by default
        $default_active_widgets = array(
            'alex-grid',
            'alice-grid',
            'alter-carousel',
			'banner',
			'buzz-list',
			'carbon-slider',
			'featured-list',
			'news-ticker',
			'pholox-slider',
			'timeline',
			'category',
			'social-count',
			'tag-cloud'
        );
        
        // Get current active modules
        $active_modules = get_option('ultimate_post_kit_active_modules', array());
        
        // Make sure $active_modules is an array
        if (!is_array($active_modules)) {
            $active_modules = array();
        }
        
        // Check if active_modules option exists and is not empty
        // If it's a new installation or option doesn't exist, we'll set our defaults
        $modified = false;
        
        foreach ($default_active_widgets as $widget) {
            // Only set if not already defined (prevents overriding user settings on existing installations)
            if (!isset($active_modules[$widget])) {
                $active_modules[$widget] = 'on';
                $modified = true;
            }
        }
        
        // Update the option if changes were made
        if ($modified) {
            update_option('ultimate_post_kit_active_modules', $active_modules);
        }
    }
}

// Initialize the Setup Wizard
Setup_Wizard::get_instance();

use Elementor\TemplateLibrary\Source_Local;

add_action('wp_ajax_ultimate_post_kit_import_elementor_template', function () {
		check_ajax_referer( 'ultimate_post_kit_setup_wizard_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'ultimate-post-kit' ) ) );
			wp_die();
		}

		$json_url = isset( $_POST['import_url'] ) ? esc_url_raw( wp_unslash( $_POST['import_url'] ) ) : '';

        $response = wp_safe_remote_get($json_url, array(
            'timeout' => 60,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => esc_html__('Failed to fetch template from URL.', 'ultimate-post-kit')]);
            wp_die();
        }

        $sourceData = wp_remote_retrieve_body($response);
        $sourceData2 = json_decode($sourceData, true);

        if (!$sourceData2 || !is_array($sourceData2)) {
            wp_send_json_error(['message' => esc_html__('Failed to fetch template from URL.', 'ultimate-post-kit')]);
            wp_die();
        }

        $temp_file = wp_upload_dir()['path'] . '/elementor_import_' . time() . '.json';
        file_put_contents($temp_file, $sourceData);

        // Initialize Elementor's Template Importer
        if (!class_exists('\Elementor\TemplateLibrary\Source_Local')) {
            wp_delete_file($temp_file);
            wp_send_json_error(['message' => esc_html__('Elementor is not installed or activated!', 'ultimate-post-kit')]);
            wp_die();
        }

        $manager = new Source_Local();
        $templateData = $manager->import_template('elementor_template', $temp_file);
        wp_delete_file($temp_file); // Delete temp file after import

        if (is_wp_error($templateData) || !is_array($templateData) || empty($templateData[0]['template_id'])) {
            wp_send_json_error(['message' => esc_html__('Failed to import template!', 'ultimate-post-kit')]);
            wp_die();
        }

        $template_id = $templateData[0]['template_id'];
        $metaData = get_post_meta($template_id);

        $page_title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : esc_html__("No Title", 'ultimate-post-kit');

        // Validate Elementor Data
        if (!isset($metaData['_elementor_data'][0])) {
            wp_send_json_error(['message' => esc_html__('Elementor data not found in template.', 'ultimate-post-kit')]);
            wp_die();
        }

        $_elementor_data = wp_slash($metaData['_elementor_data'][0]);

        // Create New Page
        $new_post_id = wp_insert_post([
            'post_type'    => 'page',
            'post_status'  => empty($page_title) ? 'draft' : 'publish',
            'post_title'   => $page_title,
            'post_content' => '',
        ]);

        if (is_wp_error($new_post_id)) {
            wp_send_json_error(['message' => esc_html__('Failed to create page!', 'ultimate-post-kit')]);
            wp_die();
        }

        // Assign Elementor Template Data
        update_post_meta($new_post_id, '_elementor_data', $_elementor_data);

        // Import Page Settings if available
        if (isset($metaData['_elementor_page_settings'][0])) {
            $_elementor_page_settings = is_serialized($metaData['_elementor_page_settings'][0])
                ? unserialize($metaData['_elementor_page_settings'][0], ['allowed_classes' => false])
                : $metaData['_elementor_page_settings'][0];
            update_post_meta($new_post_id, '_elementor_page_settings', $_elementor_page_settings);
        }

        update_post_meta($new_post_id, '_elementor_template_type', $sourceData2['type'] ?? '');
        update_post_meta($new_post_id, '_elementor_edit_mode', 'builder');
//        update_post_meta($new_post_id, '_wp_page_template', !empty($pageTemplate) ? $pageTemplate : 'elementor_header_footer');

        wp_send_json_success([
            'message'   => esc_html__('The template was imported successfully.', 'ultimate-post-kit'),
            'ids'       => $new_post_id,
            'edit_link' => admin_url('post.php?post=' . $new_post_id . '&action=elementor'),
        ]);
	}
);


add_action('wp_ajax_ultimate_post_kit_import_elementor_bundle_template', function () {
    check_ajax_referer('ultimate_post_kit_setup_wizard_nonce', 'nonce');

	if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'ultimate-post-kit' ) ) );
        wp_die();
    }

    $file_url = isset($_POST['import_url']) ? esc_url_raw(wp_unslash($_POST['import_url'])) : '';

    if (!filter_var($file_url, FILTER_VALIDATE_URL) || 0 !== strpos($file_url, 'http')) {
        wp_send_json_error(['message' => esc_html__('Invalid import URL', 'ultimate-post-kit')]);
    }

    $remote_zip_request = wp_safe_remote_get($file_url, array(
        'timeout' => 60,
    ));

    if (is_wp_error($remote_zip_request)) {
        wp_send_json_error(['message' => esc_html__('Failed to fetch template from URL.', 'ultimate-post-kit')]);
    }


    if (200 !== $remote_zip_request['response']['code']) {
        wp_send_json_error(['message' => esc_html__('Failed to fetch template from URL.', 'ultimate-post-kit')]);
    }

    $kit_zip_path = Plugin::$instance->uploads_manager->create_temp_file($remote_zip_request['body'], 'kit.zip');

    $app = Plugin::$instance->app;
    if (!$app) {
        Plugin::$instance->uploads_manager->remove_file_or_dir(dirname($kit_zip_path));
        wp_send_json_error(['message' => esc_html__('Elementor app not available', 'ultimate-post-kit')]);
    }

    $import_export_module = $app->get_component('import-export');

    try {
        $result = $import_export_module->upload_kit($kit_zip_path, 'local');

        // The kit is unpacked into its session folder; drop the downloaded zip,
        // as Elementor's own importer does, so imports leave no copies in uploads.
        Plugin::$instance->uploads_manager->remove_file_or_dir(dirname($kit_zip_path));

        $manifest = $result['manifest'] ?? [];
        $plugins = $manifest['plugins'];

        $missingPlugins = [];
        foreach ($plugins as $plugin) {
            $pluginSlug = $plugin['plugin'].".php";
            if (is_plugin_inactive($pluginSlug)) {
                $missingPlugins[] = $plugin;
            }
        }

        if (count($missingPlugins)) {
            wp_send_json_error([
                'plugins' => $missingPlugins,
                'message' => esc_html__('Missing plugins', 'ultimate-post-kit'),
            ]);
        }

        $tmp_folder_id = $result['session'];
        $includes = [];
        $selectedCustomPostTypes = [];

        if (isset($manifest['templates'])) {
            $includes[] = 'templates';
        }

        if (isset($manifest['content'])) {
            $includes[] = 'content';
        }

        if (isset($manifest['site-settings'])) {
            $includes[] = 'settings';
        }

        if (isset($manifest['custom-post-type-title'])) {
            $selectedCustomPostTypes = array_keys($manifest['custom-post-type-title']);
        }

        $settings = [
            'id'                      => '',
            'session'                 => $tmp_folder_id,
            'include'                 => $includes,
            'overrideConditions'      => [],
            'selectedCustomPostTypes' => $selectedCustomPostTypes,
        ];

        $import = $import_export_module->import_kit($tmp_folder_id, $settings, true);

        // Deliberately NOT calling
        // Plugin::$instance->uploads_manager->enable_unfiltered_files_upload() here.
        // That permanently sets Elementor's `elementor_unfiltered_files_upload` option,
        // which Elementor itself surfaces behind an explicit security warning and an
        // opt-in confirmation. Importing a template must not silently relax another
        // plugin's upload filtering for the whole site.

        wp_send_json_success($import);
    } catch (\Throwable $e) {
        if (file_exists($kit_zip_path)) {
            Plugin::$instance->uploads_manager->remove_file_or_dir(dirname($kit_zip_path));
        }
        wp_send_json_error(['message' => esc_html__('Import failed: ', 'ultimate-post-kit') . esc_html($e->getMessage())]);
    }
});

add_action('wp_ajax_ultimate_post_kit_import_elementor_bundle_runner_template', function () {
    check_ajax_referer('ultimate_post_kit_setup_wizard_nonce', 'nonce');

	if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'ultimate-post-kit' ) ) );
        wp_die();
    }

    $runner = isset($_POST['runner']) ? sanitize_text_field(wp_unslash($_POST['runner'])) : '';
    $sessionId = isset($_POST['sessionId']) ? sanitize_text_field(wp_unslash($_POST['sessionId'])) : '';

    if (!$runner || !$sessionId) {
        wp_send_json_error(['message' => esc_html__('Required Param Is Missing.', 'ultimate-post-kit')]);
    }

    $app = Plugin::$instance->app;
    if (!$app) {
        wp_send_json_error(['message' => esc_html__('Elementor app not available.', 'ultimate-post-kit')]);
    }

    try {
        // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged, WordPress.PHP.IniSet.max_execution_time_Disallowed -- raise the limit only for this admin-triggered template import, which can exceed the default.
        @ini_set('max_execution_time', 60 * 5);

        $import_export_module = $app->get_component('import-export');
        $import = $import_export_module->import_kit_by_runner($sessionId, $runner);

        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- hooking into Elementor's own action, not a plugin-defined hook.
        do_action('elementor/import-export/import-kit/runner/after-run', $import);
        wp_send_json_success($import);
    } catch (\Throwable $throwable) {
        wp_send_json_error(['message' => $throwable->getMessage()]);
    }
});

← Back to Directory Edit File 🔒 Chmod

WP File Manager