← Back
Editing: template-service.php
<?php namespace Aepro\Ai; use Aepro\Admin\TemplateSettingsSchema; use Aepro\Classes\CacheManager; if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Single place that creates and changes Dynific templates. * Used by the "Create Template" modal (AJAX) and by the AI abilities. */ class TemplateService { const POST_TYPE = 'ae_global_templates'; /** * Render modes available without Pro (matches the modal's long-standing behaviour). */ const FREE_RENDER_MODES = [ 'normal', 'post_template' ]; /** * Statuses a template can be given by update(). */ const STATUSES = [ 'draft', 'pending', 'publish', 'private' ]; /** * Render modes the AI publishes on create: they never show on the site by themselves, * only inside a listing widget that uses them, and they render nothing while draft. */ const AUTO_PUBLISH_RENDER_MODES = [ 'block_layout', 'acf_repeater_layout' ]; /** * Most posts assign_to_posts() changes in one call. */ const MAX_ASSIGN_POSTS = 50; /** * Per-post template override meta ("Select Layout" box on the post edit screen). */ const POST_TEMPLATE_META = 'ae_post_template'; /** * Capability required to create templates. * * @return string */ public static function get_create_capability() { $post_type_object = get_post_type_object( self::POST_TYPE ); return ( $post_type_object && isset( $post_type_object->cap->create_posts ) ) ? $post_type_object->cap->create_posts : 'edit_posts'; } /** * Capability required to publish templates. * * @return string */ public static function get_publish_capability() { $post_type_object = get_post_type_object( self::POST_TYPE ); return ( $post_type_object && isset( $post_type_object->cap->publish_posts ) ) ? $post_type_object->cap->publish_posts : 'publish_posts'; } /** * Create a template and store its settings. * * The modal always creates a draft. The AI ($strict) may pass status; without it, block * layouts and repeater layouts are published (see AUTO_PUBLISH_RENDER_MODES), others are drafts. * * @param array $args Unslashed input: template_type, template_name, rule_post_type, * preview_post_id, page_layout, … (same keys as the modal), status (AI only). * @param bool $strict true = return an error for Pro-locked types (AI); * false = silently fall back to post_template like the modal. * @return array|\WP_Error */ public static function create( array $args, $strict = false ) { if ( ! get_post_type_object( self::POST_TYPE ) ) { return new \WP_Error( 'aep_invalid_post_type', __( 'Invalid post type.', 'ae-pro' ), [ 'status' => 400 ] ); } if ( ! current_user_can( self::get_create_capability() ) ) { return new \WP_Error( 'aep_forbidden', __( 'You are not allowed to create templates.', 'ae-pro' ), [ 'status' => 403 ] ); } $render_mode = self::resolve_render_mode( isset( $args['template_type'] ) ? $args['template_type'] : '', $strict ); if ( is_wp_error( $render_mode ) ) { return $render_mode; } $status = $strict ? self::resolve_create_status( $args, $render_mode ) : 'draft'; if ( is_wp_error( $status ) ) { return $status; } $template_name = isset( $args['template_name'] ) ? sanitize_text_field( $args['template_name'] ) : ''; if ( '' === $template_name ) { $template_name = __( 'No Title', 'ae-pro' ); } // Always inserted as draft; the status is set after the settings so save_post sees them. $post_id = wp_insert_post( [ 'post_type' => self::POST_TYPE, 'post_title' => $template_name, 'post_status' => 'draft', ], true ); if ( is_wp_error( $post_id ) ) { $post_id->add_data( [ 'status' => 500 ] ); return $post_id; } $values = array_merge( [ 'render_mode' => $render_mode ], self::sanitize_values( $args, false ) ); self::write_values( $post_id, $values, $render_mode ); // AI-built content goes through Elementor's tools, which need the document marked as an // Elementor document (otherwise publishing a staged draft copies nothing). if ( $strict ) { $document = \Elementor\Plugin::$instance->documents->get( $post_id ); if ( $document ) { $document->set_is_built_with_elementor( true ); } } // The returned status is read back, so a failed update reports draft. if ( 'draft' !== $status ) { wp_update_post( [ 'ID' => $post_id, 'post_status' => $status, ] ); } return [ 'post_id' => $post_id, 'title' => $template_name, 'render_mode' => $render_mode, 'status' => get_post_status( $post_id ), 'edit_url' => self::get_edit_url( $post_id ), ]; } /** * Is the post open in an editor (Elementor or the block editor) right now, by anyone? * Writing to it from the server would be overwritten by that editor's next save. * * @param int $post_id Post ID. * @return true|\WP_Error */ public static function check_not_open_in_editor( $post_id ) { $lock = (string) get_post_meta( absint( $post_id ), '_edit_lock', true ); $time = (int) strtok( $lock, ':' ); /** This filter is documented in wp-admin/includes/post.php */ $window = apply_filters( 'wp_check_post_lock_window', 150 ); if ( $time && $time > time() - $window ) { return new \WP_Error( 'aep_open_in_editor', __( 'This is open in the editor right now (by you or another user), and the editor would overwrite this change on its next save. If it is open in the Elementor editor, use the dynific-editor tools there. Otherwise ask the user to close it and retry in about 2 minutes.', 'ae-pro' ), [ 'status' => 409 ] ); } return true; } /** * Change an existing template: title, status and/or settings. Only the given keys change. * Pro-locked types always return an error here (no silent fallback). * * @param int $template_id Template ID. * @param array $args title, status, template_type and any create() setting key. * @return array|\WP_Error Settings after the change (see get_settings()). */ public static function update( $template_id, array $args ) { $template = self::get_template( $template_id ); if ( is_wp_error( $template ) ) { return $template; } $template_id = $template->ID; if ( ! current_user_can( 'edit_post', $template_id ) ) { return new \WP_Error( 'aep_forbidden', __( 'You are not allowed to edit this template.', 'ae-pro' ), [ 'status' => 403 ] ); } $post_data = []; if ( isset( $args['title'] ) && '' !== trim( (string) $args['title'] ) ) { $post_data['post_title'] = sanitize_text_field( (string) $args['title'] ); } if ( isset( $args['status'] ) && '' !== $args['status'] ) { $status = sanitize_key( $args['status'] ); if ( ! in_array( $status, self::STATUSES, true ) ) { return new \WP_Error( 'aep_invalid_status', __( 'Invalid status. Use draft, pending, publish or private.', 'ae-pro' ), [ 'status' => 400 ] ); } if ( in_array( $status, [ 'publish', 'private' ], true ) && ! current_user_can( self::get_publish_capability() ) ) { return new \WP_Error( 'aep_forbidden', __( 'You are not allowed to publish templates.', 'ae-pro' ), [ 'status' => 403 ] ); } // Even an unchanged status: "publish" from the editor means "save my changes and publish", // and the unsaved editor changes are only reachable from the editor. if ( is_wp_error( self::check_not_open_in_editor( $template_id ) ) ) { return new \WP_Error( 'aep_open_in_editor', __( 'The template is open in the Elementor editor and its changes there are NOT saved yet; changing the status here would publish the old saved version. Use dynific-editor-save-document (status=publish) in the editor. If that tool is not available, ask the user to click Publish/Update in the editor.', 'ae-pro' ), [ 'status' => 409 ] ); } if ( $status !== $template->post_status ) { $post_data['post_status'] = $status; } } $values = self::sanitize_values( $args, true ); if ( isset( $args['template_type'] ) && '' !== $args['template_type'] ) { $render_mode = self::resolve_render_mode( $args['template_type'], true ); if ( is_wp_error( $render_mode ) ) { return $render_mode; } $values['render_mode'] = $render_mode; } if ( ! $post_data && ! $values && empty( $args['status'] ) ) { return new \WP_Error( 'aep_nothing_to_update', __( 'Nothing to update. Pass title, status or a template setting.', 'ae-pro' ), [ 'status' => 400 ] ); } // Meta first, so the cache rebuilt on save_post sees the new settings. if ( $values ) { $render_mode = isset( $values['render_mode'] ) ? $values['render_mode'] : get_post_meta( $template_id, 'ae_render_mode', true ); // The archive post type follows rule_post_type, like create(). if ( 'post_type_archive_template' === $render_mode && ! isset( $values['rule_post_type'] ) && isset( $values['render_mode'] ) ) { $values['rule_post_type'] = get_post_meta( $template_id, 'ae_rule_post_type', true ); } self::write_values( $template_id, $values, $render_mode ); } if ( $post_data ) { $post_data['ID'] = $template_id; $result = wp_update_post( wp_slash( $post_data ), true ); if ( is_wp_error( $result ) ) { $result->add_data( [ 'status' => 500 ] ); return $result; } } // Content built with Elementor's build-composition is staged as a draft (autosave): // publishing must promote it, or the live template keeps its old content. if ( isset( $status ) && 'publish' === $status ) { $staged = CompositionService::publish_staged_draft( $template_id ); if ( is_wp_error( $staged ) ) { return $staged; } } // Meta-only changes do not fire save_post; the template index must still be rebuilt. CacheManager::instance()->clear_transients( $template_id, get_post( $template_id ) ); return self::get_settings( $template_id ); } /** * Current settings of a template, plus where it applies and what blocks it from applying. * * @param int $template_id Template ID. * @return array|\WP_Error */ public static function get_settings( $template_id ) { $template = self::get_template( $template_id ); if ( is_wp_error( $template ) ) { return $template; } $template_id = $template->ID; $render_mode = get_post_meta( $template_id, 'ae_render_mode', true ); $settings = []; foreach ( TemplateSettingsSchema::get_shared_meta_keys() as $field => $meta_key ) { $value = get_post_meta( $template_id, $meta_key, true ); if ( '' !== $value && [] !== $value && 'render_mode' !== $field ) { $settings[ $field ] = $value; } } $open_in_editor = is_wp_error( self::check_not_open_in_editor( $template_id ) ); $notes = self::get_notes( $template, $render_mode, $settings ); if ( $open_in_editor ) { array_unshift( $notes, 'Open in the editor right now: changes made there are not in the saved version until saved with dynific-editor-save-document (or the user clicks Publish/Update).' ); } return [ 'template_id' => $template_id, 'title' => WidgetCatalog::clean( get_the_title( $template ) ), 'status' => $template->post_status, 'template_type' => self::get_template_type( $render_mode ), 'render_mode' => $render_mode, 'open_in_editor' => $open_in_editor, 'settings' => $settings, 'notes' => $notes, 'edit_url' => self::get_edit_url( $template_id ), ]; } /** * Set, reset or disable the per-post template override on several posts. All or nothing. * * @param array $args post_ids (int[]), action (assign|use_global|disable), template_id (for assign). * @return array|\WP_Error */ public static function assign_to_posts( array $args ) { $action = isset( $args['action'] ) ? sanitize_key( $args['action'] ) : 'assign'; $post_ids = array_values( array_unique( array_filter( array_map( 'absint', isset( $args['post_ids'] ) ? (array) $args['post_ids'] : [] ) ) ) ); if ( ! in_array( $action, [ 'assign', 'use_global', 'disable' ], true ) ) { return new \WP_Error( 'aep_invalid_action', __( 'Invalid action. Use assign, use_global or disable.', 'ae-pro' ), [ 'status' => 400 ] ); } if ( ! $post_ids || count( $post_ids ) > self::MAX_ASSIGN_POSTS ) { /* translators: %d: maximum number of posts. */ return new \WP_Error( 'aep_invalid_posts', sprintf( __( 'Pass 1 to %d post IDs.', 'ae-pro' ), self::MAX_ASSIGN_POSTS ), [ 'status' => 400 ] ); } $template = null; $template_type = ''; if ( 'assign' === $action ) { $template = self::get_template( isset( $args['template_id'] ) ? $args['template_id'] : 0 ); if ( is_wp_error( $template ) ) { return $template; } if ( 'post_template' !== get_post_meta( $template->ID, 'ae_render_mode', true ) ) { return new \WP_Error( 'aep_not_single_template', __( 'Only single post templates (template_type=single) can be assigned to posts.', 'ae-pro' ), [ 'status' => 400 ] ); } if ( 'publish' !== $template->post_status ) { return new \WP_Error( 'aep_template_not_published', __( 'The template is not published, so it would not show. Publish it first with dynific/update-template (ask the user).', 'ae-pro' ), [ 'status' => 409 ] ); } $template_type = get_post_meta( $template->ID, 'ae_rule_post_type', true ); } $posts = []; // Validate every post before changing any. foreach ( $post_ids as $post_id ) { $post = get_post( $post_id ); if ( ! $post || self::POST_TYPE === $post->post_type || ! is_post_type_viewable( $post->post_type ) ) { /* translators: %d: post ID. */ return new \WP_Error( 'aep_invalid_post', sprintf( __( 'Post %d does not exist or cannot use a template.', 'ae-pro' ), $post_id ), [ 'status' => 404 ] ); } if ( ! current_user_can( 'edit_post', $post_id ) ) { /* translators: %d: post ID. */ return new \WP_Error( 'aep_forbidden', sprintf( __( 'You are not allowed to edit post %d.', 'ae-pro' ), $post_id ), [ 'status' => 403 ] ); } // Free version only resolves templates for posts and pages. if ( ! aepro_is_pro_active() && ! in_array( $post->post_type, [ 'post', 'page' ], true ) ) { return new \WP_Error( 'aep_pro_required', __( 'Templates on custom post types require Dynific Addons Pro.', 'ae-pro' ), [ 'status' => 403 ] ); } $posts[] = $post; } $items = []; $warnings = []; foreach ( $posts as $post ) { if ( 'assign' === $action ) { update_post_meta( $post->ID, self::POST_TEMPLATE_META, (string) $template->ID ); if ( $template_type && $template_type !== $post->post_type ) { /* translators: 1: post ID, 2: post type, 3: template post type. */ $warnings[] = sprintf( __( 'Post %1$d is a "%2$s"; the template was designed for "%3$s".', 'ae-pro' ), $post->ID, $post->post_type, $template_type ); } } elseif ( 'disable' === $action ) { update_post_meta( $post->ID, self::POST_TEMPLATE_META, 'none' ); } else { delete_post_meta( $post->ID, self::POST_TEMPLATE_META ); } $items[] = [ 'post_id' => $post->ID, 'title' => WidgetCatalog::clean( get_the_title( $post ) ), 'post_type' => $post->post_type, 'url' => get_permalink( $post ), ]; } return [ 'action' => $action, 'template_id' => $template ? $template->ID : null, 'posts' => $items, 'warnings' => $warnings, ]; } /** * Elementor editor URL for a template. * * @param int $post_id Template ID. * @return string */ public static function get_edit_url( $post_id ) { return admin_url( 'post.php?post=' . absint( $post_id ) . '&action=elementor' ); } /** * @return \WP_Post|\WP_Error */ private static function get_template( $template_id ) { $template_id = absint( $template_id ); // get_post( 0 ) would return the global post. $template = $template_id ? get_post( $template_id ) : null; if ( ! $template || self::POST_TYPE !== $template->post_type || 'trash' === $template->post_status ) { return new \WP_Error( 'aep_not_template', __( 'Dynific template not found.', 'ae-pro' ), [ 'status' => 404 ] ); } return $template; } /** * Template type key → render mode, with the Pro lock. * * @return string|\WP_Error */ private static function resolve_render_mode( $template_type, $strict ) { $options = TemplateSettingsSchema::get_template_type_options(); $type = sanitize_key( (string) $template_type ); if ( ! isset( $options[ $type ] ) ) { return new \WP_Error( 'aep_invalid_type', __( 'Invalid template type.', 'ae-pro' ), [ 'status' => 400 ] ); } $render_mode = $options[ $type ]['render_mode']; if ( ! aepro_is_pro_active() && ! in_array( $render_mode, self::FREE_RENDER_MODES, true ) ) { if ( $strict ) { return new \WP_Error( 'aep_pro_required', __( 'This template type requires Dynific Addons Pro.', 'ae-pro' ), [ 'status' => 403 ] ); } $render_mode = 'post_template'; } return $render_mode; } /** * Status for an AI-created template: the requested one, or publish for layout types. * * @return string|\WP_Error */ private static function resolve_create_status( array $args, $render_mode ) { $can_publish = current_user_can( self::get_publish_capability() ); if ( ! isset( $args['status'] ) || '' === $args['status'] ) { return $can_publish && in_array( $render_mode, self::AUTO_PUBLISH_RENDER_MODES, true ) ? 'publish' : 'draft'; } $status = sanitize_key( $args['status'] ); if ( ! in_array( $status, self::STATUSES, true ) ) { return new \WP_Error( 'aep_invalid_status', __( 'Invalid status. Use draft, pending, publish or private.', 'ae-pro' ), [ 'status' => 400 ] ); } if ( in_array( $status, [ 'publish', 'private' ], true ) && ! $can_publish ) { return new \WP_Error( 'aep_forbidden', __( 'You are not allowed to publish templates.', 'ae-pro' ), [ 'status' => 403 ] ); } return $status; } private static function get_template_type( $render_mode ) { foreach ( TemplateSettingsSchema::get_template_type_options() as $key => $option ) { if ( $option['render_mode'] === $render_mode ) { return $key; } } return ''; } /** * Sanitized setting values keyed by shared meta field. * * @param array $args Input (create() keys). * @param bool $only_given true = only keys present in $args (update); false = every field with defaults (create). * @return array */ private static function sanitize_values( array $args, $only_given ) { $is_pro = aepro_is_pro_active(); // field => [ input key, sanitizer ]. $fields = [ 'usage_area' => [ 'usage_area', function ( $value ) { return TemplateSettingsSchema::sanitize_usage_area( $value, '' ); }, ], 'custom_usage_area' => [ 'custom_usage_area', [ __CLASS__, 'text' ] ], 'rule_post_type' => [ 'rule_post_type', function ( $value ) use ( $is_pro ) { $post_type = TemplateSettingsSchema::sanitize_post_type( $value, 'post' ); // Free version: restrict to built-in post types only. return ! $is_pro && ! in_array( $post_type, [ 'post', 'page' ], true ) ? 'post' : $post_type; }, ], 'preview_post' => [ 'preview_post_id', function ( $value ) { $id = absint( $value ); // Only posts the user may view (a private/draft post would leak into the preview). return $id && get_post( $id ) && aepro_user_can_view_post( $id ) ? $id : ''; }, ], 'rule_taxonomy' => [ 'rule_taxonomy', function ( $value ) { return TemplateSettingsSchema::sanitize_taxonomy( $value, '' ); }, ], 'preview_term' => [ 'preview_term', function ( $value ) { $id = absint( $value ); return $id && get_term( $id ) ? $id : ''; }, ], 'repeater_loc' => [ 'repeater_loc', function ( $value ) { return TemplateSettingsSchema::sanitize_repeater_location( $value, 'post' ); }, ], 'acf_field_type' => [ 'acf_field_type', function ( $value ) { return TemplateSettingsSchema::sanitize_acf_field_type( $value, 'repeater' ); }, ], 'acf_repeater' => [ 'acf_repeater_name', [ __CLASS__, 'text' ] ], 'acf_flexible' => [ 'acf_flexible_name', [ __CLASS__, 'text' ] ], 'apply_global' => [ 'apply_global', function ( $value ) { return ! empty( $value ) && 'false' !== $value ? 'true' : ''; }, ], 'hook_apply_on' => [ 'hook_apply_on', function ( $value ) { return TemplateSettingsSchema::sanitize_apply_on_values( (array) $value ); }, ], 'hook_post_types' => [ 'hook_post_types', function ( $value ) { return TemplateSettingsSchema::sanitize_post_type_list( (array) $value ); }, ], 'hook_posts_selected' => [ 'hook_posts_selected', [ __CLASS__, 'text' ] ], 'hook_posts_excluded' => [ 'hook_posts_excluded', [ __CLASS__, 'text' ] ], 'hook_taxonomies' => [ 'hook_taxonomies', function ( $value ) { return TemplateSettingsSchema::sanitize_taxonomy_list( (array) $value ); }, ], 'hook_terms_selected' => [ 'hook_terms_selected', [ __CLASS__, 'text' ] ], 'hook_terms_excluded' => [ 'hook_terms_excluded', [ __CLASS__, 'text' ] ], 'page_layout' => [ 'page_layout', function ( $value ) { return TemplateSettingsSchema::sanitize_page_layout( $value, '' ); }, ], ]; $values = []; foreach ( $fields as $field => $definition ) { list( $input_key, $sanitizer ) = $definition; if ( array_key_exists( $input_key, $args ) ) { $values[ $field ] = call_user_func( $sanitizer, $args[ $input_key ] ); } elseif ( ! $only_given ) { $values[ $field ] = call_user_func( $sanitizer, '' ); } } return $values; } private static function write_values( $post_id, array $values, $render_mode ) { $meta_keys = TemplateSettingsSchema::get_shared_meta_keys(); foreach ( $values as $field => $value ) { update_post_meta( $post_id, $meta_keys[ $field ], $value ); } if ( 'post_type_archive_template' === $render_mode && isset( $values['rule_post_type'] ) ) { update_post_meta( $post_id, $meta_keys['rule_post_archive'], $values['rule_post_type'] ); } } /** * Plain-language hints for the AI: is the template live, and does another template win? * * @return string[] */ private static function get_notes( \WP_Post $template, $render_mode, array $settings ) { $notes = []; $is_global = ! empty( $settings['apply_global'] ); if ( 'publish' !== $template->post_status ) { $notes[] = 'Not live: the template is ' . $template->post_status . '. It only applies to the site after it is published.'; } if ( 'post_template' === $render_mode ) { $post_type = isset( $settings['rule_post_type'] ) ? $settings['rule_post_type'] : 'post'; if ( $is_global ) { $notes[] = 'Applies to every "' . $post_type . '" post that has no own template override (assign one per post with dynific/assign-template-to-post).'; $others = CacheManager::instance()->get_post_global_templates( $post_type ); $others = is_array( $others ) ? array_diff( array_map( 'intval', array_keys( $others ) ), [ $template->ID ] ) : []; if ( $others ) { $notes[] = 'Other published global templates for "' . $post_type . '": ' . implode( ', ', $others ) . '. Only one is used; turn apply_global off on the others to be sure this one applies.'; } } else { $notes[] = 'Not applied globally (apply_global=false): it shows only on posts assigned with dynific/assign-template-to-post.'; } } if ( 'archive_template' === $render_mode && ! $is_global ) { $notes[] = 'Not applied globally (apply_global=false): set apply_global=true to use it for all "' . ( isset( $settings['rule_taxonomy'] ) ? $settings['rule_taxonomy'] : '' ) . '" archives.'; } return $notes; } private static function text( $value ) { return is_scalar( $value ) ? sanitize_text_field( (string) $value ) : ''; } }
Save File
Cancel