plugin = $plugin;
}
public function register() {
add_action( 'admin_init', array( $this, 'redirect_retired_recipes' ), 1 );
add_action( 'admin_menu', array( $this, 'add_menu' ), 30 );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'admin_init', array( $this, 'backfill_installed_previews' ), 50 );
add_filter( 'wp_get_attachment_url', array( $this, 'preview_attachment_url' ), 10, 2 );
add_action( 'admin_post_divi_powers_download_design_pack', array( $this, 'download_pack' ) );
add_action( 'admin_post_divi_powers_install_design_asset', array( $this, 'install_asset' ) );
add_action( 'admin_post_divi_powers_install_design_collection', array( $this, 'install_collection' ) );
add_action( 'admin_post_divi_powers_refresh_cloud_catalog', array( $this, 'refresh_cloud_catalog' ) );
add_action( 'admin_post_divi_powers_test_cloud_catalog', array( $this, 'test_cloud_catalog' ) );
add_action( 'admin_post_divi_powers_update_design_assets', array( $this, 'update_design_assets' ) );
add_action( 'admin_post_divi_powers_install_all_design_assets', array( $this, 'install_all_design_assets' ) );
add_action( 'wp_ajax_divi_powers_builder_design_catalog', array( $this, 'ajax_builder_catalog' ) );
add_action( 'wp_ajax_divi_powers_builder_install_design', array( $this, 'ajax_builder_install' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'render_builder_library_config' ), 5 );
add_filter( 'divi_powers_dashboard_cards', array( $this, 'dashboard_card' ), 20 );
add_filter( 'upload_mimes', array( $this, 'allow_divi_json_mime' ), 10, 2 );
add_filter( 'wp_check_filetype_and_ext', array( $this, 'recognize_divi_json_export' ), 10, 5 );
}
/** Keep old bookmarks useful without restoring the retired Recipes screen. */
public function redirect_retired_recipes() {
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( 'divi-powers-recipes' !== $page || ! current_user_can( 'edit_theme_options' ) ) {
return;
}
wp_safe_redirect( admin_url( 'admin.php?page=divi-powers-design-library&dp_library_message=recipes_moved' ) );
exit;
}
/** Give the Visual Builder app window a small authenticated cloud-library endpoint. */
public function render_builder_library_config() {
if (
! current_user_can( 'edit_theme_options' )
|| ! $this->plugin->is_power_enabled( 'design_library' )
|| ! function_exists( 'et_core_is_fb_enabled' )
|| ! et_core_is_fb_enabled()
) {
return;
}
$config = array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'divi_powers_builder_library' ),
);
wp_register_script( 'fivedp-library-config', false, array(), DIVI_POWERS_VERSION, false );
wp_enqueue_script( 'fivedp-library-config' );
wp_add_inline_script( 'fivedp-library-config', 'window.diviPowersDesignLibrary=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';' );
}
/** Return the visual cloud catalog used by the Divi modal component. */
public function ajax_builder_catalog() {
if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to browse this library.', '5d-powers-for-divi' ) ), 403 ); }
check_ajax_referer( 'divi_powers_builder_library', 'nonce' );
$items = array();
foreach ( $this->assets() as $asset ) {
$post = $this->installed_post( $asset['id'] );
$installed_version = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
$preview_url = $this->asset_preview_url( $asset );
$full_preview_url = $this->asset_preview_url( $asset, true );
$items[] = array(
'id' => $asset['id'],
'title' => $asset['title'],
'description' => $asset['description'],
'type' => $asset['type'],
'category' => $asset['category_label'],
'preview' => $preview_url,
'fullPreview' => $full_preview_url ?: $preview_url,
'edition' => strtoupper( $asset['edition'] ),
'version' => $asset['version'],
'installed' => (bool) $post,
'outdated' => $installed_version && version_compare( $installed_version, $asset['version'], '<' ),
'accessible' => $this->can_access_asset( $asset ),
'installable' => (bool) $asset['installable'],
'setup' => $asset['setup'],
'setupActions' => array_map(
static function ( $action ) {
return array( 'label' => $action['label'], 'url' => admin_url( 'admin.php?page=' . $action['page'] ) );
},
$asset['setup_actions']
),
'search' => strtolower( $asset['title'] . ' ' . $asset['description'] . ' ' . implode( ' ', $asset['tags'] ) ),
);
}
$collections = array();
foreach ( $this->collections() as $collection ) {
$collections[] = array(
'id' => $collection['id'],
'title' => $collection['title'],
'assetIds' => array_values( $collection['asset_ids'] ),
'accessible' => true,
);
}
wp_send_json_success( array( 'items' => $items, 'collections' => $collections ) );
}
/** Install one design, a collection, a visible type, or the complete catalog from Divi. */
public function ajax_builder_install() {
if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to add designs.', '5d-powers-for-divi' ) ), 403 ); }
check_ajax_referer( 'divi_powers_builder_library', 'nonce' );
$asset_id = isset( $_POST['asset'] ) ? sanitize_text_field( wp_unslash( $_POST['asset'] ) ) : '';
$collection_id = isset( $_POST['collection'] ) ? sanitize_key( wp_unslash( $_POST['collection'] ) ) : '';
$type = isset( $_POST['type'] ) ? sanitize_key( wp_unslash( $_POST['type'] ) ) : '';
$all = ! empty( $_POST['all'] );
$targets = array();
if ( $asset_id ) {
$asset = $this->asset( $asset_id );
if ( $asset ) { $targets[] = $asset; }
} elseif ( $collection_id ) {
$collection = $this->collection( $collection_id );
foreach ( is_array( $collection['asset_ids'] ?? null ) ? $collection['asset_ids'] : array() as $id ) { $asset = $this->asset( $id ); if ( $asset ) { $targets[] = $asset; } }
} elseif ( $type || $all ) {
foreach ( $this->assets() as $asset ) { if ( $all || $type === $asset['type'] ) { $targets[] = $asset; } }
}
if ( ! $targets ) { wp_send_json_error( array( 'message' => __( 'That design is unavailable.', '5d-powers-for-divi' ) ), 404 ); }
$installed = 0;
$updated = 0;
$ids = array();
foreach ( $targets as $asset ) {
if ( empty( $asset['installable'] ) || ! $this->can_access_asset( $asset ) ) { continue; }
$post = $this->installed_post( $asset['id'] );
$version = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
if ( $version && ! version_compare( $version, $asset['version'], '<' ) ) { $ids[] = $asset['id']; continue; }
$result = $this->upsert_asset( $asset );
if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ), 400 ); }
$ids[] = $asset['id'];
if ( $result['updated'] ) { $updated++; } else { $installed++; }
}
$response = array( 'ids' => $ids, 'installed' => $installed, 'updated' => $updated );
if ( $asset_id && 1 === count( $targets ) ) {
$post = $this->installed_post( $targets[0]['id'] );
if ( $post ) {
$content_errors = Divi_Powers_Native_Layouts::executable_content_errors( (string) $post->post_content );
if ( ! empty( $content_errors ) ) {
wp_send_json_error( array( 'message' => implode( ' ', $content_errors ) ), 400 );
}
$response['design'] = array(
'id' => $targets[0]['id'],
'title' => $targets[0]['title'],
'type' => $targets[0]['type'],
'content' => $this->remap_power_ids( (string) $post->post_content ),
);
}
}
wp_send_json_success( $response );
}
/** Add bundled thumbnails to managed masters installed before previews shipped. */
public function backfill_installed_previews() {
if (
! current_user_can( 'edit_theme_options' )
|| ! $this->plugin->is_power_enabled( 'design_library' )
|| DIVI_POWERS_VERSION === get_option( self::PREVIEW_VERSION_OPTION, '' )
) {
return;
}
$this->ensure_divi_library_types();
$failures = array();
foreach ( $this->assets() as $asset ) {
$post = $this->installed_post( $asset['id'] );
if ( $post ) {
$result = $this->attach_preview( $post->ID, $asset );
if ( is_wp_error( $result ) ) {
$failures[ $asset['id'] ] = array(
'code' => $result->get_error_code(),
'message' => $result->get_error_message(),
);
}
}
}
if ( $failures ) {
update_option(
self::PREVIEW_ERROR_OPTION,
array(
'version' => DIVI_POWERS_VERSION,
'assets' => $failures,
),
false
);
return;
}
delete_option( self::PREVIEW_ERROR_OPTION );
update_option( self::PREVIEW_VERSION_OPTION, DIVI_POWERS_VERSION, false );
}
/**
* Resolve managed preview attachments from the plugin bundle.
*
* These attachments deliberately reference immutable bundled images instead
* of copying 36 duplicate files into uploads on every Divi Powers site.
*
* @param string|false $url WordPress attachment URL.
* @param int $attachment_id Attachment ID.
* @return string|false
*/
public function preview_attachment_url( $url, $attachment_id ) {
$asset_id = (string) get_post_meta( $attachment_id, self::PREVIEW_ASSET_META, true );
if ( '' === $asset_id ) {
return $url;
}
$local = apply_filters( 'divi_powers_design_library_local_preview', '', $asset_id );
if ( $local ) { return esc_url_raw( $local ); }
$cloud_url = esc_url_raw( (string) get_post_meta( $attachment_id, self::PREVIEW_URL_META, true ) );
if ( $cloud_url && $this->plugin->is_power_enabled( 'cloud_catalog' ) ) {
return $cloud_url;
}
$preview_name = $this->preview_filename( $asset_id );
return DIVI_POWERS_URL . 'assets/design-library/previews/' . rawurlencode( $preview_name );
}
/**
* Let authorized site designers select Divi's native JSON export files.
*
* The stricter content validation happens in recognize_divi_json_export().
*
* @param array $mimes Allowed MIME types.
* @return array
*/
public function allow_divi_json_mime( $mimes ) {
if ( current_user_can( 'edit_theme_options' ) ) {
$mimes['json'] = 'application/json|text/plain';
}
return $mimes;
}
/**
* Correct MIME sniffing for a genuine Divi JSON export.
*
* Divi page exports can be detected as text/html because their JSON data
* contains block markup and Code module content. Only JSON files with Divi's
* own export context are corrected, and only for authorized site designers.
*
* @param array $check WordPress file type result.
* @param string $file Temporary file path.
* @param string $filename Original filename.
* @param string[] $mimes Allowed MIME types.
* @param string|bool $real_mime Detected MIME type.
* @return array
*/
public function recognize_divi_json_export( $check, $file, $filename, $mimes, $real_mime ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
if (
! current_user_can( 'edit_theme_options' ) ||
'json' !== strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ) ||
! is_readable( $file ) ||
filesize( $file ) > 20 * MB_IN_BYTES
) {
return $check;
}
$contents = file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$export = is_string( $contents ) ? json_decode( $contents, true ) : null;
if (
! is_array( $export ) ||
'et_builder' !== ( $export['context'] ?? '' ) ||
( ! isset( $export['data'] ) && ! isset( $export['presets'] ) && ! isset( $export['global_variables'] ) )
) {
return $check;
}
return array(
'ext' => 'json',
'type' => 'application/json',
'proper_filename' => false,
);
}
public function add_menu() {
if ( ! $this->plugin->is_power_enabled( 'design_library' ) ) {
return;
}
add_submenu_page(
'divi-powers',
__( 'Design Library', '5d-powers-for-divi' ),
__( 'Design Library', '5d-powers-for-divi' ),
'edit_theme_options',
'divi-powers-design-library',
array( $this, 'render_page' )
);
}
public function enqueue_assets() {
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( 'divi-powers-design-library' !== $page ) {
return;
}
wp_enqueue_style(
'divi-powers-design-library',
DIVI_POWERS_URL . 'assets/css/design-library.css',
array( 'divi-powers-admin' ),
DIVI_POWERS_VERSION
);
wp_add_inline_style( 'divi-powers-design-library', '.dp-component-card.is-locked .dp-component-card__preview{position:relative;filter:saturate(.55)}.dp-component-card.is-locked .dp-component-card__preview:after{content:"PRO";position:absolute;right:14px;top:14px;padding:6px 9px;border-radius:999px;background:#17132d;color:#fff;font-size:11px;font-weight:800;letter-spacing:.08em}.dp-component-card__actions strong.is-locked{color:#6d3df5}' );
wp_enqueue_script(
'divi-powers-design-library',
DIVI_POWERS_URL . 'assets/js/design-library.js',
array(),
DIVI_POWERS_VERSION,
true
);
}
public function dashboard_card( $cards ) {
if ( ! $this->plugin->is_power_enabled( 'design_library' ) || ! is_array( $cards ) ) {
return $cards;
}
array_splice(
$cards,
2,
0,
array(
array(
'number' => '3',
'title' => __( 'Start from native Divi designs', '5d-powers-for-divi' ),
'description' => __( 'Download curated Divi 5 packs whose presets and variables remain editable in Divi.', '5d-powers-for-divi' ),
'url' => admin_url( 'admin.php?page=divi-powers-design-library' ),
'link' => __( 'Open Design Library →', '5d-powers-for-divi' ),
),
)
);
foreach ( $cards as $index => &$card ) {
$card['number'] = (string) ( $index + 1 );
}
unset( $card );
return $cards;
}
public function render_page() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to access the 5D Powers for Divi Design Library.', '5d-powers-for-divi' ) );
}
$assets = $this->assets();
$collections = $this->collections();
$cloud = $this->cloud_catalog();
$cloud_status = $this->cloud_status();
$update_count = $this->available_update_count( $assets );
$divi_ready = function_exists( 'et_builder_d5_enabled' ) && et_builder_d5_enabled();
$asset_map = array();
$groups = array( 'layout' => array(), 'section' => array(), 'row' => array(), 'module' => array() );
foreach ( $assets as $asset ) {
$asset_map[ $asset['id'] ] = $asset;
if ( isset( $groups[ $asset['type'] ] ) ) { $groups[ $asset['type'] ][] = $asset; }
}
$group_labels = array( 'layout' => __( 'Pages', '5d-powers-for-divi' ), 'section' => __( 'Sections', '5d-powers-for-divi' ), 'row' => __( 'Rows', '5d-powers-for-divi' ), 'module' => __( 'Modules', '5d-powers-for-divi' ) );
$install_all_url = wp_nonce_url( admin_url( 'admin-post.php?action=divi_powers_install_all_design_assets' ), 'divi_powers_install_all_design_assets' );
?>
render_message(); ?>
render_cloud_readiness( $cloud, $cloud_status, $update_count ); ?>
installed_post( $collection_asset_id ) ) { $installed_count++; } }
$collection_url = wp_nonce_url( admin_url( 'admin-post.php?action=divi_powers_install_design_collection&collection=' . rawurlencode( $collection['id'] ) ), 'divi_powers_install_design_collection_' . $collection['id'] );
?>
asset_preview_url( $thumb_asset ); if ( $thumb_url ) : ?>
; ?>)
$type_assets ) : if ( ! $type_assets ) { continue; } ?>
render_asset_card( $asset ); } ?>
packs();
$assets = $this->assets();
$collections = $this->collections();
$downloads = $this->download_records();
$cloud = $this->cloud_catalog();
$cloud_status = $this->cloud_status();
$update_count = $this->available_update_count( $assets );
$divi_ready = function_exists( 'et_builder_d5_enabled' ) && et_builder_d5_enabled();
?>
render_message(); ?>
render_cloud_readiness( $cloud, $cloud_status, $update_count ); ?>
installed_post( $collection_asset_id ) ) { $installed_count++; }
}
$collection_url = wp_nonce_url(
admin_url( 'admin-post.php?action=divi_powers_install_design_collection&collection=' . rawurlencode( $collection['id'] ) ),
'divi_powers_install_design_collection_' . $collection['id']
);
?>
render_asset_card( $asset ); ?>
403 ) );
}
$slug = isset( $_GET['pack'] ) ? sanitize_key( wp_unslash( $_GET['pack'] ) ) : '';
check_admin_referer( 'divi_powers_download_design_pack_' . $slug );
$pack = $this->pack( $slug );
if ( ! $pack ) {
wp_die( esc_html__( 'That 5D Powers for Divi design pack does not exist.', '5d-powers-for-divi' ), '', array( 'response' => 404 ) );
}
$file = $this->pack_file( $pack );
if ( ! $file || ! is_readable( $file ) ) {
wp_die( esc_html__( 'The design pack file is unavailable.', '5d-powers-for-divi' ), '', array( 'response' => 404 ) );
}
$records = $this->download_records();
$records[ $pack['slug'] ] = array(
'version' => $pack['version'],
'downloaded_at' => time(),
);
update_option( self::OPTION_KEY, $records, false );
$filename = sanitize_file_name( 'divi-powers-' . $pack['slug'] . '.json' );
nocache_headers();
header( 'Content-Type: application/json; charset=utf-8' );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
header( 'Content-Length: ' . (string) filesize( $file ) );
header( 'X-Content-Type-Options: nosniff' );
readfile( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_readfile
exit;
}
/** Install or update a managed master item in Divi Library. */
public function install_asset() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to install 5D Powers for Divi assets.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
$asset_id = isset( $_GET['asset'] ) ? sanitize_text_field( wp_unslash( $_GET['asset'] ) ) : '';
check_admin_referer( 'divi_powers_install_design_asset_' . $asset_id );
$asset = $this->asset( $asset_id );
if ( ! $asset ) {
$this->redirect_with_message( 'missing_asset' );
}
if ( empty( $asset['installable'] ) ) {
$this->redirect_with_message( 'missing_asset' );
}
if ( ! $this->can_access_asset( $asset ) ) {
$this->redirect_with_message( 'pro_required' );
}
$result = $this->upsert_asset( $asset );
if ( is_wp_error( $result ) ) {
$this->redirect_with_message( $result->get_error_code() );
}
$this->redirect_with_message( $result['updated'] ? 'updated' : 'installed' );
}
/** Clear the local manifest cache and immediately request the current catalog. */
public function refresh_cloud_catalog() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to refresh the 5D Powers for Divi catalog.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'divi_powers_refresh_cloud_catalog' );
delete_transient( self::CLOUD_CACHE_KEY );
$catalog = $this->cloud_catalog( true );
$this->redirect_with_message( ! empty( $catalog['assets'] ) ? 'cloud_refreshed' : 'cloud_failed' );
}
/** Run a fresh cloud request and report whether the remote catalog is usable. */
public function test_cloud_catalog() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to test the 5D Powers for Divi catalog.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'divi_powers_test_cloud_catalog' );
delete_transient( self::CLOUD_CACHE_KEY );
$catalog = $this->cloud_catalog( true );
$this->redirect_with_message( ! empty( $catalog['assets'] ) ? 'cloud_test_passed' : 'cloud_test_failed' );
}
/** Update every installed managed master for which the catalog has a newer version. */
public function update_design_assets() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to update 5D Powers for Divi designs.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'divi_powers_update_design_assets' );
$updates = array();
foreach ( $this->assets() as $asset ) {
$post = $this->installed_post( $asset['id'] );
$installed = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
if ( $installed && version_compare( $installed, $asset['version'], '<' ) && $this->can_access_asset( $asset ) ) {
if ( is_wp_error( $this->asset_content( $asset ) ) ) { $this->redirect_with_message( 'invalid_asset' ); }
$updates[] = $asset;
}
}
foreach ( $updates as $asset ) {
$result = $this->upsert_asset( $asset );
if ( is_wp_error( $result ) ) { $this->redirect_with_message( $result->get_error_code() ); }
}
wp_safe_redirect( add_query_arg( array( 'dp_library_message' => 'assets_updated', 'dp_updated' => count( $updates ) ), admin_url( 'admin.php?page=divi-powers-design-library' ) ) );
exit;
}
/** Add every accessible cloud design to Divi, skipping current managed masters. */
public function install_all_design_assets() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to install 5D Powers for Divi designs.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
check_admin_referer( 'divi_powers_install_all_design_assets' );
$targets = array();
foreach ( $this->assets() as $asset ) {
if ( empty( $asset['installable'] ) || ! $this->can_access_asset( $asset ) ) { continue; }
$post = $this->installed_post( $asset['id'] );
$installed = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
if ( $installed && ! version_compare( $installed, $asset['version'], '<' ) ) { continue; }
if ( is_wp_error( $this->asset_content( $asset ) ) ) { $this->redirect_with_message( 'invalid_asset' ); }
$targets[] = $asset;
}
$installed_count = 0;
$updated_count = 0;
foreach ( $targets as $asset ) {
$result = $this->upsert_asset( $asset );
if ( is_wp_error( $result ) ) { $this->redirect_with_message( $result->get_error_code() ); }
if ( $result['updated'] ) { $updated_count++; } else { $installed_count++; }
}
wp_safe_redirect( add_query_arg( array( 'dp_library_message' => 'all_installed', 'dp_installed' => $installed_count, 'dp_updated' => $updated_count ), admin_url( 'admin.php?page=divi-powers-design-library' ) ) );
exit;
}
/** Install or update every managed master in a registered collection. */
public function install_collection() {
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_die( esc_html__( 'You are not allowed to install 5D Powers for Divi collections.', '5d-powers-for-divi' ), '', array( 'response' => 403 ) );
}
$collection_id = isset( $_GET['collection'] ) ? sanitize_key( wp_unslash( $_GET['collection'] ) ) : '';
check_admin_referer( 'divi_powers_install_design_collection_' . $collection_id );
$collection = $this->collection( $collection_id );
if ( ! $collection ) {
$this->redirect_with_message( 'missing_collection' );
}
$assets = array();
foreach ( $collection['asset_ids'] as $asset_id ) {
$asset = $this->asset( $asset_id );
if ( ! $asset || empty( $asset['installable'] ) ) {
$this->redirect_with_message( 'invalid_collection' );
}
if ( ! $this->can_access_asset( $asset ) ) { $this->redirect_with_message( 'pro_required' ); }
if ( is_wp_error( $this->asset_content( $asset ) ) ) {
$this->redirect_with_message( 'invalid_asset' );
}
$assets[] = $asset;
}
$installed = 0;
$updated = 0;
foreach ( $assets as $asset ) {
$result = $this->upsert_asset( $asset );
if ( is_wp_error( $result ) ) {
$this->redirect_with_message( $result->get_error_code() );
}
if ( $result['updated'] ) { $updated++; } else { $installed++; }
}
$url = add_query_arg(
array(
'dp_library_message' => 'collection_installed',
'dp_installed' => $installed,
'dp_updated' => $updated,
),
admin_url( 'admin.php?page=divi-powers-design-library' )
);
wp_safe_redirect( $url );
exit;
}
/**
* Ensure a set of managed masters exists for another Divi Powers service.
*
* Pro funnel blueprints use this public seam instead of duplicating Lite's
* manifest parser or writing directly to Divi's library storage. Existing
* managed masters are updated in place and locally customized masters are
* preserved by upsert_asset()'s normal customized-copy policy.
*
* @param string[] $asset_ids Managed asset identifiers.
* @return array|WP_Error Map of asset ID to installed Divi Library post ID.
*/
public function ensure_managed_assets( $asset_ids ) {
if ( ! current_user_can( 'edit_theme_options' ) ) {
return new WP_Error( 'forbidden', __( 'You are not allowed to install 5D Powers for Divi assets.', '5d-powers-for-divi' ) );
}
$result = array();
foreach ( array_values( array_unique( array_filter( array_map( 'strval', is_array( $asset_ids ) ? $asset_ids : array() ) ) ) ) as $asset_id ) {
$asset = $this->asset( $asset_id );
if ( ! $asset || empty( $asset['installable'] ) ) {
return new WP_Error( 'missing_asset', __( 'A required 5D Powers for Divi design asset is unavailable.', '5d-powers-for-divi' ) );
}
if ( ! $this->can_access_asset( $asset ) ) { return new WP_Error( 'pro_required', __( 'An active 5D Powers for Divi Pro license is required for this design.', '5d-powers-for-divi' ) ); }
$installed = $this->upsert_asset( $asset );
if ( is_wp_error( $installed ) ) {
return $installed;
}
$result[ $asset_id ] = absint( $installed['post_id'] );
}
return $result;
}
/**
* Create or update one managed Divi Library master.
*
* A locally edited master is preserved as a customized copy before the new
* managed master is created, so collection updates remain non-destructive.
*
* @param array $asset Normalized asset definition.
* @return array|WP_Error
*/
private function upsert_asset( $asset ) {
$this->ensure_divi_library_types();
$content = $this->asset_content( $asset );
if ( is_wp_error( $content ) ) { return $content; }
$content_errors = Divi_Powers_Native_Layouts::executable_content_errors( $content );
if ( ! empty( $content_errors ) ) {
return new WP_Error( 'unsafe_design_content', implode( ' ', $content_errors ) );
}
$asset_id = $asset['id'];
$existing = $this->installed_post( $asset_id );
$original_existing = $existing;
$detached_custom = null;
$rollback = $existing ? array(
'title' => $existing->post_title,
'content' => $existing->post_content,
'meta' => array(
self::ASSET_META => get_post_meta( $existing->ID, self::ASSET_META, true ),
self::VERSION_META => get_post_meta( $existing->ID, self::VERSION_META, true ),
self::HASH_META => get_post_meta( $existing->ID, self::HASH_META, true ),
self::CLOUD_ASSET_META => get_post_meta( $existing->ID, self::CLOUD_ASSET_META, true ),
'_thumbnail_id' => get_post_meta( $existing->ID, '_thumbnail_id', true ),
),
) : null;
$updated = (bool) $existing;
if ( $existing ) {
$stored_hash = (string) get_post_meta( $existing->ID, self::HASH_META, true );
$current_hash = $this->content_hash( (string) $existing->post_content );
$bundled_hash = $this->content_hash( $content );
$matches_saved = $stored_hash && hash_equals( $stored_hash, $current_hash );
$matches_bundle = hash_equals( $bundled_hash, $current_hash );
if ( ! $matches_saved && ! $matches_bundle ) {
$detached_custom = array( 'post_id' => $existing->ID, 'title' => $existing->post_title, 'asset_meta' => get_post_meta( $existing->ID, self::ASSET_META, true ) );
update_post_meta( $existing->ID, self::ASSET_META, $asset_id . '/custom-' . $existing->ID );
wp_update_post( array( 'ID' => $existing->ID, 'post_title' => $existing->post_title . ' — Customized Copy' ) );
$existing = null;
$updated = false;
}
}
$post_data = array(
'post_type' => 'et_pb_layout',
'post_status' => 'publish',
'post_title' => $asset['title'],
'post_content' => wp_slash( $content ),
);
if ( $existing ) {
$post_data['ID'] = $existing->ID;
$post_id = wp_update_post( $post_data, true );
} else {
$post_id = wp_insert_post( $post_data, true );
}
if ( is_wp_error( $post_id ) ) {
if ( $detached_custom ) {
wp_update_post( array( 'ID' => $detached_custom['post_id'], 'post_title' => $detached_custom['title'] ) );
update_post_meta( $detached_custom['post_id'], self::ASSET_META, $detached_custom['asset_meta'] );
}
return new WP_Error( 'install_failed' );
}
update_post_meta( $post_id, self::ASSET_META, $asset_id );
update_post_meta( $post_id, self::VERSION_META, $asset['version'] );
if ( ! empty( $asset['cloud'] ) ) { update_post_meta( $post_id, self::CLOUD_ASSET_META, 1 ); } else { delete_post_meta( $post_id, self::CLOUD_ASSET_META ); }
update_post_meta( $post_id, '_et_pb_built_for_post_type', 'page' );
update_post_meta( $post_id, '_et_pb_template_type', $asset['type'] );
update_post_meta( $post_id, '_et_pb_use_divi_5', 'on' );
if ( taxonomy_exists( 'layout_type' ) ) {
wp_set_object_terms( $post_id, $asset['type'], 'layout_type', false );
}
if ( taxonomy_exists( 'module_width' ) ) {
wp_set_object_terms( $post_id, 'regular', 'module_width', false );
}
if ( taxonomy_exists( 'scope' ) ) {
wp_set_object_terms( $post_id, 'non_global', 'scope', false );
}
if ( taxonomy_exists( 'layout_category' ) ) {
wp_set_object_terms( $post_id, array( 'Divi Powers', $asset['category_label'] ), 'layout_category', false );
}
clean_post_cache( $post_id );
$saved_post = get_post( $post_id );
$saved_hash = $this->content_hash( $saved_post ? (string) $saved_post->post_content : $content );
update_post_meta( $post_id, self::HASH_META, $saved_hash );
$preview = $this->attach_preview( $post_id, $asset );
if ( is_wp_error( $preview ) ) {
if ( $original_existing && $existing ) {
wp_update_post( array( 'ID' => $post_id, 'post_title' => $rollback['title'], 'post_content' => wp_slash( $rollback['content'] ) ) );
foreach ( $rollback['meta'] as $meta_key => $meta_value ) {
if ( '' === (string) $meta_value ) { delete_post_meta( $post_id, $meta_key ); } else { update_post_meta( $post_id, $meta_key, $meta_value ); }
}
} else {
wp_delete_post( $post_id, true );
}
if ( $detached_custom ) {
wp_update_post( array( 'ID' => $detached_custom['post_id'], 'post_title' => $detached_custom['title'] ) );
update_post_meta( $detached_custom['post_id'], self::ASSET_META, $detached_custom['asset_meta'] );
}
return $preview;
}
$installs = $this->install_records();
$installs[ $asset_id ] = array( 'post_id' => absint( $post_id ), 'version' => $asset['version'], 'installed_at' => time() );
update_option( self::INSTALLS_OPTION, $installs, false );
return array( 'post_id' => absint( $post_id ), 'updated' => $updated );
}
/**
* Attach or refresh the bundled visual preview used by Divi's library grid.
*
* The attachment record points at the plugin-bundled image. This avoids an
* uploads-directory dependency and keeps the managed previews replaceable
* on upgrade without creating duplicate media files.
*
* @return true|WP_Error
*/
private function attach_preview( $post_id, $asset ) {
$preview_name = $this->preview_filename( $asset['id'] );
$preview_url = ! empty( $asset['preview_url'] ) ? esc_url_raw( $asset['preview_url'] ) : DIVI_POWERS_URL . 'assets/design-library/previews/' . rawurlencode( $preview_name );
$preview_hash = hash( 'sha256', $asset['id'] . '|' . $asset['version'] . '|' . $preview_name );
$attachments = get_posts(
array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 1,
'meta_key' => self::PREVIEW_ASSET_META, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Single-record lookup of plugin-owned preview metadata.
'meta_value' => $asset['id'], // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Single-record lookup of plugin-owned preview metadata.
)
);
$attachment_id = ! empty( $attachments ) ? absint( $attachments[0]->ID ) : 0;
if ( ! $attachment_id ) {
$attachment_id = wp_insert_attachment(
array(
'guid' => $preview_url,
'post_mime_type' => 'image/png',
'post_status' => 'inherit',
'post_title' => sprintf(
/* translators: %s: design title. */
__( '%s Preview', '5d-powers-for-divi' ), $asset['title'] ),
),
'',
$post_id,
true
);
if ( is_wp_error( $attachment_id ) ) {
return $attachment_id;
}
}
wp_update_attachment_metadata(
$attachment_id,
array(
'width' => 800,
'height' => 600,
'file' => 'divi-powers-previews/' . $preview_name,
'sizes' => array(),
)
);
update_post_meta( $attachment_id, '_wp_attached_file', 'divi-powers-previews/' . $preview_name );
update_post_meta( $attachment_id, self::PREVIEW_ASSET_META, $asset['id'] );
update_post_meta( $attachment_id, self::PREVIEW_HASH_META, $preview_hash );
if ( ! empty( $asset['preview_url'] ) ) { update_post_meta( $attachment_id, self::PREVIEW_URL_META, $preview_url ); } else { delete_post_meta( $attachment_id, self::PREVIEW_URL_META ); }
update_post_meta( $attachment_id, '_wp_attachment_image_alt', sprintf(
/* translators: %s: design title. */
__( 'Preview of %s', '5d-powers-for-divi' ), $asset['title'] ) );
// set_post_thumbnail() rejects virtual attachments on some WordPress hosts.
update_post_meta( $post_id, '_thumbnail_id', absint( $attachment_id ) );
clean_post_cache( $post_id );
return absint( get_post_thumbnail_id( $post_id ) ) === absint( $attachment_id )
? true
: new WP_Error( 'preview_attach_failed', sprintf(
/* translators: %s: design title. */
__( 'The preview for %s could not be attached.', '5d-powers-for-divi' ), $asset['title'] ) );
}
/** Return the stable bundled filename for a managed asset preview. */
private function preview_filename( $asset_id ) {
$filename = preg_replace( '/^dp-/', '', strtolower( (string) $asset_id ) );
$filename = str_replace( '/', '--', $filename );
$filename = preg_replace( '/[^a-z0-9_-]/', '-', $filename );
return trim( $filename, '-' ) . '.png';
}
/** Resolve remote previews first, then the bundled offline preview. */
private function asset_preview_url( $asset, $full = false ) {
$local = apply_filters( 'divi_powers_design_library_local_preview', '', $asset['id'] );
if ( $local ) { return esc_url_raw( $local ); }
$preferred = $full ? ( $asset['full_preview_url'] ?? '' ) : ( $asset['preview_url'] ?? '' );
$fallback_remote = $full ? ( $asset['preview_url'] ?? '' ) : ( $asset['full_preview_url'] ?? '' );
if ( $this->plugin->is_power_enabled( 'cloud_catalog' ) && ( $preferred || $fallback_remote ) ) {
return $preferred ?: $fallback_remote;
}
$filename = $this->preview_filename( $asset['id'] );
$file = DIVI_POWERS_PATH . 'assets/design-library/previews/' . $filename;
return is_readable( $file ) ? DIVI_POWERS_URL . 'assets/design-library/previews/' . rawurlencode( $filename ) : '';
}
private function render_asset_card( $asset ) {
$post = $this->installed_post( $asset['id'] );
$installed = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
$outdated = $installed && version_compare( $installed, $asset['version'], '<' );
$action = wp_nonce_url( admin_url( 'admin-post.php?action=divi_powers_install_design_asset&asset=' . rawurlencode( $asset['id'] ) ), 'divi_powers_install_design_asset_' . $asset['id'] );
$filters = implode( ' ', array_unique( array_merge( array( $asset['type'], $asset['category'] ), $asset['tags'] ) ) );
$accessible = $this->can_access_asset( $asset );
$preview = $this->asset_preview_url( $asset );
$full_preview = $this->asset_preview_url( $asset, true );
?>
![<?php echo esc_attr( sprintf(
/* translators: %s: design title. */
__( 'Preview of %s', '5d-powers-for-divi' ), $asset['title'] ) ); ?>](<?php echo esc_url( $preview ); ?>)
plugin->is_power_enabled( 'cloud_catalog' ) ) {
?>
installed_post( $asset['id'] );
$installed = $post ? (string) get_post_meta( $post->ID, self::VERSION_META, true ) : '';
if ( $installed && version_compare( $installed, $asset['version'], '<' ) && $this->can_access_asset( $asset ) ) { $count++; }
}
return $count;
}
private function can_access_asset( $asset ) {
// Every design supplied by this plugin is available without a license.
return true;
}
private function render_message() {
$preview_error = get_option( self::PREVIEW_ERROR_OPTION, array() );
if ( is_array( $preview_error ) && ! empty( $preview_error['assets'] ) ) {
$first_error = reset( $preview_error['assets'] );
$detail = is_array( $first_error ) && ! empty( $first_error['message'] ) ? ' ' . $first_error['message'] : '';
printf(
'',
esc_html( sprintf(
/* translators: 1: number of failed previews, 2: error detail prefixed with a space. */
__( '5D Powers for Divi could not attach %1$d library preview(s). The repair will retry automatically.%2$s', '5d-powers-for-divi' ), count( $preview_error['assets'] ), $detail ) )
);
}
$message = isset( $_GET['dp_library_message'] ) ? sanitize_key( wp_unslash( $_GET['dp_library_message'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$messages = array(
'recipes_moved' => __( 'Recipes are now prewired native patterns in the Interactions & Navigation collection.', '5d-powers-for-divi' ),
'installed' => __( 'Component installed in the Divi Library.', '5d-powers-for-divi' ),
'updated' => __( 'The managed Divi Library master was updated. Existing page copies were not changed.', '5d-powers-for-divi' ),
'collection_installed' => sprintf(
/* translators: 1: newly installed component count, 2: updated component count. */
__( 'Collection ready: %1$d component(s) installed and %2$d managed master(s) updated.', '5d-powers-for-divi' ),
isset( $_GET['dp_installed'] ) ? absint( $_GET['dp_installed'] ) : 0, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
isset( $_GET['dp_updated'] ) ? absint( $_GET['dp_updated'] ) : 0 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
),
'cloud_refreshed' => __( 'The latest 5D Powers for Divi Cloud Catalog is now cached on this site.', '5d-powers-for-divi' ),
'cloud_failed' => __( 'The cloud catalog could not be refreshed. Bundled designs remain available.', '5d-powers-for-divi' ),
'cloud_disabled' => __( 'Enable Online Design Catalog in the Feature Manager before downloading an online design.', '5d-powers-for-divi' ),
'cloud_test_passed' => __( 'Cloud connection passed. This site can read the current published catalog.', '5d-powers-for-divi' ),
'cloud_test_failed' => __( 'Cloud connection failed. The bundled offline catalog is still available; review the Cloud Readiness details below.', '5d-powers-for-divi' ),
'assets_updated' => sprintf(
/* translators: %d: number of updated managed components. */
__( '%d managed component(s) updated. Customized copies and page content were preserved.', '5d-powers-for-divi' ), isset( $_GET['dp_updated'] ) ? absint( $_GET['dp_updated'] ) : 0 ), // phpcs:ignore WordPress.Security.NonceVerification.Recommended
'all_installed' => sprintf(
/* translators: 1: newly added designs, 2: updated designs. */
__( 'Cloud library synced: %1$d design(s) added and %2$d managed design(s) updated.', '5d-powers-for-divi' ),
isset( $_GET['dp_installed'] ) ? absint( $_GET['dp_installed'] ) : 0, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
isset( $_GET['dp_updated'] ) ? absint( $_GET['dp_updated'] ) : 0 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
),
'divi_required' => __( 'Divi must be active before components can be installed.', '5d-powers-for-divi' ),
'invalid_asset' => __( 'The bundled component could not be read.', '5d-powers-for-divi' ),
'missing_asset' => __( 'That component is not registered.', '5d-powers-for-divi' ),
'missing_collection' => __( 'That component collection is not registered.', '5d-powers-for-divi' ),
'invalid_collection' => __( 'That collection contains an unavailable component and could not be installed.', '5d-powers-for-divi' ),
'install_failed' => __( 'WordPress could not install that component.', '5d-powers-for-divi' ),
'cloud_unavailable' => __( 'The cloud design could not be downloaded. Refresh the catalog and try again.', '5d-powers-for-divi' ),
'invalid_cloud_asset' => __( 'The downloaded cloud design failed its integrity check and was not installed.', '5d-powers-for-divi' ),
'pro_required' => __( 'An active 5D Powers for Divi Pro license is required to install that design.', '5d-powers-for-divi' ),
);
if ( isset( $messages[ $message ] ) ) {
$is_error = in_array( $message, array( 'divi_required', 'invalid_asset', 'missing_asset', 'missing_collection', 'invalid_collection', 'install_failed', 'cloud_unavailable', 'invalid_cloud_asset', 'pro_required', 'cloud_failed', 'cloud_disabled', 'cloud_test_failed' ), true );
printf( '', esc_attr( $is_error ? 'notice-error' : 'notice-success' ), esc_html( $messages[ $message ] ) );
}
}
private function redirect_with_message( $message ) {
wp_safe_redirect( add_query_arg( 'dp_library_message', sanitize_key( $message ), admin_url( 'admin.php?page=divi-powers-design-library' ) ) );
exit;
}
private function assets() {
$manifest = $this->manifest_data();
$candidates = is_array( $manifest['assets'] ?? null ) ? $manifest['assets'] : array();
$assets = array();
foreach ( $candidates as $candidate ) {
$asset = $this->normalize_asset( $candidate );
if ( $asset ) { $assets[] = $asset; }
}
$by_id = array();
foreach ( $assets as $asset ) { $by_id[ $asset['id'] ] = $asset; }
$cloud = $this->cloud_catalog();
foreach ( is_array( $cloud['assets'] ?? null ) ? $cloud['assets'] : array() as $candidate ) {
// The directory edition lists public downloads only; paid remote designs are supplied by Pro.
if ( 'pro' === ( $candidate['edition'] ?? '' ) ) { continue; }
$asset = $this->normalize_asset( $candidate );
if ( $asset ) { $by_id[ $asset['id'] ] = $asset; }
}
return apply_filters( 'divi_powers_design_library_assets', array_values( $by_id ) );
}
private function collections() {
$manifest = $this->manifest_data();
$candidates = is_array( $manifest['collections'] ?? null ) ? $manifest['collections'] : array();
$collections = array();
foreach ( $candidates as $candidate ) {
$collection = $this->normalize_collection( $candidate );
if ( $collection ) { $collections[] = $collection; }
}
return apply_filters( 'divi_powers_design_library_collections', $collections );
}
private function collection( $id ) {
foreach ( $this->collections() as $collection ) { if ( $id === $collection['id'] ) { return $collection; } }
return null;
}
private function normalize_collection( $candidate ) {
if ( ! is_array( $candidate ) ) { return null; }
$id = sanitize_key( (string) ( $candidate['id'] ?? '' ) );
$asset_ids = array_values( array_unique( array_filter( array_map(
static function( $asset_id ) { return preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( (string) $asset_id ) ); },
is_array( $candidate['asset_ids'] ?? null ) ? $candidate['asset_ids'] : array()
) ) ) );
if ( ! $id || ! $asset_ids ) { return null; }
return array(
'id' => $id,
'title' => sanitize_text_field( (string) ( $candidate['title'] ?? $id ) ),
'description' => sanitize_text_field( (string) ( $candidate['description'] ?? '' ) ),
'tier' => sanitize_key( (string) ( $candidate['tier'] ?? 'lite' ) ),
'requirement' => sanitize_text_field( (string) ( $candidate['requirement'] ?? __( 'No additional runtime requirement.', '5d-powers-for-divi' ) ) ),
'asset_ids' => $asset_ids,
);
}
private function asset( $id ) {
foreach ( $this->assets() as $asset ) { if ( $id === $asset['id'] ) { return $asset; } }
return null;
}
private function normalize_asset( $candidate ) {
if ( ! is_array( $candidate ) ) { return null; }
$id = preg_replace( '/[^a-z0-9_\/-]/', '', strtolower( (string) ( $candidate['id'] ?? '' ) ) );
$source = ltrim( str_replace( '\\', '/', (string) ( $candidate['source'] ?? '' ) ), '/' );
$content_url = $this->normalize_cloud_url( $candidate['content_url'] ?? '' );
$type = sanitize_key( (string) ( $candidate['type'] ?? 'layout' ) );
if ( ! $id || ( ! $source && ! $content_url ) || false !== strpos( $source, '..' ) || ! in_array( $type, array( 'layout', 'section', 'row', 'module' ), true ) ) { return null; }
$category = sanitize_key( (string) ( $candidate['category'] ?? 'general' ) );
$setup_actions = array();
foreach ( is_array( $candidate['setup_actions'] ?? null ) ? $candidate['setup_actions'] : array() as $setup_action ) {
if ( ! is_array( $setup_action ) ) { continue; }
$page = sanitize_key( (string) ( $setup_action['page'] ?? '' ) );
$label = sanitize_text_field( (string) ( $setup_action['label'] ?? '' ) );
if ( $page && $label ) { $setup_actions[] = array( 'page' => $page, 'label' => $label ); }
}
$setup = array_values(
array_filter(
array_map(
'sanitize_text_field',
is_array( $candidate['setup'] ?? null ) ? $candidate['setup'] : array()
)
)
);
return array(
'id' => $id,
'version' => preg_replace( '/[^0-9A-Za-z.\-]/', '', (string) ( $candidate['version'] ?? '1.0.0' ) ),
'title' => sanitize_text_field( (string) ( $candidate['title'] ?? $id ) ),
'description' => sanitize_text_field( (string) ( $candidate['description'] ?? '' ) ),
'type' => $type,
'category' => $category,
'category_label' => sanitize_text_field( (string) ( $candidate['category_label'] ?? __( 'General', '5d-powers-for-divi' ) ) ),
'preview_label' => sanitize_text_field( (string) ( $candidate['preview_label'] ?? __( 'Native Divi', '5d-powers-for-divi' ) ) ),
'source' => $source,
'content_url' => $content_url,
'preview_url' => $this->normalize_cloud_url( $candidate['preview_url'] ?? '' ),
'full_preview_url' => $this->normalize_cloud_url( $candidate['full_preview_url'] ?? '' ),
'checksum' => preg_replace( '/[^a-f0-9]/', '', strtolower( (string) ( $candidate['checksum'] ?? '' ) ) ),
'release_notes' => sanitize_textarea_field( (string) ( $candidate['release_notes'] ?? '' ) ),
'released_at' => sanitize_text_field( (string) ( $candidate['released_at'] ?? '' ) ),
'cloud' => (bool) $content_url,
'section_index' => isset( $candidate['section_index'] ) ? absint( $candidate['section_index'] ) : null,
'installable' => ! array_key_exists( 'installable', $candidate ) || ! empty( $candidate['installable'] ),
'edition' => in_array( sanitize_key( (string) ( $candidate['edition'] ?? ( 'funnel' === $category ? 'pro' : 'lite' ) ) ), array( 'lite', 'pro' ), true ) ? sanitize_key( (string) ( $candidate['edition'] ?? ( 'funnel' === $category ? 'pro' : 'lite' ) ) ) : 'lite',
'setup' => array_slice( $setup, 0, 6 ),
'setup_actions' => array_slice( $setup_actions, 0, 4 ),
'tags' => array_values( array_filter( array_map( 'sanitize_key', is_array( $candidate['tags'] ?? null ) ? $candidate['tags'] : array() ) ) ),
);
}
/** Accept cloud downloads and previews only from explicitly trusted HTTPS hosts. */
private function normalize_cloud_url( $candidate ) {
$url = esc_url_raw( (string) $candidate, array( 'https' ) );
if ( '' === $url ) {
return '';
}
$parts = wp_parse_url( $url );
if (
! is_array( $parts )
|| 'https' !== strtolower( (string) ( $parts['scheme'] ?? '' ) )
|| empty( $parts['host'] )
|| isset( $parts['user'] )
|| isset( $parts['pass'] )
|| ( isset( $parts['port'] ) && 443 !== (int) $parts['port'] )
) {
return '';
}
$host = strtolower( rtrim( (string) $parts['host'], '.' ) );
$allowed_hosts = apply_filters( 'divi_powers_cloud_asset_hosts', array( 'divipowers.com', 'www.divipowers.com' ) );
$allowed_hosts = is_array( $allowed_hosts ) ? array_map(
static function ( $allowed_host ) {
return strtolower( trim( (string) $allowed_host ) );
},
$allowed_hosts
) : array();
return in_array( $host, $allowed_hosts, true ) ? $url : '';
}
private function asset_content( $asset ) {
if ( ! empty( $asset['content_url'] ) ) {
if ( ! $this->plugin->is_power_enabled( 'cloud_catalog' ) ) {
return new WP_Error( 'cloud_disabled', __( 'Enable Online Design Catalog in the Feature Manager before downloading an online design.', '5d-powers-for-divi' ) );
}
$headers = array( 'Accept' => 'application/json' );
$response = wp_safe_remote_get( $asset['content_url'], array( 'timeout' => 20, 'redirection' => 0, 'limit_response_size' => self::MAX_CLOUD_ASSET_BYTES, 'headers' => $headers, 'user-agent' => 'Divi Powers/' . DIVI_POWERS_VERSION ) );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return new WP_Error( 'cloud_unavailable', __( 'The cloud design could not be downloaded. Try refreshing the catalog.', '5d-powers-for-divi' ) ); }
$body = wp_remote_retrieve_body( $response );
$payload = strlen( $body ) <= self::MAX_CLOUD_ASSET_BYTES ? json_decode( $body, true ) : null;
$content = is_array( $payload ) && is_string( $payload['content'] ?? null ) ? $payload['content'] : '';
$checksum = is_array( $payload ) ? preg_replace( '/[^a-f0-9]/', '', strtolower( (string) ( $payload['checksum'] ?? '' ) ) ) : '';
if ( '' === trim( $content ) || self::MAX_CLOUD_ASSET_CONTENT_BYTES < strlen( $content ) || ( ! empty( $asset['checksum'] ) && ! hash_equals( $asset['checksum'], $checksum ) ) || ( $checksum && ! hash_equals( $checksum, hash( 'sha256', str_replace( array( "\r\n", "\r" ), "\n", $content ) ) ) ) ) {
return new WP_Error( 'invalid_cloud_asset', __( 'The downloaded design failed its integrity check.', '5d-powers-for-divi' ) );
}
return $content;
}
$root = apply_filters( 'divi_powers_design_library_local_root', DIVI_POWERS_PATH . 'assets/design-library', $asset['source'] );
$base = realpath( $root );
$file = realpath( $root . '/' . $asset['source'] );
if ( ! $base || ! $file || 0 !== strpos( $file, $base . DIRECTORY_SEPARATOR ) || ! is_readable( $file ) ) { return new WP_Error( 'invalid_asset' ); }
$data = json_decode( (string) file_get_contents( $file ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$content = is_array( $data['data'] ?? null ) ? reset( $data['data'] ) : '';
if ( ! is_string( $content ) || '' === trim( $content ) ) { return new WP_Error( 'invalid_asset' ); }
if ( null !== $asset['section_index'] ) {
$sections = $this->serialized_divi_sections( $content );
if ( ! isset( $sections[ $asset['section_index'] ] ) ) { return new WP_Error( 'invalid_asset' ); }
$content = $sections[ $asset['section_index'] ];
}
return $content;
}
private function serialized_divi_sections( $content ) {
$sections = array();
$opening = '';
$offset = 0;
$length = strlen( $content );
while ( $offset < $length ) {
$start = strpos( $content, $opening, $offset );
if ( false === $start ) { break; }
$end = strpos( $content, $closing, $start );
if ( false === $end ) { break; }
$end += strlen( $closing );
$sections[] = substr( $content, $start, $end - $start );
$offset = $end;
}
return $sections;
}
private function content_hash( $content ) {
$content = str_replace( array( "\r\n", "\r" ), "\n", (string) $content );
for ( $pass = 0; $pass < 2; $pass++ ) {
$unslashed = wp_unslash( $content );
if ( $unslashed === $content ) { break; }
$content = $unslashed;
}
/*
* Divi 5 serializes module data inside block-comment JSON. WordPress saves
* that JSON with its HTML-safe encoding flags, so characters such as < and
* > may come back as \u003c and \u003e even though the component is
* semantically untouched. Canonicalize those reversible encodings before
* comparing a library master with the bundled source.
*/
$content = str_ireplace(
array( '\\u003c', '\\u003e', '\\u0026', '\\u0022', '\\u0027' ),
array( '<', '>', '&', '"', "'" ),
$content
);
return hash( 'sha256', trim( $content ) );
}
/**
* Remap every coordinated Power ID immediately before Builder insertion.
*
* The managed Library master keeps stable IDs for non-destructive updates,
* while each page copy receives a fresh suffix. Reusing a pattern therefore
* cannot connect its controls to targets from an earlier insertion.
*
* @param string $content Serialized Divi block content.
* @return string
*/
private function remap_power_ids( $content ) {
$keys = 'triggerPowerId|triggerTargetPowerId|autoTriggerWatchPowerId|contentToggleTargetA|contentToggleTargetB|contentGroupId|contentGroupTargetPowerId|scrollNavGroupId|scrollNavTargetPowerId';
$suffix = strtolower( wp_generate_password( 7, false, false ) );
$map = array();
$result = preg_replace_callback(
'/("(?:' . $keys . ')"\s*:\s*")([^"\\\\]+)(")/',
static function ( $matches ) use ( &$map, $suffix ) {
$original = sanitize_title( $matches[2] );
if ( '' === $original ) { return $matches[0]; }
if ( ! isset( $map[ $original ] ) ) {
$map[ $original ] = substr( $original, 0, 52 ) . '-' . $suffix;
}
return $matches[1] . $map[ $original ] . $matches[3];
},
(string) $content
);
return is_string( $result ) ? $result : (string) $content;
}
private function installed_post( $asset_id ) {
$posts = get_posts( array( 'post_type' => 'et_pb_layout', 'post_status' => array( 'publish', 'draft', 'private' ), 'posts_per_page' => 1, 'meta_key' => self::ASSET_META, 'meta_value' => $asset_id ) ); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Single-record lookup of a managed Divi Library asset.
return ! empty( $posts ) ? $posts[0] : null;
}
/**
* Divi defers its library post-type registration on some admin-post requests.
* Register the same storage primitives for this request when that happens.
*/
private function ensure_divi_library_types() {
if ( ! post_type_exists( 'et_pb_layout' ) ) {
register_post_type(
'et_pb_layout',
array(
'label' => __( 'Divi Library', '5d-powers-for-divi' ),
'public' => false,
'show_ui' => false,
'show_in_rest' => false,
'supports' => array( 'title', 'editor', 'revisions' ),
)
);
}
add_post_type_support( 'et_pb_layout', 'thumbnail' );
foreach ( array( 'layout_type', 'layout_category', 'module_width', 'scope' ) as $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
register_taxonomy( $taxonomy, 'et_pb_layout', array( 'public' => false, 'show_ui' => false ) );
}
}
}
private function install_records() {
$records = get_option( self::INSTALLS_OPTION, array() );
return is_array( $records ) ? $records : array();
}
private function packs() {
$data = $this->manifest_data();
if ( empty( $data['packs'] ) || ! is_array( $data['packs'] ) ) {
return array();
}
$packs = array();
foreach ( $data['packs'] as $candidate ) {
$pack = $this->normalize_pack( $candidate );
if ( $pack ) {
$packs[] = $pack;
}
}
return $packs;
}
private function manifest_data() {
$manifest = DIVI_POWERS_PATH . self::MANIFEST;
if ( ! is_readable( $manifest ) ) { return array(); }
$data = json_decode( (string) file_get_contents( $manifest ), true ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
return is_array( $data ) && in_array( (int) ( $data['schema'] ?? 0 ), array( 1, 2, 3 ), true ) ? apply_filters( 'divi_powers_design_library_bundled_manifest', $data ) : array();
}
/** Retrieve a small versioned cloud manifest; retain bundled assets on failure. */
private function cloud_catalog( $force = false ) {
if ( ! $this->plugin->is_power_enabled( 'cloud_catalog' ) ) {
return array();
}
if ( ! $force ) {
$cached = get_transient( self::CLOUD_CACHE_KEY );
if ( is_array( $cached ) ) {
if ( is_array( $cached['assets'] ?? null ) ) {
$cached['assets'] = array_slice( $cached['assets'], 0, self::MAX_CLOUD_ASSETS );
}
$status = $this->cloud_status();
if ( empty( $status['source'] ) ) {
$status['source'] = 'cache';
$status['count'] = count( is_array( $cached['assets'] ?? null ) ? $cached['assets'] : array() );
update_option( self::CLOUD_STATUS_OPTION, $status, false );
}
return $cached;
}
}
$started = microtime( true );
$previous = $this->cloud_status();
$local = apply_filters( 'divi_powers_cloud_catalog_local', null );
if ( is_array( $local ) && 1 === absint( $local['schema'] ?? 0 ) && is_array( $local['assets'] ?? null ) ) {
$local['assets'] = array_slice( $local['assets'], 0, self::MAX_CLOUD_ASSETS );
set_transient( self::CLOUD_CACHE_KEY, $local, self::CLOUD_CACHE_TTL );
update_option( self::CLOUD_STATUS_OPTION, array( 'state' => 'connected', 'source' => 'studio-bridge', 'last_attempt' => time(), 'last_success' => time(), 'count' => count( $local['assets'] ), 'generated_at' => sanitize_text_field( (string) ( $local['generated_at'] ?? '' ) ), 'response_ms' => absint( ( microtime( true ) - $started ) * 1000 ), 'error' => '' ), false );
return $local;
}
$response = wp_safe_remote_get( self::CLOUD_CATALOG_URL, array( 'timeout' => 12, 'redirection' => 0, 'limit_response_size' => self::MAX_CLOUD_CATALOG_BYTES, 'headers' => array( 'Accept' => 'application/json' ), 'user-agent' => 'Divi Powers/' . DIVI_POWERS_VERSION ) );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
$error = is_wp_error( $response ) ? $response->get_error_message() : sprintf(
/* translators: %d: HTTP response status code. */
__( 'Cloud endpoint returned HTTP %d.', '5d-powers-for-divi' ), wp_remote_retrieve_response_code( $response ) );
update_option( self::CLOUD_STATUS_OPTION, array( 'state' => 'fallback', 'source' => 'bundled-fallback', 'last_attempt' => time(), 'last_success' => absint( $previous['last_success'] ?? 0 ), 'count' => 0, 'generated_at' => '', 'response_ms' => absint( ( microtime( true ) - $started ) * 1000 ), 'error' => sanitize_text_field( $error ) ), false );
return array();
}
$body = wp_remote_retrieve_body( $response );
$data = strlen( $body ) <= self::MAX_CLOUD_CATALOG_BYTES ? json_decode( $body, true ) : null;
if ( ! is_array( $data ) || 1 !== absint( $data['schema'] ?? 0 ) || ! is_array( $data['assets'] ?? null ) || self::MAX_CLOUD_ASSETS < count( $data['assets'] ) ) {
update_option( self::CLOUD_STATUS_OPTION, array( 'state' => 'fallback', 'source' => 'bundled-fallback', 'last_attempt' => time(), 'last_success' => absint( $previous['last_success'] ?? 0 ), 'count' => 0, 'generated_at' => '', 'response_ms' => absint( ( microtime( true ) - $started ) * 1000 ), 'error' => __( 'Cloud endpoint returned an invalid catalog.', '5d-powers-for-divi' ) ), false );
return array();
}
set_transient( self::CLOUD_CACHE_KEY, $data, self::CLOUD_CACHE_TTL );
update_option( self::CLOUD_STATUS_OPTION, array( 'state' => 'connected', 'source' => 'remote', 'last_attempt' => time(), 'last_success' => time(), 'count' => count( $data['assets'] ), 'generated_at' => sanitize_text_field( (string) ( $data['generated_at'] ?? '' ) ), 'response_ms' => absint( ( microtime( true ) - $started ) * 1000 ), 'error' => '' ), false );
return $data;
}
private function cloud_status() {
$status = get_option( self::CLOUD_STATUS_OPTION, array() );
return is_array( $status ) ? $status : array();
}
private function pack( $slug ) {
foreach ( $this->packs() as $pack ) {
if ( $slug === $pack['slug'] ) {
return $pack;
}
}
return null;
}
private function normalize_pack( $candidate ) {
if ( ! is_array( $candidate ) ) {
return null;
}
$slug = sanitize_key( (string) ( $candidate['slug'] ?? '' ) );
$version = preg_replace( '/[^0-9A-Za-z.\-]/', '', (string) ( $candidate['version'] ?? '' ) );
$file = ltrim( str_replace( '\\', '/', (string) ( $candidate['file'] ?? '' ) ), '/' );
if ( ! $slug || ! $version || ! $file || false !== strpos( $file, '..' ) || 'json' !== strtolower( pathinfo( $file, PATHINFO_EXTENSION ) ) ) {
return null;
}
return array(
'slug' => $slug,
'version' => $version,
'title' => sanitize_text_field( (string) ( $candidate['title'] ?? $slug ) ),
'eyebrow' => sanitize_text_field( (string) ( $candidate['eyebrow'] ?? __( 'DESIGN PACK', '5d-powers-for-divi' ) ) ),
'description' => sanitize_text_field( (string) ( $candidate['description'] ?? '' ) ),
'file' => $file,
'format' => sanitize_key( (string) ( $candidate['format'] ?? 'divi-layout-json' ) ),
'release_model' => sanitize_key( (string) ( $candidate['release_model'] ?? 'additive' ) ),
'minimum_divi' => sanitize_text_field( (string) ( $candidate['minimum_divi'] ?? '5.0.0' ) ),
'runtime_requirement' => sanitize_text_field( (string) ( $candidate['runtime_requirement'] ?? '' ) ),
'includes' => array_values( array_filter( array_map( 'sanitize_text_field', is_array( $candidate['includes'] ?? null ) ? $candidate['includes'] : array() ) ) ),
'presets' => array_values( array_filter( array_map( 'sanitize_text_field', is_array( $candidate['presets'] ?? null ) ? $candidate['presets'] : array() ) ) ),
'import_notice' => sanitize_text_field( (string) ( $candidate['import_notice'] ?? '' ) ),
'import_steps' => array_values( array_filter( array_map( 'sanitize_text_field', is_array( $candidate['import_steps'] ?? null ) ? $candidate['import_steps'] : array() ) ) ),
);
}
private function pack_file( $pack ) {
$root = apply_filters( 'divi_powers_design_library_local_root', DIVI_POWERS_PATH . 'assets/design-library', $pack['file'] );
$base = realpath( $root );
$file = realpath( $root . '/' . $pack['file'] );
if ( ! $base || ! $file || 0 !== strpos( $file, $base . DIRECTORY_SEPARATOR ) ) {
return null;
}
return $file;
}
private function download_records() {
$records = get_option( self::OPTION_KEY, array() );
return is_array( $records ) ? $records : array();
}
}