fs = aipt_fs();
if (is_admin()) {
add_action('wp_loaded', [$this, 'checkPlanChange']);
}
$this->setupFreemiusHooks();
if (false === get_transient(self::PLAN_STATE_TRANSIENT)) {
$this->savePlanState();
}
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;
}
/**
* Freemius olay dinleyicilerini ayarlar
*/
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';
}
/**
* Centrally handles detected Freemius plan changes.
*
* @return array|WP_Error Operation result or error.
*/
private function processDetectedPlanChange() {
try {
delete_transient(self::PLAN_STATE_TRANSIENT);
$this->plan_type_memo = null;
$this->savePlanState();
if (PremiumClassGuard::exists('\AIPT\Premium\Licensing\EntitlementService')) {
\AIPT\Premium\Licensing\EntitlementService::invalidateOnPlanChange();
}
return [
'success' => true,
'message' => 'Plan change processed and local plan state refreshed successfully.'
];
} catch (\Exception $e) {
return new WP_Error('exception_in_process_plan_change', $e->getMessage());
}
}
/**
* 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). Refreshing the plan state here means the admin-only
* checkPlanChange() will no longer see the change, so a downgrade is
* detected and signalled here as well.
*
* @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 {
$old_state = $this->decrypt_plan_state_data(get_transient(self::PLAN_STATE_TRANSIENT));
$old_plan = isset($old_state['plan']) && is_string($old_state['plan']) ? $old_state['plan'] : '';
$this->processDetectedPlanChange();
if ($this->isDowngrade($old_plan, $this->getPlanType())) {
do_action( 'aipt_license_downgrade' );
}
}
/**
* Premium versiyon aktivasyonunu işler
*/
public function handleUpgrade(): void {
$this->processDetectedPlanChange();
}
/**
* Premium versiyon deaktivasyonunu işler (downgrade)
*/
public function handleDowngrade(): void {
$this->processDetectedPlanChange();
do_action( 'aipt_license_downgrade' );
}
/**
* 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();
}
private function getCurrentPlanState(): array {
return [
'plan' => $this->getPlanType(),
'is_registered' => $this->is_registered(),
'license_id' => $this->getLicenseId()
];
}
private function savePlanState(): void {
$plan_state = $this->getCurrentPlanState();
$encrypted_data = $this->encrypt_plan_state_data($plan_state);
set_transient(self::PLAN_STATE_TRANSIENT, $encrypted_data);
}
/**
* Plan state verisini şifreler
*
* @param array $data Şifrelenecek plan state verisi
* @return mixed Şifrelenmiş veri veya başarısızlık durumunda orijinal veri
*/
private function encrypt_plan_state_data(array $data) {
try {
$json = wp_json_encode($data);
if (!is_string($json)) {
$this->log_encryption_failure('json_encode_failed', 'wp_json_encode returned false');
return $data;
}
$encrypted = \AIPT\Utils\Encryption::encrypt($json);
if (is_string($encrypted) && '' !== $encrypted) {
return $encrypted;
}
$this->log_encryption_failure('encrypt_failed', 'Encryption returned empty data');
return $data;
} catch (\Exception $e) {
$this->log_encryption_failure('encrypt_exception', $e->getMessage());
return $data;
}
}
/**
* Plan state verisini çözer
*
* @param mixed $data Çözülecek veri
* @return array Çözülmüş veri veya boş array
*/
private function decrypt_plan_state_data($data): array {
if (empty($data)) {
return [];
}
if (is_string($data)) {
try {
$json = \AIPT\Utils\Encryption::decrypt($data, null, true);
if (is_string($json) && '' !== $json) {
$decoded = json_decode($json, true);
if (is_array($decoded)) {
return $decoded;
}
$raw = base64_decode($json, true);
if (is_string($raw)) {
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
return $decoded;
}
}
}
} catch (\Exception $e) {
}
return $this->decrypt_legacy_cbc_plan_state( $data );
}
if (is_array($data)) {
return $data;
}
return [];
}
/**
* One-time backward-compatible read of a legacy plan-state value.
*
* Reads prefix-less AES-256-CBC payloads formatted as base64(iv . ciphertext)
* with a key derived from sha256(NONCE_KEY . NONCE_SALT). This preserves an
* existing paid-plan cache during the upgrade to Utils\Encryption; the next
* savePlanState() call re-encrypts it in the current format. Returns [] on
* any failure and never generates or stores a key.
*
* @param string $data Legacy encrypted plan-state payload.
* @return array Decrypted plan-state data, or an empty array on failure.
*/
private function decrypt_legacy_cbc_plan_state( string $data ): array {
if ( ! function_exists( 'openssl_decrypt' ) ) {
return [];
}
$salt = ( defined( 'NONCE_KEY' ) ? NONCE_KEY : '' ) . ( defined( 'NONCE_SALT' ) ? NONCE_SALT : '' );
if ( '' === $salt ) {
$salt = (string) get_option( 'aipt_encryption_key', '' );
}
if ( '' === $salt ) {
return [];
}
$key = hash( 'sha256', $salt, true );
$raw = base64_decode( $data, true );
if ( false === $raw || strlen( $raw ) <= 16 ) {
return [];
}
$iv = substr( $raw, 0, 16 );
$ciphertext = substr( $raw, 16 );
if ( strlen( $iv ) !== 16 ) {
return [];
}
$ciphertext = base64_decode( $ciphertext, true );
if ( false === $ciphertext ) {
return [];
}
$json = openssl_decrypt( $ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
if ( false === $json ) {
return [];
}
$decoded = json_decode( $json, true );
return is_array( $decoded ) ? $decoded : [];
}
/**
* Şifreleme başarısızlığını loglar
*
* @param string $event_type Olay tipi
* @param string $error_message Hata mesajı (opsiyonel)
*/
private function log_encryption_failure(string $event_type, string $error_message = ''): void {
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log(sprintf(
'[AIPT FsManager] Encryption event: %s%s',
$event_type,
$error_message ? " - {$error_message}" : ''
));
}
}
public function checkPlanChange(): void {
$oldStateEncrypted = get_transient(self::PLAN_STATE_TRANSIENT);
$oldState = $this->decrypt_plan_state_data($oldStateEncrypted);
$currentState = $this->getCurrentPlanState();
if (empty($oldState)) {
$this->savePlanState();
return;
}
if ($oldState['plan'] !== $currentState['plan'] ||
$oldState['license_id'] !== $currentState['license_id']) {
$is_downgrade = $this->isDowngrade($oldState['plan'], $currentState['plan']);
$this->processDetectedPlanChange();
if ($is_downgrade) {
do_action( 'aipt_license_downgrade' );
}
}
}
/**
* Check if plan change is a downgrade.
*
* @param string $old_plan Old plan type.
* @param string $new_plan New plan type.
* @return bool True if this is a downgrade.
*/
private function isDowngrade(string $old_plan, string $new_plan): bool {
$plan_hierarchy = [
'free' => 0,
'pro' => 1,
'business' => 2,
];
$old_level = $plan_hierarchy[$old_plan] ?? 0;
$new_level = $plan_hierarchy[$new_plan] ?? 0;
return $new_level < $old_level;
}
public function is_registered(): bool {
return $this->fs && $this->fs->is_registered();
}
public function getPlanType(): string {
if (null !== $this->plan_type_memo) {
return $this->plan_type_memo;
}
if (!$this->is_registered()) {
$this->plan_type_memo = 'free';
return $this->plan_type_memo;
}
$cached_state = $this->decrypt_plan_state_data(get_transient(self::PLAN_STATE_TRANSIENT));
$cached_plan = $cached_state['plan_type'] ?? $cached_state['plan'] ?? '';
$cached_license_id = isset($cached_state['license_id']) ? (string) $cached_state['license_id'] : '';
$cached_is_registered = ! empty($cached_state['is_registered']);
$current_license_id = (string) $this->getLicenseId();
$conflict = $this->detectSdkConflict();
$sdk_hijacked = $conflict['has_conflict'] && !$conflict['our_sdk_registered'];
$has_matching_license = (
$cached_license_id !== ''
&& $current_license_id !== ''
&& hash_equals($cached_license_id, $current_license_id)
);
if (in_array($cached_plan, ['pro', 'business'], true) && $sdk_hijacked && $has_matching_license) {
$this->plan_type_memo = $cached_plan;
return $this->plan_type_memo;
}
if ($this->fs->is_plan_or_trial('business')) {
$plan_type = 'business';
} elseif ($this->fs->is_plan_or_trial('pro')) {
$plan_type = 'pro';
} else {
$plan_type = 'free';
}
$stable_unchanged = (
$cached_plan === $plan_type
&& $cached_license_id === $current_license_id
&& true === $cached_is_registered
);
if (! $stable_unchanged) {
set_transient(self::PLAN_STATE_TRANSIENT, $this->encrypt_plan_state_data([
'plan' => $plan_type,
'plan_type' => $plan_type,
'is_registered' => true,
'license_id' => $current_license_id,
'cached_at' => time(),
'source' => 'fresh',
]), DAY_IN_SECONDS);
}
$this->plan_type_memo = $plan_type;
return $this->plan_type_memo;
}
/**
* Force sync license data from Freemius servers and return fresh plan type.
*
* Use when plan_mismatch is detected - this ensures we have the latest
* license data before retrying plan update to remote API.
*
* @return string Fresh plan type after sync (free|pro|business)
*/
public function forceSyncFromFreemius(): string {
if (!$this->fs || !$this->is_registered()) {
return 'free';
}
try {
$this->fs->sync_install([], true);
delete_transient(self::PLAN_STATE_TRANSIENT);
$this->plan_type_memo = null;
return $this->getPlanType();
} catch (\Exception $e) {
if (defined('WP_DEBUG') && WP_DEBUG) {
}
return $this->getPlanType();
}
}
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 only, so a page render never waits on the Freemius API. The
* snapshot wins; the built-in id covers the time before its first refresh.
*
* @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;
return $plan_id > 0 ? $plan_id : 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) {
if (defined('WP_DEBUG') && WP_DEBUG) {
}
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;
}
/**
* Freemius kullanıcı ID'sini getirir
*
* @return string Kullanıcı ID'si veya boş 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 null (the modal falls back to a price-less card)
* and queues a one-off cron event (scheduled on shutdown) that fills the
* cache through refreshBusinessPlanPricing(). Override with the
* `aipt_business_plan_pricing` filter (return null to hide prices).
*
* @return array|null { currency, currencySymbol, monthly, annual,
* annualSavings, annualDiscountPercent } or null.
*/
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', null);
return is_array($filtered) ? $filtered : null;
}
if (!$this->pricing_refresh_queued) {
$this->pricing_refresh_queued = true;
add_action('shutdown', [$this, 'scheduleBusinessPricingRefresh']);
}
$filtered = apply_filters('aipt_business_plan_pricing', null);
return is_array($filtered) ? $filtered : null;
}
/**
* 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.
*/
public function refreshBusinessPlanPricing(): void {
$pricing = $this->resolveBusinessPlanPricing();
if (is_array($pricing)) {
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.
*
* @return array|null
*/
private function resolveBusinessPlanPricing(): ?array {
if (!function_exists('aipt_fs')) {
return null;
}
try {
$fs = aipt_fs();
if (!is_object($fs) || !method_exists($fs, 'get_api_plugin_scope')) {
return null;
}
$api = $fs->get_api_plugin_scope();
$result = $api->get('pricing.json?is_enriched=true');
if (!is_object($result) || empty($result->plans) || !is_array($result->plans)) {
return null;
}
foreach ($result->plans as $plan) {
if (is_object($plan) && isset($plan->name) && 'business' === strtolower((string) $plan->name)) {
$snapshot = self::extractPlanPricing($plan);
if (is_array($snapshot)) {
return $snapshot;
}
}
}
foreach ($result->plans as $plan) {
$snapshot = self::extractPlanPricing($plan);
if (is_array($snapshot)) {
return $snapshot;
}
}
} catch (\Throwable $e) {
return null;
}
return null;
}
/**
* 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('business');
}
public function hasProFeature(): bool {
return $this->is_registered() && ($this->fs->is_plan_or_trial('pro') || $this->fs->is_plan_or_trial('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();
}
/**
* Plan önbelleğini temizler
*/
public function clearPlanCache(): void {
delete_transient(self::PLAN_STATE_TRANSIENT);
$this->plan_type_memo = null;
$this->savePlanState();
}
/**
* Plan değişikliğinde yapılacak tüm işlemleri merkezi olarak yönetir.
* Bu metod, Freemius hook'larından veya periyodik kontrolden çağrılmalıdır.
*
* @return array|WP_Error İşlem sonucu veya hata
*/
public function handlePlanChange() {
return $this->processDetectedPlanChange();
}
/**
* 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;
}
$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_cache_fallback_to_free = false;
if ($this->is_registered()) {
$cached_state = $this->decrypt_plan_state_data(get_transient(self::PLAN_STATE_TRANSIENT));
$cached_plan = $cached_state['plan_type'] ?? $cached_state['plan'] ?? '';
if (in_array($cached_plan, ['pro', 'business'], true)) {
$current_plan = $this->getPlanType();
$is_cache_fallback_to_free = ($current_plan === 'free');
}
}
$is_affected = $is_unregistered || $is_licensed_but_locked || $is_cache_fallback_to_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 = '
' . esc_html($conflict['conflicting_sdk_file']) . '',
'' . esc_html("\$this_sdk_version = '999.99.99';") . '',
'' . esc_html("\$this_sdk_version = '1.99.99';") . ''
) . '%s
%s
%s