← Back
Editing: widget-area-values.php
<?php namespace ElementsKit_Lite\Compatibility\Data_Migration; defined( 'ABSPATH' ) || exit; /** * Fills empty Widget Area values saved in Elementor documents. * * Until 4.2.0 editing a Widget Area wrote its value to only one repeater item, so * the others stayed empty. An empty value makes the widget look up its content by * its own ID, and once the widget is copied or imported that ID changes while the * content is still stored under the key of the original widget. The item then * renders blank, and the layout importer skips it, although the content exists. * * This points every item at the content it really has and leaves no value empty. * * It runs from a stored version flag rather than `upgrader_process_complete`. That * hook fires with the old plugin code still loaded, so it can never run code that * the same update delivers, and it does not fire for manual (FTP) updates at all. * * When it runs: once per site, after updating from 4.2.0 or earlier to the version that * ships this file, and once on a fresh install. Never again after it finishes, unless * MIN_VERSION is raised. * * TODO: Remove this class 2-3 releases (about 6 months) after the version that ships it, * once 80-90% of sites run that version or later. Check the version share at * https://api.wordpress.org/stats/plugin/1.0/elementskit-lite * * Removing it is safe: a site that never ran it keeps its old empty values, which render * the way they always did, and nothing else depends on this class. To remove it: * 1. Delete this file. * 2. Delete `new Compatibility\Data_Migration\Widget_Area_Values();` from plugin.php, * or every page load fails with a fatal error. * 3. Optionally clean up, for example on plugin update: * delete_option( 'ekit_widget_area_values_migration' ); * wp_clear_scheduled_hook( 'ekit_widget_area_values_migration_batch' ); * * Keep the sibling key lookup in modules/layout-manager/library-source.php and in the * layout API's layouts.php: layouts on the library server can still hold empty values. * * @since 4.3.0 */ class Widget_Area_Values { /** * A run recorded by this plugin version or later counts, so the migration runs once * rather than on every release. Must not be above the current plugin version, because * a finished run records that version and would otherwise never count as finished. * Raise it, along with the plugin version, to run the migration again. */ const MIN_VERSION = '4.1.0'; const OPTION ='ekit_widget_area_values_migration'; const CRON_HOOK = 'ekit_widget_area_values_migration_batch'; const LOCK = 'ekit_widget_area_values_migration_lock'; const BATCH_SIZE = 50; /** * Seconds a queued batch may wait before an admin page runs it instead of WP-Cron. */ const CRON_GRACE = 300; const SLUG_PREFIX = 'dynamic-content-widget-'; /** * Widgets that keep Widget Areas in a repeater, one area per item. */ const REPEATER_WIDGETS = array( 'elementskit-tab' => array( 'repeater' => 'ekit_tab_items', 'field' => 'ekit_tab_content', ), 'elementskit-advance-accordion' => array( 'repeater' => 'ekit_accordion_items', 'field' => 'acc_content', ), 'elementskit-advanced-slider' => array( 'repeater' => 'ekit_slider_tab_items', 'field' => 'ekit_slider_tab_content', ), 'elementskit-advanced-toggle' => array( 'repeater' => 'ekit_toggle_items', 'field' => 'ekit_toggle_content', ), ); /** * Widgets that keep a single Widget Area in a top-level control. */ const SINGLE_WIDGETS = array( 'elementskit-header-offcanvas' => 'ekit_offcanvas_content', 'elementskit-unfold' => 'unfold_widget_content', 'elementskit-popup-modal' => 'popup_widget_content', ); public function __construct() { add_action( 'init', array( $this, 'maybe_schedule' ) ); add_action( self::CRON_HOOK, array( $this, 'run_batch' ) ); // Keeps the migration moving on sites where WP-Cron does not run. add_action( 'admin_init', array( $this, 'run_overdue_batch' ) ); } /** * Run a batch from an admin page, only when WP-Cron has not picked it up in time. * * Admin pages must not normally wait for the migration. admin_init also fires for * admin-ajax, which includes the Elementor editor saving a document a batch could be * rewriting, so that is left out as well. * * @return void */ public function run_overdue_batch() { if ( wp_doing_ajax() ) { return; } $next = wp_next_scheduled( self::CRON_HOOK ); if ( $next && $next < time() - self::CRON_GRACE ) { $this->run_batch(); } } /** * Queue the next batch while the migration is unfinished. * * @return void */ public function maybe_schedule() { if ( $this->is_complete() || wp_next_scheduled( self::CRON_HOOK ) ) { return; } wp_schedule_single_event( time(), self::CRON_HOOK ); } /** * Migrate one batch of documents. * * @return void */ public function run_batch() { if ( $this->is_complete() || get_transient( self::LOCK ) ) { return; } set_transient( self::LOCK, 1, MINUTE_IN_SECONDS ); $state = $this->get_state(); $cursor = isset( $state['cursor'] ) ? absint( $state['cursor'] ) : 0; $ids = $this->get_document_ids( $cursor ); if ( empty( $ids ) ) { update_option( self::OPTION, array( 'version' => \ElementsKit_Lite::version(), 'complete' => true ), true ); delete_transient( self::LOCK ); return; } $slugs = $this->get_content_slugs(); foreach ( $ids as $id ) { $this->migrate_document( (int) $id, $slugs ); $cursor = (int) $id; } update_option( self::OPTION, array( 'version' => \ElementsKit_Lite::version(), 'cursor' => $cursor ), true ); delete_transient( self::LOCK ); if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { wp_schedule_single_event( time(), self::CRON_HOOK ); } } /** * Fill the Widget Area values of an element tree. * * @param array $elements Elementor element tree. * @param array $slugs Published content slugs, as slug => true. * @param int $time Timestamp stored in rewritten values. * @return array { 0: array migrated tree, 1: bool whether anything changed } */ public static function migrate_elements( array $elements, array $slugs, $time ) { $changed = false; foreach ( $elements as $position => $element ) { if ( ! is_array( $element ) ) { continue; } $type = isset( $element['widgetType'] ) ? $element['widgetType'] : ''; if ( ! empty( $element['id'] ) && isset( self::REPEATER_WIDGETS[ $type ] ) ) { $changed = self::migrate_repeater( $element, $slugs, $time ) || $changed; } elseif ( ! empty( $element['id'] ) && isset( self::SINGLE_WIDGETS[ $type ] ) ) { $changed = self::migrate_single( $element, $slugs, $time ) || $changed; } if ( ! empty( $element['elements'] ) && is_array( $element['elements'] ) ) { list( $element['elements'], $children_changed ) = self::migrate_elements( $element['elements'], $slugs, $time ); $changed = $children_changed || $changed; } $elements[ $position ] = $element; } return array( $elements, $changed ); } /** * Fill the values of a repeater widget, mirroring its Widget_Area_Utils::parse() lookups. * * @param array $element Elementor widget data, updated in place. * @param array $slugs Published content slugs, as slug => true. * @param int $time Timestamp stored in rewritten values. * @return bool Whether anything changed. */ private static function migrate_repeater( array &$element, array $slugs, $time ) { $config = self::REPEATER_WIDGETS[ $element['widgetType'] ]; $repeater = $config['repeater']; $field = $config['field']; if ( empty( $element['settings'][ $repeater ] ) || ! is_array( $element['settings'][ $repeater ] ) ) { return false; } $widget_id = (string) $element['id']; $keys = array( $widget_id ); foreach ( $element['settings'][ $repeater ] as $item ) { $key = is_array( $item ) && isset( $item[ $field ] ) ? self::get_value_key( $item[ $field ] ) : ''; if ( '' !== $key ) { $keys[] = $key; } } $keys = array_values( array_unique( $keys ) ); // The switch style of Advanced Toggle looks up by position first. $position_first = 'elementskit-advanced-toggle' === $element['widgetType'] && isset( $element['settings']['ekit_advanced_toggle_style'] ) && 'switch-style' === $element['settings']['ekit_advanced_toggle_style']; $changed = false; $number = 0; foreach ( $element['settings'][ $repeater ] as $index => $item ) { if ( ! is_array( $item ) ) { continue; } ++$number; $lookups = array(); if ( ! empty( $item['_id'] ) ) { $lookups[] = (string) $item['_id']; } if ( $position_first ) { array_unshift( $lookups, (string) $number ); } else { $lookups[] = (string) $number; } $value = isset( $item[ $field ] ) ? (string) $item[ $field ] : ''; $value_key = self::get_value_key( $value ); $own_key = '' !== $value_key ? $value_key : $widget_id; // What the item shows today is correct, whatever else may match. This is the // same lookup parse() does, so a migrated item keeps showing the same post. if ( self::has_content( $own_key, $lookups, $slugs ) ) { if ( '' !== $value_key ) { continue; } $element['settings'][ $repeater ][ $index ][ $field ] = $own_key . '***' . $time; $changed = true; continue; } // Another key must match what identifies this item, never a plain position: // posts of deleted items stay behind and would land on the wrong item. $other_lookups = $position_first || empty( $item['_id'] ) ? $lookups : array( (string) $item['_id'] ); $new_key = self::find_content_key( array_diff( $keys, array( $own_key ) ), $other_lookups, $slugs ); if ( null === $new_key ) { // Without content an existing value is harmless, so only fill an empty one. if ( '' !== $value_key ) { continue; } $new_key = $widget_id; } $element['settings'][ $repeater ][ $index ][ $field ] = $new_key . '***' . $time; $changed = true; } return $changed; } /** * Fill the value of a widget with a single Widget Area. * * @param array $element Elementor widget data, updated in place. * @param array $slugs Published content slugs, as slug => true. * @param int $time Timestamp stored in rewritten values. * @return bool Whether anything changed. */ private static function migrate_single( array &$element, array $slugs, $time ) { $field = self::SINGLE_WIDGETS[ $element['widgetType'] ]; $widget_id = (string) $element['id']; $value = isset( $element['settings'][ $field ] ) ? (string) $element['settings'][ $field ] : ''; if ( '' !== self::get_value_key( $value ) ) { return false; } $new_key = $widget_id; // Popup Modal stored its content as "popup-{widget id}" before moving to "{widget id}-99", // and an empty value with that post still shows it, on old and new Pro alike. if ( 'elementskit-popup-modal' === $element['widgetType'] && isset( $slugs[ self::get_slug( 'popup', $widget_id ) ] ) ) { $new_key = 'popup'; } if ( ! isset( $element['settings'] ) || ! is_array( $element['settings'] ) ) { $element['settings'] = array(); } $element['settings'][ $field ] = $new_key . '***' . $time; return true; } /** * Find the first key that has content, trying the lookups in order. * * @param array $keys Candidate keys, in priority order. * @param array $lookups Index suffixes, in priority order. * @param array $slugs Published content slugs, as slug => true. * @return string|null */ private static function find_content_key( array $keys, array $lookups, array $slugs ) { foreach ( $lookups as $lookup ) { foreach ( $keys as $key ) { if ( isset( $slugs[ self::get_slug( $key, $lookup ) ] ) ) { return $key; } } } return null; } private static function has_content( $key, array $lookups, array $slugs ) { return null !== self::find_content_key( array( $key ), $lookups, $slugs ); } private static function get_slug( $key, $lookup ) { return strtolower( self::SLUG_PREFIX . $key . '-' . $lookup ); } private static function get_value_key( $value ) { if ( ! is_string( $value ) ) { return ''; } $parts = explode( '***', $value ); return trim( $parts[0] ); } private function is_complete() { $state = $this->get_state(); return ! empty( $state['complete'] ); } /** * Get the stored state, ignoring anything stored by a version older than MIN_VERSION. * * @return array */ private function get_state() { $state = get_option( self::OPTION, array() ); if ( ! is_array( $state ) || ! isset( $state['version'] ) || version_compare( $state['version'], self::MIN_VERSION, '<' ) ) { return array(); } return $state; } /** * Get the next Elementor documents. Revisions keep their history. * * Searching the JSON here would read every document on each batch, which is slow on a * site with many of them, so this only pages through IDs. migrate_document() skips * documents without a Widget Area. * * @param int $cursor Last processed post ID. * @return array */ private function get_document_ids( $cursor ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery return $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID AND pm.meta_key = '_elementor_data' WHERE p.ID > %d AND p.post_type <> 'revision' ORDER BY p.ID ASC LIMIT %d", $cursor, self::BATCH_SIZE ) ); } /** * Whether raw Elementor JSON may hold a widget with a Widget Area. * * @param string $raw Raw `_elementor_data` value. * @return bool */ private function has_widget_area_widget( $raw ) { foreach ( array_merge( array_keys( self::REPEATER_WIDGETS ), array_keys( self::SINGLE_WIDGETS ) ) as $type ) { if ( false !== strpos( $raw, '"widgetType":"' . $type . '"' ) ) { return true; } } return false; } /** * Get the slugs of published Widget Area content, which is what parse() can render. * * @return array slug => true */ private function get_content_slugs() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $slugs = $wpdb->get_col( $wpdb->prepare( "SELECT post_name FROM {$wpdb->posts} WHERE post_type = %s AND post_status = %s", 'elementskit_content', 'publish' ) ); return array_fill_keys( array_map( 'strtolower', $slugs ), true ); } /** * Migrate and save one document. Documents that need no change are never rewritten. * * @param int $id Post ID. * @param array $slugs Published content slugs, as slug => true. * @return void */ private function migrate_document( $id, array $slugs ) { $raw = get_post_meta( $id, '_elementor_data', true ); if ( ! is_string( $raw ) || ! $this->has_widget_area_widget( $raw ) ) { return; } $elements = json_decode( $raw, true ); if ( ! is_array( $elements ) ) { return; } list( $elements, $changed ) = self::migrate_elements( $elements, $slugs, time() ); if ( ! $changed ) { return; } $json = wp_json_encode( $elements ); if ( false === $json ) { return; } // update_post_meta() unslashes its value and would otherwise break the JSON escapes. update_metadata( 'post', $id, '_elementor_data', wp_slash( $json ) ); // Drop Elementor's cached widget output so the new values take effect. delete_post_meta( $id, '_elementor_element_cache' ); } }
Save File
Cancel