← Back
Editing: library-source.php
<?php namespace ElementsKit_Lite\Modules\Layout_Manager; defined( 'ABSPATH' ) || exit; use Elementor\TemplateLibrary\Source_Base; use Elementor\Plugin; class Library_Source extends Source_Base { /** * How many levels of Widget Areas inside Widget Areas are imported. */ const MAX_IMPORT_DEPTH = 5; /** * Current Widget Area nesting level of the import. * * @var int */ private $import_depth = 0; /** * Map original Elementor element IDs to the IDs generated for the import. * * @var array<string,string> */ private $element_id_map = array(); /** * Original imported elements keyed by their pre-import Elementor IDs. * * This is needed because Elementor may mutate repeater item IDs during * normal import processing, while ElementsKit dynamic content posts are * still stored under the original repeater IDs from the remote payload. * * @var array<string,array> */ private $original_elements = array(); public function get_id() { return 'elementskit-layout-manager'; } public function get_title() { return __( 'ElementsKit Layout Manager', 'elementskit-lite' ); } public function register_data() {} public function save_item( $template_data ) { return new \WP_Error( 'invalid_request', 'Cannot save template to a elementskit layout manager' ); } public function update_item( $new_data ) { return new \WP_Error( 'invalid_request', 'Cannot update template to a elementskit layout manager' ); } public function delete_template( $template_id ) { return new \WP_Error( 'invalid_request', 'Cannot delete template from a elementskit layout manager' ); } public function export_template( $template_id ) { return new \WP_Error( 'invalid_request', 'Cannot export template from a elementskit layout manager' ); } public function get_items( $args = array() ) { return array(); } public function get_item( $template_id ) { $templates = $this->get_items(); return $templates[ $template_id ]; } public function request_template_data( $template_id ) { if ( empty( $template_id ) ) { return; } $query = array_merge( array( 'action' => 'get_layout_data', 'layout_id' => $template_id, ), \ElementsKit_Lite::license_data() ); $request_url = \ElementsKit_Lite::api_url() . 'layout-manager-api/' . '?' . http_build_query( $query ); $response = wp_remote_get( $request_url, array( 'timeout' => 30, ) ); if ( is_wp_error( $response ) ) { throw new \Exception( esc_html( $response->get_error_message() ) ); } $response_code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $response_code ) { throw new \Exception( sprintf( /* translators: %d: HTTP response code. */ esc_html__( 'Template API request failed with status code %d.', 'elementskit-lite' ), absint( $response_code ) ) ); } return wp_remote_retrieve_body( $response ); } /** * Get remote template data and prepare it for insertion into Elementor. * * In addition to Elementor's normal import processing, this recreates the * hidden `elementskit_content` posts used by WIDGETAREA controls and rewrites * widget settings so the imported widgets point to their newly-created local * dynamic content. * * @param array $args Template request arguments. * @param string $context Template source context. * * @return array * @throws \Exception When the remote template payload has no content. */ public function get_data( array $args, $context = 'display' ) { $data = $this->request_template_data( $args['template_id'] ); $data = json_decode( $data, true ); if ( ! empty( $data['error'] ) ) { throw new \Exception( esc_html( $data['error'] ) ); } if ( empty( $data ) || empty( $data['content'] ) ) { throw new \Exception( esc_html__( 'Template does not have any content', 'elementskit-lite' ) ); } $data['content'] = $this->prepare_imported_content( $data['content'], $data ); $post_id = ! empty( $args['editor_post_id'] ) ? absint( $args['editor_post_id'] ) : 0; $document = $post_id ? \Elementor\Plugin::instance()->documents->get( $post_id ) : null; if ( $document ) { // The editor shows this HTML as soon as the layout is inserted. Render it in edit // mode, as Elementor does for its own templates, so editor-only markup such as the // Widget Area "Edit Content" button is there before the widget re-renders. $editor = \Elementor\Plugin::instance()->editor; $is_edit_mode = $editor->is_edit_mode(); $editor->set_edit_mode( true ); try { $data['content'] = $document->get_elements_raw_data( $data['content'], true ); } finally { $editor->set_edit_mode( $is_edit_mode ); } } return $data; } /** * Run an element tree through the import, including the Widget Areas inside it. * * Also used for Widget Area content itself, so a Tab placed inside another Tab * keeps its content. Nesting stops at MAX_IMPORT_DEPTH to survive circular data. * * @param array $content Elementor element tree. * @param array $template_data Full remote template payload. * * @return array */ private function prepare_imported_content( array $content, array $template_data ) { $outer_map = $this->element_id_map; $outer_elements = $this->original_elements; ++$this->import_depth; $this->original_elements = $this->get_elements_by_id( $content ); $content = $this->replace_elements_ids_with_map( $content ); $content = $this->process_export_import_content( $content, 'on_import' ); if ( $this->import_depth <= self::MAX_IMPORT_DEPTH ) { $content = $this->import_widget_area_content( $content, $template_data ); } --$this->import_depth; $this->element_id_map = $outer_map; $this->original_elements = $outer_elements; return $content; } /** * Replace Elementor element IDs while keeping a lookup of old ID to new ID. * * Elementor normally replaces IDs during import. ElementsKit also needs the * old-to-new map so widget-area posts can be recreated under the new widget * IDs that will exist after insertion. * * @param array $content Elementor element tree. * * @return array */ private function replace_elements_ids_with_map( $content ) { $this->element_id_map = array(); return Plugin::$instance->db->iterate_data( $content, function( $element ) { if ( ! empty( $element['id'] ) ) { $old_id = $element['id']; $element['id'] = \Elementor\Utils::generate_random_string(); $this->element_id_map[ $old_id ] = $element['id']; } return apply_filters( 'elementor/document/element/replace_id', $element ); } ); } /** * Flatten an Elementor element tree into an ID-keyed lookup. * * @param array $content Elementor element tree. * * @return array<string,array> */ private function get_elements_by_id( $content ) { $elements = array(); Plugin::$instance->db->iterate_data( $content, function( $element ) use ( &$elements ) { if ( ! empty( $element['id'] ) ) { $elements[ $element['id'] ] = $element; } return $element; } ); return $elements; } /** * Import all supported ElementsKit WIDGETAREA contents in the element tree. * * Supported widgets are defined in get_widget_area_import_config(). Each * matching widget has its hidden `elementskit_content` post copied from the * remote payload/local source and its saved WIDGETAREA value rewritten. * * @param array $content Elementor element tree after normal import. * @param array $template_data Full remote template payload. * * @return array */ private function import_widget_area_content( array $content, array $template_data ) { $config = $this->get_widget_area_import_config(); return Plugin::$instance->db->iterate_data( $content, function( $element ) use ( $template_data, $config ) { if ( empty( $element['id'] ) || empty( $element['widgetType'] ) || empty( $config[ $element['widgetType'] ] ) ) { return $element; } $old_element_id = array_search( $element['id'], $this->element_id_map, true ); if ( ! $old_element_id ) { return $element; } if ( empty( $element['settings'] ) || ! is_array( $element['settings'] ) ) { return $element; } $original_element = isset( $this->original_elements[ $old_element_id ] ) ? $this->original_elements[ $old_element_id ] : array(); foreach ( $config[ $element['widgetType'] ] as $widget_area_config ) { if ( ! empty( $widget_area_config['repeater'] ) ) { $element = $this->import_repeater_widget_area_content( $element, $old_element_id, $widget_area_config, $template_data, $original_element ); } else { $element = $this->import_single_widget_area_content( $element, $old_element_id, $widget_area_config, $template_data, $original_element ); } } return $element; } ); } /** * Import a widget-area field stored directly in a widget's settings. * * Used by widgets like Header Offcanvas, Popup Modal, and Unfold where the * WIDGETAREA control is not inside a repeater. * * @param array $element Imported Elementor widget data. * @param string $old_element_id Original widget ID from the remote payload. * @param array $config Widget-area import config. * @param array $template_data Full remote template payload. * @param array $original_element Original widget data before Elementor import processing. * * @return array */ private function import_single_widget_area_content( array $element, $old_element_id, array $config, array $template_data, array $original_element = array() ) { $field = $config['field']; $original_settings = isset( $original_element['settings'] ) && is_array( $original_element['settings'] ) ? $original_element['settings'] : $element['settings']; $old_value = array_key_exists( $field, $original_settings ) ? $original_settings[ $field ] : ''; $old_keys = $this->get_widget_area_source_keys( $old_value, $old_element_id, isset( $config['source_keys'] ) ? $config['source_keys'] : array() ); $new_key = $this->get_new_widget_area_key( $config, $element['id'] ); $old_indexes = $this->get_widget_area_indexes( $config, $old_element_id, 0 ); $new_indexes = $this->get_widget_area_destination_indexes( $config, $element['id'], 0, array(), $element ); $lookups = array( array( 'keys' => $old_keys, 'indexes' => $old_indexes, ), ); foreach ( $new_indexes as $new_index ) { $this->create_imported_widget_area_post( $lookups, $new_key, $new_index, $template_data ); } $element['settings'][ $field ] = $new_key . '***' . time(); return $element; } /** * Import widget-area fields stored inside repeater items. * * Every repeater item gets a unique saved WIDGETAREA value, even if the * remote JSON omitted the field. Missing values fall back to the original * widget ID, matching Widget_Area_Utils::parse() behavior. * * @param array $element Imported Elementor widget data. * @param string $old_element_id Original widget ID from the remote payload. * @param array $config Widget-area import config. * @param array $template_data Full remote template payload. * @param array $original_element Original widget data before Elementor import processing. * * @return array */ private function import_repeater_widget_area_content( array $element, $old_element_id, array $config, array $template_data, array $original_element = array() ) { $repeater = $config['repeater']; $field = $config['field']; if ( empty( $element['settings'][ $repeater ] ) || ! is_array( $element['settings'][ $repeater ] ) ) { return $element; } $original_items = isset( $original_element['settings'][ $repeater ] ) && is_array( $original_element['settings'][ $repeater ] ) ? $original_element['settings'][ $repeater ] : $element['settings'][ $repeater ]; // Older versions saved the value on only one item, so an item's content can // sit under a sibling's key while its own value is empty. $sibling_keys = array(); foreach ( $original_items as $original_item ) { if ( is_array( $original_item ) && ! empty( $original_item[ $field ] ) ) { $sibling_keys[] = $this->extract_widget_area_key( $original_item[ $field ], $old_element_id ); } } foreach ( $element['settings'][ $repeater ] as $index => $item ) { if ( ! is_array( $item ) ) { continue; } $original_item = isset( $original_items[ $index ] ) && is_array( $original_items[ $index ] ) ? $original_items[ $index ] : $item; $old_value = array_key_exists( $field, $original_item ) ? $original_item[ $field ] : ''; $own_key = $this->extract_widget_area_key( $old_value, $old_element_id ); $new_key = $this->get_new_widget_area_key( $config, $element['id'] ); $old_indexes = $this->get_widget_area_indexes( $config, $old_element_id, $index, $original_item ); $new_indexes = $this->get_widget_area_destination_indexes( $config, $element['id'], $index, $item, $element ); // A sibling's key is matched by what identifies this item, never by a plain // position: posts of deleted items stay behind and would land on another item. $other_indexes = array_merge( $this->get_widget_area_destination_indexes( $config, $old_element_id, $index, $original_item, $element ), $this->get_widget_area_indexes_from_types( array( 'repeater_id' ), $config, $old_element_id, $index, $original_item ) ); $lookups = array( array( 'keys' => array( $own_key ), 'indexes' => $old_indexes, ), array( 'keys' => array_diff( $this->get_widget_area_source_keys( $old_value, $old_element_id, $sibling_keys ), array( $own_key ) ), 'indexes' => array_unique( $other_indexes ), ), ); foreach ( $new_indexes as $new_index ) { $this->create_imported_widget_area_post( $lookups, $new_key, $new_index, $template_data ); } $primary_new_index = reset( $new_indexes ); $element['settings'][ $repeater ][ $index ][ $field ] = $primary_new_index ? $new_key . '***' . $primary_new_index . '***' . time() : $new_key . '***' . time(); } return $element; } /** * Resolve the key that should be saved in a WIDGETAREA control after import. * * Most widgets use their new Elementor widget ID as the key. The config can * override this for widgets that intentionally use a literal key. * * @param array $config Widget-area import config. * @param string $element_id Imported Elementor widget ID. * * @return string */ private function get_new_widget_area_key( array $config, $element_id ) { if ( isset( $config['new_key'] ) ) { return $config['new_key']; } return $element_id; } /** * Build the destination indexes used for newly-created local hidden posts. * * Source lookup can try several legacy indexes, but the importer should * create only one local post per widget-area item. The destination index is * therefore based on the widget's active render path. * * @param array $config Widget-area import config. * @param string $element_id Imported Elementor widget ID. * @param int $index Zero-based repeater position. * @param array $item Repeater item data. * @param array $element Imported Elementor widget data. * * @return array<int,string|int> */ private function get_widget_area_destination_indexes( array $config, $element_id, $index, array $item, array $element ) { $index_types = isset( $config['destination_indexes'] ) ? $config['destination_indexes'] : $config['indexes']; if ( ! empty( $config['destination_indexes_by_setting'] ) && ! empty( $element['settings'] ) ) { $setting_name = $config['destination_indexes_by_setting']['setting']; $setting_value = isset( $element['settings'][ $setting_name ] ) ? $element['settings'][ $setting_name ] : ''; $value_indexes = isset( $config['destination_indexes_by_setting']['values'][ $setting_value ] ) ? $config['destination_indexes_by_setting']['values'][ $setting_value ] : array(); $index_types = ! empty( $value_indexes ) ? $value_indexes : $config['destination_indexes_by_setting']['default']; } return $this->get_widget_area_indexes_from_types( $index_types, $config, $element_id, $index, $item ); } /** * Build the widget-area indexes used in hidden post titles. * * Hidden posts are titled `dynamic-content-widget-{key}-{index}`. The index * can be fixed, the widget ID, a repeater item ID, or a numeric repeater * position depending on the widget render code. * * @param array $config Widget-area import config. * @param string $element_id Widget ID to use when requested by config. * @param int $index Zero-based repeater position. * @param array $item Repeater item data. * * @return array<int,string|int> */ private function get_widget_area_indexes( array $config, $element_id, $index, array $item = array() ) { return $this->get_widget_area_indexes_from_types( $config['indexes'], $config, $element_id, $index, $item ); } /** * Convert index type names to concrete widget-area post title indexes. * * @param array $index_types Index type names from config. * @param array $config Widget-area import config. * @param string $element_id Widget ID to use when requested by config. * @param int $index Zero-based repeater position. * @param array $item Repeater item data. * * @return array<int,string|int> */ private function get_widget_area_indexes_from_types( array $index_types, array $config, $element_id, $index, array $item = array() ) { $indexes = array(); foreach ( $index_types as $index_type ) { if ( 'fixed' === $index_type && isset( $config['index'] ) ) { $indexes[] = $config['index']; } elseif ( 'element_id' === $index_type ) { $indexes[] = $element_id; } elseif ( 'repeater_id' === $index_type ) { $indexes[] = ! empty( $item['_id'] ) ? $item['_id'] : absint( $index ) + 1; } elseif ( 'position' === $index_type ) { $indexes[] = absint( $index ) + 1; } } $indexes = array_filter( array_unique( $indexes ) ); return $indexes; } /** * Describe every widget-area field the layout importer knows how to restore. * * The config mirrors each widget's Widget_Area_Utils::parse() call. Keeping * this list aligned with widget render code is what lets remote * `elementskit_content` posts be matched and recreated correctly. * * Sources may be looked up by position, but repeater content must not be created by * position: parse() falls back to it, so an item added later would show this content. * * @return array<string,array<int,array>> */ private function get_widget_area_import_config() { return array( 'elementskit-header-offcanvas' => array( array( 'field' => 'ekit_offcanvas_content', 'indexes' => array( 'fixed' ), 'index' => 99, ), ), 'elementskit-unfold' => array( array( 'field' => 'unfold_widget_content', 'indexes' => array( 'fixed' ), 'index' => 99, ), ), 'elementskit-popup-modal' => array( array( 'field' => 'popup_widget_content', // Popups saved before the "{widget id}-99" format use "popup-{widget id}". 'indexes' => array( 'fixed', 'element_id' ), 'source_keys' => array( 'popup' ), // "element_id" keeps the content readable by older ElementsKit Pro versions. 'destination_indexes' => array( 'fixed', 'element_id' ), 'index' => 99, ), ), 'elementskit-advance-accordion' => array( array( 'repeater' => 'ekit_accordion_items', 'field' => 'acc_content', 'indexes' => array( 'repeater_id', 'position' ), 'destination_indexes' => array( 'repeater_id' ), ), ), 'elementskit-advanced-slider' => array( array( 'repeater' => 'ekit_slider_tab_items', 'field' => 'ekit_slider_tab_content', 'indexes' => array( 'repeater_id', 'position' ), 'destination_indexes' => array( 'repeater_id' ), ), ), 'elementskit-tab' => array( array( 'repeater' => 'ekit_tab_items', 'field' => 'ekit_tab_content', 'indexes' => array( 'repeater_id', 'position' ), 'destination_indexes' => array( 'repeater_id' ), ), ), 'elementskit-advanced-toggle' => array( array( 'repeater' => 'ekit_toggle_items', 'field' => 'ekit_toggle_content', 'indexes' => array( 'repeater_id', 'position' ), 'destination_indexes_by_setting' => array( 'setting' => 'ekit_advanced_toggle_style', 'values' => array( 'switch-style' => array( 'position' ), ), 'default' => array( 'repeater_id' ), ), ), ), ); } /** * Extract the stored widget-area key from a control value. * * Values are saved as `{key}***{timestamp}`. Empty values mean the widget * should fall back to its widget ID, which is how the control behaved before * content was edited. * * @param mixed $value Saved WIDGETAREA control value. * @param string $fallback Key to use when the control value is empty. * * @return string */ private function extract_widget_area_key( $value, $fallback ) { if ( '' === $value || null === $value ) { return $fallback; } $value = explode( '***', (string) $value ); return sanitize_key( $value[0] ); } /** * Build all possible source keys for a widget-area control. * * Saved WIDGETAREA values can point to an older widget key, while untouched * items render from the widget ID fallback. Trying both keeps imports aligned * with Widget_Area_Utils::parse() and tolerant of exporter differences. * * @param mixed $value Saved WIDGETAREA control value. * @param string $fallback Key used by the widget render fallback. * @param array $sibling_keys Keys saved on the other items of the same repeater. * * @return array<int,string> */ private function get_widget_area_source_keys( $value, $fallback, array $sibling_keys = array() ) { $keys = array_merge( array( $this->extract_widget_area_key( $value, $fallback ), $fallback, ), $sibling_keys ); return array_values( array_filter( array_unique( array_map( 'sanitize_key', $keys ) ) ) ); } /** * Create a local `elementskit_content` post for an imported widget area. * * The method first finds source Elementor data from the remote payload or an * existing local post, then creates the destination post under the new * imported widget key/index. * * @param array $source_lookups Lookups to try in order, each with `keys` and `indexes`. * @param string $new_key Destination widget-area key for local data. * @param string $new_widget_area_id Destination index for the new hidden post. * @param array $template_data Full remote template payload. * * @return void */ private function create_imported_widget_area_post( array $source_lookups, $new_key, $new_widget_area_id, array $template_data ) { if ( ! is_user_logged_in() ) { wp_die( esc_html__( 'You must be logged in.', 'elementskit-lite' ), 401 ); } if ( ! current_user_can( 'edit_posts' ) ) { wp_die( esc_html__( 'You are not allowed to access this page.', 'elementskit-lite' ), 403 ); } $destination_title = 'dynamic-content-widget-' . $new_key . '-' . $new_widget_area_id; if ( \ElementsKit_Lite\Utils::get_page_by_slug( $destination_title, 'elementskit_content', 'any' ) ) { return; } $source_data = $this->get_widget_area_source_data( $source_lookups, $template_data ); if ( empty( $source_data['elementor_data'] ) ) { return; } $builder_post_id = wp_insert_post( array( 'post_content' => isset( $source_data['post_content'] ) ? $source_data['post_content'] : '', 'post_title' => $destination_title, 'post_name' => sanitize_title( $destination_title ), 'post_status' => current_user_can( 'publish_posts' ) ? 'publish' : 'pending', 'post_type' => 'elementskit_content', 'post_author' => get_current_user_id(), ) ); if ( is_wp_error( $builder_post_id ) ) { return; } update_post_meta( $builder_post_id, '_wp_page_template', 'elementor_canvas' ); update_post_meta( $builder_post_id, '_elementor_edit_mode', 'builder' ); update_post_meta( $builder_post_id, '_elementor_template_type', 'wp-post' ); update_post_meta( $builder_post_id, '_elementor_version', defined( 'ELEMENTOR_VERSION' ) ? ELEMENTOR_VERSION : '' ); update_post_meta( $builder_post_id, '_elementor_data', wp_slash( wp_json_encode( $source_data['elementor_data'] ) ) ); } /** * Find and prepare source Elementor data for a widget area. * * The remote payload is checked first, then a local post of the same name. * * @param array $source_lookups Lookups to try in order, see create_imported_widget_area_post(). * @param array $template_data Full remote template payload. * * @return array{elementor_data?:array,post_content?:string} */ private function get_widget_area_source_data( array $source_lookups, array $template_data ) { $remote_posts = isset( $template_data['elementskit_content'] ) && is_array( $template_data['elementskit_content'] ) ? $template_data['elementskit_content'] : array(); foreach ( $source_lookups as $lookup ) { foreach ( $lookup['keys'] as $old_key ) { foreach ( $lookup['indexes'] as $widget_area_id ) { $source_title = 'dynamic-content-widget-' . $old_key . '-' . $widget_area_id; if ( isset( $remote_posts[ $source_title ]['content'] ) && $this->is_element_tree( $remote_posts[ $source_title ]['content'] ) ) { return array( 'elementor_data' => $this->prepare_imported_content( $remote_posts[ $source_title ]['content'], $template_data ), 'post_content' => '', ); } $source_post = \ElementsKit_Lite\Utils::get_page_by_slug( $source_title, 'elementskit_content' ); if ( ! $source_post ) { continue; } $elementor_data = json_decode( (string) get_post_meta( $source_post->ID, '_elementor_data', true ), true ); if ( $this->is_element_tree( $elementor_data ) ) { return array( 'elementor_data' => $this->prepare_imported_content( $elementor_data, $template_data ), 'post_content' => $source_post->post_content, ); } } } } return array(); } /** * Whether a value is a non-empty list of Elementor elements. Anything else would be * stored as the post's content and break every later render of it. * * @param mixed $data Candidate element tree. * * @return bool */ private function is_element_tree( $data ) { if ( ! is_array( $data ) || empty( $data ) ) { return false; } foreach ( $data as $element ) { if ( ! is_array( $element ) || empty( $element['elType'] ) ) { return false; } } return true; } }
Save File
Cancel