prefix-derived table names or keys from hardcoded internal arrays (never request input). Direct queries hit plugin-owned tables that have no WP REST/cache layer. Variables flagged as non-prefixed are local helpers / loop indices, not globals. CSV import/export streams use fopen()/fread()/fwrite()/fclose() because WP_Filesystem_API has no equivalent streaming interface and the operations are admin-only. set_time_limit()/ini_set() are needed inside long-running CSV exports + activation cleanup; they're capability-gated and short-circuit when running under PHP-FPM. /* Plugin Name: Rooster One Plugin URI: https://rooster.systems/one/ Description: The unified AI commerce & content suite — one plugin does the work of a whole stack. Anthropic/Voyage AI: messaging, recommendations, attribution, loyalty, merchandising. Version: 10.2 Requires at least: 7.0 Tested up to: 7.0 Requires PHP: 7.4 Author: Oxford Metadata Ltd Author URI: https://oxfordmetadata.co.uk License: GPL3 Tags: ai-chat, content-recommendations, semantic-search, conversational-ai, claude */ // Ensure the plugin is only loaded within WordPress if (!defined('ABSPATH')) { exit; } /** * Centralised debug logger. Calls error_log() only when WP_DEBUG and * WP_DEBUG_LOG are both enabled, so production sites stay quiet by default. * Used in place of bare error_log() throughout the plugin. * * @param string|mixed $message Message or value to log. */ if (!function_exists('aieo_debug_log')) { function aieo_debug_log($message) { if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Single gated entry point for plugin diagnostics. error_log(is_scalar($message) ? (string) $message : wp_json_encode($message)); } } } /** * Prefer the plugin's BUNDLED translations over an incomplete wp.org language * pack. WordPress loads .mo/.l10n.php from wp-content/languages/plugins/ (the * translate.wordpress.org GlotPress pack) BEFORE the plugin's own languages/ * dir and returns early — so a stub pack (e.g. the 10-string Greek pack) would * shadow our full bundled file and leave most of the admin UI in English. * Redirect any global-dir load for our domain to the bundled file whenever we * ship one for that locale; other locales keep using their wp.org packs. */ if (!function_exists('aieo_prefer_bundled_textdomain')) { function aieo_prefer_bundled_textdomain($mofile, $domain) { if ('ai-eshop-optimizer' !== $domain) { return $mofile; } // Only override when WP is about to load from the global languages dir. if (0 === strpos($mofile, WP_LANG_DIR)) { $bundled = plugin_dir_path(__FILE__) . 'languages/' . basename($mofile); if (is_readable($bundled)) { return $bundled; } } return $mofile; } } add_filter('load_textdomain_mofile', 'aieo_prefer_bundled_textdomain', 10, 2); /** * Stop WordPress from (re)installing the incomplete translate.wordpress.org * language pack for this plugin. We are listed on wp.org, so WP's translations * updater keeps fetching the community GlotPress pack — which currently has * only ~6 Greek strings — into wp-content/languages/plugins/ on every * translations cron and plugin update. That stub then shows up as a second, * "stale" Greek file in Loco; although aieo_prefer_bundled_textdomain() above * already redirects loading back to our COMPLETE bundled catalogue, the stub * keeps reappearing, confuses translators and clutters the languages dir. * Dropping our slug from the update transient means the stub is never fetched. */ if (!function_exists('aieo_block_wporg_translation_pack')) { function aieo_block_wporg_translation_pack($transient) { if (isset($transient->translations) && is_array($transient->translations)) { foreach ($transient->translations as $i => $t) { if (isset($t['slug']) && 'ai-eshop-optimizer' === $t['slug']) { unset($transient->translations[$i]); } } $transient->translations = array_values($transient->translations); } return $transient; } } add_filter('pre_set_site_transient_update_plugins', 'aieo_block_wporg_translation_pack'); add_filter('site_transient_update_plugins', 'aieo_block_wporg_translation_pack'); // Load text domain IMMEDIATELY for AJAX requests (before any classes load) // This ensures translations are available during whitelisted AJAX requests if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { // phpcs:ignore PluginCheck.CodeAnalysis.DiscouragedFunctions.load_plugin_textdomainFound -- Fallback for non-WordPress.org hosted translations load_plugin_textdomain( 'ai-eshop-optimizer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); } if (!defined('AIEO_VERSION')) { define('AIEO_VERSION', '10.2'); } // Schema/data-migration counter, independent of the plugin version. Bumped when // aieo_run_db_migrations() gains a new step. v1=#33 sessions index trim, // v2=#34 reco reverse-ref table + backfill, v3=#35 analytics atomic-swap procs. if (!defined('AIEO_DB_VERSION')) { define('AIEO_DB_VERSION', 3); } // Guarded: the runtime plugin loads FIRST (WP sorts active_plugins and // "-runtime" sorts before "/"), and it pre-seeds AIEO_FILE/AIEO_DIR/AIEO_URI // (pointing at THIS plugin's path, same values) so its bundled classes work // even when the core fatals. Unguarded re-defines here warned on every // request under PHP 8.5 and become fatal on PHP 9. if (!defined('AIEO_FILE')) { define('AIEO_FILE', __FILE__); } if (!defined('AIEO_BASE')) { define('AIEO_BASE', trailingslashit(plugin_basename(AIEO_FILE))); } if (!defined('AIEO_DIR')) { define('AIEO_DIR', plugin_dir_path(__FILE__)); } if (!defined('AIEO_URI')) { define('AIEO_URI', plugin_dir_url(__FILE__)); } define('AIEO_orders_upload_endpoint', 'https://uploads.eshop-optimizer.com/wp-json/aieo/v1/order_uploads'); // Capability required to access the plugin admin pages // Using 'edit_pages' allows editor, shop_manager, and admin roles to access // (edit_pages is shared by Editor, Shop Manager, and Administrator) define('AIEO_CAPABILITY', 'edit_pages'); // Declare WooCommerce feature compatibility if WooCommerce is active. // `variation_gallery` + `wc-visual-attribute` are WC 10.9+ experimental features; // AIEO writes its data into WC's canonical keys so they Just Work when toggled on. add_action('before_woocommerce_init', function () { if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) { \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true); \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('variation_gallery', __FILE__, true); \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('wc-visual-attribute', __FILE__, true); } }); // Load the plugin class require_once plugin_dir_path(__FILE__) . '/includes/class-eshop-optimizer.php'; // Low-balance AI-credit email alerts (daily cron poll of the Rooster Portal + // operator-chosen billing email/threshold). Self-contained. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-credit-notifier.php'; AIEO_Credit_Notifier::init(); // Self-serve Rooster account signup (email → double opt-in → auto-connect → // 14-day Pro trial). Optional by construction: registers admin handlers and a // dismissible notice only; no request leaves the site until the operator // explicitly submits the form. Core plugin only. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-rooster-signup.php'; // Canonical AI-credit attribution source slugs (X-OM-Source). Loaded early so // every AI caller can tag itself. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-ai-sources.php'; // SQL layer split (Phase-1 perf, 2026-06-13). sprocs.php (~6.3k lines of // CREATE PROCEDURE installers, which itself pulls in dmm-schema.php ~3.5k // lines + brand-vitals-schema.php) used to load HERE on every request, // including anonymous storefront page views that never touch it. Now: // • sql-runtime-helpers.php — the handful of helpers runtime code calls // (charset/collate, aieo_dbdelta, table probes, role columns) — always; // • the full DDL layer — only where installers/exports actually run: // admin, AJAX, cron, CLI, plus activation/deactivation/upgrade via // aieo_load_sql_layer() (called inside those entry points). require_once plugin_dir_path(__FILE__) . '/includes/sql/sql-runtime-helpers.php'; // Armed at load, not on an init hook: a stored-procedure CALL can be issued from // anything (cron, CLI, an mu-plugin, another plugin), so the guard has to be in // place before the first query we could possibly be blamed for. Idempotent, and // one client-side flag check per query. if (function_exists('aieo_install_sproc_drain_guard')) { aieo_install_sproc_drain_guard(); } /** * Load the full SQL/DDL layer (sprocs + dmm-schema + brand-vitals schema) * on demand. Idempotent. MUST run before any aieo_create_* / aieo_drop_sp_* * call — the activation / deactivation / upgrade entry points all invoke it * as their first statement, so every call path is covered regardless of * request context. */ function aieo_load_sql_layer() { require_once plugin_dir_path(__FILE__) . '/includes/sql/sprocs.php'; } if (is_admin() || wp_doing_ajax() || wp_doing_cron() || (defined('WP_CLI') && WP_CLI)) { aieo_load_sql_layer(); } // Load Session Tracker (Core analytics functionality). // AIEO Session Tracker has a canonical copy at // ai-eshop-optimizer-runtime/includes/class-aieo-session-tracker.php // (moved 2026-05-16 — see runtime plugin's STATUS.md). When the // autoloader mu-plugin AND the runtime plugin are present, this // require_once is a no-op (the autoloader resolved the class first). // When the admin plugin is installed STANDALONE — typical for a fresh // wp.org download where neither the autoloader nor the runtime ship — // the require_once loads our own fallback copy. This guard is the // stability boundary that lets the admin plugin work on any host // without external prerequisites. if ( ! class_exists( 'AIEO_Session_Tracker' ) ) { require_once plugin_dir_path( __FILE__ ) . '/includes/class-aieo-session-tracker.php'; } // Load Session Schema Migrator (Database migration tools) require_once plugin_dir_path(__FILE__) . '/includes/class-session-schema-migrator.php'; // Load Recommendations Cache (Multi-tier cache for product recommendations) require_once plugin_dir_path(__FILE__) . '/includes/class-recommendations-cache.php'; // Serve built *.min.css / *.min.js via a global URL-rewrite filter (no // per-enqueue edits). No-ops when SCRIPT_DEBUG is on or a .min file is absent. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-asset-min.php'; AIEO_Asset_Min::register(); // Central wp_set_script_translations() wiring for all JS handles that use wp.i18n. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-script-translations.php'; require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-admin-color.php'; // Per-device (desktop/mobile) value controls for EVERY AIEO block — adds the // editor "Responsive (per device)" panel + render-time scoped CSS via global // filters keyed on aieo/* (covers all 19 blocks + any future one automatically). require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-responsive-controls.php'; AIEO_Responsive_Controls::register(); // wpDataTables report-page enhancements (glass tooltips + origin tagging), // ported from the standalone om-wpdt-enhancements plugin. register() only // adds hooks — the front-end enqueue is page-scoped (aieo_wpdt_enhance_pages // option, managed on Tools → Product/Orders analytics) and the origin-tag // fires solely on the wdt_save_table_frontend AJAX action. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-wpdt-enhancements.php'; AIEO_WPDT_Enhancements::register(); // Load Wishlist (favorites storage + AJAX endpoints; phase-1 of the // migration from om-product-page-essentials). // AIEO_Wishlist has a canonical copy in the runtime plugin // (ai-eshop-optimizer-runtime/includes/class-aieo-wishlist.php — moved // 2026-05-06). With autoloader+runtime present, the require_once below // is a no-op. Without them, the admin plugin loads its own fallback // copy so wishlist still works on a standalone install. if ( ! class_exists( 'AIEO_Wishlist' ) ) { require_once plugin_dir_path( __FILE__ ) . '/includes/class-aieo-wishlist.php'; } // Phase-2 PPE compatibility shim — proxies om_ppe_wishlist_toggle → // aieo_wishlist_toggle so themes / widgets / external callers that // reference the legacy endpoint keep working after PPE's wishlist // module is disabled. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-wishlist-compat.php'; // Star Ratings (AIEO_Ratings) — canonical copy lives in the runtime // plugin (ai-eshop-optimizer-runtime/includes/class-aieo-ratings.php — // moved 2026-05-06). With autoloader+runtime present, the require_once // below is a no-op. Without them, the admin plugin loads its own // fallback copy so ratings still work on a standalone install. The // REST sibling class is admin-only and always loads from here. if ( ! class_exists( 'AIEO_Ratings' ) ) { require_once plugin_dir_path( __FILE__ ) . '/includes/class-aieo-ratings.php'; } require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-ratings-rest.php'; // WooCommerce native reviews as a first-class rating source. Most shops run // WC reviews as their default (often only) rating signal, so this mirrors // them into wp_aieo_ratings permanently — backfill + full comment lifecycle. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-ratings-wc-bridge.php'; // Per-brand flat projection (sibling of core_product_vitals). Read+refresh // model for wp_aieo_core_brand_vitals — sole front-end source for every // brand-shopping surface (A-Z catalogue, sliders, archive, navigator). require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-core-brand-vitals.php'; // Classic-PHP shortcode wrappers for the three "post-related-*" blocks // (brands / categories / needs). Re-registers the legacy Pods-era // `[related_brand_shortcode]` and `[secondary_brand_shortcode]` aliases // so themes that hard-code them in single.php keep working. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-post-relations-shortcodes.php'; // FAQ content type (`faq`) + grouping taxonomy (`faq_group`) + the [faq] / // [aieo_faq] accordion shortcode (self-contained, own scoped CSS). The entry // list is surfaced from the DMM "Custom Post Types" nav group, not a stray // top-level menu. Self-instantiates at file end. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-faq.php'; // The store CPTs — theme-owned `store_location` + plugin-owned `aieo_store` — // are surfaced from the DMM "Custom Post Types" nav group, so drop their stray // top-level sidebar menus. (The `faq` CPT already registers show_in_menu=false.) add_filter('register_post_type_args', function ($args, $post_type) { if (in_array($post_type, array('store_location', 'aieo_store'), true)) { $args['show_in_menu'] = false; } return $args; }, 20, 2); // `aieo/menu` block — renders a WP menu as an inline strip (header) or // accordion (footer); replaces the roosterx-ff [ff_simple_menu] shortcode + // the hand-coded footer markup with a proper menu-picker block. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-menu-block.php'; // `aieo/header-actions` block — extensible header icon row (menu/navigator burger // now; account/stores later). Sits inside .ff-header__actions; the menu icon opens // the Navigator via the theme's data-aieo-navigator-trigger handler. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-header-actions-block.php'; // `aieo/trust-badges` block — configurable trust strip (icon + title + // subtitle columns); replaces the hand-coded ff-trust-strip / roosterx trust // tiles. Bundled in the runtime too (class_exists-guarded). require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-trust-badges-block.php'; // `aieo/social-icons` block — social links (FB/IG/Pinterest/YouTube/TikTok) with // colour, shape (round/square) + responsive gap. Bundled in the runtime too. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-social-icons-block.php'; // Per-customer engagement-signal query helpers (favourite brands, // wishlisted brands, rated brands) — bridges brand_affinity_json + // wp_aieo_wishlist + wp_aieo_ratings to blocks/navigator/push triggers. require_once plugin_dir_path(__FILE__) . '/includes/dmm/class-aieo-customer-intelligence-query.php'; // Attribution — source tracking for every add-to-cart event. // See ATTRIBUTION-SCHEMA-BRIEF.md for the schema + GA4 contract. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-attribution.php'; // Canonical read-through for per-order facts (revenue + channel). D1 single- // source-of-truth accessor — see documentation/ORDER_DATA_MAP.md. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-order-facts.php'; // ROI Wizard cost ledger (operator/connector ad-spend per dimension per period). // See documentation/ROI_WIZARD_PLAN.md. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-attribution-cost.php'; if ( class_exists( 'AIEO_Attribution_Cost' ) ) { AIEO_Attribution_Cost::init(); } // Shared attribution-block renderer (styled table + channel vocabulary) used // by BOTH the order-email origin block and the Gravity notification block. // Bundled identically in the runtime plugin (checkout-whitelist delegate) — // class_exists-guarded so whichever copy loads first wins. if ( ! class_exists( 'AIEO_Attribution_Block' ) ) { require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-attribution-block.php'; } // Order origin + attribution block in the staff (admin) order emails — replaces // the unreliable PixelYourSite origin line (marketplace vs Site + channel/campaign). // Also bundled in the runtime plugin: optimised sites trim THIS plugin off // checkout requests, where synchronous gateways (cheque/COD/bacs) send the // staff new-order email — the runtime delegate renders the block there. if ( ! class_exists( 'AIEO_Order_Origin_Email' ) ) { require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-order-origin-email.php'; } if ( class_exists( 'AIEO_Order_Origin_Email' ) ) { AIEO_Order_Origin_Email::register(); } // Google Ads generation (§20) — compose a campaign from what the shop already // knows, create it PAUSED, and let a human decide whether it ever spends. The // classes load unconditionally because the composer is also reachable from the // Claude abilities, not only from the admin tab. require_once plugin_dir_path( __FILE__ ) . '/includes/ads/class-aieo-ads-plan.php'; require_once plugin_dir_path( __FILE__ ) . '/includes/ads/class-aieo-ads-composer.php'; require_once plugin_dir_path( __FILE__ ) . '/includes/ads/class-aieo-ads-google-driver.php'; // Gravity Forms choice-field distributions — turns every checkbox/select answer // into an audience breakdown that ad copy and targeting can be grounded in. require_once plugin_dir_path( __FILE__ ) . '/includes/class-aieo-form-insights.php'; // A new submission changes the numbers, so drop the cached report rather than // letting the merchant read a distribution that is up to 15 minutes stale. add_action( 'gform_after_submission', function ( $entry, $form ) { if ( class_exists( 'AIEO_Form_Insights' ) && is_array( $form ) && ! empty( $form['id'] ) ) { AIEO_Form_Insights::flush( (int) $form['id'] ); } unset( $entry ); }, 20, 2 ); // ROI Wizard subtab — self-registers onto the DMM module bus when it loads // (same pattern as the marketplace-order-importer). See documentation/ROI_WIZARD_PLAN.md. add_action( 'aieo_dmm_register_dynamic_modules', function ( $dmm ) { if ( ! class_exists( 'AIEO_DMM_Module_Base' ) ) { return; } require_once plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-roi-wizard.php'; require_once plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-ad-connectors.php'; require_once plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-utm-explorer.php'; // Guarded: the Ads tab is optional, and a partial deploy that is missing it // must degrade to "no Ads tab" rather than fataling the whole admin. $aieo_ads_module = plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-ads.php'; if ( file_exists( $aieo_ads_module ) ) { require_once $aieo_ads_module; } if ( is_object( $dmm ) && method_exists( $dmm, 'register_module' ) ) { if ( class_exists( 'AIEO_DMM_ROI_Wizard' ) ) { $dmm->register_module( new AIEO_DMM_ROI_Wizard() ); } if ( class_exists( 'AIEO_DMM_Ad_Connectors' ) ) { $dmm->register_module( new AIEO_DMM_Ad_Connectors() ); } if ( class_exists( 'AIEO_DMM_Ads' ) ) { $dmm->register_module( new AIEO_DMM_Ads() ); } // UTM Explorer is consolidated onto the ROI Wizard page (the ROI Wizard // composes + renders it), so it is required above but NOT a separate tab. } }, 10, 1 ); // Tier-2 session × attribution bridge — query helpers JOINing the // Session Tracker tables with the Attribution Engine table for joint // engagement-attribution analytics. Backs 11 Claude abilities. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-session-attribution-bridge.php'; // Heuristic conversion-probability model — buckets historical sessions // on engagement (scroll-depth × time-on-page) and reports empirical // P(cart-add) per bucket. Backs the buy-probability-* abilities. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-conversion-probability-model.php'; // Perf — source-level PageSpeed mitigations: non-critical CSS deferral // + LCP image preload on PDP. Hookless until front-end render. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-perf.php'; // AIEO Star Ratings → SEO-plugin schema bridge. Feeds the materialized // `wp_aieo_rating_stats` aggregate into Product JSON-LD emitted by // AIOSEO / Yoast / Rank Math so Google's rich snippet uses the AIEO // star data (WC reviews are off on this site). Falls back to its own // JSON-LD block if no SEO plugin is detected. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-ratings-schema.php'; // SEO engine (Stage A). The offline head BUILDER (AIEO_SEO_Head_Builder) // materialises wp_aieo_seo_head_cache on save/cron; the thin, bundled // AIEO_SEO_Head emitter serves that cache with one read. All AIEO_SEO_* // classes autoload from includes/seo/ via the mu-plugin autoloader. The // builder + store (AIEO_SEO_Store) are core-only; the emitter is bundled in // both plugins. The builder self-gates on AIEO_SEO_Store::is_active_provider() // so registering its hooks is harmless while AIOSEO is still active. if ( class_exists( 'AIEO_SEO_Head_Builder' ) ) { AIEO_SEO_Head_Builder::register_build_hooks(); } // SEO editor metabox (admin only) — the canonical-category picker + SEO title / // meta / canonical-override / noindex, all written to wp_aieo_seo_posts // (nothing in postmeta). Allowed regardless of provider state so operators can // pin canonical categories before cut-over. if ( is_admin() && class_exists( 'AIEO_SEO_Post_Metabox' ) ) { AIEO_SEO_Post_Metabox::register(); } // Slug monitor (admin only, A2) — auto-create a 301 when a published object's // slug/URL changes so existing links don't 404. Writes via AIEO_SEO_Redirects. if ( is_admin() && class_exists( 'AIEO_SEO_Slug_Monitor' ) ) { AIEO_SEO_Slug_Monitor::register(); } // SEO schema self-heal — the same maybe_install() delta pattern every other // feature uses (Carts/Ratings/Attribution/Consent). Creates/upgrades the SEO // tables when the bundled schema version is newer than what's installed, so an // existing site picks up new tables (e.g. the A2 redirects + 404 log) on the // next admin load after a file upload — no reactivation / version bump needed. if ( is_admin() ) { add_action( 'admin_init', static function () { $seo_schema = AIEO_DIR . 'includes/dmm/sql/seo-schema.php'; if ( file_exists( $seo_schema ) ) { require_once $seo_schema; if ( function_exists( 'aieo_seo_maybe_install' ) ) { aieo_seo_maybe_install(); } } }, 5 ); // Identity substrate (Customer Intelligence Core, Phase A) — same self-heal // net: wp_aieo_subjects + wp_aieo_session_identity install on the next admin // load after a file upload, no reactivation / version bump needed. add_action( 'admin_init', static function () { $subjects_schema = AIEO_DIR . 'includes/dmm/sql/subjects-schema.php'; if ( file_exists( $subjects_schema ) ) { require_once $subjects_schema; if ( function_exists( 'aieo_subjects_maybe_install' ) ) { aieo_subjects_maybe_install(); } } }, 5 ); // Social (site-owned apps, master plan R3′) local schema self-heal. add_action( 'admin_init', static function () { $social_schema = AIEO_DIR . 'includes/dmm/sql/social-schema.php'; if ( file_exists( $social_schema ) ) { require_once $social_schema; if ( function_exists( 'aieo_social_install_schema' ) && get_option( 'aieo_social_schema_version' ) !== ( defined( 'AIEO_SOCIAL_SCHEMA_VERSION' ) ? AIEO_SOCIAL_SCHEMA_VERSION : '1' ) ) { aieo_social_install_schema(); update_option( 'aieo_social_schema_version', defined( 'AIEO_SOCIAL_SCHEMA_VERSION' ) ? AIEO_SOCIAL_SCHEMA_VERSION : '1', false ); } } }, 5 ); } // ── Social (site-owned) runtime bootstrap ────────────────────────────────── // Loaded on EVERY request (not just admin): the OAuth callback + publish paths // are REST/cron, not admin. Each require is file_exists-guarded so a partial // deploy can never fatal. The shop owns its platform apps + tokens locally // (R3′); nothing here is portal-brokered. add_action( 'plugins_loaded', static function () { foreach ( array( 'includes/social/class-aieo-social-store.php', 'includes/social/connectors/class-aieo-social-connector-x.php', 'includes/social/connectors/class-aieo-social-connector-linkedin.php', 'includes/social/connectors/class-aieo-social-connector-tiktok.php', 'includes/social/class-aieo-social-oauth.php', 'includes/social/drivers/class-aieo-social-driver-base.php', 'includes/social/drivers/class-aieo-social-driver-facebook.php', 'includes/social/drivers/class-aieo-social-driver-instagram.php', 'includes/social/drivers/class-aieo-social-driver-x.php', 'includes/social/drivers/class-aieo-social-driver-linkedin.php', 'includes/social/drivers/class-aieo-social-driver-tiktok.php', 'includes/social/class-aieo-social-ai-writer.php', 'includes/social/class-aieo-social-video.php', 'includes/social/class-aieo-social-video-metabox.php', 'includes/social/class-aieo-social-metabox.php', 'includes/social/class-aieo-social-jobs.php', 'includes/social/class-aieo-social-broadcast.php', 'includes/social/class-aieo-social-outcome-reporter.php', 'includes/social/class-aieo-social-boost.php', 'includes/class-aieo-product-affinity.php', // Before the boost slate and the SEO pillars, both of which read it. 'includes/class-aieo-basket-role.php', 'includes/class-aieo-boost-candidates.php', 'includes/class-aieo-campaign-forecasts.php', ) as $rel ) { $abs = AIEO_DIR . $rel; if ( file_exists( $abs ) ) { require_once $abs; } } if ( class_exists( 'AIEO_Social_Jobs' ) ) { AIEO_Social_Jobs::init(); } if ( class_exists( 'AIEO_Social_Outcome_Reporter' ) ) { AIEO_Social_Outcome_Reporter::init(); } if ( class_exists( 'AIEO_Boost_Candidates' ) ) { AIEO_Boost_Candidates::init(); } // Behaviour-informed SEO opportunity grid. Sits next to the boost scorer // because the boost scorer READS its table (the seo_opportunity component). // It shipped for a long time with a rebuild() nobody scheduled — see // AIEO_SEO_Opportunity_Scorer::init() for why that mattered. Self-gated on // seo.enabled; scheduling happens on `init`. // Explicit require rather than trusting the mu-plugin autoloader: this is // the one class whose absence was invisible for months, so its wiring does // not get to depend on a loader that may not be installed everywhere. $aieo_opp_file = AIEO_DIR . 'includes/seo/class-aieo-seo-opportunity-scorer.php'; if ( file_exists( $aieo_opp_file ) ) { require_once $aieo_opp_file; } if ( class_exists( 'AIEO_SEO_Opportunity_Scorer' ) ) { AIEO_SEO_Opportunity_Scorer::init(); } if ( class_exists( 'AIEO_Campaign_Forecasts' ) ) { AIEO_Campaign_Forecasts::init(); } if ( class_exists( 'AIEO_Social_OAuth' ) ) { add_action( 'rest_api_init', array( 'AIEO_Social_OAuth', 'register_routes' ) ); } if ( class_exists( 'AIEO_Social_Metabox' ) ) { AIEO_Social_Metabox::register(); } if ( class_exists( 'AIEO_Social_Video_Metabox' ) ) { AIEO_Social_Video_Metabox::register(); } // Register the site-owned platform drivers built on the Facebook pattern. add_filter( 'aieo_social_platforms', static function ( $drivers ) { foreach ( array( 'instagram' => 'AIEO_Social_Driver_Instagram', 'x' => 'AIEO_Social_Driver_X', 'linkedin' => 'AIEO_Social_Driver_Linkedin', 'tiktok' => 'AIEO_Social_Driver_Tiktok', ) as $code => $class ) { if ( class_exists( $class ) ) { $drivers[ $code ] = $class; } } return $drivers; } ); }, 9 ); // Signal registry — the declarative catalogue of EVERY metric this plugin // computes (table, producer, cron, consumers) plus cheap live health. Read it // before building any new metric: this exists because a scorer that already // shipped got rebuilt from scratch by someone who had no way to discover it. // Admin/CLI only: it is a diagnostic catalogue, not a runtime dependency, and // the front end must not pay to load it. Everything that needs it outside those // contexts (the Claude ability, the opportunity-scorer cron) lazy-requires it. // file_exists-guarded like every other require in this file: an UNGUARDED // require_once here white-screens all of wp-admin AND every WP-CLI command on // any build where the file is missing (a .distignore slip, a half-finished // rsync, the runtime/core plugin split where only one copy carries it). A // diagnostic catalogue must never be able to take the site down; the three // callers that need it outside this path already lazy-require it defensively. if ( is_admin() || ( defined( 'WP_CLI' ) && WP_CLI ) ) { $aieo_registry_file = plugin_dir_path( __FILE__ ) . 'includes/class-aieo-signal-registry.php'; if ( file_exists( $aieo_registry_file ) ) { require_once $aieo_registry_file; } } // SEO score column on the product/post/page list tables (toggle via Screen // Options). Reads stored scores in one query per page; gated on seo.enabled. if ( is_admin() && class_exists( 'AIEO_SEO_Admin_Columns' ) ) { AIEO_SEO_Admin_Columns::register(); } // Goal tracker (site-profiles Phase 3): server-side conversion events (form // submits, newsletter signups, LearnDash enrol/complete, registrations) into // the session event stream — the content analog of add-to-cart. Consent-safe // by construction (records only alongside the consented session cookie). // Capability shim (products are content, content is products): 60+ AIEO // handlers historically gate on manage_woocommerce, which NO user holds on // sites without WooCommerce (quhoma, alfavitari, portals) - every rebuild/ // export button dies with Permission denied there. Grant it to // administrators when WooCommerce is absent; zero change on shops. add_filter('user_has_cap', function ($allcaps) { if (!empty($allcaps['manage_options']) && empty($allcaps['manage_woocommerce']) && !class_exists('WooCommerce')) { $allcaps['manage_woocommerce'] = true; } return $allcaps; }); // Canonical landing/campaign stats — parses landing_path + utm_* out of the // session statics and keeps the durable daily rollup. Registers only the // aieo_archive_run hook here; the heavy lifting runs inside the crons. if ( file_exists( AIEO_DIR . 'includes/class-aieo-landing-stats.php' ) ) { require_once AIEO_DIR . 'includes/class-aieo-landing-stats.php'; if ( class_exists( 'AIEO_Landing_Stats' ) ) { AIEO_Landing_Stats::register(); } } // Goal collector — byte-identical dual-copy (§21 Gap 1). The require is // class_exists-guarded (runtime's copy may already be loaded via the autoloader) // and the file itself carries a co-load return guard. // // Single-registration guarantee: with BOTH plugins active, core AND runtime each // add the SAME static callable at init@20 — WP dedupes identical callbacks by // unique id, so it binds once — and register() additionally carries a static-flag // guard, so the hooks attach exactly once regardless of order. The // AIEO_RUNTIME_OWNS_GOALS check below is a best-effort early-out (it only skips // when runtime's file-load already defined the constant before this line runs); it // is NOT what guarantees single registration. if ( ! class_exists( 'AIEO_Goal_Tracker' ) && file_exists( AIEO_DIR . 'includes/class-aieo-goal-tracker.php' ) ) { require_once AIEO_DIR . 'includes/class-aieo-goal-tracker.php'; } if ( class_exists( 'AIEO_Goal_Tracker' ) && ! defined( 'AIEO_RUNTIME_OWNS_GOALS' ) ) { add_action( 'init', array( 'AIEO_Goal_Tracker', 'register' ), 20 ); } // Front-end emit: when the runtime plugin is present it OWNS the SEO head // (defines AIEO_RUNTIME_OWNS_SEO_HEAD + registers AIEO_SEO_Head itself); // otherwise the core registers the emitter standalone. DEFERRED to // plugins_loaded@11: the runtime defines its OWNS constant at its own file // load, which runs AFTER this core file is included (plugins load // alphabetically: ai-eshop-optimizer before ai-eshop-optimizer-runtime), so an // include-time !defined() check would always be true and the core would // register too. Checking on plugins_loaded — after every plugin's main file // has run — makes the skip reliable. Mirrors the AIEO_RUNTIME_OWNS_SSO_DISPLAY // gate precedent; register() is idempotent as a second safety net. add_action( 'plugins_loaded', static function () { // Canonical-category permalink filters (A1.3) — registered UNCONDITIONALLY // (NOT under the OWNS_SEO_HEAD gate): register() is idempotent (static // $done), so whichever plugin calls first wins and the other no-ops. This // decouples the permalink filter from the head-emitter OWNS constant, so it // can never end up registered in NEITHER plugin. Self-gated on // active-provider; harmless no-op without %product_cat%. NOT admin-gated: // must be active during the offline build so get_permalink() materialises // the canonical-category URL. if ( class_exists( 'AIEO_SEO_Primary_Term' ) ) { AIEO_SEO_Primary_Term::register(); } // Visible breadcrumb shortcode [aieo_breadcrumb] (the aieo/breadcrumb block // auto-registers via block.json). Idempotent; shares AIEO_SEO_Breadcrumb's // resolver with the JSON-LD BreadcrumbList so the trail uses the pinned // canonical category. if ( class_exists( 'AIEO_SEO_Breadcrumb' ) ) { AIEO_SEO_Breadcrumb::register(); } // Static sitemap (A1.4): the /sitemap.xml PHP fallback + the robots.txt // Sitemap line — self-gated on active-provider (core-free). In production // nginx serves the static file at the edge; the build runs offline via the // seo_sitemap data-prep stage. if ( class_exists( 'AIEO_SEO_Sitemap' ) ) { AIEO_SEO_Sitemap::register(); } // Redirect engine (A2): serves 301/302/307/410 + logs 404s. The runtime OWNS // it when present — its bundled copy + the aieo-seo-redirects mu-plugin serve // front-end redirects, so the core must NOT touch the class here. Referencing // it while the runtime copy is already declared triggered a "Cannot redeclare // class AIEO_SEO_Redirects" fatal on admin requests (e.g. product save). The // core registers it ONLY standalone (runtime absent). if ( ! defined( 'AIEO_RUNTIME_OWNS_SEO_HEAD' ) && class_exists( 'AIEO_SEO_Redirects' ) ) { AIEO_SEO_Redirects::register(); } // Head emitter: the runtime OWNS it when present (defines // AIEO_RUNTIME_OWNS_SEO_HEAD + registers its bundled copy); the core // registers it only standalone. if ( defined( 'AIEO_RUNTIME_OWNS_SEO_HEAD' ) ) { return; } if ( class_exists( 'AIEO_SEO_Head' ) ) { AIEO_SEO_Head::register(); } }, 11 ); // Product Swatches runtime + AJAX — canonical copies live in the // runtime plugin (ai-eshop-optimizer-runtime/includes/dmm/modules/). // With the runtime present, these require_once calls are no-ops // (class_exists short-circuits). Without it — i.e. on sites that // run the main plugin standalone — the admin plugin loads its own // bundled copy so the frontend swatch render still works. if ( ! class_exists( 'AIEO_DMM_Swatches_Runtime' ) ) { require_once plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-swatches-runtime.php'; } if ( ! class_exists( 'AIEO_DMM_Swatches_Ajax' ) ) { require_once plugin_dir_path( __FILE__ ) . '/includes/dmm/modules/class-aieo-dmm-swatches-ajax.php'; } // Load AI Chat addon (Claude-powered conversational search) require_once plugin_dir_path(__FILE__) . '/ai-eshop-chat-addon.php'; // Load Discount & Marketplace Management (DMM) bootstrap. require_once plugin_dir_path(__FILE__) . '/includes/dmm/class-aieo-dmm.php'; // The capability registry — what this install exposes and what each part // costs. Loaded unconditionally because WP-CLI, the assistant and the Home // counter all read it, and a lazily-required registry is one that is missing // exactly when support needs it. require_once plugin_dir_path(__FILE__) . '/includes/dmm/class-aieo-capability-registry.php'; // Saved & Abandoned Carts subsystem — storefront save/share/resume on a // dedicated table pair (wp_aieo_carts + wp_aieo_cart_items) PLUS a permanent // abandoned-cart log captured from wc-checkout-draft orders (with outcome // tracking) before WooCommerce purges them. Bootstrap loads the data layer, // the storefront feature, and the hourly capture job. require_once plugin_dir_path(__FILE__) . '/includes/carts/class-aieo-carts.php'; // Server Events (Track B) — server-side conversion forwarding (Facebook CAPI // today; GA4 Measurement Protocol later). Loaded + booted UNCONDITIONALLY: the // server side is pure backend with no front-end surface and must run with or // without the runtime. Hook callbacks lazy-reference their deps, so load order // is irrelevant. The browser pixel surface (B2b) is wired separately behind a // dedicated AIEO_RUNTIME_OWNS_PIXEL constant. require_once plugin_dir_path(__FILE__) . '/includes/server-events/class-aieo-server-events.php'; AIEO_Server_Events::instance(); // First-party GDPR consent (Track C) — one source of truth (cookie + allows() // API), Google Consent Mode v2 signals, and a thin first-party banner. The // session-tracker consent gates consult this first; external CMPs remain the // fallback when the banner is off. Core-loaded (front-end surface). require_once plugin_dir_path(__FILE__) . '/includes/consent/class-aieo-consent.php'; AIEO_Consent::instance()->register(); // Google One Tap (recognise-only) — thin front-end loader. Renders the GSI // loader for logged-out visitors when the merchant enables One Tap (Consent/GDPR // page) + a Google client_id is set (Social Login). The JS gates on the // `personalize` consent flag + skips logged-in browsers. Default-OFF. require_once plugin_dir_path(__FILE__) . '/includes/social-login/class-aieo-one-tap.php'; AIEO_One_Tap::register(); // Panel manifest — the single descriptor the Rooster panel polls // (uploads/aieo-panel/manifest.json). Self-contained; rewrites on push/SEO engine // + VAPID changes (debounced). Registers the `wp aieo push prepare` / // `verify-readiness` CLI commands. Activation also defaults a FRESH site's push // engine to paused (add_option no-op → existing live sites untouched). require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-panel-manifest.php'; AIEO_Panel_Manifest::register(); register_activation_hook(__FILE__, 'aieo_panel_manifest_activate'); // WC 10.9 forward-compat migration — relocates botiga_variation_gallery // + product_attribute_* term metas into WooCommerce's canonical keys // (`_product_image_gallery`, `color`) so that when a merchant enables // the `variation_gallery` / `wc-visual-attribute` feature toggles the // data is already where WC expects it. Idempotent, batched via Action // Scheduler; also exposed as `wp aieo migrate wc-compat`. require_once plugin_dir_path(__FILE__) . '/includes/migrations/class-aieo-wc-compat-migration.php'; AIEO_WC_Compat_Migration::bootstrap(); // Audience-vocabulary migration — rewrites SAVED audience rule trees after the // segment rename ('lapsed' → 'overdue') and the deletion of the 'dormant' // segment. This MUST be wired: nothing validates a segment slug at compile time // (AIEO_Audience_Rules::compile() turns any slug into a perfectly valid // `segments_json LIKE '%"x"%'`), so a saved rule naming a dead segment stays // syntactically fine and silently starts matching ZERO customers the moment the // assignment sproc stops writing that slug — 13,883 → 0 for 'dormant', 1,872 → 0 // for 'lapsed' on the reference bed. The workflow gated on such an audience does // not error; it just stops sending. Same shape as the wc-compat migration above: // version-gated self-heal plus `wp aieo migrate audience-vocabulary [--dry-run]`. require_once plugin_dir_path(__FILE__) . '/includes/migrations/class-aieo-audience-vocabulary-migration.php'; AIEO_Audience_Vocabulary_Migration::bootstrap(); // Load Claude Abilities API bootstrap — registers 21 read-only abilities // (audience priorities, product needs, recos, attribution, ratings, // brand vitals, customer lookalikes) under the `aieo` category for the // woocommerce-claude MCP server / Claude Code skill harness to call. // Exposed at /wp-json/wp-abilities/v1/abilities/ when WP 6.9+. require_once plugin_dir_path(__FILE__) . '/includes/claude/class-aieo-claude-bootstrap.php'; add_action('init', array('AIEO\\Claude\\Bootstrap', 'init'), 5); // Merchant Insights Chat - wp-admin chat page. if ( is_admin() || ( defined('DOING_AJAX') && DOING_AJAX ) ) { require_once plugin_dir_path(__FILE__) . '/includes/chat/class-aieo-merchant-chat.php'; add_action('init', array('AIEO_Merchant_Chat', 'init'), 20); } // External-database connection registry (ERP / sister-store DBs). // Always loaded — its hooks are admin-conditional internally, but the // connection helper (AIEO_ERP::for_connection_id) needs to be reachable // from cron and wp-cli too. require_once plugin_dir_path(__FILE__) . '/includes/erp/class-aieo-erp.php'; // Retention + Remote-Export bootstrap (2026-05). // Schedules the nightly aggregate-rollup cron, the configurable remote // export cron, and binds AE/Reco archive handlers to the shared // `aieo_archive_run` hook fired by AIEO_Session_Tracker::archive_sessions(). // Installs the 5 rollup tables + remote-export state bookkeeping table. // MUST load AFTER class-aieo-erp.php — the remote-export manager calls // AIEO_ERP::for_connection_id() to talk to the destination DB. require_once plugin_dir_path(__FILE__) . '/includes/class-aieo-retention-bootstrap.php'; AIEO_Retention_Bootstrap::init(); // IAPI control panel (Phase C-α+ admin UI). if ( is_admin() ) { require_once plugin_dir_path(__FILE__) . '/includes/admin/class-aieo-iapi-admin.php'; } // Ctrl/Cmd+K command palette — overlay restricted to AIEO admin pages only. if ( is_admin() ) { require_once plugin_dir_path(__FILE__) . '/includes/admin/class-aieo-command-palette.php'; } // Initialize the plugin function AIEO_init() { // Phase-1 perf gate: class AIEO is the admin monolith (menus, CSV-export // pipeline, Rooster API client, DB optimizer — ~6.4k lines). Its hooks // are admin_menu / admin_bar_menu / admin_post_* / wp_ajax_* plus ONE // frontend-relevant hook: the wp_head admin-bar CSS fix. So: // • admin + AJAX requests construct it eagerly (status quo); // • all other requests defer to init and construct it only for // logged-in users — the only visitors who can see the admin bar. // Deciding at init (not here at plugins_loaded) avoids forcing // early user determination, which breaks late-registered auth // filters (session tokens, 2FA). // Anonymous storefront / REST / cron traffic skips the class entirely: // none of its hooks can fire there. if (is_admin() || wp_doing_ajax()) { new AIEO(); } else { add_action('init', function () { if (is_user_logged_in()) { new AIEO(); } }, 0); } // ALWAYS initialize Session Tracker to register REST endpoints // The tracker will handle whether to enqueue scripts based on settings AIEO_Session_Tracker::get_instance(); // Initialize Recommendations Cache hooks (invalidation on product save/delete) // Only when WooCommerce is active (recommendations are WooCommerce-specific) if ( class_exists( 'WooCommerce' ) && class_exists( 'AIEO_Recommendations_Cache' ) ) { AIEO_Recommendations_Cache::init_hooks(); } // Discount & Marketplace Management bootstrap (menu, modules, hooks). if ( class_exists( 'AIEO_DMM' ) ) { AIEO_DMM::instance(); } // Saved & Abandoned Carts — boots the storefront save/share/resume // hooks + the hourly abandoned-cart capture job. Tables install lazily. // Skipped when the runtime plugin is present: it owns the frontend // surface (AIEO_RUNTIME_OWNS_AJAX) and instantiates AIEO_Carts itself, // so the feature keeps working on trimmed-whitelist requests where this // admin plugin isn't loaded. (AIEO_Carts::instance() is a singleton, so // even un-gated double calls are harmless — this just honours the contract.) if ( class_exists( 'AIEO_Carts' ) && ! defined( 'AIEO_RUNTIME_OWNS_AJAX' ) ) { AIEO_Carts::instance(); } // IAPI control panel — admin-only. if ( is_admin() && class_exists( 'AIEO_IAPI_Admin' ) ) { AIEO_IAPI_Admin::instance(); } // Wishlist — table install runs lazily on plugins_loaded via the // class's own maybe_install(); this just kicks the singleton so // the AJAX hooks + asset localisation register on every load. if ( class_exists( 'AIEO_Wishlist' ) ) { AIEO_Wishlist::instance(); } // PPE compatibility shim — routes legacy `om_ppe_wishlist_toggle` // AJAX calls to the AIEO endpoint + emits a shim `omPPEWishlist` // global. Safe to run alongside PPE (our handler wins on priority). if ( class_exists( 'AIEO_Wishlist_PPE_Compat' ) ) { AIEO_Wishlist_PPE_Compat::instance(); } // Star Ratings — table install runs lazily; this kicks the singleton // so the AJAX hooks + asset enqueue + admin menu register on every load. if ( class_exists( 'AIEO_Ratings' ) ) { AIEO_Ratings::instance(); } if ( class_exists( 'AIEO_Ratings_REST' ) ) { AIEO_Ratings_REST::instance(); } // Product Swatches runtime — frontend renderer that emits per-card // swatch markup from `wp_aieo_dmm_swatches_cache` without // instantiating WC_Product_Variation objects. Gated internally by // `aieo_dmm_swatches_runtime_enabled` so the kill-switch flip // happens via the Swatches admin tab. AJAX class always registers // its endpoints so the cart/quick-view round-trips work regardless // of the render flag. if ( class_exists( 'AIEO_DMM_Swatches_Runtime' ) ) { AIEO_DMM_Swatches_Runtime::instance(); } if ( class_exists( 'AIEO_DMM_Swatches_Ajax' ) ) { AIEO_DMM_Swatches_Ajax::instance(); } // Core Brand Vitals — registers auto-mark-dirty hooks on product/term // saves and the AJAX bundle endpoint for the brand-slider block. if ( class_exists( 'AIEO_Core_Brand_Vitals' ) ) { AIEO_Core_Brand_Vitals::instance(); } // Attribution — boots the singleton so AJAX endpoints + schema // install + order backfill hook all register. Cheap no-op when // the table is already in place. if ( class_exists( 'AIEO_Attribution' ) ) { AIEO_Attribution::instance(); } // Identity substrate resolver (Customer Intelligence Core, Phase A) — // registers the hourly Action-Scheduler tick that drains the session→subject // queue (wp_aieo_session_identity → wp_aieo_subjects) and the wp_login // identification rung. No-op when the tables/queue are empty. if ( class_exists( 'AIEO_Subject_Resolver' ) ) { AIEO_Subject_Resolver::bootstrap(); } // Behavioural embedding (Customer Intelligence Core, §15) — the interaction // aggregation job (raw firehose → wp_aieo_interaction_summary), the per-subject // vector builder (interaction-weighted aggregation of item Voyage vectors → // wp_aieo_chat_embeddings post_type='user'), and the serving layer // (recommendations / lookalikes / instigators + digest personalisation). Each // AS job is a cheap no-op until the substrate has data. // Explicit requires so the behavioural layer loads even on installs without // the mu-plugin autoloader (#27) — otherwise class_exists() below is false and // the AS jobs silently never schedule. foreach ( array( 'class-aieo-interaction-summary.php', 'class-aieo-behavioural-vector.php', 'class-aieo-behavioural-reco.php' ) as $aieo_bh_file ) { $aieo_bh_path = AIEO_DIR . 'includes/' . $aieo_bh_file; if ( file_exists( $aieo_bh_path ) ) { require_once $aieo_bh_path; } } if ( class_exists( 'AIEO_Interaction_Summary' ) ) { AIEO_Interaction_Summary::bootstrap(); } if ( class_exists( 'AIEO_Behavioural_Vector' ) ) { AIEO_Behavioural_Vector::bootstrap(); } if ( class_exists( 'AIEO_Behavioural_Reco' ) ) { AIEO_Behavioural_Reco::bootstrap(); } // Operator intelligence surfaces (§17 profile, §19 audiences) + the manual // campaign/workflow engine. Explicit requires so they load without the // mu-autoloader; the runtime tick fires triggers + walks steps (INERT until // the channel engines are flipped live). foreach ( array( 'class-aieo-i18n.php', 'class-aieo-campaign-i18n.php', 'class-aieo-coupon-minter.php', 'class-aieo-merge-tags.php', 'class-aieo-customer-profile.php', 'class-aieo-customer-purchases.php', 'class-aieo-audience-rules.php', 'class-aieo-contact-discovery.php', 'class-aieo-order-rules.php', 'class-aieo-workflows.php', 'class-aieo-workflow-runtime.php', 'class-aieo-workflow-stats.php', 'class-aieo-workflow-incrementality.php', 'class-aieo-send-time.php', 'class-aieo-workflow-ab.php', 'class-aieo-order-touchpoints.php', 'class-aieo-marketing-stats.php' ) as $aieo_wf_file ) { $aieo_wf_path = AIEO_DIR . 'includes/' . $aieo_wf_file; if ( file_exists( $aieo_wf_path ) ) { require_once $aieo_wf_path; } } // Registered here rather than from the DMM module: the batch handler has to // exist in the Action Scheduler / cron request too, where admin modules are // not loaded, or a queued conversion run would never advance. if ( class_exists( 'AIEO_Contact_Discovery' ) ) { AIEO_Contact_Discovery::register_hooks(); } // Native-first coupon minter (§12) — registers order-redemption tracking + // the daily cleanup of expired-unredeemed coupons. Mints nothing on its own. // (Also registers the shared AIEO_Offer_Link apply-link consumer.) if ( class_exists( 'AIEO_Coupon_Minter' ) ) { AIEO_Coupon_Minter::bootstrap(); } // Birthday capture (§21 Gap 2) — shared byte-identical class; boot the core // copy so a core-only site (no runtime) also registers the checkout field + // syncs the value. When runtime is active it boots the same singleton first; // instance() is idempotent so the field registers once. Reads aieo_dmm_birthday. // Explicit require (not just file_exists) so it loads even without the mu // autoloader (#27), same idiom as the behavioural layer above. if ( ! class_exists( 'AIEO_Runtime_Birthday' ) && file_exists( AIEO_DIR . 'includes/class-aieo-runtime-birthday.php' ) ) { require_once AIEO_DIR . 'includes/class-aieo-runtime-birthday.php'; } if ( class_exists( 'AIEO_Runtime_Birthday' ) ) { AIEO_Runtime_Birthday::instance(); } // Unified contact-consent service (§VII.18) — single source of truth for marketing // consent (email suppression + Newsletter Plugin), shared by the checkout opt-in and // the My-Account "Email & marketing preferences" toggle. Static utility; just load it. if ( ! class_exists( 'AIEO_Contact_Consent' ) && file_exists( AIEO_DIR . 'includes/class-aieo-contact-consent.php' ) ) { require_once AIEO_DIR . 'includes/class-aieo-contact-consent.php'; } // Checkout marketing opt-in checkbox (§VII.18) — shared byte-identical class; boot the // core copy so a core-only site also registers the Store-API field. Idempotent singleton // (reads aieo_dmm_marketing_optin; zero overhead when disabled). if ( ! class_exists( 'AIEO_Runtime_Marketing_Optin' ) && file_exists( AIEO_DIR . 'includes/class-aieo-runtime-marketing-optin.php' ) ) { require_once AIEO_DIR . 'includes/class-aieo-runtime-marketing-optin.php'; } if ( class_exists( 'AIEO_Runtime_Marketing_Optin' ) ) { AIEO_Runtime_Marketing_Optin::instance(); } // AutomateWoo decommission/migration jobs (§12b) — birthday migration, AW // coupon ledger import, opt-out import. Registers AS/WP-CLI/AJAX entry points // only; NOTHING runs until an operator triggers it. $aieo_awdec_path = AIEO_DIR . 'includes/class-aieo-aw-decommission.php'; if ( ! class_exists( 'AIEO_AW_Decommission' ) && file_exists( $aieo_awdec_path ) ) { require_once $aieo_awdec_path; } if ( class_exists( 'AIEO_AW_Decommission' ) ) { AIEO_AW_Decommission::bootstrap(); } if ( class_exists( 'AIEO_Workflow_Runtime' ) ) { AIEO_Workflow_Runtime::bootstrap(); } // §IV.3 lifetime "ever bought X" rollup — nightly TRUNCATE+INSERT of // wp_aieo_customer_purchases from the order snapshots, feeding the Audience // Builder's ever_purchased_* fields. Registers only its nightly AS job; sends // nothing and rebuilds nothing until the schedule fires (or an operator runs it). if ( class_exists( 'AIEO_Customer_Purchases' ) ) { AIEO_Customer_Purchases::bootstrap(); } // Per-workflow OUTCOME rollup (campaign funnel: sent→clicked→redeemed→revenue) — // reconciles the dispatch + coupon-grant ledgers (+ optional last-click order_stats) // into wp_aieo_workflow_stats. Registers a 6-hourly AS rebuild; feeds the Campaigns // builder funnel + the AI workflow-performance ability. Reads ledgers only; sends nothing. if ( class_exists( 'AIEO_Workflow_Stats' ) ) { AIEO_Workflow_Stats::bootstrap(); } // Unified "All Marketing Performance" rollup — reconciles workflows + push triggers + // broadcasts + paid ad campaigns into wp_aieo_marketing_stats (owned + paid, one surface) // for the campaigns card + the aieo/marketing-performance chat ability. Reads only. if ( class_exists( 'AIEO_Marketing_Stats' ) ) { AIEO_Marketing_Stats::bootstrap(); } // §13 efficiency bandit — nightly Thompson-sampling variant reweight of // wp_aieo_push_templates.weight + the conversion-join reward signal + the // msg_stats rollup. Registers only its nightly AS job + schema self-heal; // reweights nothing until a pool has ≥2 active variants with data. $aieo_bandit_path = AIEO_DIR . 'includes/class-aieo-bandit.php'; if ( file_exists( $aieo_bandit_path ) ) { require_once $aieo_bandit_path; if ( class_exists( 'AIEO_Bandit' ) ) { AIEO_Bandit::bootstrap(); } } // §19.8 AI auto-suggestion — nightly opportunity scanner → the proposals inbox // (T0 suggest-only). Registers the nightly AS scan; proposes nothing until it // runs, and accepting a proposal only creates a DRAFT workflow. $aieo_proposal_path = AIEO_DIR . 'includes/class-aieo-proposal-engine.php'; if ( file_exists( $aieo_proposal_path ) ) { require_once $aieo_proposal_path; if ( class_exists( 'AIEO_Proposal_Engine' ) ) { AIEO_Proposal_Engine::bootstrap(); } } // Email channel (Customer Intelligence Core, Phase B) — INERT by default: // aieo_email_engine_status defaults to 'paused' and the sender re-checks it, // so NOTHING sends until an operator explicitly flips it live. Load the // classes, ensure the paused default exists, and register the dormant digest // (its recurring tick is only scheduled while the engine is live). $aieo_email_dir = AIEO_DIR . 'includes/dmm/email/'; foreach ( array( 'class-aieo-email-engine.php', 'class-aieo-email-sender.php', 'class-aieo-email-channel.php', 'class-aieo-email-tracking.php', 'class-aieo-email-unsubscribe.php', 'class-aieo-newsletter-digest.php', 'class-aieo-channel-cascade.php' ) as $aieo_email_file ) { if ( file_exists( $aieo_email_dir . $aieo_email_file ) ) { require_once $aieo_email_dir . $aieo_email_file; } } if ( class_exists( 'AIEO_Email_Engine' ) ) { AIEO_Email_Engine::ensure_default(); } // §VII.5 — email open/click measurement (adds opened_at; serves the pixel + click redirect). if ( class_exists( 'AIEO_Email_Tracking' ) ) { AIEO_Email_Tracking::bootstrap(); } // §VII.14 — one-click unsubscribe endpoint (footer link + List-Unsubscribe headers on every send). if ( class_exists( 'AIEO_Email_Unsubscribe' ) ) { AIEO_Email_Unsubscribe::bootstrap(); } if ( class_exists( 'AIEO_Newsletter_Digest' ) ) { AIEO_Newsletter_Digest::bootstrap(); } // Channel cascade (§11) — push-first, email-fallback primitive. Registers only // its fallback AS handler; runs nothing until a trigger calls dispatch(). if ( class_exists( 'AIEO_Channel_Cascade' ) ) { AIEO_Channel_Cascade::bootstrap(); } // Embedding backfill (Customer Intelligence Core, Phase C) — operator- // initiated, metered posts/pages embedding via Action Scheduler + a cost // preview. Registers the AS tick + admin AJAX; idle until an operator runs it. $aieo_embed_backfill = AIEO_DIR . 'includes/chat/class-aieo-embedding-backfill.php'; if ( file_exists( $aieo_embed_backfill ) ) { require_once $aieo_embed_backfill; if ( class_exists( 'AIEO_Embedding_Backfill' ) ) { AIEO_Embedding_Backfill::bootstrap(); } } // Let the pricing engine preload per-request on archive/single views. if ( class_exists( 'AIEO_DMM_Pricing_Engine' ) ) { AIEO_DMM_Pricing_Engine::instance()->register_preload_hooks(); } } add_action('plugins_loaded', 'AIEO_init'); function aieo_is_index_wp_mysql_for_speed_active() { if (!function_exists('is_plugin_active')) { include_once ABSPATH . 'wp-admin/includes/plugin.php'; } return is_plugin_active('index-wp-mysql-for-speed/index-wp-mysql-for-speed.php'); } function aieo_set_default_options() { global $wpdb; if (get_option('aieo_version') === false) { add_option('aieo_version', AIEO_VERSION, '', 'no'); } // Check if the option already exists. If not, add it. if (get_option('aieo_site_prefix') === false) { // Set the value for 'aieo_site_prefix' option $prefix_name = $wpdb->prefix; add_option('aieo_site_prefix', $prefix_name, '', 'no'); } // Always ensure correct table names (fix old installations with wrong suffix) $correct_orders_table = $wpdb->prefix . 'aieo_temp_orders'; // Use update_option instead of add_option to ensure immediate availability update_option('aieo_site_orders_table', $correct_orders_table, 'no'); $correct_store_orders_table = $wpdb->prefix . 'aieo_temp_store_orders'; update_option('aieo_store_orders_table', $correct_store_orders_table, 'no'); update_option('aieo_offline_orders', $correct_store_orders_table, 'no'); $correct_products_table = $wpdb->prefix . 'aieo_temp_product_catalogue'; update_option('aieo_site_products_table', $correct_products_table, 'no'); if (get_option('aieo_core_attribute_brands') === false) { // Set the value for 'aieo_core_attribute_brands' option $default_attribute_for_brand = 'product_brand'; add_option('aieo_core_attribute_brands', $default_attribute_for_brand, '', 'no'); } if (get_option('aieo_core_attribute_size') === false) { // Set the value for 'aieo_core_attribute_size' option $default_attribute_for_size = 'pa_size,pa_noumero,pa_megethos'; add_option('aieo_core_attribute_size', $default_attribute_for_size, '', 'no'); } if (get_option('aieo_core_attribute_color') === false) { // Set the value for 'aieo_core_attribute_color' option $default_attribute_for_color = 'pa_color,pa_colour'; add_option('aieo_core_attribute_color', $default_attribute_for_color, '', 'no'); } if (get_option('aieo_core_attribute_need') === false) { // Set the value for 'aieo_core_attribute_need' option $default_attribute_for_need = 'pa_need'; add_option('aieo_core_attribute_need', $default_attribute_for_need, '', 'no'); } if (get_option('aieo_season_days_past') === false) { // Set the value for 'aieo_season_days_past' option $default_season_days_past = '15'; add_option('aieo_season_days_past', $default_season_days_past, '', 'no'); } if (get_option('aieo_analytics_eponymous_id_field') === false) { // Set the value for 'aieo_analytics_eponymous_id_field' option $default_analytics_eponymous_id_field = 'EponymousId'; add_option('aieo_analytics_eponymous_id_field', $default_analytics_eponymous_id_field, '', 'no'); } if (get_option('aieo_season_days_after') === false) { // Set the value for 'aieo_season_days_after' option $default_season_days_after = '60'; add_option('aieo_season_days_after', $default_season_days_after, '', 'no'); } // Use update_option instead of add_option to ensure immediate availability $table_name = $wpdb->prefix . 'aieo_core_product_attributes'; update_option('aieo_core_product_attributes_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_product_category_hierarchy'; update_option('aieo_core_product_category_hierarchy_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_category_brand_popularity'; update_option('aieo_core_category_brand_popularity_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_product_vitals'; update_option('aieo_core_product_vitals_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_variation_vitals'; update_option('aieo_core_variation_vitals_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_reciprocal_products'; update_option('aieo_core_reciprocal_products_table', $table_name, 'no'); $table_name = $wpdb->prefix . 'aieo_core_brand_vitals'; update_option('aieo_core_brand_vitals_table', $table_name, 'no'); if (get_option('aieo_erp_store_products_table') === false) { // Set the value for 'aieo_erp_store_products_table' option $table_name = $wpdb->prefix . 'aieo_erp_store_products'; add_option('aieo_erp_store_products_table', $table_name, '', 'no'); } if (get_option('aieo_erp_store_orders_table') === false) { // Set the value for 'aieo_erp_store_orders_table' option $table_name = $wpdb->prefix . 'aieo_erp_store_orders'; add_option('aieo_erp_store_orders_table', $table_name, '', 'no'); } if (get_option('aieo_erp_store_customers_table') === false) { // Set the value for 'aieo_erp_store_customers_table' option $table_name = $wpdb->prefix . 'aieo_erp_store_customers'; add_option('aieo_erp_store_customers_table', $table_name, '', 'no'); } if (get_option('aieo_google_user_journey_table') === false) { // Set the value for 'aieo_google_user_journey_table' option $table_name = $wpdb->prefix . 'aieo_google_user_journey'; add_option('aieo_google_user_journey_table', $table_name, '', 'no'); } if (get_option('aieo_order_id') === false) { add_option('aieo_order_id', '1', '', 'no'); } if (get_option('aieo_max_records') === false) { add_option('aieo_max_records', '1000', '', 'no'); } if (get_option('aieo_batch_size') === false) { add_option('aieo_batch_size', '100', '', 'no'); } if (get_option('aieo_batch_sleep') === false) { add_option('aieo_batch_sleep', '0', '', 'no'); } if (get_option('aieo_include_text') === false) { add_option('aieo_include_text', '1', '', 'no'); } if (get_option('aieo_include_attributes') === false) { add_option('aieo_include_attributes', '1', '', 'no'); } // Export checkbox options - default to '0' (unchecked) so user chooses what to run if (get_option('aieo_create_attributes') === false) { add_option('aieo_create_attributes', '0', '', 'no'); } if (get_option('aieo_create_needs') === false) { add_option('aieo_create_needs', '0', '', 'no'); } if (get_option('aieo_create_need_suggestions') === false) { add_option('aieo_create_need_suggestions', '0', '', 'no'); } if (get_option('aieo_create_catalogue') === false) { add_option('aieo_create_catalogue', '0', '', 'no'); } if (get_option('aieo_create_orders') === false) { add_option('aieo_create_orders', '0', '', 'no'); } if (get_option('aieo_erp_consolidation') === false) { add_option('aieo_erp_consolidation', '0', '', 'no'); } if (get_option('aieo_erp_merge_orders') === false) { add_option('aieo_erp_merge_orders', '0', '', 'no'); } if (get_option('aieo_include_unsold') === false) { add_option('aieo_include_unsold', '0', '', 'no'); } if (get_option('aieo_include_aggregate_stats') === false) { add_option('aieo_include_aggregate_stats', '0', '', 'no'); } if (get_option('aieo_include_aggregate_category_brand_stats') === false) { add_option('aieo_include_aggregate_category_brand_stats', '0', '', 'no'); } if (get_option('aieo_include_aggregate_cust_std_stats') === false) { add_option('aieo_include_aggregate_cust_std_stats', '0', '', 'no'); } if (get_option('aieo_include_aggregate_cust_adv_stats') === false) { add_option('aieo_include_aggregate_cust_adv_stats', '0', '', 'no'); } if (get_option('aieo_create_uuids') === false) { add_option('aieo_create_uuids', '0', '', 'no'); } if (get_option('aieo_create_export') === false) { add_option('aieo_create_export', '0', '', 'no'); } if (get_option('aieo_include_full_text') === false) { add_option('aieo_include_full_text', '0', '', 'no'); } if (get_option('aieo_include_price') === false) { add_option('aieo_include_price', '1', '', 'no'); } if (get_option('aieo_variations_choice') === false) { add_option('aieo_variations_choice', '1', '', 'no'); } if (get_option('aieo_include_eponymous') === false) { add_option('aieo_include_eponymous', '1', '', 'no'); } if (get_option('aieo_include_reciprocity') === false) { add_option('aieo_include_reciprocity', '0', '', 'no'); } if (get_option('aieo_include_seasonality') === false) { add_option('aieo_include_seasonality', '0', '', 'no'); } if (get_option('aieo_include_restricted_seasonality') === false) { add_option('aieo_include_restricted_seasonality', '0', '', 'no'); } if (get_option('aieo_instore_anonymous') === false) { add_option('aieo_instore_anonymous', '0', '', 'no'); } if (get_option('aieo_activate_utm_stats') === false) { add_option('aieo_activate_utm_stats', '0', '', 'no'); } if (get_option('aieo_google_ga4') === false) { add_option('aieo_google_ga4', '0', '', 'no'); } if (get_option('aieo_display_upsells') === false) { add_option('aieo_display_upsells', '0', '', 'no'); } if (get_option('aieo_display_cross_sells') === false) { add_option('aieo_display_cross_sells', '0', '', 'no'); } if (get_option('aieo_display_related') === false) { add_option('aieo_display_related', '0', '', 'no'); } if (get_option('aieo_display_recently_viewed_products') === false) { add_option('aieo_display_recently_viewed_products', '0', '', 'no'); } if (get_option('aieo_display_same_needs') === false) { add_option('aieo_display_same_needs', '0', '', 'no'); } if (get_option('aieo_display_categories_by_sales') === false) { add_option('aieo_display_categories_by_sales', '0', '', 'no'); } if (get_option('aieo_category_sales_period') === false) { add_option('aieo_category_sales_period', 'all_time', '', 'no'); } if (get_option('aieo_season_days_past') === false) { add_option('aieo_season_days_past', '15', '', 'no'); } if (get_option('aieo_season_days_after') === false) { add_option('aieo_season_days_after', '60', '', 'no'); } // Record initial activation date (only set once, never updated) if (get_option('aieo_initial_activation_date') === false) { add_option('aieo_initial_activation_date', current_time('mysql', true), '', 'no'); } } register_activation_hook(__FILE__, 'aieo_set_default_options'); // ----------------------------------------------------------------------------- // MU-plugin installer // ----------------------------------------------------------------------------- // AIEO ships two companion mu-plugins: // - 0-aieo-action-scheduler-core.php — AS query-limiting + retention + bypass // switch. The `0-` prefix forces it to load first (alphabetical order in // mu-plugins). Required by the new AIEO_DMM_As_Cleanup module. // - aieo-autoload.php — class autoloader for ai-eshop-optimizer + // ai-eshop-optimizer-runtime so neither plugin needs `require_once` chains // for AIEO_* classes. // Both ship inside this plugin at install/mu-plugins/. On activation we copy // them into wp-content/mu-plugins/ if either is missing OR if the bundled // version's mtime is newer than what's already there (auto-refresh on update). // Filesystem errors are reported via a transient admin notice so the operator // knows to copy them by hand on hosts where mu-plugins/ isn't writable. register_activation_hook(__FILE__, 'aieo_install_bundled_mu_plugins'); function aieo_install_bundled_mu_plugins() { $src_dir = plugin_dir_path(__FILE__) . 'install/mu-plugins/'; if (!is_dir($src_dir)) { return; } $dst_dir = defined('WPMU_PLUGIN_DIR') ? WPMU_PLUGIN_DIR : WP_CONTENT_DIR . '/mu-plugins'; if (!is_dir($dst_dir)) { // wp_mkdir_p() honours fs perms set by the host's WP config. if (!wp_mkdir_p($dst_dir)) { set_transient( 'aieo_mu_install_error', sprintf('Could not create %s. Copy install/mu-plugins/* there manually.', $dst_dir), DAY_IN_SECONDS ); return; } } // Files we ship, with optional `supersedes` clauses. Listed peer files // are legacy forks owned by the OM Optimizer Hub family. AIEO is the // canonical owner of these mu-plugins going forward — we install the // AIEO version and then DELETE the legacy peer so only one provider // of each function lives in mu-plugins/ at a time. AIEO's files // include om_* function aliases (wrapped in `function_exists()` guards // — see install/mu-plugins/0-aieo-action-scheduler-core.php tail) so // any caller of the old om_as_* names keeps working after the legacy // file is removed. $files = array( '0-aieo-action-scheduler-core.php' => array( 'supersedes' => array('0-om-action-scheduler-core.php'), ), 'aieo-autoload.php' => array(), // Lean front-end redirect server — must-use so it survives the // active_plugins load-optimisation that trims the AIEO runtime/core on // storefront + 404 paths. Loads ONLY the bundled AIEO_SEO_Redirects // class (via the autoloader above), never the full plugin. 'aieo-seo-redirects.php' => array(), 'aieo-as-ajax-query-protection.php' => array( 'supersedes' => array('om-as-ajax-query-protection.php'), ), // Collapses runaway recurring AS jobs (AutomateWoo's // `delete_old_logs/start`, which the AS-ajax read protection above // would otherwise let duplicate on every admin_init/heartbeat) back to // a single pending action. See the file header for the full mechanism. 'aieo-as-dedup-recurring-jobs.php' => array(), ); $failed = array(); foreach ($files as $name => $opts) { $src = $src_dir . $name; $dst = $dst_dir . '/' . $name; if (!file_exists($src)) { continue; } // 1. Copy the bundled AIEO version into mu-plugins/ (idempotent — // skip when the installed file is already byte-identical). // // Content comparison, not mtime. mtime is unreliable across // unzip/rsync/scp deploys, and trusting it is how the fleet drifted // into two live versions of the AS core file — 15 of 36 sites spent // months running one with a known duplicate-minting bug. The bundled // copy is the source of truth; a hand-edit on a site is drift, not // something to preserve. $needs_copy = !file_exists($dst) || md5_file($src) !== md5_file($dst); if ($needs_copy) { if (!@copy($src, $dst)) { $failed[] = $name; continue; } } // 2. Retire legacy forks AFTER the replacement is in place. // Two-step (copy then unlink) — never leaves the site without // the function definitions, even for a single request. Bundled // AIEO file exposes om_as_* aliases so legacy callers keep // working transparently. if (!empty($opts['supersedes']) && is_array($opts['supersedes'])) { foreach ($opts['supersedes'] as $peer) { if ($peer === $name) { continue; } $peer_path = $dst_dir . '/' . $peer; if (file_exists($peer_path)) { @unlink($peer_path); } } } } if (!empty($failed)) { set_transient( 'aieo_mu_install_error', 'Could not write to ' . $dst_dir . '. Copy these by hand from install/mu-plugins/: ' . implode(', ', $failed), DAY_IN_SECONDS ); } } // ----------------------------------------------------------------------------- // MU-plugin self-heal on upgrade // ----------------------------------------------------------------------------- // The installer above is an ACTIVATION hook, and a plugin update does not // re-activate. So for years a bundled mu-plugin fix only reached a site if // someone happened to deactivate/reactivate there — which is exactly how the // fleet ended up running two different versions of the AS core file, 15 sites // of them carrying a duplicate-minting bug that had been fixed months earlier. // // Re-sync whenever the plugin version changes. The gate is a single autoloaded // option compare (free — it rides the autoload bundle), so the normal request // pays nothing; the filesystem work happens once per upgrade, and only in a // context that can act on a failure notice. add_action('plugins_loaded', 'aieo_maybe_sync_bundled_mu_plugins', 1); function aieo_maybe_sync_bundled_mu_plugins() { if (get_option('aieo_mu_plugins_synced_version') === AIEO_VERSION) { return; } // Never do filesystem work on a storefront request. if (!is_admin() && !(defined('WP_CLI') && WP_CLI) && !wp_doing_cron()) { return; } aieo_install_bundled_mu_plugins(); update_option('aieo_mu_plugins_synced_version', AIEO_VERSION, true); } // Surface the install error (if any) as an admin notice on the next page load. add_action('admin_notices', function () { $msg = get_transient('aieo_mu_install_error'); if (!$msg || !current_user_can('manage_options')) { return; } printf( '
AIEO: %s