1, 'monthly_price' => 14.99, 'annual_price' => 143.88, 'currency' => 'usd', ); /** * Filter that carries the plan name the interface shows (see getDisplayPlan()). */ public const DISPLAY_PLAN_FILTER = 'aipt_display_plan_cache_only'; /** * Public pricing page: the "Compare all plans" destination for an install * that is not registered with Freemius, and the checkout destination when * the product id is unknown as well. */ public const PUBLIC_PRICING_URL = 'https://aiforwoo.com/pricing'; /** * Freemius hosted checkout, which needs no SDK registration and no * external script in wp-admin. */ private const HOSTED_CHECKOUT_BASE_URL = 'https://checkout.freemius.com'; /** * Freemius plan id of the Business plan, used until the cached pricing * snapshot supplies one, so checkout works before the first refresh. */ private const BUSINESS_PLAN_ID_FALLBACK = 29413; /** * Option that keeps the last Business plan id a pricing read found by the * plan's name. Autoloaded: getCheckoutLinks() runs on every admin page. */ private const BUSINESS_PLAN_ID_OPTION = 'aipt_business_plan_id'; /** * Snapshot key set only when the plan was matched by its name. The refresh * strips it before caching, so it never reaches the browser. */ private const SNAPSHOT_NAMED_PLAN_KEY = 'planMatchedByName'; /** * Cached SDK conflict detection result for this request. * * @var array|null */ private $sdk_conflict_info = null; /** * Request-scoped memo for getPlanType(). Reset by the SDK hook handlers when a * licence or plan change lands during the request. * * @var string|null */ private ?string $plan_type_memo = null; /** * Whether this request already queued the pricing refresh on shutdown. * * @var bool */ private $pricing_refresh_queued = false; private function __construct() { $this->fs = aipt_fs(); $this->setupFreemiusHooks(); add_action('admin_notices', [$this, 'maybeShowSdkConflictNotice']); add_action('wp_ajax_aipt_dismiss_sdk_conflict', [$this, 'handleDismissSdkConflict']); add_action(self::BUSINESS_PRICING_REFRESH_HOOK, [$this, 'refreshBusinessPlanPricing']); } public static function getInstance(): self { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Sets up the Freemius event listeners */ private function setupFreemiusHooks(): void { $this->fs->add_action('after_license_change', [$this, 'handleLicenseChange'], 10, 2); $this->fs->add_action('after_license_activation', [$this, 'handleLicenseChange'], 10, 0); $this->fs->add_action('after_license_deactivation', [$this, 'handleLicenseChange'], 10, 0); $this->fs->add_action('after_premium_version_activation', [$this, 'handleUpgrade'], 10, 0); $this->fs->add_action('after_free_version_reactivation', [$this, 'handleDowngrade'], 10, 0); $this->fs->add_filter('pricing/css_path', [$this, 'getPricingCssOverridePath']); add_filter('style_loader_src', [$this, 'bustPricingCssCache'], 10, 2); } /** * Replaces the pricing stylesheet's cache-busting `ver` query arg with * this file's own filemtime(), so editing freemius-pricing.css always * produces a new URL instead of relying on the (unrelated, effectively * static) WP core version Freemius's own enqueue call defaults to. See * setupFreemiusHooks() for why this needs the global style_loader_src * filter rather than $fs->add_filter(). * * @param string $src The stylesheet's resolved source URL. * @param string $handle The stylesheet's registered handle. * @return string */ public function bustPricingCssCache( string $src, string $handle ): string { if ( 'freemius-pricing' !== $handle ) { return $src; } $css_path = $this->resolvePricingCssPath(); if ( ! file_exists( $css_path ) ) { return $src; } return add_query_arg( 'ver', (string) filemtime( $css_path ), $src ); } /** * Absolute path to the pricing stylesheet that is actually shipping. * * webpack copies the file to dist/css/, and that is the only copy that * survives packaging: the release workflow deletes src/Assets/css and * src/Assets/webfonts from the ZIP. dist/ is also where the stylesheet's * relative `url('../webfonts/...')` @font-face sources resolve correctly, * because dist/webfonts ships. The src/ path stays as a fallback for a * checkout that has not been built yet. * * @return string */ private function resolvePricingCssPath(): string { $dist_path = AIPT_PLUGIN_DIR . 'dist/css/freemius-pricing.css'; return file_exists( $dist_path ) ? $dist_path : AIPT_PLUGIN_DIR . 'src/Assets/css/freemius-pricing.css'; } /** * Resets the plan memo and invalidates the licensing entitlement caches * (EntitlementService's good record and DirectApiVerifier's own cache), so the * next gate verifies with Freemius instead of granting the old plan's access. * Premium-only (class_exists guard, G4): a free build has nothing to invalidate. * * The downgrade signal is not sent from here: Premium fires it when Freemius * confirms a lower plan (EntitlementService). */ private function processDetectedPlanChange(): void { $this->plan_type_memo = null; if (PremiumClassGuard::exists('\AIPT\Premium\Licensing\EntitlementService')) { \AIPT\Premium\Licensing\EntitlementService::invalidateOnPlanChange(); } } /** * Handles a Freemius license or plan change for this site. * * Runs on `after_license_change` ($plan_change, $plan) and on * `after_license_activation` / `after_license_deactivation` (no arguments * are passed). * * @param string $plan_change Freemius change kind (e.g. 'upgraded', 'downgraded'), unused. * @param object|null $plan Freemius plan entity after the change, unused. */ public function handleLicenseChange($plan_change = '', $plan = null): void { $this->processDetectedPlanChange(); } /** * Handles the premium code activation. */ public function handleUpgrade(): void { $this->processDetectedPlanChange(); } /** * Handles the free code being reactivated after the premium code. */ public function handleDowngrade(): void { $this->processDetectedPlanChange(); } /** * Registered on the official `pricing/css_path` Freemius filter (see * setupFreemiusHooks()). Fires ONLY while Freemius renders its own * Pricing admin page for this plugin — no screen-detection needed. * * fs_asset_url() requires an absolute filesystem path (it string-matches * against WP_CONTENT_DIR/WP_PLUGIN_DIR to build the URL itself), so this * MUST return a real path, never a URL. * * No font enqueue here: the returned stylesheet self-hosts its own * @font-face declarations (same files aurora.scss already bundles for * the plugin's own admin UI) instead of calling Google Fonts, which * WordPress.org guideline 7 disallows for third-party CDN calls. * * Resolves through resolvePricingCssPath() rather than hardcoding the src/ * copy: the release ZIP deletes src/Assets/css (and src/Assets/webfonts), * so on a shipped build that path does not exist and fs_asset_url() would * hand Freemius a URL to a missing file. This also keeps the returned * stylesheet identical to the one bustPricingCssCache() takes its * filemtime() from. * * @param string|null $path Unused; Freemius passes null when unfiltered. * @return string Absolute path to the override stylesheet. */ public function getPricingCssOverridePath( $path ): string { return $this->resolvePricingCssPath(); } /** * The plan name the interface shows: the SDK's stored plan, replaced by the * verified plan when the Business build answers this filter. The free build * has no verified plan, so it keeps the SDK value (the premium-files notice * for a paid plan on free files depends on it). Never a Freemius call. */ public function getDisplayPlan(): string { $plan = apply_filters(self::DISPLAY_PLAN_FILTER, $this->getPlanType()); return is_string($plan) && '' !== $plan ? $plan : $this->getPlanType(); } public function is_registered(): bool { return $this->fs && $this->fs->is_registered(); } /** * The plan the Freemius SDK stores, read live and never cached, so no local * copy can name a paid plan. On the Business build the verified plan is * getDisplayPlan(). */ public function getPlanType(): string { if (null !== $this->plan_type_memo) { return $this->plan_type_memo; } if (!$this->is_registered()) { $this->plan_type_memo = PlanSlug::FREE; } elseif ($this->fs->is_plan_or_trial(PlanSlug::BUSINESS)) { $this->plan_type_memo = PlanSlug::BUSINESS; } elseif ($this->fs->is_plan_or_trial(PlanSlug::PRO)) { $this->plan_type_memo = PlanSlug::PRO; } else { $this->plan_type_memo = PlanSlug::FREE; } return $this->plan_type_memo; } public function getSiteId(): string { if (!$this->is_registered()) { return ''; } return (string)$this->fs->get_site()->id; } public function getPluginId(): string { if (!$this->fs) { return ''; } return (string)$this->fs->get_id(); } /** * One-click activation for a premium build that is installed but not * running: a paid plan on the free files whose premium copy was uploaded * and never activated. The Freemius SDK tells such a user "already * installed, activate it", but its notices are hidden on the plugin's own * pages, so the "your plan is live, the files are not" modal offers this * link instead of sending them to download the files again. * * Built with add_query_arg(), not wp_nonce_url(): the value travels to * the browser as an href, where wp_nonce_url()'s HTML-escaped "&" * would break the query string. * * @return string plugins.php activation URL with its nonce, or '' when the premium build is running, the plan is free, the premium build is not installed, or the user cannot activate it. */ public function getPremiumActivateUrl(): string { if (!$this->fs || $this->fs->is_premium() || !$this->hasProFeature()) { return ''; } $basename = (string)$this->fs->premium_plugin_basename(); $installed = function_exists('get_plugins') ? (array)get_plugins() : []; if ('' === $basename || !isset($installed[$basename])) { return ''; } if (!current_user_can('activate_plugin', $basename)) { return ''; } return add_query_arg( [ 'action' => 'activate', 'plugin' => rawurlencode($basename), '_wpnonce' => wp_create_nonce('activate-plugin_' . $basename), ], admin_url('plugins.php') ); } /** * Freemius account-management URL for the current site/license. * * Thin wrapper around the Freemius SDK's own get_account_url() so the * Settings License card never reaches into the SDK instance directly. * Freemius only adds the Account page for a registered install: for an * install that skipped the opt-in, or has not confirmed it by email * yet, that address answers "Sorry, you are not allowed to access this * page", so it gets '' here and the card links getConnectUrl() instead. * * @return string Absolute URL, or '' when the SDK instance is unavailable or the install is not connected. */ public function getAccountUrl(): string { if (!$this->is_registered()) { return ''; } return (string)$this->fs->get_account_url(); } /** * Freemius's own license sync for the Settings License card's "Refresh * license status": its account page action that re-reads the license * and plan from Freemius, for a license renewed or upgraded elsewhere * (e.g. at users.freemius.com) that this site has not picked up yet. * The SDK builds the URL and its nonce with add_query_arg(), so the * value is a plain href. * * @return string Absolute URL, or '' when the install is not connected (Freemius adds no account page), the SDK is unavailable or lacks the helper, or the call fails. */ public function getLicenseSyncUrl(): string { if (!$this->is_registered() || !is_callable([$this->fs, '_get_sync_license_url'])) { return ''; } try { return (string)$this->fs->_get_sync_license_url(); } catch (\Throwable $e) { return ''; } } /** * Where an install that is not connected to Freemius connects its * account: Freemius's own reconnect destination, which clears a skipped * or unconfirmed opt-in and opens the opt-in screen again. * * @return string Absolute URL, or '' when the install is connected or the SDK instance is unavailable. */ public function getConnectUrl(): string { if (!$this->fs || $this->is_registered()) { return ''; } return (string)$this->fs->get_reconnect_url(); } /** * Upgrade/upsell destination for the current Freemius connection state. * * admin.php?page=ai-product-tools-pricing only exists once the site is * registered: Freemius withholds the Pricing submenu/page while the * install is unregistered (e.g. the "Activate Free Version" / skip * connection state), so a direct request to that slug 403s there. An * unregistered install gets Freemius's hosted Business checkout (annual) * or the public pricing page instead, never the reconnect screen, which * would send a user who skipped the opt-in back to it. * * @return string Absolute URL, or '' when the SDK instance is unavailable. */ public function getUpgradeUrl(): string { if (!$this->fs) { return ''; } if (!$this->is_registered()) { return $this->getCheckoutLinks()['urls']['annual']; } return admin_url('admin.php?page=ai-product-tools-pricing'); } /** * Freemius plan id of the Business plan, read from the cached pricing * snapshot or the kept option only, so a page render never waits on the * Freemius API. Order: the snapshot's id, the id the last successful * name-matched read kept, then the built-in id. The built-in id stays the * last resort (owner decision 2026-11-22), so this never returns an * unknown id and checkout links never fall back to the pricing page. * * @return int Plan id. */ private function getBusinessPlanId(): int { $pricing = $this->getBusinessPlanPricing(); $plan_id = is_array($pricing) && isset($pricing['planId']) && is_numeric($pricing['planId']) ? (int) $pricing['planId'] : 0; if ($plan_id > 0) { return $plan_id; } $kept = get_option(self::BUSINESS_PLAN_ID_OPTION, 0); $kept = is_numeric($kept) ? (int) $kept : 0; return $kept > 0 ? $kept : self::BUSINESS_PLAN_ID_FALLBACK; } /** * Where the upgrade modal's primary button goes, per billing cycle. * * - 'sdk': a registered install opens the Freemius SDK's own in-dashboard * checkout with the Business plan preselected, so the purchase stays * tied to the install and the license activates automatically. * - 'hosted': an install that is not registered opens Freemius's hosted * checkout for the Business plan (the caller opens it in a new tab). * - 'pricing': an install that is not registered and has no product id, * so both cycles go to the public pricing page. * * `pricingUrl` is the "Compare all plans" destination. * * @return array{mode:string,urls:array{monthly:string,annual:string},pricingUrl:string} */ public function getCheckoutLinks(): array { $cycles = ['monthly', 'annual']; $plan_id = $this->getBusinessPlanId(); $links = [ 'mode' => 'pricing', 'urls' => ['monthly' => '', 'annual' => ''], 'pricingUrl' => self::PUBLIC_PRICING_URL, ]; if ($this->is_registered()) { $links['pricingUrl'] = admin_url('admin.php?page=ai-product-tools-pricing'); foreach ($cycles as $cycle) { $links['urls'][$cycle] = (string) $this->fs->checkout_url($cycle, false, ['plan_id' => $plan_id]); } $links['mode'] = 'sdk'; return $links; } $plugin_id = $this->fs ? (int) $this->fs->get_id() : 0; foreach ($cycles as $cycle) { $links['urls'][$cycle] = $plugin_id > 0 ? sprintf( '%s/product/%d/plan/%d/?billing_cycle=%s', self::HOSTED_CHECKOUT_BASE_URL, $plugin_id, $plan_id, $cycle ) : self::PUBLIC_PRICING_URL; } $links['mode'] = $plugin_id > 0 ? 'hosted' : 'pricing'; return $links; } /** * What the Settings License card shows about this site's license, read * from the Freemius data stored on the site (no API call): the account * email, the plan title, the status, the renewal or expiry date in the * site's date format, the billing cycle and how many sites use it. * Never the license key. * * @return array{connected:bool,pendingActivation:bool,accountEmail:string,planTitle:string,status:string,trialEndsOn:string,expiresOn:string,renewsOn:string,isLifetime:bool,billingCycle:string,sitesUsed:int|null,sitesLimit:int|null} */ public function getLicenseSummary(): array { $summary = [ 'connected' => false, 'pendingActivation' => false, 'accountEmail' => '', 'planTitle' => '', 'status' => 'none', 'trialEndsOn' => '', 'expiresOn' => '', 'renewsOn' => '', 'isLifetime' => false, 'billingCycle' => '', 'sitesUsed' => null, 'sitesLimit' => null, ]; if (!$this->fs) { return $summary; } try { if (!$this->is_registered()) { $summary['pendingActivation'] = is_callable([$this->fs, 'is_pending_activation']) && (bool) $this->fs->is_pending_activation(); return $summary; } $summary['connected'] = true; return $this->readLicenseDetails($summary); } catch (\Throwable $e) { Logger::warn('settings', 'License summary could not be read', array('error' => $e->getMessage())); return $summary; } } /** * The account, plan, trial and license details of a connected install. * An older Freemius SDK loaded by another plugin may lack the license * helpers, so each one falls back to the license field it reads. * * @param array $summary The connected install's summary so far. * @return array */ private function readLicenseDetails(array $summary): array { $user = $this->fs->get_user(); if (is_object($user) && !empty($user->email)) { $summary['accountEmail'] = (string) $user->email; } $plan = $this->fs->get_plan(); if (is_object($plan) && !empty($plan->title)) { $summary['planTitle'] = (string) $plan->title; } if ($this->fs->is_trial()) { $summary['status'] = 'trial'; $site = $this->fs->get_site(); if (is_object($site) && !empty($site->trial_ends)) { $summary['trialEndsOn'] = self::siteDate((string) $site->trial_ends); } } $license = $this->fs->_get_license(); if (!is_object($license)) { return $summary; } $summary['isLifetime'] = is_callable([$license, 'is_lifetime']) ? (bool) $license->is_lifetime() : !isset($license->expiration); if (!$summary['isLifetime'] && !empty($license->expiration)) { $summary['expiresOn'] = self::siteDate((string) $license->expiration); } $summary['sitesUsed'] = is_callable([$license, 'total_activations']) ? (int) $license->total_activations() : (int) ($license->activated ?? 0) + (int) ($license->activated_local ?? 0); $is_unlimited = is_callable([$license, 'is_unlimited']) ? (bool) $license->is_unlimited() : !isset($license->quota); $summary['sitesLimit'] = $is_unlimited ? null : (int) $license->quota; if ('trial' !== $summary['status']) { $is_expired = is_callable([$license, 'is_expired']) ? (bool) $license->is_expired() : !$summary['isLifetime'] && strtotime((string) $license->expiration . ' UTC') < time(); if (!empty($license->is_cancelled)) { $summary['status'] = 'cancelled'; } elseif ($is_expired) { $summary['status'] = 'expired'; } else { $summary['status'] = 'active'; } } $subscription = isset($license->id) ? $this->fs->_get_subscription($license->id) : null; if (is_object($subscription)) { $cycle = (int) ($subscription->billing_cycle ?? 0); $summary['billingCycle'] = 12 === $cycle ? 'annual' : (1 === $cycle ? 'monthly' : ''); $is_renewing = is_callable([$subscription, 'is_active']) && (bool) $subscription->is_active(); if (!empty($subscription->next_payment) && $is_renewing) { $summary['renewsOn'] = self::siteDate((string) $subscription->next_payment); } } elseif ($summary['isLifetime']) { $summary['billingCycle'] = 'lifetime'; } return $summary; } /** * A Freemius UTC datetime as a date in the site's own date format. * * @param string $utc_datetime Freemius datetime ("Y-m-d H:i:s", UTC). * @return string */ private static function siteDate(string $utc_datetime): string { $timestamp = strtotime($utc_datetime . ' UTC'); return false === $timestamp ? '' : (string) wp_date((string) get_option('date_format', 'Y-m-d'), $timestamp); } public function getLicenseId(): string { if (!$this->is_registered() || !$this->fs->has_active_valid_license()) { return ''; } return (string)$this->fs->_get_license()->id; } /** * Returns the Freemius user ID * * @return string User ID, or an empty string */ public function getUserId(): string { if (!$this->is_registered() || !$this->fs->is_registered()) { return ''; } $user = $this->fs->get_user(); return $user ? (string)$user->id : ''; } /** * Return the cached Business-plan pricing snapshot for the upgrade UI. * * Render-safe: reads the transient only and never calls Freemius. On a * cold cache it returns the built-in price (BUSINESS_PRICING_BUILT_IN) and * queues a one-off cron event (scheduled on shutdown) that fills the * cache through refreshBusinessPlanPricing(); after a failed refresh it * returns the built-in price too. A site that has not connected to * Freemius (no opt-in, no activated licence) queues nothing, so Freemius * is never asked before the merchant agreed to it, and its upgrade UI * keeps the built-in price. Override with the * `aipt_business_plan_pricing` filter (return null to hide prices). * * @return array|null { currency, currencySymbol, monthly, annual, * annualSavings, annualDiscountPercent } or null * when the filter hides prices. */ public function getBusinessPlanPricing(): ?array { $cached = get_transient(self::BUSINESS_PRICING_TRANSIENT); if (is_array($cached)) { $filtered = apply_filters('aipt_business_plan_pricing', $cached); return is_array($filtered) ? $filtered : null; } if (self::BUSINESS_PRICING_UNAVAILABLE === $cached) { $filtered = apply_filters('aipt_business_plan_pricing', self::builtInBusinessPlanPricing()); return is_array($filtered) ? $filtered : null; } if (!$this->pricing_refresh_queued && $this->is_registered()) { $this->pricing_refresh_queued = true; add_action('shutdown', [$this, 'scheduleBusinessPricingRefresh']); } $filtered = apply_filters('aipt_business_plan_pricing', self::builtInBusinessPlanPricing()); return is_array($filtered) ? $filtered : null; } /** * The built-in Business price as a snapshot of the same shape as a live * one. It carries no plan id, so getBusinessPlanId() keeps reading the * kept option and then the built-in plan id. * * @return array|null */ private static function builtInBusinessPlanPricing(): ?array { return self::extractPlanPricing((object) array('pricing' => array((object) self::BUSINESS_PRICING_BUILT_IN))); } /** * Queue the one-off cron event that refreshes the pricing cache. * * Runs on shutdown so the page render itself only reads the cache. */ public function scheduleBusinessPricingRefresh(): void { if (!wp_next_scheduled(self::BUSINESS_PRICING_REFRESH_HOOK)) { wp_schedule_single_event(time(), self::BUSINESS_PRICING_REFRESH_HOOK); } } /** * Fetch the Business-plan pricing from Freemius and cache it. * * Runs from the cron event queued by getBusinessPlanPricing(), so the * blocking API call never delays an admin page. Caches the pricing array * (12h) or, on any failure, the 'unavailable' sentinel (1h) so a failing * lookup is not retried on every cron run. On a site that has not * connected to Freemius it does nothing, not even cache the sentinel: an * event queued before the merchant disconnected, or by an older version, * must not ask Freemius either. */ public function refreshBusinessPlanPricing(): void { if (!$this->is_registered()) { return; } $pricing = $this->resolveBusinessPlanPricing(); if (is_array($pricing)) { if (!empty($pricing[self::SNAPSHOT_NAMED_PLAN_KEY]) && isset($pricing['planId']) && (int) $pricing['planId'] > 0) { update_option(self::BUSINESS_PLAN_ID_OPTION, (int) $pricing['planId'], true); } unset($pricing[self::SNAPSHOT_NAMED_PLAN_KEY]); set_transient(self::BUSINESS_PRICING_TRANSIENT, $pricing, self::BUSINESS_PRICING_TTL); } else { set_transient(self::BUSINESS_PRICING_TRANSIENT, self::BUSINESS_PRICING_UNAVAILABLE, self::BUSINESS_PRICING_NEG_TTL); } } /** * Fetch enriched Business-plan pricing from the Freemius API. * * Uses get_api_plugin_scope()->get('pricing.json?is_enriched=true') — the * public API scope + endpoint that Freemius' own pricing AJAX handler uses * to feed freemius-pricing.js. Returns plans whose ->pricing arrays carry * the real pricing entries (raw objects; extractPlanPricing reads them via * properties). _sync_plans() deliberately omits pricing, hence the enriched * endpoint. Guarded by method_exists() + try/catch so SDK drift or network * failures never fatal the admin UI. Called from * refreshBusinessPlanPricing() (cron) only, never on a page render. * Each failure logs one warn with its reason, once per refresh; the * upgrade modal shows the built-in price meanwhile. * * @return array|null */ private function resolveBusinessPlanPricing(): ?array { if (!function_exists('aipt_fs')) { self::logPricingUnavailable('sdk_missing'); return null; } try { $fs = aipt_fs(); if (!is_object($fs) || !method_exists($fs, 'get_api_plugin_scope')) { self::logPricingUnavailable('sdk_without_pricing_api'); return null; } $api = $fs->get_api_plugin_scope(); $result = $api->get('pricing.json?is_enriched=true'); if (is_object($result) && isset($result->error)) { $code = is_object($result->error) && isset($result->error->code) && is_scalar($result->error->code) ? (string) $result->error->code : ''; self::logPricingUnavailable('api_error', array('code' => $code)); return null; } if (!is_object($result) || empty($result->plans) || !is_array($result->plans)) { self::logPricingUnavailable('no_plans'); return null; } foreach ($result->plans as $plan) { if (is_object($plan) && isset($plan->name) && PlanSlug::BUSINESS === strtolower((string) $plan->name)) { $snapshot = self::extractPlanPricing($plan); if (is_array($snapshot)) { $snapshot[self::SNAPSHOT_NAMED_PLAN_KEY] = true; return $snapshot; } } } foreach ($result->plans as $plan) { $snapshot = self::extractPlanPricing($plan); if (is_array($snapshot)) { return $snapshot; } } } catch (\Throwable $e) { self::logPricingUnavailable('exception', array('error' => $e->getMessage())); return null; } self::logPricingUnavailable('no_priced_plan'); return null; } /** * Record why the Business plan pricing could not be loaded. * * @param string $reason Short machine-readable reason. * @param array $context Extra safe context (an exception message). */ private static function logPricingUnavailable(string $reason, array $context = array()): void { Logger::warn('settings', 'Business plan pricing could not be loaded', array('reason' => $reason) + $context); } /** * Normalize a single-site monthly/annual pricing snapshot from a Freemius * plan. Pure + duck-typed against FS_Plugin_Plan / FS_Pricing so it stays * unit-testable without booting the SDK and resilient to entity drift. * * @param object|null $plan FS_Plugin_Plan-like (->pricing: FS_Pricing[]). * @return array|null Normalized snapshot, or null when nothing is priced. */ public static function extractPlanPricing($plan): ?array { if (!is_object($plan) || !isset($plan->pricing) || !is_array($plan->pricing)) { return null; } $selected = null; $bestScore = -1; foreach ($plan->pricing as $pricing) { if (!is_object($pricing)) { continue; } $monthly = (isset($pricing->monthly_price) && is_numeric($pricing->monthly_price)) ? (float) $pricing->monthly_price : null; $annual = (isset($pricing->annual_price) && is_numeric($pricing->annual_price)) ? (float) $pricing->annual_price : null; $hasMonthly = (null !== $monthly && $monthly > 0); $hasAnnual = (null !== $annual && $annual > 0); if (!$hasMonthly && !$hasAnnual) { continue; } $licenses = $pricing->licenses ?? null; $isSingleSite = (1 === (int) $licenses); $score = ($isSingleSite ? 2 : 0) + (($hasMonthly && $hasAnnual) ? 1 : 0); if ($score > $bestScore) { $bestScore = $score; $selected = array( 'monthly' => $hasMonthly ? $monthly : null, 'annual' => $hasAnnual ? $annual : null, 'currency' => $pricing->currency ?? null, ); } } if (null === $selected) { return null; } $currency = self::normalizeCurrency($selected['currency']); $monthly = $selected['monthly']; $annual = $selected['annual']; $snapshot = array( 'planId' => (isset($plan->id) && is_numeric($plan->id) && (int) $plan->id > 0) ? (int) $plan->id : null, 'currency' => $currency['code'], 'currencySymbol' => $currency['symbol'], 'monthly' => $monthly, 'annual' => $annual, 'annualSavings' => null, 'annualDiscountPercent' => null, 'annualMonthsFree' => null, ); if (null !== $monthly && null !== $annual && $monthly > 0) { $yearlyAtMonthly = $monthly * 12; $savings = round($yearlyAtMonthly - $annual, 2); if ($savings > 0) { $snapshot['annualSavings'] = $savings; $snapshot['annualDiscountPercent'] = (int) floor($savings / $yearlyAtMonthly * 100); $snapshot['annualMonthsFree'] = (int) round($savings / $monthly); } } $tierBuckets = array(); $tierScores = array(); foreach ($plan->pricing as $pricing) { if (!is_object($pricing)) { continue; } $monthly = (isset($pricing->monthly_price) && is_numeric($pricing->monthly_price)) ? (float) $pricing->monthly_price : null; $annual = (isset($pricing->annual_price) && is_numeric($pricing->annual_price)) ? (float) $pricing->annual_price : null; $hasMonthly = (null !== $monthly && $monthly > 0); $hasAnnual = (null !== $annual && $annual > 0); if (!$hasMonthly && !$hasAnnual) { continue; } $rawLicenses = $pricing->licenses ?? null; if (null === $rawLicenses) { continue; } $licenses = (int) $rawLicenses; $score = ($hasMonthly && $hasAnnual) ? 1 : 0; if (!isset($tierBuckets[$licenses]) || $score > $tierScores[$licenses]) { $tierBuckets[$licenses] = array( 'licenses' => $licenses, 'monthly' => $hasMonthly ? $monthly : null, 'annual' => $hasAnnual ? $annual : null, ); $tierScores[$licenses] = $score; } } ksort($tierBuckets); $snapshot['tiers'] = (count($tierBuckets) > 1) ? array_values($tierBuckets) : null; return $snapshot; } /** * Map a Freemius currency code to a display symbol. FS_Pricing::$currency is * one of usd|gbp|eur (lowercase); the SDK exposes no public symbol helper, * so we map the known set and fall back to the uppercased code. * * @param string|null $currency * @return array{code:string,symbol:string} */ public static function normalizeCurrency(?string $currency): array { $code = (is_string($currency) && '' !== $currency) ? strtolower($currency) : 'usd'; $symbols = array( 'usd' => '$', 'eur' => '€', 'gbp' => '£', ); return array( 'code' => strtoupper($code), 'symbol' => $symbols[$code] ?? strtoupper($code), ); } /** * Compute the savings percentage of a multi-site tier versus paying * single-site pricing for the same seat count. Pure + framework-free so * it stays unit-testable and reusable by the frontend via the snapshot. * * Formula: 1 - (tier_annual / (tier_licenses * single_site_annual)), * returned as a rounded integer percent. Returns null when any input is * missing or non-positive (guards every division). * * @param array $tier {licenses: int, annual: float|null}. * @param array $singleSite {annual: float|null}. * @return int|null Savings percent (0-100), or null when not computable. */ public static function computeTierSavingsPercent(array $tier, array $singleSite): ?int { $tierAnnual = $tier['annual'] ?? null; $tierLicenses = $tier['licenses'] ?? null; $siteAnnual = $singleSite['annual'] ?? null; if (!is_numeric($tierAnnual) || (float) $tierAnnual <= 0) { return null; } if (!is_numeric($tierLicenses) || (int) $tierLicenses <= 0) { return null; } if (!is_numeric($siteAnnual) || (float) $siteAnnual <= 0) { return null; } $ratio = (float) $tierAnnual / ((int) $tierLicenses * (float) $siteAnnual); return (int) round((1 - $ratio) * 100); } public function hasBusinessFeature(): bool { return $this->is_registered() && $this->fs->is_plan_or_trial(PlanSlug::BUSINESS); } public function hasProFeature(): bool { return $this->is_registered() && ($this->fs->is_plan_or_trial(PlanSlug::PRO) || $this->fs->is_plan_or_trial(PlanSlug::BUSINESS)); } /** * Checks if user is using premium version files (not just Freemius plan) * This is different from hasProFeature() which only checks Freemius plan */ public function isUsingPremiumFiles(): bool { return $this->fs && $this->fs->is_premium(); } /** * Get the Freemius SDK version bundled with this plugin. * * Reads directly from the SDK's start.php to avoid hardcoding. * Result is statically cached — file is read at most once per request. * * @return string SDK version (e.g. '2.13.0') or empty string if unreadable. */ private function getBundledSdkVersion(): string { static $version = null; if ($version !== null) { return $version; } $start_file = AIPT_PLUGIN_DIR . 'vendor/freemius/wordpress-sdk/start.php'; if (!file_exists($start_file)) { $version = ''; return $version; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents $content = file_get_contents($start_file, false, null, 0, 500); if ($content && preg_match('/\$this_sdk_version\s*=\s*\'([^\']+)\'/', $content, $matches)) { $version = $matches[1]; } else { $version = ''; } return $version; } /** * Build SDK conflict detection result (static helper for testability). * * @param object $newest_data Freemius newest SDK data object (with version, sdk_path). * @param object $active_plugins_obj Full Freemius active plugins registry. * @param string $bundled_version Our bundled SDK version. * @param callable|null $get_plugin_data_resolver Optional resolver for get_plugin_data(). If null, uses WordPress function. * * @return array{has_conflict: bool, active_version: string, active_sdk_path: string, active_plugin_path: string, our_sdk_registered: bool, conflicting_plugin_name: string, conflicting_plugin_file: string, conflicting_sdk_file: string} */ public static function buildSdkConflictResultForTesting( $newest_data, $active_plugins_obj, $bundled_version, $get_plugin_data_resolver = null ): array { $result = [ 'has_conflict' => false, 'active_version' => $bundled_version, 'active_sdk_path' => '', 'active_plugin_path' => '', 'our_sdk_registered' => true, 'conflicting_plugin_name' => '', 'conflicting_plugin_file' => '', 'conflicting_sdk_file' => '', ]; if (empty($active_plugins_obj) || !is_object($active_plugins_obj)) { return $result; } if (!empty($newest_data) && is_object($newest_data)) { $newest_version = $newest_data->version ?? ''; $newest_sdk_path = $newest_data->sdk_path ?? ''; $result['active_version'] = $newest_version; $result['active_sdk_path'] = $newest_sdk_path; if ( !empty($newest_sdk_path) && isset($active_plugins_obj->plugins[$newest_sdk_path]) && is_object($active_plugins_obj->plugins[$newest_sdk_path]) ) { $result['active_plugin_path'] = $active_plugins_obj->plugins[$newest_sdk_path]->plugin_path ?? ''; } $is_dev_version = version_compare($newest_version, '10.0.0', '>='); $is_different_plugin = ( !empty($newest_sdk_path) && strpos($newest_sdk_path, 'ai-product-tools') === false ); if ($is_dev_version && $is_different_plugin) { $result['has_conflict'] = true; if (!empty($result['active_plugin_path'])) { $abs_plugin_file = WP_PLUGIN_DIR . '/' . ltrim($result['active_plugin_path'], '/'); if ($get_plugin_data_resolver !== null && is_callable($get_plugin_data_resolver)) { $plugin_data = $get_plugin_data_resolver($abs_plugin_file); } else { if (!function_exists('get_plugin_data')) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $plugin_data = get_plugin_data($abs_plugin_file, false, false); } if (!empty($plugin_data['Name'])) { $result['conflicting_plugin_name'] = $plugin_data['Name']; } if (file_exists($abs_plugin_file)) { $result['conflicting_plugin_file'] = $abs_plugin_file; } } if (!empty($newest_sdk_path)) { $abs_sdk_file = WP_PLUGIN_DIR . '/' . ltrim($newest_sdk_path, '/'); if (file_exists($abs_sdk_file)) { $result['conflicting_sdk_file'] = $abs_sdk_file; } } } } if (!empty($active_plugins_obj->plugins) && is_array($active_plugins_obj->plugins)) { $our_sdk_found = false; foreach ($active_plugins_obj->plugins as $sdk_path => $data) { if (strpos($sdk_path, 'ai-product-tools') !== false) { $our_sdk_found = true; break; } } $result['our_sdk_registered'] = $our_sdk_found; } return $result; } /** * Detect if another plugin's Freemius SDK is overriding ours. * * Freemius loads only the newest SDK globally. When a third-party plugin * bundles a development SDK (e.g. 999.99.99 from Composer dev-master), * it always wins `version_compare()` and can cause license detection * failures for plugins using stable SDK versions. * * @return array{has_conflict: bool, active_version: string, active_sdk_path: string, active_plugin_path: string, our_sdk_registered: bool, conflicting_plugin_name: string, conflicting_plugin_file: string, conflicting_sdk_file: string} */ public function detectSdkConflict(): array { if ($this->sdk_conflict_info !== null) { return $this->sdk_conflict_info; } global $fs_active_plugins; $active_plugins = $fs_active_plugins; if (empty($active_plugins) || !is_object($active_plugins)) { $active_plugins = get_option('fs_active_plugins'); } $newest_data = null; if (!empty($active_plugins) && is_object($active_plugins) && !empty($active_plugins->newest)) { $newest_data = $active_plugins->newest; } $result = self::buildSdkConflictResultForTesting( $newest_data, $active_plugins, $this->getBundledSdkVersion() ); $this->sdk_conflict_info = $result; return $result; } /** * Show admin notice when an SDK conflict is detected. * * Only shown on plugin pages (WordPress.org Guideline 10/11 compliant) * and dismissible with a 30-day snooze. */ public function maybeShowSdkConflictNotice(): void { if (!$this->isPluginAdminPage()) { return; } $dismissed = get_transient(self::SDK_CONFLICT_DISMISS_TRANSIENT); if ($dismissed) { return; } $conflict = $this->detectSdkConflict(); if (!$conflict['has_conflict']) { return; } $is_unregistered = !$this->is_registered(); $is_licensed_but_locked = false; if ($this->is_registered() && !empty($this->getLicenseId()) && function_exists('aipt_fs')) { $fs = aipt_fs(); if (is_object($fs) && method_exists($fs, 'can_use_premium_code')) { $is_licensed_but_locked = !$fs->can_use_premium_code(); } } $is_shown_paid_sdk_free = in_array($this->getDisplayPlan(), PlanSlug::PAID, true) && PlanSlug::FREE === $this->getPlanType(); $is_affected = $is_unregistered || $is_licensed_but_locked || $is_shown_paid_sdk_free; if (!$is_affected) { return; } $plugin_label = !empty($conflict['conflicting_plugin_name']) ? $conflict['conflicting_plugin_name'] : (!empty($conflict['active_plugin_path']) ? dirname($conflict['active_plugin_path']) : ''); $conflicting_plugin = !empty($plugin_label) ? '' . esc_html($plugin_label) . '' : esc_html__('another plugin', 'ai-product-tools'); $sdk_version = esc_html($conflict['active_version']); $step_b_li = ''; if (!empty($conflict['conflicting_sdk_file']) && current_user_can('manage_options')) { $step_b_li = '
  • ' . sprintf( /* translators: 1: absolute path to conflicting SDK start.php, 2: old version string, 3: replacement version string */ esc_html__( 'Advanced: Or edit the offending file directly. Open %1$s and change line 18 from %2$s to %3$s.', 'ai-product-tools' ), '' . esc_html($conflict['conflicting_sdk_file']) . '', '' . esc_html("\$this_sdk_version = '999.99.99';") . '', '' . esc_html("\$this_sdk_version = '1.99.99';") . '' ) . '
  • '; } // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- $conflicting_plugin, $sdk_version, $step_b_li all pre-escaped above. HTML in //
  • tags is intentional. printf( '

    %s

    %s

    • %s
    • %s

    %s

    ', esc_attr(wp_create_nonce('aipt_dismiss_sdk_conflict')), esc_html__('AI Product Tools: Freemius SDK Conflict Detected', 'ai-product-tools'), sprintf( /* translators: 1: Conflicting plugin name or folder path, 2: SDK version number */ esc_html__( 'A development version of the Freemius SDK (v%2$s) bundled by %1$s is overriding this plugin\'s license system. This may cause your plan to appear as "Free" even if you have an active license. Please contact the developer of %1$s and ask them to use a stable Freemius SDK version, or follow the steps below.', 'ai-product-tools' ), $conflicting_plugin, $sdk_version ), sprintf( /* translators: 1: Plugin name or folder path, 2: HTML link to Plugins admin page */ esc_html__( 'Recommended: Deactivate %1$s from the %2$s page.', 'ai-product-tools' ), $conflicting_plugin, '
    ' . esc_html__('Plugins', 'ai-product-tools') . '' ), $step_b_li, sprintf( /* translators: 1: SDK version string, 2: Freemius debug page link */ esc_html__('Diagnostic: Active SDK v%1$s | See %2$s for details.', 'ai-product-tools'), $sdk_version, 'Freemius Debug' ) ); // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped $this->enqueueDismissScript(); } /** * Enqueue the inline dismiss script for the SDK conflict notice. */ private function enqueueDismissScript(): void { static $enqueued = false; if ($enqueued) { return; } $enqueued = true; add_action('admin_footer', function () { ?>