WP_REST_Server::READABLE, 'callback' => array( $this, 'get_custom_fields' ), 'permission_callback' => array( $this, 'check_permissions' ), 'args' => array( 'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 200, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'page' => array( 'type' => 'integer', 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), ), ), ) ); register_rest_route( 'aipt/v1', '/custom-variables', array( $this->custom_variables_read_endpoint(), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'save_custom_variable' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_custom_variable' ), 'permission_callback' => array( $this, 'check_permissions_write' ), ), ) ); } /** * The GET endpoint of `/custom-variables`, shared with the Business * build's registration of the same route. * * @return array */ public function custom_variables_read_endpoint() { return array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_custom_variables' ), 'permission_callback' => array( $this, 'check_permissions' ), 'args' => array( 'per_page' => array( 'type' => 'integer', 'default' => 100, 'minimum' => 1, 'maximum' => 200, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), 'page' => array( 'type' => 'integer', 'default' => 1, 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ), ), ); } /** * Read permission for custom variables and the custom-field catalog. * * Both feed the Settings page only (variables are site-wide prompt * configuration, the catalog lists product meta keys), so reads follow * the same capability as the writes. * * @return bool */ public function check_permissions() { return current_user_can( 'manage_aipt_settings' ); } /** * Write permission for custom variables. * * Custom variables are site-wide prompt configuration injected into every * generation, and the only UI that edits them lives on the Settings page * (manage_aipt_settings). Writes therefore follow the Settings write model: * manage_aipt_settings plus a valid REST nonce. * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public function check_permissions_write( $request ) { if ( ! current_user_can( 'manage_aipt_settings' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to manage custom variables.', 'ai-product-tools' ), array( 'status' => 403 ) ); } if ( ! \AIPT\Utils\RestNonceGuard::isCookieAuthenticated() ) { return true; } $nonce = ''; if ( $request instanceof WP_REST_Request ) { $nonce = $request->get_header( 'X-WP-Nonce' ); if ( empty( $nonce ) ) { $nonce = $request->get_param( '_wpnonce' ); } } $nonce = is_string( $nonce ) ? sanitize_text_field( wp_unslash( $nonce ) ) : ''; if ( '' === $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) { return new WP_Error( 'rest_cookie_invalid_nonce', __( 'Cookie check failed', 'ai-product-tools' ), array( 'status' => 403 ) ); } return true; } /** * Get saved custom variables * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_custom_variables($request) { try { $variables = get_option('aipt_custom_variables', array()); $unique_variables = array(); $seen_ids = array(); foreach ($variables as $variable) { if (isset($variable['id']) && !in_array($variable['id'], $seen_ids)) { $unique_variables[] = $variable; $seen_ids[] = $variable['id']; } } $variables = $unique_variables; $per_page = $request->get_param('per_page'); $page = $request->get_param('page'); $total = count($variables); $offset = ($page - 1) * $per_page; $paginated_variables = array_slice($variables, $offset, $per_page); $response = new WP_REST_Response($paginated_variables, 200); $response->header('X-WP-Total', $total); $response->header('X-WP-TotalPages', (int) ceil($total / $per_page)); return $response; } catch (\Exception $e) { return new WP_Error( 'aipt_custom_variables_error', __('Error fetching custom variables.', 'ai-product-tools'), array('status' => 500) ); } } /** * Saving a custom variable is Business. This handler only refuses it; * the Business build registers its own in its place * (`Premium\CustomFields\CustomVariablesController`). GET stays open * so stored variables keep resolving in prompts. * * @param WP_REST_Request $request Request object. * @return WP_Error */ public function save_custom_variable($request) { return self::custom_variables_plan_denial(); } /** * Deleting a custom variable is Business too; see save_custom_variable(). * * @param WP_REST_Request $request Request object. * @return WP_Error */ public function delete_custom_variable($request) { return self::custom_variables_plan_denial(); } /** * Plan denial shared by the custom variable write routes, here and in the * Business build's own handlers. * * Gate: 'aipt_custom_variables_can_edit', granted by Premium for any paid plan. * * @return WP_Error */ public static function custom_variables_plan_denial() { return PlanDenial::error( 'custom_variables', PlanDenial::PLAN_PAID, __( 'Business plan adds custom prompt variables.', 'ai-product-tools' ) ); } /** * Get default WooCommerce product fields * * @return array */ private function get_default_product_fields() { return array( array('key' => 'name', 'label' => __('Product Name', 'ai-product-tools')), array('key' => 'description', 'label' => __('Description', 'ai-product-tools')), array('key' => 'short_description', 'label' => __('Short Description', 'ai-product-tools')), array('key' => 'sku', 'label' => __('SKU', 'ai-product-tools')), array('key' => 'price', 'label' => __('Price', 'ai-product-tools')), array('key' => 'regular_price', 'label' => __('Regular Price', 'ai-product-tools')), array('key' => 'sale_price', 'label' => __('Sale Price', 'ai-product-tools')), array('key' => 'stock_status', 'label' => __('Stock Status', 'ai-product-tools')), array('key' => 'stock_quantity', 'label' => __('Stock Quantity', 'ai-product-tools')), array('key' => 'weight', 'label' => __('Weight', 'ai-product-tools')), array('key' => 'length', 'label' => __('Length', 'ai-product-tools')), array('key' => 'width', 'label' => __('Width', 'ai-product-tools')), array('key' => 'height', 'label' => __('Height', 'ai-product-tools')), ); } /** * Get WooCommerce product attributes * * @return array */ private function get_product_attributes() { try { $fields = array(); if (function_exists('wc_get_attribute_taxonomies')) { $attributes = wc_get_attribute_taxonomies(); foreach ($attributes as $attr) { $key = 'pa_' . $attr->attribute_name; $label = !empty($attr->attribute_label) ? $attr->attribute_label : wc_attribute_label($key); $fields[$key] = $label; } } if (function_exists('wc_get_products')) { $products = wc_get_products(array( 'limit' => 50, 'return' => 'objects', 'status' => array('publish', 'private', 'draft') )); foreach ($products as $product) { $product_attributes = $product->get_attributes(); if (empty($product_attributes)) { continue; } foreach ($product_attributes as $attribute) { $attr_name = $attribute->get_name(); $label = function_exists('wc_attribute_label') ? wc_attribute_label($attr_name) : ucfirst(str_replace('_', ' ', $attr_name)); if (!isset($fields[$attr_name])) { $fields[$attr_name] = $label; } } } } $result = array(); foreach ($fields as $key => $label) { $result[] = array( 'key' => $key, 'label' => $label, ); } return $result; } catch (\Exception $e) { return array(); } } /** * Get ACF fields if available * * @return array */ private function get_acf_fields() { if (!function_exists('acf_get_field_groups')) { return array(); } $acf_fields = array(); $field_groups = acf_get_field_groups(array('post_type' => 'product')); foreach ($field_groups as $group) { $fields = acf_get_fields($group); foreach ($fields as $field) { $acf_fields[] = array( 'key' => $field['name'], 'label' => $field['label'] ); } } return $acf_fields; } /** * Get custom meta fields * * @return array */ private function get_custom_meta_fields() { global $wpdb; $cached = get_transient( self::META_KEYS_TRANSIENT ); if ( is_array( $cached ) ) { return $cached; } try { $query = $wpdb->prepare( "SELECT DISTINCT pm.meta_key FROM {$wpdb->postmeta} pm INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE p.post_type = %s AND pm.meta_key NOT LIKE %s AND pm.meta_key NOT IN ('_edit_lock', '_edit_last', '_thumbnail_id') ORDER BY pm.meta_key ASC", 'product', $wpdb->esc_like('_') . '%' ); $results = $wpdb->get_results($query); if ( ! is_array( $results ) ) { if ( $wpdb->last_error ) { } return array(); } $fields = array_map(function($field) { return array( 'key' => $field->meta_key, 'label' => ucwords(str_replace('_', ' ', $field->meta_key)) ); }, $results); set_transient( self::META_KEYS_TRANSIENT, $fields, self::META_KEYS_TTL ); return $fields; } catch (\Exception $e) { return array(); } } /** * Get all custom fields * * @param WP_REST_Request $request Request object. * * @return WP_REST_Response|WP_Error */ public function get_custom_fields($request) { try { $fields = array( 'default' => array( 'label' => __('Default Fields', 'ai-product-tools'), 'fields' => $this->get_default_product_fields() ), 'attributes' => array( 'label' => __('Product Attributes', 'ai-product-tools'), 'fields' => $this->get_product_attributes() ), 'taxonomies' => array( 'label' => __('Taxonomies', 'ai-product-tools'), 'fields' => array( array('key' => 'product_cat', 'label' => __('Product Categories', 'ai-product-tools')), array('key' => 'product_tag', 'label' => __('Product Tags', 'ai-product-tools')) ) ), 'custom_meta' => array( 'label' => __('Custom Fields', 'ai-product-tools'), 'fields' => $this->get_custom_meta_fields() ) ); $acf_fields = $this->get_acf_fields(); if (!empty($acf_fields)) { $fields['acf'] = array( 'label' => __('Advanced Custom Fields', 'ai-product-tools'), 'fields' => $acf_fields ); } foreach ($fields as $group_key => $group) { if (!isset($group['label']) || !isset($group['fields']) || !is_array($group['fields'])) { unset($fields[$group_key]); } } return new WP_REST_Response( $this->paginate_open_ended_groups( $fields, $request ), 200 ); } catch (\Exception $e) { return new WP_Error( 'aipt_custom_fields_error', __('Error fetching custom fields.', 'ai-product-tools'), array('status' => 500) ); } } /** * Slice the groups that grow with the store (custom meta and ACF) by the * request's page and per_page. Without per_page, as for internal callers * and the Settings modal, nothing is sliced. * * @param array $fields Groups keyed by group key. * @param WP_REST_Request|null $request Request object, or null for internal callers. * @return array */ private function paginate_open_ended_groups( array $fields, $request ) { if ( ! $request instanceof WP_REST_Request ) { return $fields; } $per_page = (int) $request->get_param( 'per_page' ); $page = max( 1, (int) $request->get_param( 'page' ) ); if ( $per_page < 1 ) { return $fields; } foreach ( array( 'custom_meta', 'acf' ) as $group_key ) { if ( isset( $fields[ $group_key ] ) ) { $fields[ $group_key ]['fields'] = array_slice( $fields[ $group_key ]['fields'], ( $page - 1 ) * $per_page, $per_page ); } } return $fields; } }