Fix File
•
/
home
/
sportsfe...
/
httpdocs
/
wp-conte...
/
plugins
/
content-...
/
inc
/
freemius
/
includes
•
File:
class-freemius.php
•
Content:
<?php /** * @package Freemius * @copyright Copyright (c) 2015, Freemius, Inc. * @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3 * @since 1.0.3 */ if ( ! defined( 'ABSPATH' ) ) { exit; } // "final class" class Freemius extends Freemius_Abstract { /** * SDK Version * * @var string */ public $version = WP_FS__SDK_VERSION; #region Plugin Info /** * @since 1.0.1 * * @var string */ private $_slug; /** * @since 1.0.0 * * @var string */ private $_plugin_basename; /** * @since 2.2.1 * * @var string */ private $_premium_plugin_basename; /** * @since 1.0.0 * * @var string */ private $_free_plugin_basename; /** * @since 1.0.0 * * @var string */ private $_plugin_dir_path; /** * @since 1.0.0 * * @var string */ private $_plugin_dir_name; /** * @since 1.0.0 * * @var string */ private $_plugin_main_file_path; /** * @var string[] */ private $_plugin_data; /** * @since 1.0.9 * * @var string */ private $_plugin_name; /** * @since 1.2.2 * * @var string */ private $_module_type; #endregion Plugin Info /** * @since 1.0.9 * * @var bool If false, don't turn Freemius on. */ private $_is_on; /** * @since 1.1.3 * * @var bool If false, don't turn Freemius on. */ private $_is_anonymous; /** * @since 1.0.9 * @var bool If false, issues with connectivity to Freemius API. */ private $_has_api_connection; /** * @since 1.0.9 * @since 2.0.0 Default to true since we need the property during the instance construction, prior to the dynamic_init() execution. * @var bool Hints the SDK if plugin can support anonymous mode (if skip connect is visible). */ private $_enable_anonymous = true; /** * @since 1.1.7.5 * @var bool Hints the SDK if plugin should run in anonymous mode (only adds feedback form). */ private $_anonymous_mode; /** * @since 1.1.9 * @var bool Hints the SDK if plugin have any free plans. */ private $_is_premium_only; /** * @since 1.2.1.6 * @var bool Hints the SDK if plugin have premium code version at all. */ private $_has_premium_version; /** * @since 1.2.1.6 * @var bool Hints the SDK if plugin should ignore pending mode by simulating a skip. */ private $_ignore_pending_mode; /** * @since 1.0.8 * @var bool Hints the SDK if the plugin has any paid plans. */ private $_has_paid_plans; /** * @since 1.2.1.5 * @var int Hints the SDK if the plugin offers a trial period. If negative, no trial, if zero - has a trial but * without a specified period, if positive - the number of trial days. */ private $_trial_days = - 1; /** * @since 1.2.1.5 * @var bool Hints the SDK if the trial requires a payment method or not. */ private $_is_trial_require_payment = false; /** * @since 1.0.7 * @var bool Hints the SDK if the plugin is WordPress.org compliant. */ private $_is_org_compliant; /** * @since 1.0.7 * @var bool Hints the SDK if the plugin is has add-ons. */ private $_has_addons; /** * @since 2.4.5 * @var string Navigation type: 'menu' or 'tabs'. */ private $_navigation; const NAVIGATION_MENU = 'menu'; const NAVIGATION_TABS = 'tabs'; /** * @since 1.1.6 * @var string[]bool. */ private $_permissions; /** * @var FS_Storage */ private $_storage; /** * @since 1.2.2.7 * @var FS_Cache_Manager */ private $_cache; /** * @since 1.0.0 * * @var FS_Logger */ private $_logger; /** * @since 1.0.4 * * @var FS_Plugin */ private $_plugin = false; /** * @since 1.0.4 * * @var FS_Plugin|false */ private $_parent_plugin = false; /** * @since 1.1.1 * * @var Freemius */ private $_parent = false; /** * @since 1.0.1 * * @var FS_User */ private $_user = false; /** * @since 1.0.1 * * @var FS_Site */ private $_site = false; /** * @since 1.0.1 * * @var FS_Plugin_License */ private $_license; /** * @since 1.0.2 * * @var FS_Plugin_Plan[] */ private $_plans = false; /** * @var FS_Plugin_License[] * @since 1.0.5 */ private $_licenses = false; /** * @since 1.0.1 * * @var FS_Admin_Menu_Manager */ private $_menu; /** * @var FS_Admin_Notices */ private $_admin_notices; /** * @since 1.1.6 * * @var FS_Admin_Notices */ private static $_global_admin_notices; /** * @var FS_Logger * @since 1.0.0 */ private static $_static_logger; /** * @var FS_Options * @since 1.0.2 */ private static $_accounts; /** * @since 1.2.2 * * @var number */ private $_module_id; /** * @var Freemius[] */ private static $_instances = array(); /** * @since 1.2.3 * * @var FS_Affiliate */ private $affiliate = null; /** * @since 1.2.3 * * @var FS_AffiliateTerms */ private $plugin_affiliate_terms = null; /** * @since 1.2.3 * * @var FS_AffiliateTerms */ private $custom_affiliate_terms = null; /** * @since 2.0.0 * * @var bool */ private $_is_multisite_integrated; /** * @since 2.0.0 * * @var bool True if the current request is for a network admin screen and the plugin is network active. */ private $_is_network_active; /** * @since 2.0.0 * * @var int|null The original blog ID the plugin was loaded with. */ private $_blog_id = null; /** * @since 2.0.0 * * @var int|null The current execution context. When true, run on network context. When int, run on the specified blog context. */ private $_context_is_network_or_blog_id = null; /** * @since 2.0.0 * * @var string */ private $_dynamically_added_top_level_page_hook_name = ''; /** * @author Leo Fajardo (@leorw) * @since 2.3.1 * * @var bool */ private $is_whitelabeled; /** * @author Leo Fajardo (@leorw) * @since 2.4.0 * * @var bool */ private $_is_bundle_license_auto_activation_enabled = false; #region Uninstall Reasons IDs const REASON_NO_LONGER_NEEDED = 1; const REASON_FOUND_A_BETTER_PLUGIN = 2; const REASON_NEEDED_FOR_A_SHORT_PERIOD = 3; const REASON_BROKE_MY_SITE = 4; const REASON_SUDDENLY_STOPPED_WORKING = 5; const REASON_CANT_PAY_ANYMORE = 6; const REASON_OTHER = 7; const REASON_DIDNT_WORK = 8; const REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION = 9; const REASON_COULDNT_MAKE_IT_WORK = 10; const REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE = 11; const REASON_NOT_WORKING = 12; const REASON_NOT_WHAT_I_WAS_LOOKING_FOR = 13; const REASON_DIDNT_WORK_AS_EXPECTED = 14; const REASON_TEMPORARY_DEACTIVATION = 15; #endregion /** * @author Leo Fajardo (@leorw) * @since 2.3.1 * * @var boolean|null */ private $_use_external_pricing = null; /** * @author Leo Fajardo (@leorw) * @since 2.4.2 * * @var string|null */ private $_pricing_js_path = null; const VERSION_MAX_CHARS = 16; const LANGUAGE_MAX_CHARS = 8; /* Ctor ------------------------------------------------------------------------------------------------------------------*/ /** * Main singleton instance. * * @author Vova Feldman (@svovaf) * @since 1.0.0 * * @param number $module_id * @param string|bool $slug * @param bool $is_init Since 1.2.1 Is initiation sequence. */ private function __construct( $module_id, $slug = false, $is_init = false ) { $main_file = false; if ( $is_init && is_numeric( $module_id ) && is_string( $slug ) ) { $main_file = $this->store_id_slug_type_path_map( $module_id, $slug ); } $this->_module_id = $module_id; $this->_slug = $this->get_slug(); $this->_module_type = $this->get_module_type(); $this->_blog_id = is_multisite() ? get_current_blog_id() : null; $this->_storage = FS_Storage::instance( $this->_module_type, $this->_slug ); // If not set or 24 hours have already passed from the last time it's set, set the last load timestamp to the current time. if ( ! isset( $this->_storage->last_load_timestamp ) || $this->_storage->last_load_timestamp < ( time() - ( WP_FS__TIME_24_HOURS_IN_SEC ) ) ) { $this->_storage->last_load_timestamp = time(); } $this->_cache = FS_Cache_Manager::get_manager( WP_FS___OPTION_PREFIX . "cache_{$module_id}" ); $this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $this->get_unique_affix(), WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK ); $this->_plugin_main_file_path = $this->_find_caller_plugin_file( $is_init, $main_file ); $this->_plugin_dir_path = plugin_dir_path( $this->_plugin_main_file_path ); $this->_plugin_basename = $this->get_plugin_basename(); $this->_free_plugin_basename = str_replace( '-premium/', '/', $this->_plugin_basename ); $this->_is_multisite_integrated = ( defined( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) && ( true === constant( "WP_FS__PRODUCT_{$module_id}_MULTISITE" ) ) ); $this->_is_network_active = ( is_multisite() && $this->_is_multisite_integrated && // Themes are always network activated, but the ACTUAL activation is per site. $this->is_plugin() && ( is_plugin_active_for_network( $this->_plugin_basename ) || // Plugin network level activation or uninstall. ( fs_is_network_admin() && is_plugin_inactive( $this->_plugin_basename ) ) ) ); $this->_storage->set_network_active( $this->_is_network_active, $this->is_delegated_connection() ); if ( ! isset( $this->_storage->is_network_activated ) ) { $this->_storage->is_network_activated = $this->_is_network_active; } if ( $this->_storage->is_network_activated != $this->_is_network_active ) { // Update last activation level. $this->_storage->is_network_activated = $this->_is_network_active; $this->maybe_adjust_storage(); } #region Migration if ( is_multisite() ) { /** * If the install_timestamp exists on the site level but doesn't exist on the * network level storage, it means that we need to process the storage with migration. * * The code in this `if` scope will only be executed once and only for the first site that will execute it because once we migrate the storage data, install_timestamp will be already set in the network level storage. * * @author Vova Feldman (@svovaf) * @since 2.0.0 */ if ( false === $this->_storage->get( 'install_timestamp', false, true ) && false !== $this->_storage->get( 'install_timestamp', false, false ) ) { // Initiate storage migration. $this->_storage->migrate_to_network(); // Migrate module cache to network level storage. $this->_cache->migrate_to_network(); } } #endregion $base_name_split = explode( '/', $this->_plugin_basename ); $this->_plugin_dir_name = $base_name_split[0]; if ( $this->_logger->is_on() ) { $this->_logger->info( 'plugin_main_file_path = ' . $this->_plugin_main_file_path ); $this->_logger->info( 'plugin_dir_path = ' . $this->_plugin_dir_path ); $this->_logger->info( 'plugin_basename = ' . $this->_plugin_basename ); $this->_logger->info( 'free_plugin_basename = ' . $this->_free_plugin_basename ); $this->_logger->info( 'plugin_dir_name = ' . $this->_plugin_dir_name ); } // Remember link between file to slug. $this->store_file_slug_map(); // Store plugin's initial install timestamp. if ( ! isset( $this->_storage->install_timestamp ) ) { $this->_storage->install_timestamp = WP_FS__SCRIPT_START_TIME; } if ( ! is_object( $this->_plugin ) ) { $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->get(); } $this->_admin_notices = FS_Admin_Notices::instance( $this->_slug . ( $this->is_theme() ? ':theme' : '' ), /** * Ensure that the admin notice will always have a title by using the stored plugin title if available and * retrieving the title via the "get_plugin_name" method if there is no stored plugin title available. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ ( is_object( $this->_plugin ) && isset( $this->_plugin->title ) ? $this->_plugin->title : $this->get_plugin_name() ), $this->get_unique_affix() ); if ( 'true' === fs_request_get( 'fs_clear_api_cache' ) || fs_request_is_action( 'restart_freemius' ) ) { FS_Api::clear_cache(); $this->_cache->clear(); } $this->register_constructor_hooks(); /** * Starting from version 2.0.0, `FS_Site` entities no longer have the `plan` property and have `plan_id` * instead. This should be called before calling `_load_account()`, otherwise, `$this->_site` will not be * loaded in `_load_account` for versions of SDK starting from 2.0.0. * * @author Leo Fajardo (@leorw) */ self::migrate_install_plan_to_plan_id( $this->_storage ); $this->_load_account(); $this->_version_updates_handler(); } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 */ private function maybe_adjust_storage() { $install_timestamp = null; $prev_is_premium = null; $options_to_update = array(); $is_network_admin = fs_is_network_admin(); $network_install_timestamp = $this->_storage->get( 'install_timestamp', null, true ); if ( ! $is_network_admin ) { if ( is_null( $network_install_timestamp ) ) { // Plugin was not network-activated before. return; } if ( is_null( $this->_storage->get( 'install_timestamp', null, false ) ) ) { // Set the `install_timestamp` only if it's not yet set. $install_timestamp = $network_install_timestamp; } $prev_is_premium = $this->_storage->get( 'prev_is_premium', null, true ); } else { $current_wp_user = self::_get_current_wp_user(); $current_fs_user = self::_get_user_by_email( $current_wp_user->user_email ); $network_user_info = array(); $skips_count = 0; $sites = self::get_sites(); $sites_count = count( $sites ); $blog_id_2_install_map = array(); $is_first_non_ignored_blog = true; foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); $blog_install_timestamp = $this->_storage->get( 'install_timestamp', null, $blog_id ); if ( is_null( $blog_install_timestamp ) ) { // Plugin has not been installed on this blog. continue; } $is_earlier_install = ( ! is_null( $install_timestamp ) && $blog_install_timestamp < $install_timestamp ); $install = $this->get_install_by_blog_id( $blog_id ); $update_network_user_info = false; if ( ! is_object( $install ) ) { if ( ! $this->_storage->get( 'is_anonymous', false, $blog_id ) ) { // The opt-in decision (whether to skip or opt in) is yet to be made. continue; } $skips_count ++; } else { $blog_id_2_install_map[ $blog_id ] = $install; if ( empty( $network_user_info ) ) { // Set the network user info for the 1st time. Choose any user information whether or not it is for the current WP user. $update_network_user_info = true; } if ( ! $update_network_user_info && is_object( $current_fs_user ) && $network_user_info['user_id'] != $current_fs_user->id && $install->user_id == $current_fs_user->id ) { // If an install that is owned by the current WP user is found, use its user information instead. $update_network_user_info = true; } if ( ! $update_network_user_info && $is_earlier_install && ( ! is_object( $current_fs_user ) || $current_fs_user->id == $install->user_id ) ) { // Update to the earliest install info if there's no install found so far that is owned by the current WP user; OR only if the found install is owned by the current WP user. $update_network_user_info = true; } } if ( $update_network_user_info ) { $network_user_info = array( 'user_id' => $install->user_id, 'blog_id' => $blog_id ); } $site_prev_is_premium = $this->_storage->get( 'prev_is_premium', null, $blog_id ); if ( $is_first_non_ignored_blog ) { $prev_is_premium = $site_prev_is_premium; if ( is_null( $network_install_timestamp ) ) { $install_timestamp = $blog_install_timestamp; } $is_first_non_ignored_blog = false; continue; } if ( ! is_null( $prev_is_premium ) && $prev_is_premium !== $site_prev_is_premium ) { // If a different `$site_prev_is_premium` value is found, do not include the option in the collection of options to update. $prev_is_premium = null; } if ( $is_earlier_install ) { // If an earlier install timestamp is found. $install_timestamp = $blog_install_timestamp; } } $installs_count = count( $blog_id_2_install_map ); if ( $sites_count === ( $installs_count + $skips_count ) ) { if ( ! empty( $network_user_info ) ) { $options_to_update['network_user_id'] = $network_user_info['user_id']; $options_to_update['network_install_blog_id'] = $network_user_info['blog_id']; foreach ( $blog_id_2_install_map as $blog_id => $install ) { if ( $install->user_id == $network_user_info['user_id'] ) { continue; } $this->_storage->store( 'is_delegated_connection', true, $blog_id ); } } if ( $sites_count === $skips_count ) { /** * Assume network-level skipping as the intended action if all actions identified were only * skipping of the connection (i.e., no opt-ins and delegated connections so far). */ $options_to_update['is_anonymous_ms'] = true; } else if ( $sites_count === $installs_count ) { /** * Assume network-level opt-in as the intended action if all actions identified were only opt-ins * (i.e., no delegation and skipping of the connections so far). */ $options_to_update['is_network_connected'] = true; } } } if ( ! is_null( $install_timestamp ) ) { $options_to_update['install_timestamp'] = $install_timestamp; } if ( ! is_null( $prev_is_premium ) ) { $options_to_update['prev_is_premium'] = $prev_is_premium; } if ( ! empty( $options_to_update ) ) { $this->adjust_storage( $options_to_update, $is_network_admin ); } } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 * * @param array $options * @param bool $is_network_admin */ private function adjust_storage( $options, $is_network_admin ) { foreach ( $options as $name => $value ) { $this->_storage->store( $name, $value, $is_network_admin ? true : null ); } } /** * Checks whether this module has a settings menu. * * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @return bool */ function has_settings_menu() { return ( $this->_is_network_active && fs_is_network_admin() ) ? $this->_menu->has_network_menu() : $this->_menu->has_menu(); } /** * If `true` the opt-in should be shown as a modal dialog box on the themes.php page. WordPress.org themes guidelines prohibit from redirecting the user from the themes.php page after activating a theme. * * @author Vova Feldman (@svovaf) * @since 2.4.5 * * @return bool */ function show_opt_in_on_themes_page() { if ( ! $this->is_free_wp_org_theme() ) { return false; } if ( ! $this->has_settings_menu() ) { return true; } return $this->show_settings_with_tabs(); } /** * If `true` the opt-in should be shown on the product's main setting page. * * @author Vova Feldman (@svovaf) * @since 2.4.5 * * @return bool * * @uses show_opt_in_on_themes_page(); */ function show_opt_in_on_setting_page() { return ! $this->show_opt_in_on_themes_page(); } /** * If `true` the settings should be shown using tabs. * * @author Vova Feldman (@svovaf) * @since 2.4.5 * * @return bool */ function show_settings_with_tabs() { return ( self::NAVIGATION_TABS === $this->_navigation ); } /** * Check if the context module is free wp.org theme. * * This method is helpful because: * 1. wp.org themes are limited to a single submenu item, * and sub-submenu items are most likely not allowed (never verified). * 2. wp.org themes are not allowed to redirect the user * after the theme activation, therefore, the agreed UX * is showing the opt-in as a modal dialog box after * activation (approved by @otto42, @emiluzelac, @greenshady, @grapplerulrich). * * @author Vova Feldman (@svovaf) * @since 1.2.2.7 * * @return bool */ function is_free_wp_org_theme() { return ( $this->is_theme() && $this->is_org_repo_compliant() && ! $this->is_premium() ); } /** * Checks whether this a submenu item is visible. * * @author Vova Feldman (@svovaf) * @since 1.2.2.6 * @since 1.2.2.7 Even if the menu item was specified to be hidden, when it is the context page, then show the submenu item so the user will have the right context page. * * @param string $slug * @param bool $is_tabs_visibility_check This is used to decide if the associated tab should be shown or hidden. * * @return bool */ function is_submenu_item_visible( $slug, $is_tabs_visibility_check = false ) { if ( $this->is_admin_page( $slug ) ) { /** * It is the current context page, so show the submenu item * so the user will have the right context page, even if it * was set to hidden. */ return true; } if ( ! $this->has_settings_menu() ) { // No menu settings at all. return false; } if ( ! $is_tabs_visibility_check && $this->is_org_repo_compliant() && $this->show_settings_with_tabs() ) { /** * wp.org themes are limited to a single submenu item, and * sub-submenu items are most likely not allowed (never verified). */ return false; } return $this->_menu->is_submenu_item_visible( $slug ); } /** * Check if a Freemius page should be accessible via the UI. * * @author Vova Feldman (@svovaf) * @since 1.2.2.7 * * @param string $slug * * @return bool */ function is_page_visible( $slug ) { if ( $this->is_admin_page( $slug ) ) { return true; } return $this->_menu->is_submenu_item_visible( $slug, true, true ); } /** * @author Vova Feldman (@svovaf) * @since 1.0.9 */ private function _version_updates_handler() { if ( ! isset( $this->_storage->sdk_version ) || $this->_storage->sdk_version != $this->version ) { // Freemius version upgrade mode. $this->_storage->sdk_last_version = $this->_storage->sdk_version; $this->_storage->sdk_version = $this->version; if ( empty( $this->_storage->sdk_last_version ) || version_compare( $this->_storage->sdk_last_version, $this->version, '<' ) ) { $this->_storage->sdk_upgrade_mode = true; $this->_storage->sdk_downgrade_mode = false; } else { $this->_storage->sdk_downgrade_mode = true; $this->_storage->sdk_upgrade_mode = false; } $this->do_action( 'sdk_version_update', $this->_storage->sdk_last_version, $this->version ); } $plugin_version = $this->get_plugin_version(); if ( ! isset( $this->_storage->plugin_version ) || $this->_storage->plugin_version != $plugin_version ) { // Plugin version upgrade mode. $this->_storage->plugin_last_version = $this->_storage->plugin_version; $this->_storage->plugin_version = $plugin_version; if ( empty( $this->_storage->plugin_last_version ) || version_compare( $this->_storage->plugin_last_version, $plugin_version, '<' ) ) { $this->_storage->plugin_upgrade_mode = true; $this->_storage->plugin_downgrade_mode = false; } else { $this->_storage->plugin_downgrade_mode = true; $this->_storage->plugin_upgrade_mode = false; } if ( ! empty( $this->_storage->plugin_last_version ) ) { // Different version of the plugin was installed before, therefore it's an update. $this->_storage->is_plugin_new_install = false; } $this->do_action( 'plugin_version_update', $this->_storage->plugin_last_version, $plugin_version ); } } #-------------------------------------------------------------------------------- #region Data Migration on SDK Update #-------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 1.1.5 * * @param string $sdk_prev_version * @param string $sdk_version */ function _sdk_version_update( $sdk_prev_version, $sdk_version ) { if ( empty( $sdk_prev_version ) ) { return; } if ( version_compare( $sdk_prev_version, '2.5.1', '<' ) && version_compare( $sdk_version, '2.5.1', '>=' ) ) { if ( $this->is_registered( true ) ) { /** * Migrate to new permissions layer. */ require_once WP_FS__DIR_INCLUDES . '/supplements/fs-migration-2.5.1.php'; $install_by_blog_id = is_multisite() ? $this->get_blog_install_map() : array( 0 => $this->_site ); fs_migrate_251( $this, $install_by_blog_id ); } } } /** * @author Leo Fajardo (@leorw) * @since 2.0.0 * * @param \FS_Storage $storage * @param bool|int|null $blog_id */ private static function migrate_install_plan_to_plan_id( FS_Storage $storage, $blog_id = null ) { if ( empty( $storage->sdk_version ) ) { // New installation of the plugin, no need to upgrade. return; } if ( ! version_compare( $storage->sdk_version, '2.0.0', '<' ) ) { // Previous version is >= 2.0.0, so no need to migrate. return; } // Alias. $module_type = $storage->get_module_type(); $module_slug = $storage->get_module_slug(); $installs = self::get_all_sites( $module_type, $blog_id ); $install = isset( $installs[ $module_slug ] ) ? $installs[ $module_slug ] : null; if ( ! is_object( $install ) ) { return; } if ( isset( $install->plan ) && is_object( $install->plan ) ) { if ( isset( $install->plan->id ) && ! empty( $install->plan->id ) ) { $install->plan_id = self::_decrypt( $install->plan->id ); } unset( $install->plan ); $installs[ $module_slug ] = clone $install; self::set_account_option_by_module( $module_type, 'sites', $installs, true, $blog_id ); } } /** * @author Vova Feldman (@svovaf) * @since 1.2.2.7 * * @param string $plugin_prev_version * @param string $plugin_version */ function _after_version_update( $plugin_prev_version, $plugin_version ) { if ( $this->is_theme() ) { // Expire the cache of the previous tabs since the theme may // have setting updates. $this->_cache->expire( 'tabs' ); $this->_cache->expire( 'tabs_stylesheets' ); } } /** * A special migration logic for the $_accounts, executed for all the plugins in the system: * - Moves some data to the network level storage. * - If the plugin's connection was skipped for all sites, set the plugin as if it was network skipped. * - If the plugin's connection was ignored for all sites, don't do anything in terms of the network connection. * - If the plugin was connected to all sites by the same super-admin, set the plugin as if was network opted-in for all sites. * - If there's at least one site that was connected by a super-admin, find the "main super-admin" (the one that installed the majority of the plugin installs) and set the plugin as if was network activated with the main super-admin, set all the sites that were skipped or opted-in with a different user to delegated mode. Then, prompt the currently logged super-admin to choose what to do with the ignored sites. * - If there are any sites in the network which the connection decision was not yet taken for, set this plugin into network activation mode so a super-admin can choose what to do with the rest of the sites. * * @author Vova Feldman (@svovaf) * @since 2.0.0 */ private static function migrate_accounts_to_network() { $sites = self::get_sites(); $sites_count = count( $sites ); $connection_status = array(); $plugin_slugs = array(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); self::$_accounts->migrate_to_network( $blog_id ); /** * Build a list of all Freemius powered plugins slugs. */ $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array(), $blog_id ); foreach ( $id_slug_type_path_map as $module_id => $data ) { if ( WP_FS__MODULE_TYPE_PLUGIN === $data['type'] ) { $plugin_slugs[ $data['slug'] ] = true; } } $installs = self::get_account_option( 'sites', WP_FS__MODULE_TYPE_PLUGIN, $blog_id ); if ( is_array( $installs ) ) { foreach ( $installs as $slug => $install ) { if ( ! isset( $connection_status[ $slug ] ) ) { $connection_status[ $slug ] = array(); } if ( is_object( $install ) && FS_Site::is_valid_id( $install->id ) && FS_User::is_valid_id( $install->user_id ) ) { $connection_status[ $slug ][ $blog_id ] = $install->user_id; } } } } foreach ( $plugin_slugs as $slug => $true ) { if ( ! isset( $connection_status[ $slug ] ) ) { $connection_status[ $slug ] = array(); } foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); if ( isset( $connection_status[ $slug ][ $blog_id ] ) ) { continue; } $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug ); $is_anonymous = $storage->get( 'is_anonymous', null, $blog_id ); if ( ! is_null( $is_anonymous ) ) { // Since 1.1.3 is_anonymous is an array. if ( is_array( $is_anonymous ) && isset( $is_anonymous['is'] ) ) { $is_anonymous = $is_anonymous['is']; } if ( is_bool( $is_anonymous ) && true === $is_anonymous ) { $connection_status[ $slug ][ $blog_id ] = 'skipped'; } } if ( ! isset( $connection_status[ $slug ][ $blog_id ] ) ) { $connection_status[ $slug ][ $blog_id ] = 'ignored'; } } } $super_admins = array(); foreach ( $connection_status as $slug => $blogs_status ) { $skips = 0; $ignores = 0; $connections = 0; $opted_in_users = array(); $opted_in_super_admins = array(); $storage = FS_Storage::instance( WP_FS__MODULE_TYPE_PLUGIN, $slug ); foreach ( $blogs_status as $blog_id => $status_or_user_id ) { if ( 'skipped' === $status_or_user_id ) { $skips ++; } else if ( 'ignored' === $status_or_user_id ) { $ignores ++; } else if ( FS_User::is_valid_id( $status_or_user_id ) ) { $connections ++; if ( ! isset( $opted_in_users[ $status_or_user_id ] ) ) { $opted_in_users[ $status_or_user_id ] = array(); } $opted_in_users[ $status_or_user_id ][] = $blog_id; if ( isset( $super_admins[ $status_or_user_id ] ) || self::is_super_admin( $status_or_user_id ) ) { // Cache super-admin data. $super_admins[ $status_or_user_id ] = true; // Remember opted-in super-admins for the plugin. $opted_in_super_admins[ $status_or_user_id ] = true; } } } $main_super_admin_user_id = null; $all_migrated = false; if ( $sites_count == $skips ) { // All sites were skipped -> network skip by copying the anonymous mode from any of the sites. $storage->is_anonymous_ms = $storage->is_anonymous; $all_migrated = true; } else if ( $sites_count == $ignores ) { // Don't do anything, still in activation mode. $all_migrated = true; } else if ( 0 < count( $opted_in_super_admins ) ) { // Find the super-admin with the majority of installs. $max_installs_by_super_admin = 0; foreach ( $opted_in_super_admins as $user_id => $true ) { $installs_count = count( $opted_in_users[ $user_id ] ); if ( $installs_count > $max_installs_by_super_admin ) { $max_installs_by_super_admin = $installs_count; $main_super_admin_user_id = $user_id; } } if ( $sites_count == $connections && 1 == count( $opted_in_super_admins ) ) { // Super-admin opted-in for all sites in the network. $storage->is_network_connected = true; $all_migrated = true; } // Store network user. $storage->network_user_id = $main_super_admin_user_id; $storage->network_install_blog_id = ( $sites_count == $connections ) ? // Since all sites are opted-in, associating with the main site. get_current_blog_id() : // Associating with the 1st found opted-in site. $opted_in_users[ $main_super_admin_user_id ][0]; /** * Make sure we migrate the plan ID of the network install, otherwise, if after the migration * the 1st page that will be loaded is the network level WP Admin and $storage->network_install_blog_id * is different than the main site of the network, the $this->_site will not be set since the plan_id * will be empty. */ $storage->migrate_to_network(); self::migrate_install_plan_to_plan_id( $storage, $storage->network_install_blog_id ); } else { // At least one opt-in. All the opt-in were created by a non-super-admin. if ( 0 == $ignores ) { // All sites were opted-in or skipped, all by non-super-admin. So delegate all. $storage->store( 'is_delegated_connection', true, true ); $all_migrated = true; } } if ( ! $all_migrated ) { /** * Delegate all sites that were: * 1) Opted-in by a user that is NOT the main-super-admin. * 2) Skipped and non of the sites was opted-in by a super-admin. If any site was opted-in by a super-admin, there will be a main-super-admin, and we consider the skip as if it was done by that user. */ foreach ( $blogs_status as $blog_id => $status_or_user_id ) { if ( $status_or_user_id == $main_super_admin_user_id ) { continue; } if ( FS_User::is_valid_id( $status_or_user_id ) || ( 'skipped' === $status_or_user_id && is_null( $main_super_admin_user_id ) ) ) { $storage->store( 'is_delegated_connection', true, $blog_id ); } } } if ( ( $connections + $skips > 0 ) ) { if ( $ignores > 0 ) { /** * If admin already opted-in or skipped in any of the network sites, and also * have sites which the connection decision was not yet taken, set this plugin * into network activation mode so the super-admin can choose what to do with * the rest of the sites. */ self::set_network_upgrade_mode( $storage ); } } } } /** * Set a module into network upgrade mode. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param \FS_Storage $storage * * @return bool */ private static function set_network_upgrade_mode( FS_Storage $storage ) { return $storage->is_network_activation = true; } /** * Will return true after upgrading to the SDK with the network level integration, * when the super-admin involvement is required regarding the rest of the sites. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return bool */ function is_network_upgrade_mode() { return $this->_storage->get( 'is_network_activation' ); } /** * Clear flag after the upgrade mode completion. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return bool True if network activation was on and now completed. */ private function network_upgrade_mode_completed() { if ( fs_is_network_admin() && $this->is_network_upgrade_mode() ) { $this->_storage->remove( 'is_network_activation' ); return true; } return false; } #endregion /** * This action is connected to the 'plugins_loaded' hook and helps to determine * if this is a new plugin installation or a plugin update. * * There are 3 different use-cases: * 1) New plugin installation right with Freemius: * 1.1 _activate_plugin_event_hook() will be executed first * 1.2 Since $this->_storage->is_plugin_new_install is not set, * and $this->_storage->plugin_last_version is not set, * $this->_storage->is_plugin_new_install will be set to TRUE. * 1.3 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will * be already set to TRUE. * * 2) Plugin update, didn't have Freemius before, and now have the SDK: * 2.1 _activate_plugin_event_hook() will not be executed, because * the activation hook do NOT fires on updates since WP 3.1. * 2.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install will * be empty, therefore, it will be set to FALSE. * * 3) Plugin update, had Freemius in prev version as well: * 3.1 _version_updates_handler() will be executed 1st, since FS was installed * before, $this->_storage->plugin_last_version will NOT be empty, * therefore, $this->_storage->is_plugin_new_install will be set to FALSE. * 3.2 When _plugins_loaded() will be executed, $this->_storage->is_plugin_new_install is * already set, therefore, it will not be modified. * * Use-case #3 is backward compatible, #3.1 will be executed since 1.0.9. * * NOTE: * The only fallback of this mechanism is if an admin updates a plugin based on use-case #2, * and then, the next immediate PageView is the plugin's main settings page, it will not * show the opt-in right away. The reason it will happen is because Freemius execution * will be turned off till the plugin is fully loaded at least once * (till $this->_storage->was_plugin_loaded is TRUE). * * @author Vova Feldman (@svovaf) * @since 1.1.9 * */ function _plugins_loaded() { // Update flag that plugin was loaded with Freemius at least once. $this->_storage->was_plugin_loaded = true; /** * Bug fix - only set to false when it's a plugin, due to the * execution sequence of the theme hooks and our methods, if * this will be set for themes, Freemius will always assume * it's a theme update. * * @author Vova Feldman (@svovaf) * @since 1.2.2.2 */ if ( $this->is_plugin() && ! isset( $this->_storage->is_plugin_new_install ) ) { $this->_storage->is_plugin_new_install = ( ! is_plugin_active( $this->_plugin_basename ) && empty( $this->_storage->plugin_last_version ) ); } } function _run_garbage_collector() { if ( true !== fs_get_optional_constant( 'WP_FS__ENABLE_GARBAGE_COLLECTOR', true ) ) { return; } if ( ! $this->is_user_in_admin() ) { return; } require_once WP_FS__DIR_INCLUDES . '/class-fs-lock.php'; $lock = new FS_Lock( 'garbage_collection' ); if ( $lock->is_locked() ) { return; } // Create a 1-day lock. $lock->lock( WP_FS__TIME_24_HOURS_IN_SEC ); FS_Garbage_Collector::instance()->clean(); } /** * Opens the support forum subemenu item in a new browser page. * * @author Vova Feldman (@svovaf) * @since 2.1.4 */ static function _open_support_forum_in_new_page() { ?> <script type="text/javascript"> (function ($) { $('.fs-submenu-item.wp-support-forum').parent().attr( { target: '_blank', rel: 'noopener noreferrer' } ); })(jQuery); </script> <?php } /** * @author Vova Feldman (@svovaf) * @since 1.0.9 */ private function register_constructor_hooks() { $this->_logger->entrance(); if ( is_admin() ) { add_action( 'admin_init', array( &$this, '_hook_action_links_and_register_account_hooks' ) ); if ( $this->is_plugin() ) { if ( self::is_plugin_install_page() && true !== fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) { /** * Unless the `fs_allow_updater_and_dialog` URL param exists and its value is `true`, make * Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php) * so that they won't interfere with the .org plugins' functionalities on that page (e.g. * updating of a .org plugin). */ add_filter( 'site_transient_update_plugins', array( 'Freemius', '_remove_fs_updates_from_plugin_install_page' ), 10, 2 ); } else if ( self::is_plugins_page() || self::is_updates_page() ) { /** * On the "Plugins" and "Updates" admin pages, if there are premium or non–org-compliant plugins, modify their details dialog URLs (add a Freemius-specific param) so that the SDK can determine if the plugin information dialog should show information from Freemius. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ add_action( 'admin_footer', array( 'Freemius', '_prepend_fs_allow_updater_and_dialog_flag_url_param' ) ); } $plugin_dir = dirname( $this->_plugin_dir_path ) . '/'; /** * @since 1.2.2 * * Hook to both free and premium version activations to support * auto deactivation on the other version activation. */ register_activation_hook( $plugin_dir . $this->_free_plugin_basename, array( &$this, '_activate_plugin_event_hook' ) ); register_activation_hook( $plugin_dir . $this->premium_plugin_basename(), array( &$this, '_activate_plugin_event_hook' ) ); } else { add_action( 'after_switch_theme', array( &$this, '_activate_theme_event_hook' ), 10, 2 ); add_action( 'admin_footer', array( &$this, '_style_premium_theme' ) ); } /** * Part of the mechanism to identify new plugin install vs. plugin update. * * @author Vova Feldman (@svovaf) * @since 1.1.9 */ if ( empty( $this->_storage->was_plugin_loaded ) ) { /** * During the plugin activation (not theme), 'plugins_loaded' will be already executed * when the logic gets here since the activation logic first add the activate plugins, * then triggers 'plugins_loaded', and only then include the code of the plugin that * is activated. Which means that _plugins_loaded() will NOT be executed during the * plugin activation, and that IS intentional. * * @author Vova Feldman (@svovaf) */ if ( $this->is_plugin() && $this->is_activation_mode( false ) && 0 == did_action( 'plugins_loaded' ) ) { add_action( 'plugins_loaded', array( &$this, '_plugins_loaded' ) ); } else { // If was activated before, then it was already loaded before. $this->_plugins_loaded(); } } add_action( 'plugins_loaded', array( &$this, '_run_garbage_collector' ) ); if ( ! self::is_ajax() ) { if ( ! $this->is_addon() ) { add_action( 'init', array( &$this, '_add_default_submenu_items' ), WP_FS__LOWEST_PRIORITY ); } } if ( $this->_storage->handle_gdpr_admin_notice ) { add_action( 'init', array( &$this, '_maybe_show_gdpr_admin_notice' ) ); } add_action( 'init', array( &$this, '_maybe_add_gdpr_optin_ajax_handler') ); add_action( 'init', array( &$this, '_maybe_add_pricing_ajax_handler' ) ); } if ( $this->is_plugin() ) { if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) { add_action( 'wpmu_new_blog', array( $this, '_after_new_blog_callback' ), 10, 6 ); } else { add_action( 'wp_initialize_site', array( $this, '_after_wp_initialize_site_callback' ), 11, 2 ); } register_deactivation_hook( $this->_plugin_main_file_path, array( &$this, '_deactivate_plugin_hook' ) ); } if ( is_multisite() ) { add_action( 'deactivate_blog', array( &$this, '_after_site_deactivated_callback' ) ); add_action( 'archive_blog', array( &$this, '_after_site_deactivated_callback' ) ); add_action( 'make_spam_blog', array( &$this, '_after_site_deactivated_callback' ) ); if ( version_compare( $GLOBALS['wp_version'], '5.1', '<' ) ) { add_action( 'deleted_blog', array( $this, '_after_site_deleted_callback' ), 10, 2 ); } else { add_action( 'wp_delete_site', array( $this, '_after_wpsite_deleted_callback' ) ); } add_action( 'activate_blog', array( &$this, '_after_site_reactivated_callback' ) ); add_action( 'unarchive_blog', array( &$this, '_after_site_reactivated_callback' ) ); add_action( 'make_ham_blog', array( &$this, '_after_site_reactivated_callback' ) ); } if ( $this->is_theme() && self::is_customizer() && $this->apply_filters( 'show_customizer_upsell', true ) ) { // Register customizer upsell. add_action( 'customize_register', array( &$this, '_customizer_register' ) ); } add_action( 'admin_init', array( &$this, '_redirect_on_clicked_menu_link' ), WP_FS__LOWEST_PRIORITY ); if ( $this->is_theme() && ! $this->is_migration() ) { add_action( 'admin_init', array( &$this, '_add_tracking_links' ) ); } add_action( 'admin_init', array( &$this, '_add_license_activation' ) ); add_action( 'admin_init', array( &$this, '_add_premium_version_upgrade_selection' ) ); add_action( 'admin_init', array( &$this, '_add_beta_mode_update_handler' ) ); add_action( 'admin_init', array( &$this, '_add_user_change_option' ) ); add_action( 'admin_init', array( &$this, '_add_email_address_update_option' ) ); $this->add_ajax_action( 'update_billing', array( &$this, '_update_billing_ajax_action' ) ); $this->add_ajax_action( 'start_trial', array( &$this, '_start_trial_ajax_action' ) ); $this->add_ajax_action( 'set_data_debug_mode', array( &$this, '_set_data_debug_mode' ) ); $this->add_ajax_action( 'toggle_whitelabel_mode', array( &$this, '_toggle_whitelabel_mode_ajax_handler' ) ); if ( $this->_is_network_active && fs_is_network_admin() ) { $this->add_ajax_action( 'network_activate', array( &$this, '_network_activate_ajax_action' ) ); } $this->add_ajax_action( 'install_premium_version', array( &$this, '_install_premium_version_ajax_action' ) ); $this->add_ajax_action( 'submit_affiliate_application', array( &$this, '_submit_affiliate_application' ) ); $this->add_action( 'after_plans_sync', array( &$this, '_check_for_trial_plans' ) ); $this->add_action( 'sdk_version_update', array( &$this, '_sdk_version_update' ), WP_FS__DEFAULT_PRIORITY, 2 ); $this->add_action( 'plugin_version_update', array( &$this, '_after_version_update' ), WP_FS__DEFAULT_PRIORITY, 2 ); $this->add_filter( 'after_code_type_change', array( &$this, '_after_code_type_change' ) ); add_action( 'admin_init', array( &$this, '_add_trial_notice' ) ); // @phpstan-ignore-line add_action( 'admin_init', array( &$this, '_add_affiliate_program_notice' ) ); // @phpstan-ignore-line add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_common_css' ) ); /** * Handle request to reset anonymous mode for `get_reconnect_url()` or reset the pending activation mode. * * @author Vova Feldman (@svovaf) * @since 1.2.1.5 */ if ( ( fs_request_is_action( 'reset_anonymous_mode' ) || fs_request_is_action( 'reset_pending_activation_mode' ) ) && $this->get_unique_affix() === fs_request_get_raw( 'fs_unique_affix' ) ) { add_action( 'admin_init', array( &$this, 'connect_again' ) ); } } /** * Register the required hooks right after the settings parse is completed. * * @author Vova Feldman (@svovaf) * @since 2.3.1 */ private function register_after_settings_parse_hooks() { if ( is_admin() && $this->is_theme() && $this->is_premium() && ! $this->has_active_valid_license() ) { $this->add_ajax_action( 'delete_theme_update_data', array( &$this, '_delete_theme_update_data_action' ) ); } if ( $this->show_settings_with_tabs() ) { /** * Include the required hooks to capture the theme settings' page tabs * and cache them. * * @author Vova Feldman (@svovaf) * @since 1.2.2.7 */ if ( ! $this->_cache->has_valid( 'tabs' ) ) { add_action( 'admin_footer', array( &$this, '_tabs_capture' ) ); // Add license activation AJAX callback. $this->add_ajax_action( 'store_tabs', array( &$this, '_store_tabs_ajax_action' ) ); add_action( 'admin_enqueue_scripts', array( &$this, '_store_tabs_styles' ), 9999999 ); } add_action( 'admin_footer', array( &$this, '_add_freemius_tabs' ), /** * The tabs JS code must be executed after the tabs capture logic (_tabs_capture()). * That's why the priority is 11 while the tabs capture logic is added * with priority 10. * * @author Vova Feldman (@svovaf) */ 11 ); } if ( ! self::is_ajax() ) { if ( ! $this->is_addon() || $this->is_only_premium() ) { add_action( ( $this->_is_network_active && fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu', array( &$this, '_prepare_admin_menu' ), WP_FS__LOWEST_PRIORITY ); } } } /** * Makes Freemius-related updates unavailable on the "Add Plugins" admin page (/plugin-install.php) so that * they won't interfere with the .org plugins' functionalities on that page (e.g. updating of a .org plugin). * * @author Leo Fajardo (@leorw) * @since 2.2.3 * * @param object $updates * @param string|null $transient * * @return object */ static function _remove_fs_updates_from_plugin_install_page( $updates, $transient = null ) { if ( is_object( $updates ) && isset( $updates->response ) ) { foreach ( $updates->response as $file => $plugin ) { if ( isset( $plugin->package ) && false !== strpos( $plugin->package, 'api.freemius' ) ) { unset( $updates->response[ $file ] ); } } } return $updates; } /** * Prepends the `fs_allow_updater_and_dialog` param to the plugin information URLs to tell the SDK to handle * the information that is shown on the plugin details dialog that is shown when the relevant link is clicked. * * @author Leo Fajardo (@leorw) * @since 2.2.3 * * @return void */ static function _prepend_fs_allow_updater_and_dialog_flag_url_param() { $slug_basename_map = array(); foreach ( self::$_instances as $instance ) { if ( ! $instance->is_plugin() ) { continue; } $slug_basename_map[ $instance->get_slug() ] = $instance->premium_plugin_basename(); } ?> <script type="text/javascript"> (function( $ ) { var slugBasenameMap = <?php echo json_encode( $slug_basename_map ) ?>; for ( var slug in slugBasenameMap ) { var basename = slugBasenameMap[ slug ]; // Try to get the plugin rows if on the "Plugins" page. var $pluginRows = $( '.wp-list-table.plugins tr[data-plugin="' + basename + '"]'); if ( 0 === $pluginRows.length ) { // Try to get the plugin rows if on the "Updates" page. var $pluginCheckbox = $( '#update-plugins-table input[type="checkbox"][value="' + basename + '"]' ); if ( 0 !== $pluginCheckbox.length ) { $pluginRows = $pluginCheckbox.parents( 'tr:first' ); } } if ( 0 === $pluginRows.length ) { // No plugin rows found. continue; } // Find the "View details" links and add the `fs_allow_updater_and_dialog` param to the URL. $pluginRows.find( 'a[href*="plugin-install.php?tab=plugin-information"]' ).each(function() { var $this = $( this ), href = $this.attr( 'href' ).replace( '?tab=', '?fs_allow_updater_and_dialog=true&tab='); $this.attr( 'href', href ); }); } })( jQuery ); </script> <?php } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 */ static function _maybe_add_beta_label_styles() { $has_any_beta_version = false; foreach ( self::$_instances as $instance ) { if ( $instance->is_beta() ) { $has_any_beta_version = true; break; } } if ( $has_any_beta_version ) { fs_enqueue_local_style( 'fs_plugins', '/admin/plugins.css' ); } } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 */ static function _maybe_add_beta_label_to_plugins_and_handle_confirmation() { $beta_data = array(); foreach ( self::$_instances as $instance ) { if ( ! $instance->is_premium() ) { continue; } /** * If there's an available beta version update, a confirmation message will be shown when the * "Update now" link on the "Plugins" or "Themes" page is clicked. */ $has_beta_update = $instance->has_beta_update(); $is_beta = ( // The "Beta" label is added separately for themes. $instance->is_plugin() && $instance->is_beta() ); if ( ! $is_beta && ! $has_beta_update ) { continue; } $beta_data[ $instance->get_plugin_basename() ] = array( 'is_installed_version_beta' => $is_beta ); if ( ! $has_beta_update ) { continue; } $beta_data[ $instance->get_plugin_basename() ]['beta_version_update_confirmation_message'] = sprintf( '%s %s', sprintf( fs_esc_attr_inline( 'An update to a Beta version will replace your installed version of %s with the latest Beta release - use with caution, and not on production sites. You have been warned.', 'beta-version-update-caution', $instance->get_slug() ), $instance->get_plugin_title() ), fs_esc_attr_inline( 'Would you like to proceed with the update?', 'update-confirmation', $instance->get_slug() ) ); } if ( empty( $beta_data ) ) { return; } ?> <script type="text/javascript"> ( function( $ ) { var betaData = <?php echo json_encode( $beta_data ) ?>; for ( var pluginBasename in betaData ) { if ( ! betaData.hasOwnProperty( pluginBasename ) ) { continue; } if ( ! betaData[ pluginBasename ].is_installed_version_beta ) { continue; } var $parentContainer = $( '.wp-list-table.plugins tr[data-plugin="' + pluginBasename + '"]' ); if ( 0 === $parentContainer.length ) { continue; } $parentContainer.find( '.plugin-title > strong:first-child').append( '<span class="fs-tag fs-info"><?php fs_esc_js_echo_inline( 'Beta', 'beta' ) ?></span>' ); } setTimeout( function() { // Wait a little bit before adding the event handler, otherwise, it will be overridden by the core WP logic. $( '.plugins .update-message .update-link, .themes .theme .update-message' ).on( 'click', function() { var $parentContainer = $( this ).parents( 'tr:first' ); pluginBasename = ( 0 !== $parentContainer.length ) ? $parentContainer.data( 'plugin' ) : $( this ).parents( '.theme:first' ).data( 'slug' ); if ( betaData[ pluginBasename ] && betaData[ pluginBasename ].beta_version_update_confirmation_message && ! confirm( betaData[ pluginBasename ].beta_version_update_confirmation_message ) ) { return false; } } ); }, 20 ); } )( jQuery ); </script> <?php } /** * Keeping the uninstall hook registered for free or premium plugin version may result to a fatal error that * could happen when a user tries to uninstall either version while one of them is still active. Uninstalling a * plugin will trigger inclusion of the free or premium version and if one of them is active during the * uninstallation, a fatal error may occur in case the plugin's class or functions are already defined. * * @author Leo Fajardo (@leorw) * * @since 1.2.0 */ private function unregister_uninstall_hook() { $uninstallable_plugins = (array) get_option( 'uninstall_plugins' ); unset( $uninstallable_plugins[ $this->_free_plugin_basename ] ); unset( $uninstallable_plugins[ $this->premium_plugin_basename() ] ); update_option( 'uninstall_plugins', $uninstallable_plugins ); } /** * @since 1.2.0 Invalidate module's main file cache, otherwise, FS_Plugin_Updater will not fetch updates. * * @param bool $store_prev_path */ private function clear_module_main_file_cache( $store_prev_path = true ) { if ( ! isset( $this->_storage->plugin_main_file ) || empty( $this->_storage->plugin_main_file->path ) ) { return; } if ( ! $store_prev_path ) { /** * Storing the previous path is not needed when clearing the cache after an SDK version update since * the main purpose of the cache clearing in that event is to correct a wrong plugin main file path * which causes data mix-up between plugins (e.g. titles and versions of an add-on and its parent plugin). * * @author Leo Fajardo (@leorw) * @since 2.2.1 */ unset( $this->_storage->plugin_main_file->path ); } else { $plugin_main_file = clone $this->_storage->plugin_main_file; // Store cached path (2nd layer cache). $plugin_main_file->prev_path = $plugin_main_file->path; // Clear cached path. unset( $plugin_main_file->path ); $this->_storage->plugin_main_file = $plugin_main_file; } /** * Clear global cached path. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map' ); unset( $id_slug_type_path_map[ $this->_module_id ]['path'] ); self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true ); } /** * @author Leo Fajardo (@leorw) * @since 2.0.0 */ function _hook_action_links_and_register_account_hooks() { if ( $this->is_migration() ) { return; } if ( ( self::is_plugins_page() && $this->is_plugin() ) || ( self::is_themes_page() && $this->is_theme() ) || fs_request_is_action_secure( $this->get_unique_affix() . '_reconnect' ) ) { $this->_add_tracking_links(); } if ( self::is_plugins_page() && $this->is_plugin() ) { $this->hook_plugin_action_links(); } $this->_register_account_hooks(); } /** * @author Vova Feldman (@svovaf) * @since 1.0.9 */ private function _register_account_hooks() { if ( ! is_admin() ) { return; } /** * Always show the deactivation feedback form since we added * automatic free version deactivation upon premium code activation. * * @since 1.2.1.6 */ $this->add_ajax_action( 'submit_uninstall_reason', array( &$this, '_submit_uninstall_reason_action' ) ); $this->add_ajax_action( 'cancel_subscription_or_trial', array( &$this, 'cancel_subscription_or_trial_ajax_action' ) ); if ( ! $this->is_addon() || $this->is_parent_plugin_installed() ) { if ( ( $this->is_plugin() && self::is_plugins_page() ) || ( $this->is_theme() && self::is_themes_page() ) ) { add_action( 'admin_footer', array( &$this, '_add_deactivation_feedback_dialog_box' ) ); } } } /** * Leverage backtrace to find caller plugin file path. * * @param bool $is_init Is initiation sequence. * @param string $main_file Since 2.5.0 expects the module's main file path to potentially purge the cached path. * * @return string * @since 1.0.6 * * @author Vova Feldman (@svovaf) */ private function _find_caller_plugin_file( $is_init = false, $main_file = '' ) { // Try to load the cached value of the file path. if ( isset( $this->_storage->plugin_main_file ) ) { $plugin_main_file = $this->_storage->plugin_main_file; if ( ! empty( $plugin_main_file->path ) ) { $absolute_path = $this->get_absolute_path( $plugin_main_file->path ); if ( file_exists( $absolute_path ) ) { if ( $is_init && $absolute_path !== $this->get_absolute_path( $main_file ) ) { // Update cached path if not matching the actual path. $plugin_main_file->path = $main_file; $this->_storage->plugin_main_file = $plugin_main_file; } return $absolute_path; } } } /** * @since 1.2.1 * * `clear_module_main_file_cache()` is clearing the plugin's cached path on * deactivation. Therefore, if any plugin/theme was initiating `Freemius` * with that plugin's slug, it was overriding the empty plugin path with a wrong path. * * So, we've added a special mechanism with a 2nd layer of cache that uses `prev_path` * when the class instantiator isn't the module. */ if ( ! $is_init ) { // Fetch prev path cache. if ( isset( $this->_storage->plugin_main_file ) && ! empty( $this->_storage->plugin_main_file->prev_path ) ) { $absolute_path = $this->get_absolute_path( $this->_storage->plugin_main_file->prev_path ); if ( file_exists( $absolute_path ) ) { return $absolute_path; } } wp_die( $this->get_text_inline( 'Freemius SDK couldn\'t find the plugin\'s main file. Please contact sdk@freemius.com with the current error.', 'failed-finding-main-path' ) . " Module: {$this->_slug}; SDK: " . WP_FS__SDK_VERSION . ";", $this->get_text_inline( 'Error', 'error' ), array( 'back_link' => true ) ); } /** * @since 1.2.1 * * Only the original instantiator that calls dynamic_init can modify the module's path. */ // Find caller module. $this->_storage->plugin_main_file = (object) array( 'path' => $main_file, ); return $this->get_absolute_path( $main_file ); } /** * @author Leo Fajardo (@leorw) * @since 1.2.3 * * @param string $path * * @return string */ private function get_relative_path( $path ) { $module_root_dir = $this->get_module_root_dir_path(); if ( 0 === strpos( $path, $module_root_dir ) ) { $path = substr( $path, strlen( $module_root_dir ) ); } return $path; } /** * @author Leo Fajardo (@leorw) * @since 1.2.3 * * @param string $path * @param string|bool $module_type * * @return string */ private function get_absolute_path( $path, $module_type = false ) { $module_root_dir = $this->get_module_root_dir_path( $module_type ); if ( 0 !== strpos( $path, $module_root_dir ) ) { $path = fs_normalize_path( $module_root_dir . $path ); } return $path; } /** * @author Leo Fajardo (@leorw) * @since 1.2.3 * * @param string|bool $module_type * * @return string */ private function get_module_root_dir_path( $module_type = false ) { $is_plugin = empty( $module_type ) ? $this->is_plugin() : ( WP_FS__MODULE_TYPE_PLUGIN === $module_type ); return fs_normalize_path( trailingslashit( $is_plugin ? WP_PLUGIN_DIR : get_theme_root( get_stylesheet() ) ) ); } /** * @author Leo Fajardo (@leorw) * * @param number $module_id * @param string $slug * * @return string Since 2.5.0 return the module's main file path. * * @since 1.2.2 */ private function store_id_slug_type_path_map( $module_id, $slug ) { $id_slug_type_path_map = self::$_accounts->get_option( 'id_slug_type_path_map', array() ); $store_option = false; if ( ! isset( $id_slug_type_path_map[ $module_id ] ) ) { $id_slug_type_path_map[ $module_id ] = array( 'slug' => $slug ); $store_option = true; } else if ( isset( $id_slug_type_path_map[ $module_id ]['slug'] ) && $slug !== $id_slug_type_path_map[ $module_id ]['slug'] ) { $id_slug_type_path_map[ $module_id ]['slug'] = $slug; $store_option = true; } $find_caller = empty( $id_slug_type_path_map[ $module_id ]['path'] ); if ( ! $find_caller ) { /** * This verification is for cases when suddenly the same module * is installed but with a different folder name. * * @author Vova Feldman (@svovaf) * @since 1.2.3 */ $find_caller = ! file_exists( $this->get_absolute_path( $id_slug_type_path_map[ $module_id ]['path'], $id_slug_type_path_map[ $module_id ]['type'] ) ); } foreach ( $id_slug_type_path_map as $id => $data ) { if ( empty( $id ) ) { // Remove maps with empty module ID. unset( $id_slug_type_path_map[ $id ] ); $store_option = true; continue; } /** * If the module's main file path is identical to the main file path of another module then it means that the cached path of the current module or the other one with the same path is wrong, and therefore, we need to recalculate those paths. * * @author Vova Feldman (@svovaf) * @since 2.5.0 */ if ( ! $find_caller ) { if ( $id == $module_id ) { continue; } if ( isset( $data['path'] ) && $data['path'] === $id_slug_type_path_map[ $module_id ]['path'] ) { $find_caller = true; } } } if ( $find_caller ) { $caller_main_file_and_type = $this->get_caller_main_file_and_type( $module_id ); $id_slug_type_path_map[ $module_id ]['type'] = $caller_main_file_and_type->module_type; $id_slug_type_path_map[ $module_id ]['path'] = $caller_main_file_and_type->path; $store_option = true; } if ( $store_option ) { self::$_accounts->set_option( 'id_slug_type_path_map', $id_slug_type_path_map, true ); } return $id_slug_type_path_map[ $module_id ]['path']; } /** * Identifies the caller type: plugin or theme. * * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @author Vova Feldman (@svovaf) * @since 1.2.2.3 Find the earliest module in the call stack that calls to the SDK. This fix is for cases when * add-ons are relying on loading the SDK from the parent module, and also allows themes including the * SDK an internal file instead of directly from functions.php. * @since 1.2.1.7 Knows how to handle cases when an add-on includes the parent module logic. * * @param number $module_id @since 2.5.0 */ private function get_caller_main_file_and_type( $module_id ) { self::require_plugin_essentials(); $all_plugins = fs_get_plugins( true ); $all_plugins_paths = array(); // Get active plugin's main files real full names (might be symlinks). foreach ( $all_plugins as $relative_path => $data ) { if ( false === strpos( fs_normalize_path( $relative_path ), '/' ) ) { /** * Ignore plugins that don't have a folder (e.g. Hello Dolly) since they * can't really include the SDK. * * @author Vova Feldman * @since 1.2.1.7 */ continue; } $all_plugins_paths[] = fs_normalize_path( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) ); } $caller_file_candidate = false; $caller_map = array(); $module_type = WP_FS__MODULE_TYPE_PLUGIN; $themes_dir = fs_normalize_path( get_theme_root( get_stylesheet() ) ); $plugin_dir_to_skip = false; for ( $i = 1, $bt = debug_backtrace(), $len = count( $bt ); $i < $len; $i ++ ) { if ( empty( $bt[ $i ]['file'] ) ) { continue; } if ( $i > 1 && ! empty( $bt[ $i - 1 ]['file'] ) && $bt[ $i ]['file'] === $bt[ $i - 1 ]['file'] ) { // If file same as the prev file in the stack, skip it. continue; } if ( ! empty( $bt[ $i ]['function'] ) && in_array( $bt[ $i ]['function'], array( 'do_action', 'apply_filter', // The string split is stupid, but otherwise, theme check // throws info notices. 'requir' . 'e_once', 'requir' . 'e', 'includ' . 'e_once', 'includ' . 'e', 'install_and_activate_plugin', 'try_activate_plugin', 'activate_plugin' ) ) ) { if ( 'activate_plugin' === $bt[ $i ]['function'] ) { /** * Store the directory of the activator plugin so that any other file that starts with it * cannot be mistakenly chosen as a candidate caller file. * * @author Leo Fajardo * * @since 2.3.0 */ $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] ); foreach ( $all_plugins_paths as $plugin_path ) { $plugin_dir = fs_normalize_path( dirname( $plugin_path ) . '/' ); if ( false !== strpos( $caller_file_path, $plugin_dir ) ) { $plugin_dir_to_skip = $plugin_dir; break; } } } // Ignore call stack hooks and files inclusion. continue; } $caller_file_path = fs_normalize_path( $bt[ $i ]['file'] ); if ( ! empty( $plugin_dir_to_skip ) ) { /** * Skip if it's an activator plugin file to avoid mistakenly choosing it as a candidate caller file. * * @author Leo Fajardo * * @since 2.3.0 */ if ( 0 === strpos( $caller_file_path, $plugin_dir_to_skip ) ) { continue; } } if ( 'functions.php' === basename( $caller_file_path ) ) { /** * 1. Assumes that theme's starting execution file is functions.php. * 2. This complex logic fixes symlink issues (e.g. with Vargant). * * @author Vova Feldman (@svovaf) * @since 1.2.2.5 */ if ( $caller_file_path == fs_normalize_path( realpath( trailingslashit( $themes_dir ) . basename( dirname( $caller_file_path ) ) . '/' . basename( $caller_file_path ) ) ) ) { $module_type = WP_FS__MODULE_TYPE_THEME; /** * Relative path of the theme, e.g.: * `my-theme/functions.php` * * @author Leo Fajardo (@leorw) */ $caller_file_candidate = basename( dirname( $caller_file_path ) ) . '/' . basename( $caller_file_path ); continue; } } $caller_file_hash = md5( $caller_file_path ); if ( ! isset( $caller_map[ $caller_file_hash ] ) ) { foreach ( $all_plugins_paths as $plugin_path ) { if ( empty( $plugin_path ) ) { continue; } if ( false !== strpos( $caller_file_path, fs_normalize_path( dirname( $plugin_path ) . '/' ) ) ) { $caller_map[ $caller_file_hash ] = fs_normalize_path( $plugin_path ); break; } } } if ( isset( $caller_map[ $caller_file_hash ] ) ) { $module_type = WP_FS__MODULE_TYPE_PLUGIN; $caller_file_candidate = plugin_basename( $caller_map[ $caller_file_hash ] ); } } $caller_main_file_and_type = (object) array( 'module_type' => $module_type, 'path' => $caller_file_candidate ); return apply_filters( "fs_{$module_id}_caller_main_file_and_type", $caller_main_file_and_type ); } #---------------------------------------------------------------------------------- #region Deactivation Feedback Form #---------------------------------------------------------------------------------- /** * Displays a confirmation and feedback dialog box when the user clicks on the "Deactivate" link on the plugins * page. * * @author Vova Feldman (@svovaf) * @author Leo Fajardo (@leorw) * * @since 1.1.2 */ function _add_deactivation_feedback_dialog_box() { if ( $this->is_clone() || ( is_object( $this->_site ) && ! $this->is_registered() ) ) { return; } $subscription_cancellation_dialog_box_template_params = $this->apply_filters( 'show_deactivation_subscription_cancellation', true ) ? $this->_get_subscription_cancellation_dialog_box_template_params() : array(); /** * @since 2.3.0 Developers can optionally hide the deactivation feedback form using the 'show_deactivation_feedback_form' filter. */ $show_deactivation_feedback_form = ! self::is_deactivation_snoozed(); if ( $this->has_filter( 'show_deactivation_feedback_form' ) ) { $show_deactivation_feedback_form = $this->apply_filters( 'show_deactivation_feedback_form', true ); } else if ( $this->is_addon() ) { /** * If the add-on's 'show_deactivation_feedback_form' is not set, try to inherit the value from the parent. */ $show_deactivation_feedback_form = $this->get_parent_instance()->apply_filters( 'show_deactivation_feedback_form', true ); } $uninstall_confirmation_message = $this->apply_filters( 'uninstall_confirmation_message', '' ); if ( empty( $subscription_cancellation_dialog_box_template_params ) && ! $show_deactivation_feedback_form && empty( $uninstall_confirmation_message ) ) { return; } $vars = array( 'id' => $this->_module_id ); if ( $show_deactivation_feedback_form ) { /* Check the type of user: * 1. Long-term (long-term) * 2. Non-registered and non-anonymous short-term (non-registered-and-non-anonymous-short-term). * 3. Short-term (short-term) */ $is_long_term_user = true; // Check if the site is at least 2 days old. $time_installed = $this->_storage->install_timestamp; // Difference in seconds. $date_diff = time() - $time_installed; // Convert seconds to days. $date_diff_days = floor( $date_diff / ( 60 * 60 * 24 ) ); if ( $date_diff_days < 2 ) { $is_long_term_user = false; } $is_long_term_user = $this->apply_filters( 'is_long_term_user', $is_long_term_user ); if ( $is_long_term_user ) { $user_type = 'long-term'; } else { if ( ! $this->is_registered() && ! $this->is_anonymous() ) { $user_type = 'non-registered-and-non-anonymous-short-term'; } else { $user_type = 'short-term'; } } $uninstall_reasons = $this->_get_uninstall_reasons( $user_type ); $vars['reasons'] = $uninstall_reasons; } $vars['subscription_cancellation_dialog_box_template_params'] = &$subscription_cancellation_dialog_box_template_params; $vars['show_deactivation_feedback_form'] = $show_deactivation_feedback_form; $vars['uninstall_confirmation_message'] = $uninstall_confirmation_message; /** * Load the HTML template for the deactivation feedback dialog box. * * @todo Deactivation form core functions should be loaded only once! Otherwise, when there are multiple Freemius powered plugins the same code is loaded multiple times. The only thing that should be loaded differently is the various deactivation reasons object based on the state of the plugin. */ fs_require_template( 'forms/deactivation/form.php', $vars ); } /** * @author Leo Fajardo (@leorw) * @since 1.1.2 * * @param string $user_type * * @return array The uninstall reasons for the specified user type. */ function _get_uninstall_reasons( $user_type = 'long-term' ) { $module_type = $this->_module_type; $internal_message_template_var = array( 'id' => $this->_module_id ); $plan = $this->get_plan(); if ( $this->is_registered() && is_object( $plan ) && $plan->has_technical_support() ) { $contact_support_template = fs_get_template( 'forms/deactivation/contact.php', $internal_message_template_var ); } else { $contact_support_template = ''; } $reason_found_better_plugin = array( 'id' => self::REASON_FOUND_A_BETTER_PLUGIN, 'text' => sprintf( $this->get_text_inline( 'I found a better %s', 'reason-found-a-better-plugin' ), $module_type ), 'input_type' => 'textfield', 'input_placeholder' => sprintf( $this->get_text_inline( "What's the %s's name?", 'placeholder-plugin-name' ), $module_type ), ); $reason_temporary_deactivation = array( 'id' => self::REASON_TEMPORARY_DEACTIVATION, 'text' => sprintf( $this->get_text_inline( "It's a temporary %s - I'm troubleshooting an issue", 'reason-temporary-x' ), strtolower( $this->is_plugin() ? $this->get_text_inline( 'Deactivation', 'deactivation' ) : $this->get_text_inline( 'Theme Switch', 'theme-switch' ) ) ), 'input_type' => '', 'input_placeholder' => '' ); $reason_other = array( 'id' => self::REASON_OTHER, 'text' => $this->get_text_inline( 'Other', 'reason-other' ), 'input_type' => 'textfield', 'input_placeholder' => '' ); $long_term_user_reasons = array( array( 'id' => self::REASON_NO_LONGER_NEEDED, 'text' => sprintf( $this->get_text_inline( 'I no longer need the %s', 'reason-no-longer-needed' ), $module_type ), 'input_type' => '', 'input_placeholder' => '' ), $reason_found_better_plugin, array( 'id' => self::REASON_NEEDED_FOR_A_SHORT_PERIOD, 'text' => sprintf( $this->get_text_inline( 'I only needed the %s for a short period', 'reason-needed-for-a-short-period' ), $module_type ), 'input_type' => '', 'input_placeholder' => '' ), array( 'id' => self::REASON_BROKE_MY_SITE, 'text' => sprintf( $this->get_text_inline( 'The %s broke my site', 'reason-broke-my-site' ), $module_type ), 'input_type' => '', 'input_placeholder' => '', 'internal_message' => $contact_support_template ), array( 'id' => self::REASON_SUDDENLY_STOPPED_WORKING, 'text' => sprintf( $this->get_text_inline( 'The %s suddenly stopped working', 'reason-suddenly-stopped-working' ), $module_type ), 'input_type' => '', 'input_placeholder' => '', 'internal_message' => $contact_support_template ) ); if ( $this->is_paying() ) { $long_term_user_reasons[] = array( 'id' => self::REASON_CANT_PAY_ANYMORE, 'text' => $this->get_text_inline( "I can't pay for it anymore", 'reason-cant-pay-anymore' ), 'input_type' => 'textfield', 'input_placeholder' => $this->get_text_inline( 'What price would you feel comfortable paying?', 'placeholder-comfortable-price' ) ); } $reason_dont_share_info = array( 'id' => self::REASON_DONT_LIKE_TO_SHARE_MY_INFORMATION, 'text' => $this->get_text_inline( "I don't like to share my information with you", 'reason-dont-like-to-share-my-information' ), 'input_type' => '', 'input_placeholder' => '' ); /** * If the current user has selected the "don't share data" reason in the deactivation feedback modal, inform the * user by showing additional message that he doesn't have to share data and can just choose to skip the opt-in * (the Skip button is included in the message to show). This message will only be shown if anonymous mode is * enabled and the user's account is currently not in pending activation state (similar to the way the Skip * button in the opt-in form is shown/hidden). */ if ( $this->is_enable_anonymous() && ! $this->is_pending_activation() ) { $reason_dont_share_info['internal_message'] = fs_get_template( 'forms/deactivation/retry-skip.php', $internal_message_template_var ); } $uninstall_reasons = array( 'long-term' => $long_term_user_reasons, 'non-registered-and-non-anonymous-short-term' => array( array( 'id' => self::REASON_DIDNT_WORK, 'text' => sprintf( $this->get_text_inline( "The %s didn't work", 'reason-didnt-work' ), $module_type ), 'input_type' => '', 'input_placeholder' => '' ), $reason_dont_share_info, $reason_found_better_plugin ), 'short-term' => array( array( 'id' => self::REASON_COULDNT_MAKE_IT_WORK, 'text' => $this->get_text_inline( "I couldn't understand how to make it work", 'reason-couldnt-make-it-work' ), 'input_type' => '', 'input_placeholder' => '', 'internal_message' => $contact_support_template ), $reason_found_better_plugin, array( 'id' => self::REASON_GREAT_BUT_NEED_SPECIFIC_FEATURE, 'text' => sprintf( $this->get_text_inline( "The %s is great, but I need specific feature that you don't support", 'reason-great-but-need-specific-feature' ), $module_type ), 'input_type' => 'textarea', 'input_placeholder' => $this->get_text_inline( 'What feature?', 'placeholder-feature' ) ), array( 'id' => self::REASON_NOT_WORKING, 'text' => sprintf( $this->get_text_inline( 'The %s is not working', 'reason-not-working' ), $module_type ), 'input_type' => 'textarea', 'input_placeholder' => $this->get_text_inline( "Kindly share what didn't work so we can fix it for future users...", 'placeholder-share-what-didnt-work' ) ), array( 'id' => self::REASON_NOT_WHAT_I_WAS_LOOKING_FOR, 'text' => $this->get_text_inline( "It's not what I was looking for", 'reason-not-what-i-was-looking-for' ), 'input_type' => 'textarea', 'input_placeholder' => $this->get_text_inline( "What you've been looking for?", 'placeholder-what-youve-been-looking-for' ) ), array( 'id' => self::REASON_DIDNT_WORK_AS_EXPECTED, 'text' => sprintf( $this->get_text_inline( "The %s didn't work as expected", 'reason-didnt-work-as-expected' ), $module_type ), 'input_type' => 'textarea', 'input_placeholder' => $this->get_text_inline( 'What did you expect?', 'placeholder-what-did-you-expect' ) ) ) ); // Randomize the reasons for the current user type. shuffle( $uninstall_reasons[ $user_type ] ); // Keep the following reasons as the last items in the list. $uninstall_reasons[ $user_type ][] = $reason_temporary_deactivation; $uninstall_reasons[ $user_type ][] = $reason_other; $uninstall_reasons = $this->apply_filters( 'uninstall_reasons', $uninstall_reasons ); return $uninstall_reasons[ $user_type ]; } /** * Called after the user has submitted his reason for deactivating the plugin. * * @author Leo Fajardo (@leorw) * @since 1.1.2 */ function _submit_uninstall_reason_action() { $this->_logger->entrance(); $this->check_ajax_referer( 'submit_uninstall_reason' ); $reason_id = fs_request_get( 'reason_id' ); // Check if the given reason ID is an unsigned integer. if ( ! ctype_digit( $reason_id ) ) { exit; } $reason_info = trim( fs_request_get( 'reason_info', '' ) ); if ( ! empty( $reason_info ) ) { $reason_info = substr( $reason_info, 0, 128 ); } $reason = (object) array( 'id' => $reason_id, 'info' => $reason_info, 'is_anonymous' => fs_request_get_bool( 'is_anonymous' ) ); $this->_storage->store( 'uninstall_reason', $reason ); if ( self::REASON_TEMPORARY_DEACTIVATION == $reason->id ) { $snooze_period = fs_request_get( 'snooze_period' ); if ( is_numeric( $snooze_period ) && 0 < $snooze_period ) { self::snooze_deactivation_form( (int) $snooze_period ); } } /** * If the module type is "theme", trigger the uninstall event here (on theme deactivation) since themes do * not support uninstall hook. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ if ( $this->is_theme() ) { if ( $this->is_premium() && ! $this->has_active_valid_license() ) { FS_Plugin_Updater::instance( $this )->delete_update_data(); } $this->_uninstall_plugin_event( false ); $this->remove_sdk_reference(); } // Print '1' for successful operation. echo 1; exit; } #-------------------------------------------------------------------------------- #region Deactivation Feedback Snoozing #-------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 2.4.3 * * @param int $period * * @return bool True if the value was set, false otherwise. */ private static function snooze_deactivation_form( $period ) { return ( 0 < $period && self::reset_deactivation_snoozing( $period ) ); } /** * Check if deactivation feedback form is snoozed. * * @author Vova Feldman (@svovaf) * @since 2.4.3 * * @return bool */ static function is_deactivation_snoozed() { $is_snoozed = ( ! is_multisite() || fs_is_network_admin() ) ? get_transient( 'fs_snooze_period' ) : get_site_transient( 'fs_snooze_period' ); return ( 'true' === $is_snoozed ); } /** * Reset deactivation snoozing. When `$period` is `0` will stop deactivation snoozing by deleting the transients. Otherwise, will set the transients for the selected period. * * @param int $period Period in seconds. * * @author Vova Feldman (@svovaf) * @since 2.4.3 */ private static function reset_deactivation_snoozing( $period = 0 ) { $value = ( 0 === $period ) ? null : 'true'; if ( ! is_multisite() || fs_is_network_admin() ) { return set_transient( 'fs_snooze_period', $value, $period ); } else { return set_site_transient( 'fs_snooze_period', $value, $period ); } } /** * The deactivation snooze expiration UNIX timestamp (in sec). * * @author Vova Feldman (@svovaf) * @since 2.4.3 * * @return int */ static function deactivation_snooze_expires_at() { return ( ! is_multisite() || fs_is_network_admin() ) ? (int) get_option( '_transient_timeout_fs_snooze_period' ) : (int) get_site_option( '_site_transient_timeout_fs_snooze_period' ); } #endregion /** * @author Leo Fajardo (@leorw) * @since 2.1.4 */ function cancel_subscription_or_trial_ajax_action() { $this->_logger->entrance(); $this->check_ajax_referer( 'cancel_subscription_or_trial' ); $result = $this->cancel_subscription_or_trial( fs_request_get( 'plugin_id', $this->get_id() ), false ); if ( $this->is_api_error( $result ) ) { $this->shoot_ajax_failure( $result->error->message ); } $this->shoot_ajax_success(); } /** * @author Leo Fajardo (@leorw) * @since 2.1.4 * * @param number $plugin_id * * @return object */ private function cancel_subscription_or_trial( $plugin_id ) { $fs = null; if ( $plugin_id == $this->get_id() ) { $fs = $this; } else if ( $this->is_addon_activated( $plugin_id ) ) { $fs = self::get_instance_by_id( $plugin_id ); } $result = null; if ( ! is_null( $fs ) ) { $result = $fs->is_paid_trial() ? $fs->_cancel_trial() : $fs->_downgrade_site(); } return $result; } /** * @author Leo Fajardo (@leorw) * @since 2.0.2 */ function _delete_theme_update_data_action() { FS_Plugin_Updater::instance( $this )->delete_update_data(); } #endregion #---------------------------------------------------------------------------------- #region Instance #---------------------------------------------------------------------------------- /** * Main singleton instance. * * @author Vova Feldman (@svovaf) * @since 1.0.0 * * @param number $module_id * @param string|bool $slug * @param bool $is_init Is initiation sequence. * * @return Freemius|false */ static function instance( $module_id, $slug = false, $is_init = false ) { if ( empty( $module_id ) ) { return false; } /** * Load the essential static data prior to initiating FS_Plugin_Manager since there's an essential MS network migration logic that needs to be executed prior to the initiation. */ self::_load_required_static(); if ( ! is_numeric( $module_id ) ) { if ( ! $is_init && true === $slug ) { $is_init = true; } $slug = $module_id; $module = FS_Plugin_Manager::instance( $slug )->get(); if ( is_object( $module ) ) { $module_id = $module->id; } } $key = 'm_' . $module_id; if ( ! isset( self::$_instances[ $key ] ) ) { self::$_instances[ $key ] = new Freemius( $module_id, $slug, $is_init ); } return self::$_instances[ $key ]; } /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param number $addon_id * * @return bool */ private static function has_instance( $addon_id ) { return isset( self::$_instances[ 'm_' . $addon_id ] ); } /** * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @param string|number $id_or_slug * @param string $module_type * * @return number|false */ private static function get_module_id( $id_or_slug, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) { if ( is_numeric( $id_or_slug ) ) { return $id_or_slug; } foreach ( self::$_instances as $instance ) { // Also check the module type since there can be a plugin and a theme with the same slug. if ( ( $module_type === $instance->get_module_type() ) && ( $id_or_slug === $instance->get_slug() ) ) { return $instance->get_id(); } } return false; } /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param number $id * * @return false|Freemius */ static function get_instance_by_id( $id ) { return isset ( self::$_instances[ 'm_' . $id ] ) ? self::$_instances[ 'm_' . $id ] : false; } /** * * @author Vova Feldman (@svovaf) * @since 1.0.1 * * @param string $plugin_file * @param string $module_type * * @return false|Freemius */ static function get_instance_by_file( $plugin_file, $module_type = WP_FS__MODULE_TYPE_PLUGIN ) { $slug = self::find_slug_by_basename( $plugin_file ); return ( false !== $slug ) ? self::instance( self::get_module_id( $slug, $module_type ) ) : false; } /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @return false|Freemius */ function get_parent_instance() { return self::get_instance_by_id( $this->_plugin->parent_plugin_id ); } /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param string|number $id_or_slug * * @return false|Freemius */ function get_addon_instance( $id_or_slug ) { $addon_id = self::get_module_id( $id_or_slug ); return self::instance( $addon_id ); } /** * @return Freemius[] */ static function _get_all_instances() { return self::$_instances; } #endregion ------------------------------------------------------------------ /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @return bool */ function is_parent_plugin_installed() { $is_active = self::has_instance( $this->_plugin->parent_plugin_id ); if ( $is_active ) { return true; } /** * Parent module might be a theme. If that's the case, the add-on's FS * instance will be loaded prior to the theme's FS instance, therefore, * we need to check if it's active with a "look ahead". * * @author Vova Feldman * @since 1.2.2.3 */ global $fs_active_plugins; if ( is_object( $fs_active_plugins ) && is_array( $fs_active_plugins->plugins ) ) { $active_theme = wp_get_theme(); foreach ( $fs_active_plugins->plugins as $sdk => $module ) { if ( WP_FS__MODULE_TYPE_THEME === $module->type ) { if ( $module->plugin_path == $active_theme->get_stylesheet() ) { // Parent module is a theme and it's currently active. return true; } } } } return false; } /** * Check if add-on parent plugin in activation mode. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @return bool */ function is_parent_in_activation() { $parent_fs = $this->get_parent_instance(); if ( ! is_object( $parent_fs ) ) { return false; } return ( $parent_fs->is_activation_mode() ); } /** * Is plugin in activation mode. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @param bool $and_on * * @return bool */ function is_activation_mode( $and_on = true ) { return fs_is_network_admin() ? $this->is_network_activation_mode( $and_on ) : $this->is_site_activation_mode( $and_on ); } /** * Is plugin in activation mode. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @param bool $and_on * * @return bool */ function is_site_activation_mode( $and_on = true ) { return ( ( $this->is_on() || ! $and_on ) && ( ( $this->is_premium() && true === $this->_storage->require_license_activation ) || ( ( ! $this->is_registered() || ( $this->is_only_premium() && ! $this->has_features_enabled_license() ) ) && ( ! $this->is_enable_anonymous() || ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) ) ) ) ); } /** * Checks if the SDK in network activation mode. * * @author Leo Fajardo (@leorw) * @since 2.0.0 * * @param bool $and_on * * @return bool */ private function is_network_activation_mode( $and_on = true ) { if ( ! $this->_is_network_active ) { // Not network activated. return false; } if ( $this->is_network_upgrade_mode() ) { // Special flag to enforce network activation mode to decide what to do with the sites that are not yet opted-in nor skipped. return true; } if ( ! $this->is_site_activation_mode( $and_on ) ) { // Whether the context is single site or the network, if the plugin is no longer in activation mode then it is not in network activation mode as well. return false; } if ( $this->is_network_delegated_connection() ) { // Super-admin delegated the connection to the site admins -> not activation mode. return false; } if ( $this->is_network_anonymous() && true !== $this->_storage->require_license_activation ) { // Super-admin skipped the connection network wide -> not activation mode. return false; } if ( $this->is_network_registered() ) { // Super-admin connected at least one site -> not activation mode. return false; } return true; } /** * Check if current page is the opt-in/pending-activation page. * * @author Vova Feldman (@svovaf) * @since 1.2.1.7 * * @return bool */ function is_activation_page() { if ( $this->_menu->is_activation_page( $this->show_opt_in_on_themes_page() ) ) { return true; } if ( ! $this->is_activation_mode() ) { return false; } // Check if current page is matching the activation page. return $this->is_matching_url( $this->get_activation_url() ); } /** * Check if URL path's are matching and that all querystring * arguments of the $sub_url exist in the $url with the same values. * * WARNING: * 1. This method doesn't check if the sub/domain are matching. * 2. Ignore case sensitivity. * * @author Vova Feldman (@svovaf) * @since 1.2.1.7 * * @param string $sub_url * @param string $url If argument is not set, check if the sub_url matching the current's page URL. * * @return bool */ private function is_matching_url( $sub_url, $url = '' ) { if ( empty( $url ) ) { $url = $_SERVER['REQUEST_URI']; } $url = strtolower( $url ); $sub_url = strtolower( $sub_url ); if ( parse_url( $sub_url, PHP_URL_PATH ) !== parse_url( $url, PHP_URL_PATH ) ) { // Different path - DO NOT OVERRIDE PAGE. return false; } $url_params = fs_parse_url_params( $url ); $sub_url_params = fs_parse_url_params( $sub_url ); foreach ( $sub_url_params as $key => $val ) { if ( ! isset( $url_params[ $key ] ) || $val != $url_params[ $key ] ) { // Not matching query string - DO NOT OVERRIDE PAGE. return false; } } return true; } /** * Get the basenames of all active plugins for specific blog. Including network activated plugins. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int $blog_id * * @return string[] */ private static function get_active_plugins_basenames( $blog_id = 0 ) { if ( is_multisite() && $blog_id > 0 ) { $active_basenames = get_blog_option( $blog_id, 'active_plugins' ); } else { $active_basenames = get_option( 'active_plugins' ); } if ( ! is_array( $active_basenames ) ) { $active_basenames = array(); } if ( is_multisite() ) { $network_active_basenames = get_site_option( 'active_sitewide_plugins' ); if ( is_array( $network_active_basenames ) && ! empty( $network_active_basenames ) ) { $active_basenames = array_merge( $active_basenames, array_keys( $network_active_basenames ) ); } } return $active_basenames; } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 * * @param int $blog_id * * @return array */ static function get_active_plugins_directories_map( $blog_id = 0 ) { $active_basenames = self::get_active_plugins_basenames( $blog_id ); $map = array(); foreach ( $active_basenames as $active_basename ) { $active_basename = fs_normalize_path( $active_basename ); if ( false === strpos( $active_basename, '/' ) ) { continue; } $map[ dirname( $active_basename ) ] = true; } return $map; } /** * Get collection of all active plugins. Including network activated plugins. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param int $blog_id Since 2.0.0 * * @return array[string]array */ private static function get_active_plugins( $blog_id = 0 ) { self::require_plugin_essentials(); $active_plugin = array(); $all_plugins = fs_get_plugins(); $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id ); foreach ( $active_plugins_basenames as $plugin_basename ) { $active_plugin[ $plugin_basename ] = $all_plugins[ $plugin_basename ]; } return $active_plugin; } /** * Get collection of all site active plugins for a specified blog. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int $blog_id * * @return array[string]array */ private static function get_site_active_plugins( $blog_id = 0 ) { $active_basenames = ( is_multisite() && $blog_id > 0 ) ? get_blog_option( $blog_id, 'active_plugins' ) : get_option( 'active_plugins' ); $active = array(); if ( ! is_array( $active_basenames ) ) { return $active; } foreach ( $active_basenames as $basename ) { $active[ $basename ] = array( 'is_active' => true, 'Version' => '1.0', // Dummy version. 'slug' => self::get_plugin_slug( $basename ), ); } return $active; } /** * Get collection of all plugins with their activation status for a specified blog. * * @author Vova Feldman (@svovaf) * @since 1.1.8 * * @param int $blog_id Since 2.0.0 * * @return array Key is the plugin file path and the value is an array of the plugin data. */ private static function get_all_plugins( $blog_id = 0 ) { self::require_plugin_essentials(); $all_plugins = fs_get_plugins(); $active_plugins_basenames = self::get_active_plugins_basenames( $blog_id ); foreach ( $all_plugins as $basename => &$data ) { // By default set to inactive (next foreach update the active plugins). $data['is_active'] = false; // Enrich with plugin slug. $data['slug'] = self::get_plugin_slug( $basename ); } // Flag active plugins. foreach ( $active_plugins_basenames as $basename ) { if ( isset( $all_plugins[ $basename ] ) ) { $all_plugins[ $basename ]['is_active'] = true; } } return $all_plugins; } /** * Get collection of all plugins and if they are network level activated. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return array Key is the plugin basename and the value is an array of the plugin data. */ private static function get_network_plugins() { self::require_plugin_essentials(); $all_plugins = fs_get_plugins(); $network_active_basenames = is_multisite() ? get_site_option( 'active_sitewide_plugins' ) : array(); foreach ( $all_plugins as $basename => &$data ) { // By default set to inactive (next foreach update the active plugins). $data['is_active'] = false; // Enrich with plugin slug. $data['slug'] = self::get_plugin_slug( $basename ); } // Flag active plugins. foreach ( $network_active_basenames as $basename ) { if ( isset( $all_plugins[ $basename ] ) ) { $all_plugins[ $basename ]['is_active'] = true; } } return $all_plugins; } /** * Cached result of get_site_transient( 'update_plugins' ) * * @author Vova Feldman (@svovaf) * @since 1.1.8 * * @var object */ private static $_plugins_info; /** * Helper function to get specified plugin's slug. * * @author Vova Feldman (@svovaf) * @since 1.1.8 * * @param $basename * * @return string */ private static function get_plugin_slug( $basename ) { if ( ! isset( self::$_plugins_info ) ) { self::$_plugins_info = get_site_transient( 'update_plugins' ); } $slug = ''; if ( is_object( self::$_plugins_info ) ) { if ( isset( self::$_plugins_info->no_update ) && isset( self::$_plugins_info->no_update[ $basename ] ) && ! empty( self::$_plugins_info->no_update[ $basename ]->slug ) ) { $slug = self::$_plugins_info->no_update[ $basename ]->slug; } else if ( isset( self::$_plugins_info->response ) && isset( self::$_plugins_info->response[ $basename ] ) && ! empty( self::$_plugins_info->response[ $basename ]->slug ) ) { $slug = self::$_plugins_info->response[ $basename ]->slug; } } if ( empty( $slug ) ) { // Try to find slug from FS data. $slug = self::find_slug_by_basename( $basename ); } if ( empty( $slug ) ) { // Fallback to plugin's folder name. $slug = dirname( $basename ); } return $slug; } private static $_statics_loaded = false; /** * Load static resources. * * @author Vova Feldman (@svovaf) * @since 1.0.1 */ private static function _load_required_static() { if ( self::$_statics_loaded ) { return; } self::$_static_logger = FS_Logger::get_logger( WP_FS__SLUG, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK ); self::$_static_logger->entrance(); self::$_accounts = FS_Options::instance( WP_FS__ACCOUNTS_OPTION_NAME, true ); if ( is_multisite() ) { $has_skipped_migration = ( // 'id_slug_type_path_map' - was never stored on older versions, therefore, not exists on the site level. null === self::$_accounts->get_option( 'id_slug_type_path_map', null, false ) && // 'file_slug_map' stored on the site level, so it was running an SDK version before it was integrated with MS-network. null !== self::$_accounts->get_option( 'file_slug_map', null, false ) ); /** * If the file_slug_map exists on the site level but doesn't exist on the * network level storage, it means that we need to process the storage with migration. * * The code in this `if` scope will only be executed once and only for the first site that will execute it because once we migrate the storage data, file_slug_map will be already set in the network level storage. * * @author Vova Feldman (@svovaf) * @since 2.0.0 */ if ( ( $has_skipped_migration && true !== self::$_accounts->get_option( 'ms_migration_complete', false, true ) ) || ( null === self::$_accounts->get_option( 'file_slug_map', null, true ) && null !== self::$_accounts->get_option( 'file_slug_map', null, false ) ) ) { self::migrate_options_to_network(); } } self::$_global_admin_notices = FS_Admin_Notices::instance( 'global' ); if ( ! WP_FS__DEMO_MODE ) { add_action( ( fs_is_network_admin() ? 'network_' : '' ) . 'admin_menu', array( 'Freemius', '_add_debug_section' ) ); } add_action( "wp_ajax_fs_toggle_debug_mode", array( 'Freemius', '_toggle_debug_mode' ) ); self::add_ajax_action_static( 'get_debug_log', array( 'Freemius', '_get_debug_log' ) ); self::add_ajax_action_static( 'get_db_option', array( 'Freemius', '_get_db_option' ) ); self::add_ajax_action_static( 'set_db_option', array( 'Freemius', '_set_db_option' ) ); if ( 0 == did_action( 'plugins_loaded' ) ) { add_action( 'plugins_loaded', array( 'Freemius', '_load_textdomain' ), 1 ); } $clone_manager = FS_Clone_Manager::instance(); add_action( 'init', array( $clone_manager, '_init' ) ); add_action( 'admin_footer', array( 'Freemius', '_open_support_forum_in_new_page' ) ); if ( self::is_plugins_page() || self::is_themes_page() ) { add_action( 'admin_print_footer_scripts', array( 'Freemius', '_maybe_add_beta_label_styles' ), 9 ); /** * Specifically use this hook so that the JS event handlers will work properly on the "Themes" * page. * * @author Leo Fajardo (@leorw) * @since 2.3.0 */ add_action( 'admin_footer-' . self::get_current_page(), array( 'Freemius', '_maybe_add_beta_label_to_plugins_and_handle_confirmation') ); } self::$_statics_loaded = true; } #-------------------------------------------------------------------------------- #region Clone #-------------------------------------------------------------------------------- /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @param bool $only_if_manual_resolution_is_not_hidden * * @return bool */ private function is_unresolved_clone( $only_if_manual_resolution_is_not_hidden = false ) { if ( ! $this->is_clone( $only_if_manual_resolution_is_not_hidden ) ) { return false; } return FS_Clone_Manager::instance()->has_temporary_duplicate_mode_expired(); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @param bool $only_if_manual_resolution_is_not_hidden */ function is_clone( $only_if_manual_resolution_is_not_hidden = false ) { if ( ! is_object( $this->_site ) ) { return false; } $blog_id = null; if ( fs_is_network_admin() && FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) { // Ensure that we're comparing the network install's URL with the relevant subsite's URL. $blog_id = $this->_storage->network_install_blog_id; } $site_url = Freemius::get_unfiltered_site_url( $blog_id, true, true ); if ( ! $this->_site->is_clone( $site_url ) ) { return false; } return ( ! $only_if_manual_resolution_is_not_hidden || ! FS_Clone_Manager::instance()->should_hide_manual_resolution() ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @param int|null $blog_id * @param bool $strip_protocol * @param bool $add_trailing_slash * * @return string */ static function get_unfiltered_site_url( $blog_id = null, $strip_protocol = false, $add_trailing_slash = false ) { $url = ( ! is_multisite() && defined( 'WP_SITEURL' ) ) ? WP_SITEURL : self::get_site_url_from_wp_option( $blog_id ); if ( $strip_protocol ) { $url = fs_strip_url_protocol( $url ); } if ( $add_trailing_slash ) { $url = trailingslashit( $url ); } return $url; } /** * @author Leo Fajardo (@leorw) * @since 2.6.0 * * @param int|null $blog_id * * @return string */ private static function get_site_url_from_wp_option( $blog_id = null ) { global $wp_filter; $site_url_filters = array( 'site_url' => null, 'pre_option_siteurl' => null, 'default_option_siteurl' => null, 'option_siteurl' => null, ); // Detach all URL-related filters to get the actual site's URL (stripped of potential manipulations by multilingual plugins). foreach ( $site_url_filters as $hook_name => $site_url_filter ) { if ( ! empty( $wp_filter[ $hook_name ] ) ) { $site_url_filters[ $hook_name ] = $wp_filter[ $hook_name ]; unset( $wp_filter[ $hook_name ] ); } } $url = get_site_url( $blog_id ); // Re-attach the filters back. foreach ( $site_url_filters as $hook_name => $site_url_filter ) { if ( ! empty( $site_url_filter ) ) { $wp_filter[ $hook_name ] = $site_url_filter; } } return $url; } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @param number $site_id */ function fetch_install_by_id( $site_id ) { return $this->get_current_or_network_user_api_scope()->get( "/installs/{$site_id}.json" ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @return string|object|bool */ function _handle_long_term_duplicate() { $this->_logger->entrance(); $this->delete_current_install( false ); $license_key = false; if ( is_object( $this->_license ) && ! $this->_license->is_utilized( ( WP_FS__IS_LOCALHOST_FOR_SERVER || FS_Site::is_localhost_by_address( self::get_unfiltered_site_url() ) ) ) ) { $license_key = $this->_license->secret_key; } return $this->opt_in( false, false, false, $license_key, false, false, false, null, array(), false ); } #endregion /** * @author Leo Fajardo (@leorw) * * @since 2.1.3 */ private static function migrate_options_to_network() { self::migrate_accounts_to_network(); // Migrate API options from site level to network level. $api_network_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true ); $api_network_options->migrate_to_network(); // Migrate API cache to network level storage. FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME )->migrate_to_network(); self::$_accounts->set_option( 'ms_migration_complete', true, true ); } #---------------------------------------------------------------------------------- #region Localization #---------------------------------------------------------------------------------- /** * Load framework's text domain. * * @author Vova Feldman (@svovaf) * @since 1.2.1 */ static function _load_textdomain() { if ( ! is_admin() ) { return; } global $fs_active_plugins; // Works both for plugins and themes. load_plugin_textdomain( 'freemius', false, $fs_active_plugins->newest->sdk_path . '/languages/' ); } #endregion #---------------------------------------------------------------------------------- #region Debugging #---------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 1.0.8 */ static function _add_debug_section() { if ( ! is_super_admin() ) { // Add debug page only for super-admins. return; } self::$_static_logger->entrance(); $title = sprintf( '%s [v.%s]', fs_text_inline( 'Freemius Debug' ), WP_FS__SDK_VERSION ); if ( WP_FS__DEV_MODE ) { // Add top-level debug menu item. $hook = FS_Admin_Menu_Manager::add_page( $title, $title, 'manage_options', 'freemius', array( 'Freemius', '_debug_page_render' ) ); } else { // Add hidden debug page. $hook = FS_Admin_Menu_Manager::add_subpage( '', $title, $title, 'manage_options', 'freemius', array( 'Freemius', '_debug_page_render' ) ); } if ( ! empty( $hook ) ) { add_action( "load-$hook", array( 'Freemius', '_debug_page_actions' ) ); } } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ static function _toggle_debug_mode() { check_admin_referer( 'fs_toggle_debug_mode' ); if ( ! is_super_admin() ) { return; } $is_on = fs_request_get( 'is_on', false, 'post' ); if ( fs_request_is_post() && in_array( $is_on, array( 0, 1 ) ) ) { update_option( 'fs_debug_mode', $is_on ); // Turn on/off storage logging. FS_Logger::_set_storage_logging( ( 1 == $is_on ) ); } exit; } /** * @author Vova Feldman (@svovaf) * @since 1.2.1.6 */ static function _get_debug_log() { check_admin_referer( 'fs_get_debug_log' ); if ( ! is_super_admin() ) { return; } $limit = min( ! empty( $_POST['limit'] ) ? absint( $_POST['limit'] ) : 200, 200 ); $offset = min( ! empty( $_POST['offset'] ) ? absint( $_POST['offset'] ) : 200, 200 ); $logs = FS_Logger::load_db_logs( fs_request_get( 'filters', false, 'post' ), $limit, $offset ); self::shoot_ajax_success( $logs ); } /** * @author Vova Feldman (@svovaf) * @since 1.2.1.7 */ static function _get_db_option() { check_admin_referer( 'fs_get_db_option' ); $option_name = fs_request_get( 'option_name' ); if ( ! is_super_admin() || ! fs_starts_with( $option_name, 'fs_' ) ) { self::shoot_ajax_failure(); } $value = get_option( $option_name ); $result = array( 'name' => $option_name, ); if ( false !== $value ) { if ( ! is_string( $value ) ) { $value = json_encode( $value ); } $result['value'] = $value; } self::shoot_ajax_success( $result ); } /** * @author Vova Feldman (@svovaf) * @since 1.2.1.7 */ static function _set_db_option() { check_admin_referer( 'fs_set_db_option' ); $option_name = fs_request_get( 'option_name' ); if ( ! is_super_admin() || ! fs_starts_with( $option_name, 'fs_' ) ) { self::shoot_ajax_failure(); } $option_value = fs_request_get_raw( 'option_value' ); if ( ! empty( $option_value ) ) { update_option( $option_name, $option_value ); } self::shoot_ajax_success(); } /** * @author Vova Feldman (@svovaf) * @since 1.0.8 */ static function _debug_page_actions() { self::_clean_admin_content_section(); if ( fs_request_is_action( 'restart_freemius' ) ) { check_admin_referer( 'restart_freemius' ); if ( ! is_multisite() ) { // Clear accounts data. self::$_accounts->clear( null, true ); } else { $sites = self::get_sites(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); self::$_accounts->clear( $blog_id, true ); } // Clear network level storage. self::$_accounts->clear( true, true ); } // Clear SDK reference cache. delete_option( 'fs_active_plugins' ); } else if ( fs_request_is_action( 'clear_updates_data' ) ) { check_admin_referer( 'clear_updates_data' ); if ( ! is_multisite() ) { set_site_transient( 'update_plugins', null ); set_site_transient( 'update_themes', null ); } else { $current_blog_id = get_current_blog_id(); $sites = self::get_sites(); foreach ( $sites as $site ) { switch_to_blog( self::get_site_blog_id( $site ) ); set_site_transient( 'update_plugins', null ); set_site_transient( 'update_themes', null ); } switch_to_blog( $current_blog_id ); } } else if ( fs_request_is_action( 'reset_deactivation_snoozing' ) ) { check_admin_referer( 'reset_deactivation_snoozing' ); self::reset_deactivation_snoozing(); } else if ( fs_request_is_action( 'simulate_trial' ) ) { check_admin_referer( 'simulate_trial' ); $fs = freemius( fs_request_get( 'module_id' ) ); // Update SDK install to at least 24 hours before. $fs->_storage->install_timestamp = ( time() - WP_FS__TIME_24_HOURS_IN_SEC ); // Unset the trial shown timestamp. unset( $fs->_storage->trial_promotion_shown ); } else if ( fs_request_is_action( 'simulate_network_upgrade' ) ) { check_admin_referer( 'simulate_network_upgrade' ); $fs = freemius( fs_request_get( 'module_id' ) ); self::set_network_upgrade_mode( $fs->_storage ); } else if ( fs_request_is_action( 'delete_install' ) ) { check_admin_referer( 'delete_install' ); self::_delete_site_by_slug( fs_request_get( 'slug' ), fs_request_get( 'module_type' ), true, fs_request_get( 'blog_id', null ) ); } else if ( fs_request_is_action( 'delete_user' ) ) { check_admin_referer( 'delete_user' ); self::delete_user( fs_request_get( 'user_id' ) ); } else if ( fs_request_is_action( 'download_logs' ) ) { check_admin_referer( 'download_logs' ); $download_url = FS_Logger::download_db_logs( fs_request_get( 'filters', false, 'post' ) ); if ( false === $download_url ) { wp_die( 'Oops... there was an error while generating the logs download file. Please try again and if it doesn\'t work contact support@freemius.com.' ); } fs_redirect( $download_url ); } else if ( fs_request_is_action( 'migrate_options_to_network' ) ) { check_admin_referer( 'migrate_options_to_network' ); self::migrate_options_to_network(); } } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @return array */ static function get_all_modules_sites() { self::$_static_logger->entrance(); $sites_by_type = array( WP_FS__MODULE_TYPE_PLUGIN => array(), WP_FS__MODULE_TYPE_THEME => array(), ); $module_types = array_keys( $sites_by_type ); if ( ! is_multisite() ) { foreach ( $module_types as $type ) { $sites_by_type[ $type ] = self::get_all_sites( $type ); foreach ( $sites_by_type[ $type ] as $slug => $install ) { $sites_by_type[ $type ][ $slug ] = array( $install ); } } } else { $sites = self::get_sites(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); foreach ( $module_types as $type ) { $installs = self::get_all_sites( $type, $blog_id ); foreach ( $installs as $slug => $install ) { if ( ! isset( $sites_by_type[ $type ][ $slug ] ) ) { $sites_by_type[ $type ][ $slug ] = array(); } $install->blog_id = $blog_id; $sites_by_type[ $type ][ $slug ][] = $install; } } } } return $sites_by_type; } /** * @author Vova Feldman (@svovaf) * @since 1.0.8 */ static function _debug_page_render() { self::$_static_logger->entrance(); $all_modules_sites = self::get_all_modules_sites(); $licenses_by_module_type = self::get_all_licenses_by_module_type(); $vars = array( 'plugin_sites' => $all_modules_sites[ WP_FS__MODULE_TYPE_PLUGIN ], 'theme_sites' => $all_modules_sites[ WP_FS__MODULE_TYPE_THEME ], 'users' => self::get_all_users(), 'addons' => self::get_all_addons(), 'account_addons' => self::get_all_account_addons(), 'plugin_licenses' => $licenses_by_module_type[ WP_FS__MODULE_TYPE_PLUGIN ], 'theme_licenses' => $licenses_by_module_type[ WP_FS__MODULE_TYPE_THEME ] ); fs_enqueue_local_style( 'fs_debug', '/admin/debug.css' ); fs_require_once_template( 'debug.php', $vars ); } #endregion #---------------------------------------------------------------------------------- #region Connectivity Issues #---------------------------------------------------------------------------------- /** * Check if Freemius should be turned on for the current plugin install. * * Note: * $this->_is_on is updated in has_api_connectivity() * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @return bool */ function is_on() { self::$_static_logger->entrance(); if ( is_object( $this->_site ) && ! $this->is_registered() ) { return false; } if ( isset( $this->_is_on ) ) { return $this->_is_on; } // If already installed or pending then sure it's on :) if ( $this->is_registered() || $this->is_pending_activation() ) { $this->_is_on = true; return true; } return false; } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param bool $flush_if_no_connectivity * * @return bool */ private function should_run_connectivity_test( $flush_if_no_connectivity = false ) { if ( ! isset( $this->_storage->connectivity_test ) ) { // Connectivity test was never executed, or cache was cleared. return true; } if ( WP_FS__PING_API_ON_IP_OR_HOST_CHANGES ) { if ( WP_FS__IS_HTTP_REQUEST ) { if ( $_SERVER['HTTP_HOST'] != $this->_storage->connectivity_test['host'] ) { // Domain changed. return true; } if ( WP_FS__REMOTE_ADDR != $this->_storage->connectivity_test['server_ip'] ) { // Server IP changed. return true; } } } if ( $this->_storage->connectivity_test['is_connected'] && $this->_storage->connectivity_test['is_active'] ) { // API connected and Freemius is active - no need to run connectivity check. return false; } if ( $flush_if_no_connectivity ) { /** * If explicitly asked to flush when no connectivity - do it only * if at least 10 sec passed from the last API connectivity test. */ return ( isset( $this->_storage->connectivity_test['timestamp'] ) && ( WP_FS__SCRIPT_START_TIME - $this->_storage->connectivity_test['timestamp'] ) > 10 ); } /** * @since 1.1.7 Don't check for connectivity on plugin downgrade. */ $version = $this->get_plugin_version(); if ( version_compare( $version, $this->_storage->connectivity_test['version'], '>' ) ) { // If it's a plugin version upgrade and Freemius is off or no connectivity, run connectivity test. return true; } return false; } /** * @author Leo Fajardo (@leorw) * @since 2.5.4 * * @param bool $is_update * * @return bool */ private function should_turn_fs_on( $is_update = true ) { if ( empty( $this->_plugin->opt_in_moderation ) || ! is_array( $this->_plugin->opt_in_moderation ) ) { return true; } $optin_config = $this->_plugin->opt_in_moderation; if ( WP_FS__IS_LOCALHOST && ( ! isset( $optin_config['localhost'] ) || false !== $optin_config['localhost'] ) ) { return true; } $optin_config_key = $is_update ? 'updates' : 'new'; if ( ! isset( $optin_config[ $optin_config_key ] ) ) { return true; } $visibility_percentage = $optin_config[ $optin_config_key ]; if ( 0 == $visibility_percentage ) { return false; } if ( ! is_numeric( $visibility_percentage ) ) { return true; } $min = 1; $max = 100; if ( function_exists( 'random_int' ) ) { $random = random_int( $min, $max ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.random_intFound } else { $random = rand( $min, $max ); } return ( $random <= $visibility_percentage ); } /** * Check if there's any connectivity issue to Freemius API. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param bool $flush_if_no_connectivity * * @return bool|null */ function has_api_connectivity( $flush_if_no_connectivity = false ) { $this->_logger->entrance(); if ( isset( $this->_has_api_connection ) && ( $this->_has_api_connection || ! $flush_if_no_connectivity ) ) { return $this->_has_api_connection; } if ( WP_FS__SIMULATE_NO_API_CONNECTIVITY && isset( $this->_storage->connectivity_test ) && true === $this->_storage->connectivity_test['is_connected'] ) { $this->clear_connectivity_info(); } if ( ! $this->should_run_connectivity_test( $flush_if_no_connectivity ) ) { $this->_has_api_connection = $this->_storage->connectivity_test['is_connected']; /** * @since 1.1.6 During dev mode, if there's connectivity - turn Freemius on regardless the configuration. * * @since 1.2.1.5 If the user running the premium version then ignore the 'is_active' flag and turn Freemius on to enable license key activation. */ $this->_is_on = $this->_storage->connectivity_test['is_active'] || $this->is_premium() || ( WP_FS__DEV_MODE && $this->_has_api_connection && ! WP_FS__SIMULATE_FREEMIUS_OFF ); return $this->_has_api_connection; } if ( ! empty( $this->_storage->connectivity_test ) && isset( $this->_storage->connectivity_test['is_active'] ) ) { $is_active = $this->_storage->connectivity_test['is_active']; } else { $is_active = $this->should_turn_fs_on( $this->apply_filters( 'is_plugin_update', $this->is_plugin_update() ) ); $this->store_connectivity_info( (object) array( 'is_active' => $is_active ), null ); } if ( $is_active ) { $this->_is_on = true; } return $this->_has_api_connection; } /** * @author Leo Fajardo (@leorw) * @since 2.5.4 */ private function clear_connectivity_info() { unset( $this->_storage->connectivity_test ); FS_Api::clear_force_http_flag(); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.4 * * @param object $pong * @param bool|null $is_connected */ private function store_connectivity_info( $pong, $is_connected ) { $this->_logger->entrance(); $version = $this->get_plugin_version(); if ( false === $is_connected || WP_FS__SIMULATE_FREEMIUS_OFF ) { $is_active = false; } else { $is_active = ( isset( $pong->is_active ) && true == $pong->is_active ); } $is_active = $this->apply_filters( 'is_on', $is_active, $this->is_plugin_update(), $version ); $this->_storage->connectivity_test = array( 'is_connected' => $is_connected, 'host' => $_SERVER['HTTP_HOST'], 'server_ip' => WP_FS__REMOTE_ADDR, 'is_active' => $is_active, 'timestamp' => WP_FS__SCRIPT_START_TIME, // Last version with connectivity attempt. 'version' => $version, ); $this->_has_api_connection = $is_connected; $this->_is_on = $is_active || ( WP_FS__DEV_MODE && $is_connected && ! WP_FS__SIMULATE_FREEMIUS_OFF ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.4 * * @param bool $is_connected */ private function update_connectivity_info( $is_connected ) { $this->store_connectivity_info( // This is true since we update the connection info only after a successful opt-in or license activation which means that Freemius has already been on even before the process. (object) array( 'is_active' => true ), $is_connected ); } /** * Force turning Freemius on. * * @author Vova Feldman (@svovaf) * @since 1.1.8.1 * * @return bool TRUE if successfully turned on. */ private function turn_on() { $this->_logger->entrance(); if ( $this->is_on() || ! isset( $this->_storage->connectivity_test['is_active'] ) ) { return false; } $updated_connectivity = $this->_storage->connectivity_test; $updated_connectivity['is_active'] = true; $updated_connectivity['timestamp'] = WP_FS__SCRIPT_START_TIME; $this->_storage->connectivity_test = $updated_connectivity; $this->_is_on = true; return true; } /** * Anonymous and unique site identifier (Hash). * * @author Vova Feldman (@svovaf) * @since 1.1.0 * * @param null|int $blog_id Since 2.0.0 * * @return string */ function get_anonymous_id( $blog_id = null ) { $unique_id = self::$_accounts->get_option( 'unique_id', null, $blog_id ); if ( empty( $unique_id ) || ! is_string( $unique_id ) ) { $key = self::get_unfiltered_site_url( $blog_id, true ); $secure_auth = defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : ''; if ( empty( $secure_auth ) || false !== strpos( $secure_auth, ' ' ) || 'put your unique phrase here' === $secure_auth ) { // Protect against default auth key. $secure_auth = md5( microtime() ); } /** * Base the unique identifier on the WP secure authentication key. Which * turns the key into a secret anonymous identifier. This will help us * to avoid duplicate installs generation on the backend upon opt-in. * * @author Vova Feldman (@svovaf) * @since 1.2.3 */ $unique_id = md5( $key . $secure_auth ); self::$_accounts->set_option( 'unique_id', $unique_id, true, $blog_id ); } $this->_logger->departure( $unique_id ); return $unique_id; } /** * Returns anonymous network ID. * * @since 2.4.3 * * @return string */ function get_anonymous_network_id() { return $this->get_anonymous_id( get_network()->site_id ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.4 * * @return \WP_User */ static function _get_current_wp_user() { self::require_pluggable_essentials(); self::wp_cookie_constants(); return wp_get_current_user(); } /** * Define cookie constants which are required by Freemius::_get_current_wp_user() since * it uses wp_get_current_user() which needs the cookie constants set. When a plugin * is network activated the cookie constants are only configured after the network * plugins activation, therefore, if we don't define those constants WP will throw * PHP warnings/notices. * * @author Vova Feldman (@svovaf) * @since 2.1.1 */ private static function wp_cookie_constants() { if ( defined( 'LOGGED_IN_COOKIE' ) && ( defined( 'AUTH_COOKIE' ) || defined( 'SECURE_AUTH_COOKIE' ) ) ) { return; } /** * Used to guarantee unique hash cookies * * @since 1.5.0 */ if ( ! defined( 'COOKIEHASH' ) ) { $siteurl = get_site_option( 'siteurl' ); if ( $siteurl ) { define( 'COOKIEHASH', md5( $siteurl ) ); } else { define( 'COOKIEHASH', '' ); } } if ( ! defined( 'LOGGED_IN_COOKIE' ) ) { define( 'LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH ); } /** * @since 2.5.0 */ if ( ! defined( 'AUTH_COOKIE' ) ) { define( 'AUTH_COOKIE', 'wordpress_' . COOKIEHASH ); } /** * @since 2.6.0 */ if ( ! defined( 'SECURE_AUTH_COOKIE' ) ) { define( 'SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH ); } } /** * @author Vova Feldman (@svovaf) * @since 2.1.0 * * @return int */ static function get_current_wp_user_id() { $wp_user = self::_get_current_wp_user(); return $wp_user->ID; } /** * @author Vova Feldman (@svovaf) * @since 1.2.1.7 * * @param string $email * * @return bool */ static function is_valid_email( $email ) { if ( false === filter_var( $email, FILTER_VALIDATE_EMAIL ) ) { return false; } $parts = explode( '@', $email ); if ( 2 !== count( $parts ) || empty( $parts[1] ) ) { return false; } $blacklist = array( 'admin.', 'webmaster.', 'localhost.', 'dev.', 'development.', 'test.', 'stage.', 'staging.', ); // Make sure domain is not one of the blacklisted. foreach ( $blacklist as $invalid ) { if ( 0 === strpos( $parts[1], $invalid ) ) { return false; } } // Get the UTF encoded domain name. /** * @note - The check of `defined('...')` is there to account for PHP servers compiled with some older version of ICU where the constants are not defined. * @author - @swashata */ $is_new_idn_available = ( version_compare( PHP_VERSION, '5.6.40') > 0 && defined( 'IDNA_DEFAULT' ) && defined( 'INTL_IDNA_VARIANT_UTS46' ) ); if ( $is_new_idn_available ) { $domain = idn_to_ascii( $parts[1], IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46 ); } else { $domain = idn_to_ascii( $parts[1] ); // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet } $domain = $domain . '.'; return ( checkdnsrr( $domain, 'MX' ) || checkdnsrr( $domain, 'A' ) ); } #endregion #---------------------------------------------------------------------------------- #region Email #---------------------------------------------------------------------------------- /** * Generates and sends an HTML email with customizable sections. * * @author Leo Fajardo (@leorw) * @since 1.1.2 * * @param string $to_address * @param string $subject * @param array $sections * @param array $headers * * @return bool Whether the email contents were sent successfully. */ private function send_email( $to_address, $subject, $sections = array(), $headers = array() ) { $default_sections = $this->get_email_sections(); // Insert new sections or replace the default email sections. if ( is_array( $sections ) && ! empty( $sections ) ) { foreach ( $sections as $section_id => $custom_section ) { if ( ! isset( $default_sections[ $section_id ] ) ) { // If the section does not exist, add it. $default_sections[ $section_id ] = $custom_section; } else { // If the section already exists, override it. $current_section = $default_sections[ $section_id ]; // Replace the current section's title if a custom section title exists. if ( isset( $custom_section['title'] ) ) { $current_section['title'] = $custom_section['title']; } // Insert new rows under the current section or replace the default rows. if ( isset( $custom_section['rows'] ) && is_array( $custom_section['rows'] ) && ! empty( $custom_section['rows'] ) ) { foreach ( $custom_section['rows'] as $row_id => $row ) { $current_section['rows'][ $row_id ] = $row; } } $default_sections[ $section_id ] = $current_section; } } } $vars = array( 'sections' => $default_sections ); $message = fs_get_template( 'email.php', $vars ); // Set the type of email to HTML. $headers[] = 'Content-type: text/html; charset=UTF-8'; $header_string = implode( "\r\n", $headers ); return wp_mail( $to_address, $subject, $message, $header_string ); } /** * Generates the data for the sections of the email content. * * @author Leo Fajardo (@leorw) * @since 1.1.2 * * @return array */ private function get_email_sections() { // Retrieve the current user's information so that we can get the user's email, first name, and last name below. $current_user = self::_get_current_wp_user(); // Retrieve the cURL version information so that we can get the version number below. $curl_version_information = curl_version(); $active_plugin = self::get_active_plugins(); // Generate the list of active plugins separated by new line. $active_plugin_string = ''; foreach ( $active_plugin as $plugin ) { $active_plugin_string .= sprintf( '<a href="%s">%s</a> [v%s]<br>', $plugin['PluginURI'], $plugin['Name'], $plugin['Version'] ); } $server_ip = WP_FS__REMOTE_ADDR; // Add PHP info for deeper investigation. ob_start(); phpinfo(); $php_info = ob_get_clean(); $api_domain = substr( FS_API__ADDRESS, strpos( FS_API__ADDRESS, ':' ) + 3 ); // Generate the default email sections. $sections = array( 'sdk' => array( 'title' => 'SDK', 'rows' => array( 'fs_version' => array( 'FS Version', $this->version ), 'curl_version' => array( 'cURL Version', $curl_version_information['version'] ) ) ), 'plugin' => array( 'title' => ucfirst( $this->get_module_type() ), 'rows' => array( 'name' => array( 'Name', $this->get_plugin_name() ), 'version' => array( 'Version', $this->get_plugin_version() ) ) ), 'api' => array( 'title' => 'API Subdomain', 'rows' => array( 'dns' => array( 'DNS_CNAME', function_exists( 'dns_get_record' ) ? var_export( dns_get_record( $api_domain, DNS_CNAME ), true ) : 'dns_get_record() disabled/blocked' ), 'ip' => array( 'IP', function_exists( 'gethostbyname' ) ? gethostbyname( $api_domain ) : 'gethostbyname() disabled/blocked' ), ), ), 'site' => array( 'title' => 'Site', 'rows' => array( 'unique_id' => array( 'Unique ID', $this->get_anonymous_id() ), 'address' => array( 'Address', site_url() ), 'host' => array( 'HTTP_HOST', ( ! empty( $_SERVER['HTTP_HOST'] ) ? $_SERVER['HTTP_HOST'] : '' ) ), 'hosting' => array( 'Hosting Company' => fs_request_has( 'hosting_company' ) ? fs_request_get( 'hosting_company' ) : 'Unknown', ), 'server_addr' => array( 'SERVER_ADDR', '<a href="http://www.projecthoneypot.org/ip_' . $server_ip . '">' . $server_ip . '</a>' ) ) ), 'user' => array( 'title' => 'User', 'rows' => array( 'email' => array( 'Email', $current_user->user_email ), 'first' => array( 'First', $current_user->user_firstname ), 'last' => array( 'Last', $current_user->user_lastname ) ) ), 'plugins' => array( 'title' => 'Plugins', 'rows' => array( 'active_plugins' => array( 'Active Plugins', $active_plugin_string ) ) ), 'php_info' => array( 'title' => 'PHP Info', 'rows' => array( 'info' => array( $php_info ) ), ) ); // Allow the sections to be modified by other code. $sections = $this->apply_filters( 'email_template_sections', $sections ); return $sections; } #endregion #---------------------------------------------------------------------------------- #region Initialization #---------------------------------------------------------------------------------- /** * Init plugin's Freemius instance. * * @author Vova Feldman (@svovaf) * @since 1.0.1 * * @param number $id * @param string $public_key * @param bool $is_live * @param bool $is_premium */ function init( $id, $public_key, $is_live = true, $is_premium = true ) { $this->_logger->entrance(); $this->dynamic_init( array( 'id' => $id, 'public_key' => $public_key, 'is_live' => $is_live, 'is_premium' => $is_premium, ) ); } /** * Dynamic initiator, originally created to support initiation * with parent_id for add-ons. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param array $plugin_info * * @throws Freemius_Exception */ function dynamic_init( array $plugin_info ) { $this->_logger->entrance(); $this->parse_settings( $plugin_info ); $this->register_after_settings_parse_hooks(); /** * If anonymous but there's already a user entity and the user's site is associated with a valid license or trial period, update the anonymous mode accordingly. * * @todo Remove this entire `if` block after several releases as starting from this version, the anonymous mode will already be updated accordingly after a purchase. */ if ( $this->is_anonymous() ) { $is_network_level = ( $this->_is_network_active && fs_is_network_admin() ); if ( ! $is_network_level || FS_Site::is_valid_id( $this->_storage->network_install_blog_id ) ) { if ( $this->is_paying_or_trial() ) { $this->reset_anonymous_mode( $is_network_level ); } } else { $network = get_network(); if ( is_object( $network ) ) { $main_blog_id = $network->site_id; $first_install = $this->get_install_by_blog_id( $main_blog_id ); if ( is_object( $first_install ) ) { $this->_storage->network_install_blog_id = $main_blog_id; $this->_storage->network_user_id = $first_install->user_id; } } } } if ( $this->should_stop_execution() ) { return; } if ( ! $this->is_registered() ) { if ( $this->is_anonymous() ) { // If user skipped, no need to test connectivity. $this->_has_api_connection = true; $this->_is_on = true; } else { if ( false === $this->has_api_connectivity() ) { return; } else { if ( $this->_anonymous_mode ) { // Simulate anonymous mode. $this->_is_anonymous = true; } } } } /** * This should be executed even if Freemius is off for the core module, * otherwise, the add-ons dialog box won't work properly. This is especially * relevant when the developer decided to turn FS off for existing users. * * @author Vova Feldman (@svovaf) */ if ( $this->is_user_in_admin() && 'plugin-information' === fs_request_get( 'tab', false ) && $this->should_use_freemius_updater_and_dialog() && ( ( $this->is_addon() && $this->get_slug() == fs_request_get( 'plugin', false ) ) || ( $this->has_addons() && $this->get_id() == fs_request_get( 'parent_plugin_id', false ) ) ) ) { require_once WP_FS__DIR_INCLUDES . '/fs-plugin-info-dialog.php'; new FS_Plugin_Info_Dialog( $this->is_addon() ? $this->get_parent_instance() : $this ); } // Check if Freemius is on for the current plugin. // This MUST be executed after all the plugin variables has been loaded. if ( ! $this->is_registered() && ! $this->is_on() ) { return; } if ( $this->has_api_connectivity() ) { if ( self::is_cron() ) { $this->hook_callback_to_sync_cron(); } else if ( $this->is_user_in_admin() ) { /** * Schedule daily data sync cron if: * * 1. User opted-in (for tracking). * 2. If skipped, but later upgraded (opted-in via upgrade). * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * */ if ( $this->is_registered() && $this->is_tracking_allowed() ) { $this->maybe_schedule_sync_cron(); } /** * Check if requested for manual blocking background sync. */ if ( fs_request_has( 'background_sync' ) ) { self::require_pluggable_essentials(); self::wp_cookie_constants(); $this->run_manual_sync(); } } } if ( $this->is_registered() ) { FS_Clone_Manager::instance()->maybe_resolve_new_subsite_install_automatically( $this ); $this->hook_callback_to_install_sync(); } if ( $this->is_addon() ) { if ( $this->is_parent_plugin_installed() ) { // Link to parent FS. $this->_parent = self::get_instance_by_id( $this->_plugin->parent_plugin_id ); // Get parent plugin reference. $this->_parent_plugin = $this->_parent->get_plugin(); } } if ( $this->is_user_in_admin() ) { if ( $this->is_registered() && fs_request_has( 'purchase_completed' ) ) { $this->_admin_notices->add_sticky( sprintf( /* translators: %s: License type (e.g. you have a professional license) */ $this->get_text_inline( 'You have purchased a %s license.', 'you-have-x-license' ), fs_request_get( 'purchased_plan' ) ) . sprintf( $this->get_text_inline(" The %s's %sdownload link%s, license key, and installation instructions have been sent to %s. If you can't find the email after 5 min, please check your spam box.", 'post-purchase-email-sent-message' ), $this->get_module_label( true ), ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? "products' " : '' ), ( FS_Plugin::is_valid_id( $this->get_bundle_id() ) ? 's' : '' ), sprintf( '<strong>%s</strong>', fs_request_get( 'purchase_email' ) ) ), 'plan_purchased', $this->get_text_x_inline( 'Yee-haw', 'interjection expressing joy or exuberance', 'yee-haw' ) . '!' ); } if ( $this->is_addon() ) { if ( ! $this->is_parent_plugin_installed() ) { $parent_name = $this->get_option( $plugin_info, 'parent_name', null ); if ( isset( $plugin_info['parent'] ) ) { $parent_name = $this->get_option( $plugin_info['parent'], 'name', null ); } $this->_admin_notices->add( ( ! empty( $parent_name ) ? sprintf( $this->get_text_x_inline( '%s cannot run without %s.', 'addonX cannot run without pluginY', 'addon-x-cannot-run-without-y' ), $this->get_plugin_name(), $parent_name ) : sprintf( $this->get_text_x_inline( '%s cannot run without the plugin.', 'addonX cannot run...', 'addon-x-cannot-run-without-parent' ), $this->get_plugin_name() ) ), $this->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...', 'error' ); return; } else { $is_network_admin = fs_is_network_admin(); if ( ! $this->_parent->is_registered() && $this->is_registered() ) { // If add-on activated and parent not, automatically install parent for the user. $this->activate_parent_account( $this->_parent ); } else if ( $this->_parent->is_registered() && ! $this->is_registered() && /** * If not registered for add-on and the following conditions for the add-on are met, activate add-on account. * * Network active and in network admin - network activate add-on account. * * Network active and not in network admin - activate add-on account for the current blog. * * Not network active and not in network admin - activate add-on account for the current blog. * * If not registered for add-on, not network active, and in network admin, do not handle the add-on activation. * * @author Leo Fajardo (@leorw) * @since 2.3.0 */ ( $this->is_network_active() || ! $is_network_admin ) ) { $premium_license = null; if ( ! $this->has_free_plan() && $this->is_bundle_license_auto_activation_enabled() && $this->_parent->is_activated_with_bundle_license() ) { /** * If the add-on has no free plan, try to activate the account only when there's a bundle license. * * @author Leo Fajardo (@leorw) * @since 2.4.0 */ $bundle_license = $this->get_active_parent_license( $this->_parent->_get_license()->secret_key, false ); if ( is_object( $bundle_license ) && ! empty( $bundle_license->products ) && in_array( $this->get_id(), $bundle_license->products ) ) { $premium_license = $bundle_license; } } if ( $this->has_free_plan() || is_object( $premium_license) ) { // If parent plugin activated, automatically install add-on for the user. $this->_activate_addon_account( $this->_parent, ( $this->is_network_active() && $is_network_admin ) ? true : get_current_blog_id(), $premium_license ); } } // @todo This should be only executed on activation. It should be migrated to register_activation_hook() together with other activation related logic. if ( $this->is_premium() ) { // Remove add-on download admin-notice. $this->_parent->_admin_notices->remove_sticky( array( 'addon_plan_upgraded_' . $this->_slug, 'no_addon_license_' . $this->_slug, ) ); } // $this->deactivate_premium_only_addon_without_license(); } } add_action( 'admin_init', array( &$this, '_admin_init_action' ) ); // if ( $this->is_registered() || // $this->is_anonymous() || // $this->is_pending_activation() // ) { // $this->_init_admin(); // } } /** * Should be called outside `$this->is_user_in_admin()` scope * because the updater has some logic that needs to be executed * during AJAX calls. * * Currently, we need to hook to the `http_request_host_is_external` filter. * In the future, there might be additional logic added. * * @author Vova Feldman * @since 1.2.1.6 */ if ( $this->should_use_freemius_updater_and_dialog() && ( $this->is_premium() || /** * If not premium but the premium version is installed, also instantiate the updater so that the * plugin information dialog of the premium version will have the information from the server. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->premium_plugin_basename() ) ) ) ) && $this->has_release_on_freemius() && ( ! $this->is_unresolved_clone( true ) ) ) { FS_Plugin_Updater::instance( $this ); } $this->do_action( 'initiated' ); if ( $this->_storage->prev_is_premium !== $this->_plugin->is_premium ) { if ( isset( $this->_storage->prev_is_premium ) ) { $this->apply_filters( 'after_code_type_change', // New code type. $this->_plugin->is_premium ); } else { // Set for code type for the first time. $this->_storage->prev_is_premium = $this->_plugin->is_premium; } } if ( ! $this->is_addon() ) { if ( $this->is_registered() ) { // Fix for upgrade from versions < 1.0.9. if ( ! isset( $this->_storage->activation_timestamp ) ) { $this->_storage->activation_timestamp = WP_FS__SCRIPT_START_TIME; } $this->do_action( 'after_init_plugin_registered' ); } else if ( $this->is_anonymous() ) { $this->do_action( 'after_init_plugin_anonymous' ); } else if ( $this->is_pending_activation() ) { $this->do_action( 'after_init_plugin_pending_activations' ); } } else { if ( $this->is_registered() ) { $this->do_action( 'after_init_addon_registered' ); } else if ( $this->is_anonymous() ) { $this->do_action( 'after_init_addon_anonymous' ); } else if ( $this->is_pending_activation() ) { $this->do_action( 'after_init_addon_pending_activations' ); } } } /** * @author Leo Fajardo (@leorw) * @since 2.2.3 * * @return bool */ private function should_use_freemius_updater_and_dialog() { return ( /** * Allow updater and dialog when the `fs_allow_updater_and_dialog` URL query param exists and has `true` * value, or when the current page is not the "Add Plugins" page (/plugin-install.php) and the `action` * URL query param doesn't exist or its value is not `install-plugin` so that there will be no conflicts * with the .org plugins' functionalities (e.g. installation from the "Add Plugins" page and viewing * plugin details from .org). */ ( true === fs_request_get_bool( 'fs_allow_updater_and_dialog' ) ) || ( ! self::is_plugin_install_page() && // Disallow updater and dialog when installing a plugin, otherwise .org "add-on" plugins will be affected. ( 'install-plugin' !== fs_request_get( 'action' ) ) ) ); } /** * @param string[] $permissions * @param bool $is_enabled * @param int|null $blog_id * * @return true|object `true` on success, API error object on failure. */ private function update_site_permissions( array $permissions, $is_enabled, $blog_id = null ) { $this->_logger->entrance(); $params = array( 'permissions' => implode( ',', $permissions ), 'is_enabled' => $is_enabled, ); $current_blog_id = get_current_blog_id(); $is_blog_switched = false; if ( is_numeric( $blog_id ) && $current_blog_id != $blog_id ) { $is_blog_switched = $this->switch_to_blog( $blog_id ); } $result = $this->api_site_call( '/permissions.json', 'put', $params ); if ( $is_blog_switched ) { $this->switch_to_blog( $current_blog_id ); } if ( ! $this->is_api_result_object( $result ) || ! isset( $result->install_id ) ) { $this->_logger->api_error( $result ); return $result; } return true; } /** * @param string[] $permissions * @param bool $is_enabled * @param bool $has_site_delegated_connection * * @return true|object `true` on success, API error object on failure. */ private function update_network_permissions( array $permissions, $is_enabled, &$has_site_delegated_connection ) { $this->_logger->entrance(); $install_id_2_blog_id = array(); $install_by_blog_id = $this->get_blog_install_map(); $has_site_delegated_connection = false; foreach ( $install_by_blog_id as $blog_id => $install ) { if ( $this->is_site_delegated_connection( $blog_id ) ) { // Only update permissions of non-delegated installs. $has_site_delegated_connection = true; continue; } $install_id_2_blog_id[ $install->id ] = $blog_id; } if ( empty( $install_id_2_blog_id ) ) { return true; } $params = array( 'permissions' => implode( ',', $permissions ), 'is_enabled' => $is_enabled, 'install_ids' => implode( ',', array_keys( $install_id_2_blog_id ) ), ); // Send update to FS. $result = $this->get_current_or_network_user_api_scope()->call( "/plugins/{$this->_module_id}/installs/permissions.json", 'put', $params ); if ( ! $this->is_api_result_object( $result, 'installs_metadata' ) ) { $this->_logger->api_error( $result ); return $result; } return true; } /** * @param mixed $result * * @return string */ private function get_api_error_message( $result ) { $error_message = sprintf( $this->get_text_inline( 'There was an unexpected API error while processing your request. Please try again in a few minutes and if it still doesn\'t work, contact the %s\'s author with the following:', 'unexpected-api-error' ), $this->_module_type ) . ' '; if ( $this->is_api_error( $result ) && isset( $result->error ) ) { $code = empty( $result->error->code ) ? '' : " Code: {$result->error->code}"; $error_message .= "<b>{$result->error->message}{$code}</b>"; } else { $error_message .= var_export( $result, true ); } return $error_message; } /** * @author Vova Feldman (@svovaf) * @since 2.5.1 */ function _toggle_permission_tracking_callback() { $this->_logger->entrance(); $this->check_ajax_referer( 'toggle_permission_tracking' ); if ( ! $this->is_registered( true ) ) { self::shoot_ajax_failure( 'User never opted-in.' ); } $is_enabled = fs_request_get_bool( 'is_enabled' ); $permissions = fs_request_get( 'permissions' ); if ( ! is_string( $permissions ) ) { self::shoot_ajax_failure( 'The permissions param must be a string.' ); } $permissions = explode( ',', $permissions ); $result = $this->toggle_permission_tracking( $permissions, $is_enabled ); if ( true !== $result ) { self::shoot_ajax_failure( $this->get_api_error_message( $result ) ); } self::shoot_ajax_success(); } /** * @param string[] $permissions * @param bool $is_enabled * @param int|null $blog_id * * @return bool|mixed `true` if updated successfully or no update is needed. */ private function toggle_permission_tracking( $permissions, $is_enabled, $blog_id = null ) { if ( ! $this->is_registered( true ) ) { // User never opted-in. return false; } // Check if permissions are already set as needed. if ( FS_Permission_Manager::instance( $this )->are_permissions( $permissions, $is_enabled, $blog_id ) ) { /** * Note: * When running on the network admin, there's no need to iterate through all the installs individually since network opt-in permissions are managed for ALL non-delegated installs through a single option (per permission) on the network-level storage. */ return true; } $api_managed_permissions = array_intersect( $permissions, FS_Permission_Manager::get_api_managed_permission_ids() ); if ( in_array( FS_Permission_Manager::PERMISSION_ESSENTIALS, $permissions ) && ! in_array( FS_Permission_Manager::PERMISSION_SITE, $permissions ) ) { $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_SITE; } if ( ! empty( $api_managed_permissions ) ) { $has_site_delegated_connection = false; if ( ! $is_enabled && ! in_array( FS_Permission_Manager::PERMISSION_EXTENSIONS, $api_managed_permissions ) && false === FS_Permission_Manager::instance( $this )->is_extensions_tracking_allowed( $blog_id ) ) { /** * If we are turning off a permission and the extensions permission is off too, enrich the permissions update request to also turn off extensions tracking, as currently when opting in with extensions tracking disabled the extensions tracking is off but the API isn't aware of it. * * @todo Remove this entire `if` after implementing granular opt-in that also sends the permissions to the API when opting in. */ $api_managed_permissions[] = FS_Permission_Manager::PERMISSION_EXTENSIONS; } if ( is_null( $blog_id ) && fs_is_network_admin() ) { $result = $this->update_network_permissions( $api_managed_permissions, $is_enabled, $has_site_delegated_connection ); } else { $result = $this->update_site_permissions( $api_managed_permissions, $is_enabled, $blog_id ); } if ( true !== $result ) { return $result; } if ( in_array( FS_Permission_Manager::PERMISSION_SITE, $api_managed_permissions ) ) { if ( $is_enabled ) { $this->schedule_sync_cron(); } else { $this->clear_sync_cron( ! $has_site_delegated_connection ); } } if ( in_array( FS_Permission_Manager::PERMISSION_USER, $api_managed_permissions ) ) { $this->toggle_user_permission( $is_enabled, $blog_id ); } } $this->update_tracking_permissions( $permissions, $is_enabled, $blog_id ); return true; } /** * @param bool $is_enabled * @param int|null $blog_id */ private function toggle_user_permission( $is_enabled, $blog_id = null ) { $network_or_blog_ids = is_numeric( $blog_id ) ? $blog_id : fs_is_network_admin(); if ( $is_enabled ) { $this->reset_anonymous_mode( $network_or_blog_ids ); } else { $this->skip_connection( $network_or_blog_ids ); } } /** * Opt-in back into usage tracking. * * Note: This will only work if the user opted-in previously. * * Returns: * 1. FALSE - If the user never opted-in. * 2. TRUE - If successfully opted-in back to usage tracking. * 3. object - API result on failure. * * @author Leo Fajardo (@leorw) * @since 1.2.1.5 * * @bool $is_enabled * * @return bool|object */ private function toggle_site_tracking( $is_enabled, $blog_id = null ) { $this->_logger->entrance(); return $this->toggle_permission_tracking( FS_Permission_Manager::instance( $this )->get_site_tracking_permission_names(), $is_enabled, $blog_id ); } /** * If user opted-in and later disabled usage-tracking, * re-allow tracking for licensing and updates. * * @author Leo Fajardo (@leorw) * @since 1.2.1.5 * * @param bool $is_context_single_site */ private function reconnect_locally( $is_context_single_site = false ) { $this->_logger->entrance(); if ( ! $this->is_registered() ) { return; } if ( ! fs_is_network_admin() || $is_context_single_site ) { if ( $this->is_tracking_prohibited() ) { FS_Permission_Manager::instance( $this )->update_site_tracking( true ); } } else { $installs_map = $this->get_blog_install_map(); foreach ( $installs_map as $blog_id => $install ) { /** * @var FS_Site $install */ if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) { FS_Permission_Manager::instance( $this )->update_site_tracking( true, $blog_id ); } } } } /** * Update permission tracking flags. When updating in a network context, in addition to updating the network-level flags, also update the permissions on the site-level for all non-delegated sites. * * @param string[] $permissions * @param bool $is_enabled * @param int|null $blog_id * * @return array */ private function update_tracking_permissions( $permissions, $is_enabled, $blog_id = null ) { // Alias. $permission_manager = FS_Permission_Manager::instance( $this ); $network_or_blog_ids = is_numeric( $blog_id ) ? $blog_id : fs_is_network_admin(); if ( true === $network_or_blog_ids ) { // Update the permission for all non-delegated sub-sites. $blog_ids = $this->get_non_delegated_blog_ids(); // Add the network-level to the array, to update the permission on the network-level storage. array_unshift( $blog_ids, null ); } else { if ( false === $network_or_blog_ids ) { $network_or_blog_ids = null; } $blog_ids = is_array( $network_or_blog_ids ) ? $network_or_blog_ids : array( $network_or_blog_ids ); } $result = array(); foreach ( $permissions as $permission ) { $permission = trim( $permission ); $is_permission_supported = true; foreach ( $blog_ids as $id ) { $is_permission_supported = $permission_manager->update_permission_tracking_flag( $permission, $is_enabled, $id ); } if ( ! $is_permission_supported ) { $permission = 'no_match'; } $result[ $permission ] = $is_enabled; } return $result; } /** * Parse plugin's settings (as defined by the plugin dev). * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param array $plugin_info * * @throws \Freemius_Exception */ private function parse_settings( &$plugin_info ) { $this->_logger->entrance(); $id = $this->get_numeric_option( $plugin_info, 'id', false ); $public_key = $this->get_option( $plugin_info, 'public_key', false ); $secret_key = $this->get_option( $plugin_info, 'secret_key', null ); $parent_id = $this->get_numeric_option( $plugin_info, 'parent_id', null ); $parent_name = $this->get_option( $plugin_info, 'parent_name', null ); /** * @author Vova Feldman (@svovaf) * @since 1.1.9 Try to pull secret key from external config. */ if ( is_null( $secret_key ) && defined( "WP_FS__{$this->_slug}_SECRET_KEY" ) ) { $secret_key = constant( "WP_FS__{$this->_slug}_SECRET_KEY" ); } if ( isset( $plugin_info['parent'] ) ) { $parent_id = $this->get_numeric_option( $plugin_info['parent'], 'id', null ); // $parent_slug = $this->get_option( $plugin_info['parent'], 'slug', null ); // $parent_public_key = $this->get_option( $plugin_info['parent'], 'public_key', null ); // $parent_name = $this->get_option( $plugin_info['parent'], 'name', null ); } if ( false === $id ) { throw new Freemius_Exception( array( 'error' => array( 'type' => 'ParameterNotSet', 'message' => 'Plugin id parameter is not set.', 'code' => 'plugin_id_not_set', 'http' => 500, ) ) ); } if ( false === $public_key ) { throw new Freemius_Exception( array( 'error' => array( 'type' => 'ParameterNotSet', 'message' => 'Plugin public_key parameter is not set.', 'code' => 'plugin_public_key_not_set', 'http' => 500, ) ) ); } $plugin = ( $this->_plugin instanceof FS_Plugin ) ? $this->_plugin : new FS_Plugin(); $premium_suffix = $this->get_option( $plugin_info, 'premium_suffix', '(Premium)' ); $plugin->update( array( 'id' => $id, 'type' => $this->get_option( $plugin_info, 'type', $this->_module_type ), 'public_key' => $public_key, 'slug' => $this->_slug, 'premium_slug' => $this->get_option( $plugin_info, 'premium_slug', "{$this->_slug}-premium" ), 'parent_plugin_id' => $parent_id, 'version' => $this->get_plugin_version(), 'title' => $this->get_plugin_name( $premium_suffix ), 'file' => $this->_plugin_basename, 'is_premium' => $this->get_bool_option( $plugin_info, 'is_premium', true ), 'premium_suffix' => $premium_suffix, 'is_live' => $this->get_bool_option( $plugin_info, 'is_live', true ), 'affiliate_moderation' => $this->get_option( $plugin_info, 'has_affiliation' ), 'bundle_id' => $this->get_option( $plugin_info, 'bundle_id', null ), 'bundle_public_key' => $this->get_option( $plugin_info, 'bundle_public_key', null ), 'opt_in_moderation' => $this->get_option( $plugin_info, 'opt_in', null ), ) ); if ( $plugin->is_updated() ) { // Update plugin details. $this->_plugin = FS_Plugin_Manager::instance( $this->_module_id )->store( $plugin ); } // Set the secret key after storing the plugin, we don't want to store the key in the storage. $this->_plugin->secret_key = $secret_key; /** * If the product is network integrated and activated and the current view is in the network level Admin dashboard, if the product's network-level menu located differently from the sub-site level, then use the network menu details (when set). * * @author Vova Feldman * @since 2.4.5 */ if ( $this->is_network_active() && fs_is_network_admin() ) { if ( isset( $plugin_info['menu_network'] ) && is_array( $plugin_info['menu_network'] ) && ! empty( $plugin_info['menu_network'] ) ) { $plugin_info['menu'] = $plugin_info['menu_network']; } } if ( ! isset( $plugin_info['menu'] ) ) { $plugin_info['menu'] = array(); if ( ! empty( $this->_storage->sdk_last_version ) && version_compare( $this->_storage->sdk_last_version, '1.1.2', '<=' ) ) { // Backward compatibility to 1.1.2 $plugin_info['menu']['slug'] = isset( $plugin_info['menu_slug'] ) ? $plugin_info['menu_slug'] : $this->_slug; } } $this->_menu = FS_Admin_Menu_Manager::instance( $this->_module_id, $this->_module_type, $this->get_unique_affix() ); $this->_menu->init( $plugin_info['menu'], $this->is_addon() ); $this->_has_addons = $this->get_bool_option( $plugin_info, 'has_addons', false ); $this->_has_paid_plans = $this->get_bool_option( $plugin_info, 'has_paid_plans', true ); $this->_has_premium_version = $this->get_bool_option( $plugin_info, 'has_premium_version', $this->_has_paid_plans ); $this->_ignore_pending_mode = $this->get_bool_option( $plugin_info, 'ignore_pending_mode', false ); $this->_is_org_compliant = $this->get_bool_option( $plugin_info, 'is_org_compliant', true ); $this->_is_premium_only = $this->get_bool_option( $plugin_info, 'is_premium_only', false ); if ( $this->_is_premium_only ) { // If premium only plugin, disable anonymous mode. $this->_enable_anonymous = false; $this->_anonymous_mode = false; } else { $this->_enable_anonymous = $this->get_bool_option( $plugin_info, 'enable_anonymous', true ); $this->_anonymous_mode = $this->get_bool_option( $plugin_info, 'anonymous_mode', false ); } $this->_permissions = $this->get_option( $plugin_info, 'permissions', array() ); $this->_is_bundle_license_auto_activation_enabled = $this->get_option( $plugin_info, 'bundle_license_auto_activation', false ); if ( ! empty( $plugin_info['trial'] ) ) { $this->_trial_days = $this->get_numeric_option( $plugin_info['trial'], 'days', // Default to 0 - trial without days specification. 0 ); $this->_is_trial_require_payment = $this->get_bool_option( $plugin_info['trial'], 'is_require_payment', false ); } $this->_navigation = $this->get_option( $plugin_info, 'navigation', $this->is_free_wp_org_theme() ? self::NAVIGATION_TABS : self::NAVIGATION_MENU ); } /** * @param string[] $options * @param string $key * @param mixed $default * * @return bool */ private function get_option( &$options, $key, $default = false ) { return ! empty( $options[ $key ] ) ? $options[ $key ] : $default; } private function get_bool_option( &$options, $key, $default = false ) { return isset( $options[ $key ] ) && is_bool( $options[ $key ] ) ? $options[ $key ] : $default; } private function get_numeric_option( &$options, $key, $default = false ) { return isset( $options[ $key ] ) && is_numeric( $options[ $key ] ) ? $options[ $key ] : $default; } /** * Gate keeper. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return bool */ private function should_stop_execution() { if ( empty( $this->_storage->was_plugin_loaded ) ) { /** * Don't execute Freemius until plugin was fully loaded at least once, * to give the opportunity for the activation hook to run before pinging * the API for connectivity test. This logic is relevant for the * identification of new plugin install vs. plugin update. * * @author Vova Feldman (@svovaf) * @since 1.1.9 */ return true; } if ( $this->is_activation_mode() ) { if ( ! is_admin() ) { /** * If in activation mode, don't execute Freemius outside the admin dashboard. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ return true; } if ( ! WP_FS__IS_HTTP_REQUEST ) { /** * If in activation and executed without HTTP context (e.g. CLI, Cronjob), * then don't start Freemius. * * @author Vova Feldman (@svovaf) * @since 1.1.6.3 * * @link https://wordpress.org/support/topic/errors-in-the-freemius-class-when-running-in-wordpress-in-cli */ return true; } if ( self::is_cron() ) { /** * If in activation mode, don't execute Freemius during wp crons * (wp crons have HTTP context - called as HTTP request). * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ return true; } if ( self::is_ajax() ) { /** * During activation, if running in AJAX mode, unless there's a sticky * connectivity issue notice, don't run Freemius. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ return true; } } return false; } /** * Triggered after code type has changed. * * @author Vova Feldman (@svovaf) * @since 1.1.9.1 */ function _after_code_type_change() { $this->_logger->entrance(); if ( $this->is_theme() ) { // Expire the cache of the previous tabs since the theme may // have setting updates after code type has changed. $this->_cache->expire( 'tabs' ); $this->_cache->expire( 'tabs_stylesheets' ); } if ( ! $this->is_addon() ) { add_action( is_admin() ? 'admin_init' : 'init', array( &$this, '_plugin_code_type_changed' ) ); } if ( $this->is_registered() && $this->is_premium() ) { // Purge cached payments after switching to the premium version. // @todo This logic doesn't handle purging the cache for serviceware module upgrade. $this->get_api_user_scope()->purge_cache( "/plugins/{$this->_module_id}/payments.json?include_addons=true" ); } } /** * Handles plugin's code type change (free <--> premium). * * @author Vova Feldman (@svovaf) * @since 1.0.9 */ function _plugin_code_type_changed() { $this->_logger->entrance(); if ( $this->is_premium() ) { $this->reconnect_locally(); // Activated premium code. $this->do_action( 'after_premium_version_activation' ); // Remove all sticky messages related to download of the premium version. $this->_admin_notices->remove_sticky( array( 'trial_started', 'plan_upgraded', 'plan_changed', 'license_activated', ) ); $notice = ''; if ( ! $this->is_only_premium() ) { $notice = sprintf( $this->get_text_inline( 'Premium %s version was successfully activated.', 'premium-activated-message' ), $this->_module_type ); } $license_notice = $this->get_license_network_activation_notice(); if ( ! empty( $license_notice ) ) { $notice .= ' ' . $license_notice; } if ( ! empty( $notice ) ) { $this->_admin_notices->add_sticky( trim( $notice ), 'premium_activated', $this->get_text_x_inline( 'W00t', 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!' ); } } else { // Remove sticky message related to premium code activation. $this->_admin_notices->remove_sticky( 'premium_activated' ); // Activated free code (after had the premium before). $this->do_action( 'after_free_version_reactivation' ); if ( $this->is_paying() && ! $this->is_premium() ) { $this->add_complete_upgrade_instructions_notice( sprintf( /* translators: %s: License type (e.g. you have a professional license) */ $this->get_text_inline( 'You have a %s license.', 'you-have-x-license' ), $this->get_plan_title() ), 'plan_upgraded' ); } } if ( $this->is_registered() ) { // Schedule code type changes event. $this->schedule_install_sync(); } /** * Unregister the uninstall hook for the other version of the plugin (with different code type) to avoid * triggering a fatal error when uninstalling that plugin. For example, after deactivating the "free" version * of a specific plugin, its uninstall hook should be unregistered after the "premium" version has been * activated. If we don't do that, a fatal error will occur when we try to uninstall the "free" version since * the main file of the "free" version will be loaded first before calling the hooked callback. Since the * free and premium versions are almost identical (same class or have same functions), a fatal error like * "Cannot redeclare class MyClass" or "Cannot redeclare my_function()" will occur. */ $this->unregister_uninstall_hook(); $this->clear_module_main_file_cache(); // Update is_premium of latest version. $this->_storage->prev_is_premium = $this->_plugin->is_premium; } #endregion #---------------------------------------------------------------------------------- #region Add-ons #---------------------------------------------------------------------------------- /** * Check if add-on installed and activated on site. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param string|number $id_or_slug * @param bool|null $is_premium Since 1.2.1.7 can check for specified add-on version. * * @return bool */ function is_addon_activated( $id_or_slug, $is_premium = null ) { $this->_logger->entrance(); $addon_id = self::get_module_id( $id_or_slug ); $is_activated = self::has_instance( $addon_id ); if ( ! $is_activated ) { return false; } if ( is_bool( $is_premium ) ) { // Check if the specified code version is activate. $addon = $this->get_addon_instance( $addon_id ); $is_activated = ( $is_premium === $addon->is_premium() ); } return $is_activated; } /** * Check if add-on was connected to install * * @author Vova Feldman (@svovaf) * @since 1.1.7 * * @param string|number $id_or_slug * * @return bool */ function is_addon_connected( $id_or_slug ) { $this->_logger->entrance(); $sites = self::get_all_sites( WP_FS__MODULE_TYPE_PLUGIN ); $addon_id = self::get_module_id( $id_or_slug ); $addon = $this->get_addon( $addon_id ); $slug = $addon->slug; if ( ! isset( $sites[ $slug ] ) ) { return false; } $site = $sites[ $slug ]; $plugin = FS_Plugin_Manager::instance( $addon_id )->get(); if ( $plugin->parent_plugin_id != $this->_plugin->id ) { // The given slug do NOT belong to any of the plugin's add-ons. return false; } return ( is_object( $site ) && is_numeric( $site->id ) && is_numeric( $site->user_id ) && FS_Plugin_Plan::is_valid_id( $site->plan_id ) ); } /** * Determines if add-on installed. * * NOTE: This is a heuristic and only works if the folder/file named as the slug. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param string|number $id_or_slug * * @return bool */ function is_addon_installed( $id_or_slug ) { $this->_logger->entrance(); $addon_id = self::get_module_id( $id_or_slug ); return file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $this->get_addon_basename( $addon_id ) ) ); } /** * Get add-on basename. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param string|number $id_or_slug * * @return string */ function get_addon_basename( $id_or_slug ) { $addon_id = self::get_module_id( $id_or_slug ); if ( $this->is_addon_activated( $addon_id ) ) { return self::instance( $addon_id )->get_plugin_basename(); } $addon = $this->get_addon( $addon_id ); $premium_basename = "{$addon->premium_slug}/{$addon->slug}.php"; if ( file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $premium_basename ) ) ) { return $premium_basename; } $all_plugins = $this->get_all_plugins(); foreach ( $all_plugins as $basename => $data ) { if ( $addon->slug === $data['slug'] || $addon->premium_slug === $data['slug'] ) { return $basename; } } $free_basename = "{$addon->slug}/{$addon->slug}.php"; return $free_basename; } /** * Get installed add-ons instances. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @return Freemius[] */ function get_installed_addons() { if ( $this->is_addon() ) { // Add-on cannot have add-ons. return array(); } $installed_addons = array(); foreach ( self::$_instances as $instance ) { if ( $instance->is_addon_of( $this->_plugin->id ) ) { $installed_addons[] = $instance; } } return $installed_addons; } /** * Check if any add-ons of the plugin are installed. * * @author Leo Fajardo (@leorw) * @since 1.1.1 * * @return bool */ function has_installed_addons() { if ( ! $this->has_addons() ) { return false; } foreach ( self::$_instances as $instance ) { if ( $instance->is_addon() && is_object( $instance->_parent_plugin ) ) { if ( $this->_plugin->id == $instance->_parent_plugin->id ) { return true; } } } return false; } /** * Tell Freemius that the current plugin is an add-on. * * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @param number $parent_plugin_id The parent plugin ID */ function init_addon( $parent_plugin_id ) { $this->_plugin->parent_plugin_id = $parent_plugin_id; } /** * @author Vova Feldman (@svovaf) * @since 1.0.6 * * @return bool */ function is_addon() { return ( isset( $this->_plugin->parent_plugin_id ) && is_numeric( $this->_plugin->parent_plugin_id ) ); } /** * @author Vova Feldman (@svovaf) * @since 2.3.2 * * @param number $parent_product_id * * @return bool */ function is_addon_of( $parent_product_id ) { return ( $this->is_addon() && $parent_product_id == $this->_plugin->parent_plugin_id ); } /** * Deactivate add-on if it's premium only and the user does't have a valid license. * * @param bool $is_after_trial_cancel * * @return bool If add-on was deactivated. */ private function deactivate_premium_only_addon_without_license( $is_after_trial_cancel = false ) { if ( ! $this->has_free_plan() && ! $this->has_features_enabled_license() && ! $this->_has_premium_license() ) { if ( $this->is_registered() ) { // IF wrapper is turned off because activation_timestamp is currently only stored for plugins (not addons). // if (empty($this->_storage->activation_timestamp) || // (WP_FS__SCRIPT_START_TIME - $this->_storage->activation_timestamp) > 30 // ) { /** * @todo When it's first fail, there's no reason to try and re-sync because the licenses were just synced after initial activation. * * Retry syncing the user add-on licenses. */ // Sync licenses. $this->_sync_licenses(); // } // Try to activate premium license. $this->_activate_license( true ); } if ( ! $this->has_free_plan() && ! $this->has_features_enabled_license() && ! $this->_has_premium_license() ) { // @todo Check if deactivate plugins also call the deactivation hook. $this->_parent->_admin_notices->add_sticky( sprintf( ( $is_after_trial_cancel ? $this->_parent->get_text_inline( '%s free trial was successfully cancelled. Since the add-on is premium only it was automatically deactivated. If you like to use it in the future, you\'ll have to purchase a license.', 'addon-trial-cancelled-message' ) : $this->_parent->get_text_inline( '%s is a premium only add-on. You have to purchase a license first before activating the plugin.', 'addon-no-license-message' ) ), '<b>' . $this->_plugin->title . '</b>' ) . ' ' . sprintf( '<a href="%s" aria-label="%s" class="button button-primary" style="margin-left: 10px; vertical-align: middle;">%s ➜</a>', $this->_parent->addon_url( $this->_slug ), esc_attr( sprintf( $this->_parent->get_text_inline( 'More information about %s', 'more-information-about-x' ), $this->_plugin->title ) ), $this->_parent->get_text_inline( 'Purchase License', 'purchase-license' ) ), 'no_addon_license_' . $this->_slug, ( $is_after_trial_cancel ? '' : $this->_parent->get_text_x_inline( 'Oops', 'exclamation', 'oops' ) . '...' ), ( $is_after_trial_cancel ? 'success' : 'error' ) ); deactivate_plugins( array( $this->_plugin_basename ), true ); return true; } } return false; } #endregion #---------------------------------------------------------------------------------- #region Sandbox #---------------------------------------------------------------------------------- /** * Set Freemius into sandbox mode for debugging. * * @author Vova Feldman (@svovaf) * @since 1.0.4 * * @param string $secret_key */ function init_sandbox( $secret_key ) { $this->_plugin->secret_key = $secret_key; // Update plugin details. FS_Plugin_Manager::instance( $this->_module_id )->update( $this->_plugin, true ); } /** * Check if running payments in sandbox mode. * * @author Vova Feldman (@svovaf) * @since 1.0.4 * * @return bool */ function is_payments_sandbox() { return ( ! $this->is_live() ) || isset( $this->_plugin->secret_key ); } #endregion /** * Check if running test vs. live plugin. * * @author Vova Feldman (@svovaf) * @since 1.0.5 * * @return bool */ function is_live() { return $this->_plugin->is_live; } /** * Check if super-admin skipped connection for all sites in the network. * * @author Vova Feldman (@svovaf) * @since 2.0.0 */ function is_network_anonymous() { if ( ! $this->_is_network_active ) { return false; } $is_anonymous_ms = $this->_storage->get( 'is_anonymous_ms' ); if ( empty( $is_anonymous_ms ) ) { return false; } return $is_anonymous_ms['is']; } /** * Check if super-admin opted-in for all sites in the network. * * @author Vova Feldman (@svovaf) * @since 2.0.0 */ function is_network_connected() { if ( ! $this->_is_network_active ) { return false; } return $this->_storage->get( 'is_network_connected' ); } /** * Check if the user skipped connecting the account with Freemius. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @return bool */ function is_anonymous() { if ( ! isset( $this->_is_anonymous ) ) { if ( $this->is_network_anonymous() ) { $this->_is_anonymous = true; } else if ( fs_is_network_admin() ) { /** * When not-network-anonymous, yet, running in the network admin, consider as anonymous only when ALL non-delegated sites are set to anonymous. */ $non_delegated_sites = $this->get_non_delegated_blog_ids(); foreach ( $non_delegated_sites as $blog_id ) { $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id ); if ( empty( $is_anonymous ) || false === $is_anonymous[ 'is' ] ) { $this->_is_anonymous = false; break; } } if ( false !== $this->_is_anonymous ) { $this->_is_anonymous = true; } } else { if ( ! isset( $this->_storage->is_anonymous ) ) { // Not skipped. $this->_is_anonymous = false; } else if ( is_bool( $this->_storage->is_anonymous ) ) { // For back compatibility, since the variable was boolean before. $this->_is_anonymous = $this->_storage->is_anonymous; // Upgrade stored data format to 1.1.3 format. $this->set_anonymous_mode( $this->_storage->is_anonymous ); } else { // Version 1.1.3 and later. $this->_is_anonymous = $this->_storage->is_anonymous['is']; } } } return $this->_is_anonymous; } /** * Check if the user skipped the connection of a specified site. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int $blog_id * * @return bool */ function is_anonymous_site( $blog_id = 0 ) { if ( $this->is_network_anonymous() ) { return true; } $is_anonymous = $this->_storage->get( 'is_anonymous', false, $blog_id ); if ( empty( $is_anonymous ) ) { return false; } return $is_anonymous['is']; } /** * Check if user connected his account and install pending email activation. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @return bool */ function is_pending_activation() { return $this->_storage->get( 'is_pending_activation', false ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 */ private function clear_pending_activation_mode() { // Remove the pending activation sticky notice (if it still exists). $this->_admin_notices->remove_sticky( 'activation_pending' ); // Clear the plugin's pending activation mode. unset( $this->_storage->is_pending_activation ); } /** * Check if plugin must be WordPress.org compliant. * * @since 1.0.7 * * @return bool */ function is_org_repo_compliant() { return $this->_is_org_compliant; } #-------------------------------------------------------------------------------- #region WP Cron Common #-------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * * @return object */ private function get_cron_data( $name ) { $this->_logger->entrance( $name ); /** * @var object $cron_data */ return $this->_storage->get( "{$name}_cron", null ); } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. */ private function clear_cron_data( $name ) { $this->_logger->entrance( $name ); $this->_storage->remove( "{$name}_cron" ); } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param int $cron_blog_id The cron executing blog ID. */ private function set_cron_data( $name, $cron_blog_id = 0 ) { $this->_logger->entrance( $name ); $this->_storage->store( "{$name}_cron", (object) array( 'version' => $this->get_plugin_version(), 'blog_id' => $cron_blog_id, 'sdk_version' => $this->version, 'timestamp' => WP_FS__SCRIPT_START_TIME, 'on' => true, ) ); } /** * Get the cron's executing blog ID. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * * @return int */ private function get_cron_blog_id( $name ) { $this->_logger->entrance( $name ); if ( ! is_multisite() ) { // Not a multisite. return 0; } $cron_data = $this->get_cron_data( $name ); return ( is_object( $cron_data ) && is_numeric( $cron_data->blog_id ) ) ? $cron_data->blog_id : 0; } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * * @return bool */ private function is_cron_on( $name ) { $this->_logger->entrance( $name ); /** * @var object $cron_data */ $cron_data = $this->get_cron_data( $name ); return ( ! is_null( $cron_data ) && true === $cron_data->on ); } /** * Unix timestamp for previous cron execution or false if never executed. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * * @return int|false */ private function cron_last_execution( $name ) { $this->_logger->entrance( $name ); return $this->_storage->get( "{$name}_timestamp" ); } /** * Set cron execution time to now. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. */ private function set_cron_execution_timestamp( $name ) { $this->_logger->entrance( $name ); $this->_storage->store( "{$name}_timestamp", time() ); } /** * Sets the keepalive time to now. * * @author Leo Fajardo (@leorw) * @since 2.2.3 * * @param bool|null $use_network_level_storage */ private function set_keepalive_timestamp( $use_network_level_storage = null ) { $this->_logger->entrance(); $this->_storage->store( 'keepalive_timestamp', time(), $use_network_level_storage ); } /** * Check if cron was executed in the last $period of seconds. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param int $period In seconds * * @return bool */ private function is_cron_executed( $name, $period = WP_FS__TIME_24_HOURS_IN_SEC ) { $this->_logger->entrance( $name ); $last_execution = $this->cron_last_execution( $name ); if ( ! is_numeric( $last_execution ) ) { return false; } return ( $last_execution > ( WP_FS__SCRIPT_START_TIME - $period ) ); } /** * WP Cron is executed on a site level. When running in a multisite network environment * with the network integration activated, for optimization reasons, we are consolidating * the installs data sync cron to be executed only from a single site. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int $except_blog_id Target any except the excluded blog ID. * * @return int */ private function get_cron_target_blog_id( $except_blog_id = 0 ) { if ( ! is_multisite() ) { return 0; } if ( $this->_is_network_active ) { $network_install_blog_id = $this->_storage->network_install_blog_id; if ( is_numeric( $network_install_blog_id ) && $except_blog_id != $network_install_blog_id && self::is_site_active( $network_install_blog_id ) ) { // Try to run cron from the main network blog. $install = $this->get_install_by_blog_id( $network_install_blog_id ); if ( is_object( $install ) && $this->is_tracking_allowed( $network_install_blog_id, $install ) ) { return $network_install_blog_id; } } } // Get first opted-in blog ID with active tracking. $installs = $this->get_blog_install_map(); foreach ( $installs as $blog_id => $install ) { if ( $except_blog_id != $blog_id && self::is_site_active( $blog_id ) && $this->is_tracking_allowed( $blog_id, $install ) ) { return $blog_id; } } return 0; } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param string $action_tag Callback action tag. * @param bool $is_network_clear If set to TRUE, clear sync cron even if there are installs that are still connected. */ private function clear_cron( $name, $action_tag = '', $is_network_clear = false ) { $this->_logger->entrance( $name ); if ( ! $this->is_cron_on( $name ) ) { return; } $clear_cron = true; if ( ! $is_network_clear && $this->_is_network_active ) { $installs = $this->get_blog_install_map(); foreach ( $installs as $blog_id => $install ) { /** * @var FS_Site $install */ if ( $this->is_tracking_allowed( $blog_id, $install ) ) { $clear_cron = false; break; } } } if ( ! $clear_cron ) { return; } $cron_blog_id = $this->get_cron_blog_id( $name ); $this->clear_cron_data( $name ); if ( 0 < $cron_blog_id ) { switch_to_blog( $cron_blog_id ); } if ( empty( $action_tag ) ) { $action_tag = $name; } wp_clear_scheduled_hook( $this->get_action_tag( $action_tag ) ); if ( 0 < $cron_blog_id ) { restore_current_blog(); } } /** * Unix timestamp for next cron execution or false if not scheduled. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param string $action_tag Callback action tag. * * @return int|false */ private function get_next_scheduled_cron( $name, $action_tag = '' ) { $this->_logger->entrance( $name ); if ( ! $this->is_cron_on( $name ) ) { return false; } $cron_blog_id = $this->get_cron_blog_id( $name ); if ( 0 < $cron_blog_id ) { switch_to_blog( $cron_blog_id ); } if ( empty( $action_tag ) ) { $action_tag = $name; } $next_scheduled = wp_next_scheduled( $this->get_action_tag( $action_tag ) ); if ( 0 < $cron_blog_id ) { restore_current_blog(); } return $next_scheduled; } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param string $action_tag Callback action tag. * @param string $recurrence 'single' or 'daily'. * @param int $start_at Defaults to now. * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away. * @param int $except_blog_id Target any except the excluded blog ID. */ private function schedule_cron( $name, $action_tag = '', $recurrence = 'single', $start_at = WP_FS__SCRIPT_START_TIME, $randomize_start = true, $except_blog_id = 0 ) { $this->_logger->entrance( $name ); $this->clear_cron( $name, $action_tag, true ); $cron_blog_id = $this->get_cron_target_blog_id( $except_blog_id ); if ( is_multisite() && 0 == $cron_blog_id ) { // Don't schedule cron since couldn't find a target blog. return; } if ( 0 < $cron_blog_id ) { switch_to_blog( $cron_blog_id ); } if ( 'daily' === $recurrence ) { if ( $randomize_start ) { // Schedule first sync with a random 12 hour time range from now. $start_at += rand( 0, ( WP_FS__TIME_24_HOURS_IN_SEC / 2 ) ); } // Schedule daily WP cron. wp_schedule_event( $start_at, 'daily', $this->get_action_tag( $action_tag ) ); } else if ( 'single' === $recurrence ) { // Schedule single cron. wp_schedule_single_event( $start_at, $this->get_action_tag( $action_tag ) ); } $this->set_cron_data( $name, $cron_blog_id ); if ( 0 < $cron_blog_id ) { restore_current_blog(); } } /** * Consolidated cron execution for performance optimization. The max number of API requests is based on the number of unique opted-in users. * that doesn't halt page loading. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string $name Cron name. * @param callable $callable The function that should be executed. */ private function execute_cron( $name, $callable ) { $this->_logger->entrance( $name ); // Store the last time data sync was executed. $this->set_cron_execution_timestamp( $name ); // Check if API is temporary down. if ( FS_Api::is_temporary_down() ) { return; } // @todo Add logic that identifies API latency, and reschedule the next background sync randomly between 8-16 hours. $users_2_blog_ids = array(); if ( ! is_multisite() ) { // Add dummy blog. $users_2_blog_ids[0] = array( 0 ); } else { $installs = $this->get_blog_install_map(); foreach ( $installs as $blog_id => $install ) { if ( $this->is_tracking_allowed( $blog_id, $install ) ) { if ( ! isset( $users_2_blog_ids[ $install->user_id ] ) ) { $users_2_blog_ids[ $install->user_id ] = array(); } $users_2_blog_ids[ $install->user_id ][] = $blog_id; } } } $current_blog_id = get_current_blog_id(); foreach ( $users_2_blog_ids as $user_id => $blog_ids ) { if ( 0 < $blog_ids[0] ) { $this->switch_to_blog( $blog_ids[0] ); } call_user_func_array( $callable, array( $blog_ids, ( is_multisite() ? $current_blog_id : null ) ) ); foreach ( $blog_ids as $blog_id ) { $this->do_action( "after_{$name}_cron", $blog_id ); } } if ( is_multisite() ) { $this->switch_to_blog( $current_blog_id, fs_is_network_admin() ? $this->get_network_install() : null ); $this->do_action( "after_{$name}_cron_multisite" ); } } #endregion #---------------------------------------------------------------------------------- #region Daily Sync Cron #---------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return bool */ private function is_sync_cron_scheduled() { return $this->is_cron_on( 'sync' ); } /** * Get the sync cron's executing blog ID. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return int */ private function get_sync_cron_blog_id() { return $this->get_cron_blog_id( 'sync' ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ private function run_manual_sync() { if ( ! $this->is_user_admin() ) { return; } // Run manual sync. $this->_sync_cron(); // Reschedule next cron to run 24 hours from now (performance optimization). $this->schedule_sync_cron( time() + WP_FS__TIME_24_HOURS_IN_SEC, false ); } /** * Data sync cron job. Replaces the background sync non blocking HTTP request * that doesn't halt page loading. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * @since 2.0.0 Consolidate all the data sync into the same cron for performance optimization. The max number of API requests is based on the number of unique opted-in users. */ function _sync_cron() { $this->_logger->entrance(); $this->execute_cron( 'sync', array( &$this, '_sync_cron_method' ) ); } /** * The actual data sync cron logic. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int[] $blog_ids * @param int|null $current_blog_id @since 2.2.3. This is passed from the `execute_cron` method and used by the * `_sync_plugin_license` method in order to switch to the previous blog when sending * updates for a single site in case `execute_cron` has switched to a different blog. */ function _sync_cron_method( array $blog_ids, $current_blog_id = null ) { if ( $this->is_registered() ) { if ( $this->has_paid_plan() ) { // Initiate background plan sync. $this->_sync_license( true, false, $current_blog_id ); if ( $this->is_paying() ) { // Check for premium plugin updates. $this->check_updates( true ); } } else { // Sync install(s) (only if something changed locally). if ( 1 < count( $blog_ids ) ) { $this->sync_installs(); } else { $this->sync_install(); } $this->maybe_sync_install_user(); } } } /** * Check if sync was executed in the last $period of seconds. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param int $period In seconds * * @return bool */ private function is_sync_executed( $period = WP_FS__TIME_24_HOURS_IN_SEC ) { return $this->is_cron_executed( 'sync', $period ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return bool */ private function is_sync_cron_on() { return $this->is_cron_on( 'sync' ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 */ private function maybe_schedule_sync_cron() { $next_schedule = $this->next_sync_cron(); // The event is properly scheduled, so no need to reschedule it. if ( is_numeric( $next_schedule ) && $next_schedule > time() ) { return; } $this->schedule_sync_cron(); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param int $start_at Defaults to now. * @param bool $randomize_start If true, schedule first job randomly during the next 12 hours. Otherwise, schedule job to start right away. * @param int $except_blog_id Since 2.0.0 when running in a multisite network environment, the cron execution is consolidated. This param allows excluding excluded specified blog ID from being the cron executor. */ private function schedule_sync_cron( $start_at = WP_FS__SCRIPT_START_TIME, $randomize_start = true, $except_blog_id = 0 ) { $this->schedule_cron( 'sync', 'data_sync', 'daily', $start_at, $randomize_start, $except_blog_id ); } /** * Add the actual sync function to the cron job hook. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ private function hook_callback_to_sync_cron() { $this->add_action( 'data_sync', array( &$this, '_sync_cron' ) ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param bool $is_network_clear Since 2.0.0 If set to TRUE, clear sync cron even if there are installs that are still connected. */ private function clear_sync_cron( $is_network_clear = false ) { $this->_logger->entrance(); $this->clear_cron( 'sync', 'data_sync', $is_network_clear ); } /** * Unix timestamp for next sync cron execution or false if not scheduled. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return int|false */ function next_sync_cron() { return $this->get_next_scheduled_cron( 'sync', 'data_sync' ); } /** * Unix timestamp for previous sync cron execution or false if never executed. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return int|false */ function last_sync_cron() { return $this->cron_last_execution( 'sync' ); } #endregion Daily Sync Cron ------------------------------------------------------------------ #---------------------------------------------------------------------------------- #region Async Install Sync #---------------------------------------------------------------------------------- /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return bool */ private function is_install_sync_scheduled() { return $this->is_cron_on( 'install_sync' ); } /** * Get the sync cron's executing blog ID. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return int */ private function get_install_sync_cron_blog_id() { return $this->get_cron_blog_id( 'install_sync' ); } /** * Instead of running blocking install sync event, execute non blocking scheduled wp-cron. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param int $except_blog_id Since 2.0.0 when running in a multisite network environment, the cron execution is consolidated. This param allows excluding excluded specified blog ID from being the cron executor. */ private function schedule_install_sync( $except_blog_id = 0 ) { if ( $this->is_clone() ) { return; } $this->schedule_cron( 'install_sync', 'install_sync', 'single', WP_FS__SCRIPT_START_TIME, false, $except_blog_id ); } /** * Unix timestamp for previous install sync cron execution or false if never executed. * * @todo There's some very strange bug that $this->_storage->install_sync_timestamp value is not being updated. But for sure the sync event is working. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return int|false */ function last_install_sync() { return $this->cron_last_execution( 'install_sync' ); } /** * Unix timestamp for next install sync cron execution or false if not scheduled. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @return int|false */ function next_install_sync() { return $this->get_next_scheduled_cron( 'install_sync', 'install_sync' ); } /** * Add the actual install sync function to the cron job hook. * * @author Vova Feldman (@svovaf) * @since 1.1.7.3 */ private function hook_callback_to_install_sync() { $this->add_action( 'install_sync', array( &$this, '_run_sync_install' ) ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * * @param bool $is_network_clear Since 2.0.0 If set to TRUE, clear sync cron even if there are installs that are still connected. */ private function clear_install_sync_cron( $is_network_clear = false ) { $this->_logger->entrance(); $this->clear_cron( 'install_sync', 'install_sync', $is_network_clear ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.7.3 * @since 2.0.0 Consolidate all the data sync into the same cron for performance optimization. The max number of API requests is based on the number of unique opted-in users. */ public function _run_sync_install() { $this->_logger->entrance(); $this->execute_cron( 'sync', array( &$this, '_sync_install_cron_method' ) ); } /** * The actual install(s) sync cron logic. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int[] $blog_ids * @param int|null $current_blog_id */ function _sync_install_cron_method( array $blog_ids, $current_blog_id = null ) { if ( $this->is_registered() ) { if ( 1 < count( $blog_ids ) ) { $this->sync_installs( array(), true ); } else { $this->sync_install( array(), true ); } $this->maybe_sync_install_user(); } } #endregion Async Install Sync ------------------------------------------------------------------ /** * Show a notice that activation is currently pending. * * @todo Add some sort of mechanism to allow users to update the email address they would like to opt-in with when $is_suspicious_email is true. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @param bool|string $email_address * @param bool $is_pending_trial Since 1.2.1.5 * @param bool $is_suspicious_email Since 2.5.0 Set to true when there's an indication that email address the user opted in with is fake/dummy/placeholder. * @param bool $has_upgrade_context Since 2.5.3 * @param bool $support_email_address Since 2.5.3 */ function _add_pending_activation_notice( $email_address = false, $is_pending_trial = false, $is_suspicious_email = false, $has_upgrade_context = false, $support_email_address = false ) { if ( ! is_string( $email_address ) ) { $current_user = self::_get_current_wp_user(); $email_address = $current_user->user_email; } $formatted_message_args = array( "<b>{$this->get_plugin_name()}</b>", "<b>{$email_address}</b>", ); if ( ! $has_upgrade_context || ! fs_is_network_admin() ) { /* translators: %3$s: action (e.g.: "start the trial" or "complete the opt-in") */ $formatted_message = $this->get_text_inline( 'You should receive a confirmation email for %1$s to your mailbox at %2$s. Please make sure you click the button in that email to %3$s.', 'pending-activation-message' ); $formatted_message_args[] = $is_pending_trial ? $this->get_text_inline( 'start the trial', 'start-the-trial' ) : $this->get_text_inline( 'complete the opt-in', 'complete-the-opt-in' ); $notice_title = $this->get_text_inline( 'Thanks!', 'thanks' ); } else { /* translators: %3$s: What the user is expected to receive via email (e.g.: "the installation instructions" or "a license key") */ $formatted_message = $this->get_text_inline( 'You should receive %3$s for %1$s to your mailbox at %2$s in the next 5 minutes.' ); if ( $this->has_release_on_freemius() ) { $formatted_message_args[] = $this->get_text_x_inline( 'the installation instructions', 'Part of the message telling the user what they should receive via email.', 'the-installation-instructions-phrase' ); } else { $formatted_message_args[] = $this->get_text_x_inline( 'a license key', 'Part of the message telling the user what they should receive via email.', 'a-license-key-phrase' ); $formatted_message .= ( ' ' . sprintf( /* translators: %s: activation link (e.g.: <a>Click here</a>) */ $this->get_text_inline( '%s to activate the license once you get it.', 'license-activation-link-message' ), sprintf( '<b><a href="%s">%s</a></b>', $this->get_activation_url( array( 'fs_action' => 'reset_pending_activation_mode', 'require_license' => 'true', 'fs_unique_affix' => $this->get_unique_affix(), ) ), $this->get_text_x_inline( 'Click here', 'Part of an activation link message.', 'click-here' ) ) ) ); } $formatted_message_args[] = ( ! empty( $support_email_address ) ) ? ( "<b>{$support_email_address}</b>" ) : $this->get_text_x_inline( "the product's support email address", 'Part of the message that tells the user to check their spam folder for a specific email.', 'product-support-email-address-phrase' ); $formatted_message .= ( ' ' . $this->get_text_inline( 'If you didn\'t get the email, try checking your spam folder or search for emails from %4$s.', 'check-spam-folder-message' ) ); $notice_title = $this->get_text_inline( 'Thanks for upgrading.', 'after-upgrade-thank-you-message' ); } $this->_admin_notices->add_sticky( vsprintf( $formatted_message, $formatted_message_args ), 'activation_pending', $notice_title ); } /** * Check if currently in plugin activation. * * @author Vova Feldman (@svovaf) * @since 1.1.4 * * @return bool */ function is_plugin_activation() { $result = get_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" ); return !empty($result); } /** * * NOTE: admin_menu action executed before admin_init. * * @author Vova Feldman (@svovaf) * @since 1.0.7 */ function _admin_init_action() { $is_migration = $this->is_migration(); /** * Automatically redirect to connect/activation page after plugin activation. * * @since 1.1.7 Do NOT redirect to opt-in when running in network admin mode. */ if ( $this->is_plugin_activation() ) { delete_transient( "fs_{$this->_module_type}_{$this->_slug}_activated" ); if ( isset( $_GET['activate-multi'] ) ) { /** * Don't redirect if activating multiple plugins at once (bulk activation). */ } else if ( self::is_deactivation_snoozed() && ( // Either running the free code base. ! $this->is_premium() || // Or if has a free version. ! $this->is_only_premium() || // If premium only, don't redirect if license is activated. ( $this->is_registered() && ! $this->can_use_premium_code() ) ) ) { /** * Don't redirect if activating during the deactivation snooze period (aka troubleshooting), unless activating a paid product version that the admin didn't enter its license key yet. */ } else if ( ! $is_migration ) { $this->_redirect_on_activation_hook(); return; } } if ( $is_migration ) { return; } if ( fs_request_is_action( $this->get_unique_affix() . '_skip_activation' ) ) { check_admin_referer( $this->get_unique_affix() . '_skip_activation' ); $this->skip_connection( fs_is_network_admin() ); fs_redirect( $this->get_after_activation_url( 'after_skip_url' ) ); } if ( $this->is_network_activation_mode() && fs_request_is_action( $this->get_unique_affix() . '_delegate_activation' ) ) { check_admin_referer( $this->get_unique_affix() . '_delegate_activation' ); $this->delegate_connection(); fs_redirect( $this->get_after_activation_url( 'after_delegation_url' ) ); } $this->_add_upgrade_action_link(); if ( ! ( ! $this->_is_network_active && fs_is_network_admin() ) && ( ( true === $this->_storage->require_license_activation ) || // Not registered nor anonymous. ( ! $this->is_registered() && ! $this->is_anonymous() ) || // OR, network level and in network upgrade mode. ( fs_is_network_admin() && $this->_is_network_active && $this->is_network_upgrade_mode() ) ) ) { if ( ! $this->is_pending_activation() ) { if ( ! $this->is_activation_page() ) { /** * If a user visits any other admin page before activating the premium-only theme with a valid * license, reactivate the previous theme. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ if ( $this->is_theme() && ! $this->has_settings_menu() && ! isset( $_REQUEST['fs_action'] ) && $this->can_activate_previous_theme() ) { if ( $this->is_only_premium() ) { $this->activate_previous_theme(); return; } if ( true === $this->_storage->require_license_activation ) { $this->_storage->require_license_activation = false; } } if ( ! fs_is_network_admin() && $this->is_network_activation_mode() && ! $this->is_delegated_connection() ) { return; } if ( $this->is_plugin_new_install() || $this->is_only_premium() ) { if ( ! $this->_anonymous_mode && ( ! $this->is_addon() || ! $this->_parent->is_anonymous() ) ) { // Show notice for new plugin installations. $this->_admin_notices->add( sprintf( $this->get_text_inline( 'You are just one step away - %s', 'you-are-step-away' ), sprintf( '<b><a href="%s">%s</a></b>', $this->get_activation_url( array(), ! $this->is_delegated_connection() ), sprintf( $this->get_text_x_inline( 'Complete "%s" Activation Now', '%s - plugin name. As complete "PluginX" activation now', 'activate-x-now' ), $this->get_plugin_name() ) ) ), '', 'update-nag' ); } } else { if ( $this->should_add_sticky_optin_notice() ) { $this->add_sticky_optin_admin_notice(); } if ( $this->has_filter( 'optin_pointer_element' ) ) { // Don't show admin nag if plugin update. wp_enqueue_script( 'wp-pointer' ); wp_enqueue_style( 'wp-pointer' ); $this->_enqueue_connect_essentials(); add_action( 'admin_print_footer_scripts', array( $this, '_add_connect_pointer_script' ) ); } } } } if ( $this->show_opt_in_on_themes_page() && $this->is_activation_page() ) { $this->_show_theme_activation_optin_dialog(); } } } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @return bool */ private function should_add_sticky_optin_notice() { if ( $this->is_addon() && $this->_parent->is_anonymous() ) { return false; } if ( fs_is_network_admin() ) { if ( ! $this->_is_network_active ) { return false; } if ( ! $this->is_network_activation_mode() ) { return false; } return ! isset( $this->_storage->sticky_optin_added_ms ); } if ( ! $this->is_activation_mode() ) { return false; } // If running from a blog admin and delegated the connection. return ! isset( $this->_storage->sticky_optin_added ); } /** * @author Leo Fajardo (@leorw) * @since 2.0.0 */ private function add_sticky_optin_admin_notice() { if ( ! $this->_is_network_active || ! fs_is_network_admin() ) { $this->_storage->sticky_optin_added = true; } else { $this->_storage->sticky_optin_added_ms = true; } // Show notice for new plugin installations. $this->_admin_notices->add_sticky( sprintf( $this->get_text_inline( 'We made a few tweaks to the %s, %s', 'few-plugin-tweaks' ), $this->_module_type, sprintf( '<b><a href="%s">%s</a></b>', $this->get_activation_url(), sprintf( $this->get_text_inline( 'Opt in to make "%s" better!', 'optin-x-now' ), $this->get_plugin_name() ) ) ), 'connect_account', '', 'update-nag' ); } /** * Enqueue connect requires scripts and styles. * * @author Vova Feldman (@svovaf) * @since 1.1.4 */ function _enqueue_connect_essentials() { wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'json2' ); fs_enqueue_local_script( 'postmessage', 'nojquery.ba-postmessage.min.js' ); fs_enqueue_local_script( 'fs-postmessage', 'postmessage.js' ); } /** * Add connect / opt-in pointer. * * @author Vova Feldman (@svovaf) * @since 1.1.4 */ function _add_connect_pointer_script() { $vars = array( 'id' => $this->_module_id ); $pointer_content = fs_get_template( 'connect.php', $vars ); ?> <script type="text/javascript">// <![CDATA[ jQuery(document).ready(function ($) { if ('undefined' !== typeof(jQuery().pointer)) { var element = <?php echo $this->apply_filters( 'optin_pointer_element', '$("#non_existing_element");' ) ?>; if (element.length > 0) { var optin = $(element).pointer($.extend(true, {}, { content : <?php echo json_encode( $pointer_content ) ?>, position : { edge : 'left', align: 'center' }, buttons : function () { // Don't show pointer buttons. return ''; }, pointerWidth: 482 }, <?php echo $this->apply_filters( 'optin_pointer_options_json', '{}' ) ?>)); <?php echo $this->apply_filters( 'optin_pointer_execute', " optin.pointer('open'); // Tag the opt-in pointer with custom class. $('.wp-pointer #fs_connect') .parents('.wp-pointer.wp-pointer-top') .addClass('fs-opt-in-pointer'); ", 'element', 'optin' ) ?> } } }); // ]]></script> <?php } /** * Return current page's URL. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @return string */ static function current_page_url() { $url = 'http'; if ( isset( $_SERVER["HTTPS"] ) ) { if ( $_SERVER["HTTPS"] == "on" ) { $url .= "s"; } } $url .= "://"; if ( $_SERVER["SERVER_PORT"] != "80" ) { $url .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"]; } else { $url .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]; } return esc_url( $url ); } /** * Check if the current page is the plugin's main admin settings page. * * @author Vova Feldman (@svovaf) * @since 1.0.7 * * @return bool */ function _is_plugin_page() { return fs_is_plugin_page( $this->_menu->get_raw_slug() ) || fs_is_plugin_page( $this->_slug ); } /* Events ------------------------------------------------------------------------------------------------------------------*/ /** * Delete site install from Database. * * @author Vova Feldman (@svovaf) * @since 1.0.1 * * @param bool $store * @param int|null $blog_id Since 2.0.0 * * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist). */ function _delete_site( $store = true, $blog_id = null ) { return self::_delete_site_by_slug( $this->_slug, $this->_module_type, $store, $blog_id ); } /** * Delete site install from Database. * * @author Vova Feldman (@svovaf) * @since 1.2.2.7 * * @param string $slug * @param string $module_type * @param bool $store * @param int|null $blog_id Since 2.0.0 * * @return false|int The install ID if deleted. Otherwise, FALSE (when install not exist). */ static function _delete_site_by_slug( $slug, $module_type, $store = true, $blog_id = null ) { $sites = self::get_all_sites( $module_type, $blog_id ); $install_id = false; if ( isset( $sites[ $slug ] ) ) { if ( is_object( $sites[ $slug ] ) ) { $install_id = $sites[ $slug ]->id; } unset( $sites[ $slug ] ); self::set_account_option_by_module( $module_type, 'sites', $sites, $store, $blog_id ); } return $install_id; } /** * Delete user. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param number $user_id * @param bool $store * * @return false|int The user ID if deleted. Otherwise, FALSE (when install not exist). */ private static function delete_user( $user_id, $store = true ) { $users = self::get_all_users(); if ( ! is_array( $users ) || ! isset( $users[ $user_id ] ) ) { return false; } unset( $users[ $user_id ] ); self::$_accounts->set_option( 'users', $users, $store ); return $user_id; } /** * Delete plugin's plans information. * * @param bool $store Flush to Database if true. * @param bool $keep_associated_plans If set to false, delete all plans, even if a plan is associated with an install. * * @author Vova Feldman (@svovaf) * @since 1.0.9 */ private function _delete_plans( $store = true, $keep_associated_plans = true ) { $this->_logger->entrance(); $plans = self::get_all_plans( $this->_module_type ); $plans_to_keep = array(); if ( $keep_associated_plans ) { $plans_ids_to_keep = $this->get_plans_ids_associated_with_installs(); foreach ( $plans_ids_to_keep as $plan_id ) { $plan = self::_get_plan_by_id( $plan_id ); if ( is_object( $plan ) ) { $plans_to_keep[] = self::_encrypt_entity( $plan ); } } } if ( ! empty( $plans_to_keep ) ) { $plans[ $this->_slug ] = $plans_to_keep; } else { unset( $plans[ $this->_slug ] ); } $this->set_account_option( 'plans', $plans, $store ); } /** * Delete all plugin licenses. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param bool $store */ private function _delete_licenses( $store = true ) { $this->_logger->entrance(); $all_licenses = self::get_all_licenses(); unset( $all_licenses[ $this->_module_id ] ); self::$_accounts->set_option( 'all_licenses', $all_licenses, $store ); } /** * Check if Freemius was added on new plugin installation. * * @author Vova Feldman (@svovaf) * @since 1.1.5 * * @return bool */ function is_plugin_new_install() { return isset( $this->_storage->is_plugin_new_install ) && $this->_storage->is_plugin_new_install; } /** * Check if it's the first plugin release that is running Freemius. * * @author Vova Feldman (@svovaf) * @since 1.2.1.5 * * @return bool */ function is_first_freemius_powered_version() { return empty( $this->_storage->plugin_last_version ); } /** * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @return bool|string */ private function get_previous_theme_slug() { return isset( $this->_storage->previous_theme ) ? $this->_storage->previous_theme : false; } /** * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @return bool */ private function can_activate_previous_theme() { return $this->can_activate_theme( $this->get_previous_theme_slug() ); } /** * @author Leo Fajardo (@leorw) * @since 2.5.0 * * @return bool */ private function can_activate_theme( $slug ) { if ( false !== $slug && current_user_can( 'switch_themes' ) ) { $theme_instance = wp_get_theme( $slug ); return $theme_instance->exists(); } return false; } /** * @author Leo Fajardo (@leorw) * @since 1.2.2 */ private function activate_previous_theme() { switch_theme( $this->get_previous_theme_slug() ); unset( $this->_storage->previous_theme ); global $pagenow; if ( 'themes.php' === $pagenow ) { /** * Refresh the active theme information. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ fs_redirect( $this->admin_url( $pagenow ) ); } } /** * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @return string */ function get_previous_theme_activation_url() { if ( ! $this->can_activate_previous_theme() ) { return ''; } /** * Activation URL * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ return wp_nonce_url( $this->admin_url( 'themes.php?action=activate&stylesheet=' . urlencode( $this->get_previous_theme_slug() ) ), 'switch-theme_' . $this->get_previous_theme_slug() ); } /** * Saves the slug of the previous theme if it still exists so that it can be used by the logic in the opt-in * form that decides whether to add a close button to the opt-in dialog or not. So after a premium-only theme is * activated, the close button will appear and will reactivate the previous theme if clicked. If the previous * theme doesn't exist, then there will be no close button. * * @author Leo Fajardo (@leorw) * @since 1.2.2 * * @param string $slug_or_name Old theme's slug or name. * @param bool|WP_Theme $old_theme WP_Theme instance of the old theme if it still exists. */ function _activate_theme_event_hook( $slug_or_name, $old_theme = false ) { $this->_storage->previous_theme = ( false !== $old_theme ) ? $old_theme->get_stylesheet() : $slug_or_name; $this->_activate_plugin_event_hook(); } /** * Plugin activated hook. * * @author Vova Feldman (@svovaf) * @since 1.0.1 * * @uses FS_Api */ function _activate_plugin_event_hook() { $this->_logger->entrance( 'slug = ' . $this->_slug ); if ( ! $this->is_user_admin() ) { return; } $this->unregister_uninstall_hook(); // Clear API cache on activation. FS_Api::clear_cache(); $is_premium_version_activation = $this->is_plugin() ? ( current_filter() !== ( 'activate_' . $this->_free_plugin_basename ) ) : $this->is_premium(); if ( $is_premium_version_activation && $this->is_pending_activation() ) { $this->clear_pending_activation_mode(); } $this->_logger->info( 'Activating ' . ( $is_premium_version_activation ? 'premium' : 'free' ) . ' plugin version.' ); if ( $this->is_plugin() ) { // This logic is relevant only to plugins since both the free and premium versions of a plugin can be active at the same time. // 1. If running in the activation of the FREE module, get the basename of the PREMIUM. // 2. If running in the activation of the PREMIUM module, get the basename of the FREE. $other_version_basename = $is_premium_version_activation ? $this->_free_plugin_basename : $this->premium_plugin_basename(); if ( ! $this->_is_network_active ) { /** * Themes are always network activated, but the ACTUAL activation is per site. * * During the activation, the plugin isn't yet active, therefore, * _is_network_active will be set to false even if it's a network level * activation. So we need to fix that by looking at the is_network_admin() value. * * @author Vova Feldman */ $this->_is_network_active = ( $this->_is_multisite_integrated && fs_is_network_admin() ); } /** * If the other module version is active, deactivate it. * * is_plugin_active() checks if the plugin is active on the site or the network level and * deactivate_plugins() deactivates the plugin whether it's activated on the site or network level. * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ if ( is_plugin_active( $other_version_basename ) && $this->apply_filters( 'deactivate_on_activation', true ) ) { deactivate_plugins( $other_version_basename ); } } if ( $this->is_registered() ) { if ( $is_premium_version_activation ) { $this->reconnect_locally(); } // Schedule re-activation event and sync. // $this->sync_install( array(), true ); $this->schedule_install_sync(); // If activating the premium module version, add an admin notice to congratulate for an upgrade completion. if ( $is_premium_version_activation ) { $this->_admin_notices->add( sprintf( $this->get_text_inline( 'The upgrade of %s was successfully completed.', 'successful-version-upgrade-message' ), sprintf( '<b>%s</b>', $this->_plugin->title ) ), $this->get_text_x_inline( 'W00t', 'Used to express elation, enthusiasm, or triumph (especially in electronic communication).', 'woot' ) . '!' ); } } else if ( $this->is_anonymous() ) { if ( isset( $this->_storage->is_anonymous_ms ) && $this->_storage->is_anonymous_ms['is'] ) { $plugin_version = $this->_storage->is_anonymous_ms['version']; $network = true; } else { $plugin_version = isset( $this->_storage->is_anonymous ) ? $this->_storage->is_anonymous['version'] : null; $network = false; } /** * Reset "skipped" click cache on the following: * 1. Freemius DEV mode. * 2. WordPress DEBUG mode. * 3. If a plugin and the user skipped the exact same version before. * * @since 1.2.2.7 Ulrich Pogson (@grapplerulrich) asked to not reset the SKIPPED flag if the exact same THEME version was activated before unless the developer is running with WP_DEBUG on, or Freemius debug mode on (WP_FS__DEV_MODE). * * @todo 4. If explicitly asked to retry after every activation. */ if ( WP_FS__DEV_MODE || ( ( $this->is_plugin() || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) && $this->get_plugin_version() == $plugin_version ) ) { $this->reset_anonymous_mode( $network ); } } $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() ); if ( $this->is_addon() && ! $is_trial_or_has_features_enabled_license ) { /** * When activating an add-on, try to also activate a license. * * @author Leo Fajardo (@leorw) * @since 2.3.0 */ if ( ! $this->_is_network_active ) { $this->maybe_activate_addon_license(); } else { $this->maybe_network_activate_addon_license(); } /** * Avoid redirecting to the license activation screen after automatically activating an add-on license. * * @author Leo Fajardo (@leorw) * @since 2.3.0 */ $is_trial_or_has_features_enabled_license = ( $this->is_trial() || $this->has_features_enabled_license() ); if ( $is_trial_or_has_features_enabled_license && true === $this->_storage->require_license_activation ) { $this->_storage->require_license_activation = false; } } if ( $is_premium_version_activation && ( ( ! $this->is_registered() && $this->is_anonymous() ) || ( $this->is_registered() && ! $is_trial_or_has_features_enabled_license ) ) ) { $this->_storage->require_license_activation = true; } if ( ! isset( $this->_storage->is_plugin_new_install ) ) { /** * If no previous version of plugin's version exist, it means that it's either * the first time that the plugin installed on the site, or the plugin was installed * before but didn't have Freemius integrated. * * Since register_activation_hook() do NOT fires on updates since 3.1, and only fires * on manual activation via the dashboard, is_plugin_activation() is TRUE * only after immediate activation. * * @since 1.1.4 * @link https://make.wordpress.org/core/2010/10/27/plugin-activation-hooks-no-longer-fire-for-updates/ */ $this->_storage->is_plugin_new_install = empty( $this->_storage->plugin_last_version ); } /** * Also flush when activating the premium version so that even if Freemius was off before, the API * connectivity test can be run again. * * @author Leo Fajardo (@leorw) * @since 2.2.3.1 */ $has_api_connectivity = $this->has_api_connectivity( WP_FS__DEV_MODE || $is_premium_version_activation ); if ( ! $this->_anonymous_mode && ( false !== $has_api_connectivity ) && ! $this->_isAutoInstall ) { // Store hint that the plugin was just activated to enable auto-redirection to settings. set_transient( "fs_{$this->_module_type}_{$this->_slug}_activated", true, 60 ); } /** * Activation hook is executed after the plugin's main file is loaded, therefore, * after the plugin was loaded. The logic is located at activate_plugin() * ./wp-admin/includes/plugin.php. * * @author Vova Feldman (@svovaf) * @since 1.1.9 */ $this->_storage->was_plugin_loaded = true; } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 */ private function maybe_activate_addon_license() { $parent_fs = $this->get_parent_instance(); if ( ! is_object( $parent_fs ) || ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() ) ) { // Try to activate a license only if the parent plugin is active and has a valid `install`. return; } $license = $this->get_active_parent_license(); if ( ! is_object( $license ) ) { return; } if ( $this->is_bundle_license_auto_activation_enabled() && ! empty( $license->products ) ) { $this->activate_bundle_license( $license ); return; } if ( ! $this->is_registered() ) { // Opt in with a license key. $this->opt_in( $parent_fs->get_current_or_network_user()->email, false, false, $license->secret_key ); } else { // Activate the license. $install = $this->api_site_call( '/', 'put', array( 'license_key' => $this->apply_filters( 'license_key', $license->secret_key ) ) ); if ( ! FS_Api::is_api_error( $install ) ) { $this->_sync_addon_license( $this->get_id(), true ); } } } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 * * @param FS_Plugin_License $license */ private function maybe_network_activate_addon_license( $license = null ) { $parent_fs = $this->get_parent_instance(); if ( ! is_object( $parent_fs ) || ( ! $parent_fs->is_registered() && ! $parent_fs->is_network_registered() ) ) { // Try to activate a license only if the parent plugin is active and has a valid `install`. return; } $license = ( ! is_null( $license ) ) ? $license : $this->get_active_parent_license(); if ( ! is_object( $license ) ) { return; } if ( $this->is_bundle_license_auto_activation_enabled() && ! empty( $license->products ) ) { $this->activate_bundle_license( $license ); return; } if ( ! $this->is_network_registered() ) { $sites = $this->get_sites_for_network_level_optin(); if ( count( $sites ) > $license->left() ) { // If the add-on is network active, try to activate the license only if it can be activated on all sites. return; } // Opt in with a license key. $this->opt_in( $parent_fs->get_user()->email, false, false, $license->secret_key, false, false, false, null, $sites ); } else { $blog_2_install_map = array(); $site_ids = array(); $all_sites = Freemius::get_sites(); foreach ( $all_sites as $site ) { $blog_id = Freemius::get_site_blog_id( $site ); $install = $this->get_install_by_blog_id( $blog_id ); if ( is_object( $install ) && FS_Plugin_License::is_valid_id( $install->license_id ) ) { // Skip license activation for installs that are already associated with a license. continue; } if ( is_object( $install ) ) { $blog_2_install_map[ $blog_id ] = $install; } else { $site_ids[] = $blog_id; } } if ( ( count( $blog_2_install_map ) + count( $site_ids ) ) > $license->left() ) { return; } $user = $this->get_current_or_network_user(); if ( ! empty( $blog_2_install_map ) ) { $result = $this->activate_license_on_many_installs( $user, $license->secret_key, $blog_2_install_map ); if ( true !== $result ) { return; } } if ( ! empty( $site_ids ) ) { $this->activate_license_on_many_sites( $user, $license->secret_key, $site_ids ); } } } /** * Tries to activate a bundle license for all supported products if the current product is activated with a bundle license. This is called after activating an available license (not via the license activation dialog but by clicking on a license activation button) for a product via its "Account" page. * * @author Leo Fajardo (@leorw) * @since 2.4.0 * * @param FS_Plugin_License $license * @param array $sites * @param int $blog_id */ private function maybe_activate_bundle_license( FS_Plugin_License $license = null, $sites = array(), $blog_id = 0 ) { if ( ! is_object( $license ) && $this->has_active_valid_license() ) { $license = $this->_license; } if ( ! is_object( $license ) ) { return; } $parent_license = ( ! empty( $license->products ) ) ? $license : $this->get_active_parent_license( $license->secret_key ); if ( is_object( $parent_license ) ) { $this->activate_bundle_license( $parent_license, $sites, $blog_id ); } } /** * Try to activate a bundle license for all the bundle products installed on the site. * (1) If a child product install already has a license, the bundle license won't be activated. * (2) On multi-site networks, if the attempt to activate the bundle license is triggered from the network admin, the bundle license activation will only work for non-delegated sites and only if none of them is associated with a license. Even if one of the sites has the product installed with a license key, skip the bundle license activation for the product. * (3) On multi-site networks, if the attempt to activate the bundle license is triggered from a site-level admin, only activate the license if the product is site-level activated or delegated, and the product installation is not yet associated with a license. * * @author Leo Fajardo (@leorw) * @since 2.4.0 * * @param FS_Plugin_License $license * @param array $sites * @param int $current_blog_id */ private function activate_bundle_license( $license, $sites = array(), $current_blog_id = 0 ) { $is_network_admin = fs_is_network_admin(); $installs_by_blog_map = array(); $site_info_by_blog_map = array(); /** * Try to activate the license for all supported products. * * @author Leo Fajardo */ foreach ( $license->products as $product_id ) { $fs = self::get_instance_by_id( $product_id ); if ( ! is_object( $fs ) ) { continue; } if ( ! $fs->has_paid_plan() ) { continue; } if ( ! $fs->is_addon() && ! FS_Plan_Manager::instance()->has_paid_plan( $fs->_plans ) ) { /** * The parent product can be free-only but can have its `has_paid_plan` flag set to `true` when * there is a context bundle. */ continue; } if ( $current_blog_id > 0 ) { $fs->switch_to_blog( $current_blog_id ); } if ( $fs->has_active_valid_license() ) { continue; } if ( ! $is_network_admin || $current_blog_id > 0 ) { if ( $fs->is_network_active() && ! $fs->is_delegated_connection( $current_blog_id ) ) { // Do not try to activate the license in the site level if the product is network active and the connection was not delegated. continue; } } else { if ( ! $fs->is_network_active() ) { // Do not try to activate the license in the network level if the product is not network active. continue; } if ( $fs->is_network_delegated_connection() ) { // Do not try to activate the license in the network level if the activation has been delegated to site admins. continue; } $has_install_with_license = false; // Collection of sites that have an install entity that is not activated with a license or non-delegated sites that have no install entity, or both types of site. $filtered_sites = array(); if ( empty( $sites ) ) { $all_sites = self::get_sites(); foreach ( $all_sites as $site ) { $sites[] = array( 'blog_id' => self::get_site_blog_id( $site ) ); } } else { // Populate the map here to avoid calling `$fs->get_site_info( $site );` in the other `for` loop below. foreach ( $sites as $site ) { if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) { continue; } $site_info_by_blog_map[ $site['blog_id'] ] = $site; } } foreach ( $sites as $site ) { if ( ! isset( $site['blog_id'] ) || ! is_numeric( $site['blog_id'] ) ) { continue; } $blog_id = $site['blog_id']; if ( ! isset( $installs_by_blog_map[ $blog_id ] ) ) { $installs_by_blog_map[ $blog_id ] = self::get_all_sites( $fs->get_module_type(), $blog_id ); } $installs = $installs_by_blog_map[ $blog_id ]; $install = null; if ( isset( $installs[ $fs->get_slug() ] ) ) { $install = $installs[ $fs->get_slug() ]; if ( is_object( $install ) && ( ! FS_Site::is_valid_id( $install->id ) || ! FS_User::is_valid_id( $install->user_id ) || ! FS_Plugin_Plan::is_valid_id( $install->plan_id ) ) ) { $install = null; } } if ( is_object( $install ) && FS_Plugin_License::is_valid_id( $install->license_id ) ) { $has_install_with_license = true; break; } if ( $fs->is_site_delegated_connection( $blog_id ) ) { // Site activation delegated, don't activate bundle license on the site in the network admin. continue; } if ( ! isset( $site_info_by_blog_map[ $blog_id ] ) ) { $site_info_by_blog_map[ $blog_id ] = $fs->get_site_info( $site ); } $filtered_sites[] = $site_info_by_blog_map[ $blog_id ]; } if ( $has_install_with_license || empty( $filtered_sites ) ) { // Do not try to activate the license at the network level if there's any install with a license or there's no site to activate the license on. continue; } $sites = $filtered_sites; } $fs->activate_migrated_license( $license->secret_key, null, null, $sites, ( $current_blog_id > 0 ? $current_blog_id : null ) ); } } /** * Returns a parent license that can be activated for the context product. * * @author Leo Fajardo (@leorw) * @since 2.3.0 * * @param string|null $license_key * @param bool $flush * * @return FS_Plugin_License */ function get_active_parent_license( $license_key = null, $flush = true ) { $parent_licenses_endpoint = "/plugins/{$this->get_id()}/parent_licenses.json?filter=activatable"; $fs = $this; if ( $this->is_addon() ) { $parent_instance = $this->get_parent_instance(); if ( is_object( $parent_instance ) && $parent_instance->is_registered() ) { $fs = $parent_instance; } } $foreign_licenses = $fs->get_foreign_licenses_info( self::get_all_licenses( $this->get_parent_id() ) ); if ( ! empty ( $foreign_licenses ) ) { $foreign_licenses = array( // Prefix with `+` to tell the server to include foreign licenses in the licenses collection. 'ids' => ( urlencode( '+' ) . implode( ',', $foreign_licenses['ids'] ) ), 'license_keys' => implode( ',', array_map( 'urlencode', $foreign_licenses['license_keys'] ) ) ); $parent_licenses_endpoint = add_query_arg( $foreign_licenses, $parent_licenses_endpoint ); } $result = $fs->get_current_or_network_user_api_scope()->get( $parent_licenses_endpoint, $flush ); if ( ! $this->is_api_result_object( $result, 'licenses' ) || ! is_array( $result->licenses ) || empty( $result->licenses ) ) { return null; } $parent_license = null; if ( empty( $license_key ) ) { $parent_license = $result->licenses[0]; } else { foreach ( $result->licenses as $license ) { if ( $license_key === $license->secret_key ) { $parent_license = $license; break; } } } if ( ! is_null( $parent_license ) ) { $parent_license = new FS_Plugin_License( $parent_license ); } return $parent_license; } /** * @author Leo Fajardo (@leorw) * @since 2.3.0 * * @return array */ function get_sites_for_network_level_optin() { $sites = array(); $all_sites = self::get_sites(); foreach ( $all_sites as $site ) { $blog_id = self::get_site_blog_id( $site ); if ( ! $this->is_site_delegated_connection( $blog_id ) && ! $this->is_installed_on_site( $blog_id ) ) { $sites[] = $this->get_site_info( $site ); } } return $sites; } /** * Delete account. * * @author Vova Feldman (@svovaf) * @since 1.0.3 * * @param bool $check_user Enforce checking if user have plugins activation privileges. */ function delete_account_event( $check_user = true ) { $this->_logger->entrance( 'slug = ' . $this->_slug ); if ( $check_user && ! $this->is_user_admin() ) { return; } $this->do_action( 'before_account_delete' ); // Clear all admin notices. $this->_admin_notices->clear_all_sticky( false ); $this->_delete_site( false ); $delete_network_common_data = true; if ( $this->_is_network_active ) { $installs = $this->get_blog_install_map(); // Don't delete common network data unless no other installs left. $delete_network_common_data = empty( $installs ); } if ( $delete_network_common_data ) { $this->_delete_plans( false ); $this->_delete_licenses( false ); // Delete add-ons related to plugin's account. $this->_delete_account_addons( false ); } // @todo Delete plans and licenses of add-ons. self::$_accounts->store(); /** * IMPORTANT: * Clear crons must be executed before clearing all storage. * Otherwise, the cron will not be cleared. */ if ( $delete_network_common_data ) { $this->clear_sync_cron(); } $this->clear_install_sync_cron(); // Clear all storage data. $this->_storage->clear_all( true, array( 'is_delegated_connection', 'connectivity_test', 'is_on', ), false ); // Send delete event. $this->get_api_site_scope()->call( '/', 'delete' ); $this->do_action( 'after_account_delete' ); } /** * Delete network level account. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param bool $check_user Enforce checking if user have plugins activation privileges. */ function delete_network_account_event( $check_user = true ) { $this->_logger->entrance( 'slug = ' . $this->_slug ); if ( $check_user && ! $this->is_user_admin() ) { return; } $this->do_action( 'before_network_account_delete' ); // Clear all admin notices. $this->_admin_notices->clear_all_sticky(); $this->_delete_plans( false, false ); $this->_delete_licenses( false ); // Delete add-ons related to plugin's account. $this->_delete_account_addons( false ); // @todo Delete plans and licenses of add-ons. self::$_accounts->store( true ); /** * IMPORTANT: * Clear crons must be executed before clearing all storage. * Otherwise, the cron will not be cleared. */ $this->clear_sync_cron( true ); $this->clear_install_sync_cron( true ); $sites = self::get_sites(); $install_ids = array(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); if ( $this->is_site_delegated_connection( $blog_id ) ) { continue; } $install_id = $this->_delete_site( true, $blog_id ); // Clear all storage data. $this->_storage->clear_all( true, array( 'connectivity_test' ), $blog_id ); if ( FS_Site::is_valid_id( $install_id ) ) { $install_ids[] = $install_id; } switch_to_blog( $blog_id ); $this->do_action( 'after_account_delete' ); restore_current_blog(); } $this->_storage->clear_all( true, array( 'connectivity_test', 'is_on', ), true ); // Send delete event. if ( ! empty( $install_ids ) ) { $result = $this->get_current_or_network_user_api_scope()->call( "/plugins/{$this->_module_id}/installs.json?ids=" . implode( ',', $install_ids ), 'delete' ); } $this->do_action( 'after_network_account_delete' ); } /** * Plugin deactivation hook. * * @author Vova Feldman (@svovaf) * @since 1.0.1 */ function _deactivate_plugin_hook() { $this->_logger->entrance( 'slug = ' . $this->_slug ); if ( ! $this->is_user_admin() ) { return; } $is_network_deactivation = fs_is_network_admin(); $storage_keys_for_removal = array(); $this->_admin_notices->clear_all_sticky(); $storage_keys_for_removal[] = 'sticky_optin_added'; if ( isset( $this->_storage->sticky_optin_added ) ) { unset( $this->_storage->sticky_optin_added ); } if ( ! isset( $this->_storage->is_plugin_new_install ) ) { // Remember that plugin was already installed. $this->_storage->is_plugin_new_install = false; } // Hook to plugin uninstall. register_uninstall_hook( $this->_plugin_main_file_path, array( 'Freemius', '_uninstall_plugin_hook' ) ); $this->clear_module_main_file_cache(); $this->clear_sync_cron( $this->_is_network_active ); $this->clear_install_sync_cron(); if ( $this->is_registered() ) { if ( $this->is_premium() && ! $this->has_active_valid_license() ) { FS_Plugin_Updater::instance( $this )->delete_update_data(); } if ( $is_network_deactivation ) { // Send deactivation event. $this->sync_installs( array( 'is_active' => false, ) ); } else { // Send deactivation event. $this->sync_install( array( 'is_active' => false, ) ); } } else { if ( false === $this->has_api_connectivity() && ! $this->is_premium() ) { // Reset connectivity test cache. $this->clear_connectivity_info(); $storage_keys_for_removal[] = 'connectivity_test'; } } if ( $is_network_deactivation ) { if ( isset( $this->_storage->sticky_optin_added_ms ) ) { unset( $this->_storage->sticky_optin_added_ms ); } if ( ! empty( $storage_keys_for_removal ) ) { $sites = self::get_sites(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); foreach ( $storage_keys_for_removal as $key ) { $this->_storage->remove( $key, false, $blog_id ); } $this->_storage->save( $blog_id ); } } } // Clear API cache on deactivation. FS_Api::clear_cache(); $this->remove_sdk_reference(); } /** * @author Vova Feldman (@svovaf) * @since 1.1.6 */ private function remove_sdk_reference() { global $fs_active_plugins; foreach ( $fs_active_plugins->plugins as $sdk_path => $data ) { if ( $this->_plugin_basename == $data->plugin_path ) { unset( $fs_active_plugins->plugins[ $sdk_path ] ); break; } } fs_fallback_to_newest_active_sdk(); } /** * @author Vova Feldman (@svovaf) * @since 1.1.3 * * @param bool $is_anonymous * @param bool|int $network_or_blog_id Since 2.0.0 */ private function set_anonymous_mode( $is_anonymous = true, $network_or_blog_id = 0 ) { // Store information regarding skip to try and opt-in the user // again in the future. $skip_info = array( 'is' => $is_anonymous, 'timestamp' => WP_FS__SCRIPT_START_TIME, 'version' => $this->get_plugin_version(), ); if ( true === $network_or_blog_id ) { $this->_storage->is_anonymous_ms = $skip_info; } else { $this->_storage->store( 'is_anonymous', $skip_info, $network_or_blog_id ); } $this->network_upgrade_mode_completed(); // Update anonymous mode cache. $this->_is_anonymous = $is_anonymous; } /** * @author Vova Feldman (@svovaf) * @since 2.5.1 * * @param bool|int $network_or_blog_id */ private function unset_anonymous_mode( $network_or_blog_id = 0 ) { if ( true === $network_or_blog_id ) { unset( $this->_storage->is_anonymous_ms ); } else { $this->_storage->remove( 'is_anonymous', true, $network_or_blog_id ); } } /** * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int $blog_id Site ID. * @param int $user_id User ID. * @param string $domain Site domain. * @param string $path Site path. * @param int $network_id Network ID. Only relevant on multi-network installations. * @param array $meta Metadata. Used to set initial site options. * * @uses Freemius::is_license_network_active() to check if the context license was network activated by the super-admin. * @uses Freemius::is_network_connected() to check if the super-admin network opted-in. * @uses Freemius::is_network_anonymous() to check if the super-admin network skipped. * @uses Freemius::is_network_delegated_connection() to check if the super-admin network delegated the connection to the site admins. */ public function _after_new_blog_callback( $blog_id, $user_id, $domain, $path, $network_id, $meta ) { $this->_logger->entrance(); if ( ! $this->_is_network_active ) { FS_Clone_Manager::instance()->store_blog_install_info( $blog_id ); return; } $site = null; $new_blog_id = $blog_id; if ( $this->is_premium() && $this->is_network_connected() && is_object( $this->_license ) && $this->_license->can_activate( FS_Site::is_localhost_by_address( $domain ) ) && $this->is_license_network_active( $blog_id ) ) { /** * Running the premium version, the license was network activated, and the license can also be activated on the current site -> so try to opt-in with the license key. */ $current_blog_id = get_current_blog_id(); $license = clone $this->_license; $this->switch_to_blog( $blog_id ); // Opt-in with network user. $this->install_with_user( $this->get_network_user(), $license->secret_key, false, false, false ); if ( is_object( $this->_site ) ) { if ( $this->_site->license_id == $license->id ) { /** * If the license was activated successfully, sync the license data from the remote server. */ $this->_license = $license; $this->sync_site_license(); } } $site = $this->_site; $this->switch_to_blog( $current_blog_id ); if ( is_object( $site ) ) { FS_Clone_Manager::instance()->store_blog_install_info( $blog_id, $site ); // Already connected (with or without a license), so no need to continue. return; } } if ( $this->is_network_anonymous() ) { /** * Opt-in was network skipped so automatically skip the opt-in for the new site. */ $this->skip_site_connection( $blog_id ); } else if ( $this->is_network_delegated_connection() ) { /** * Opt-in was network delegated so automatically delegate the opt-in for the new site's admin. */ $this->delegate_site_connection( $blog_id ); } else if ( $this->is_network_connected() ) { /** * Opt-in was network activated so automatically opt-in with the network user and new site admin. */ $current_blog_id = get_current_blog_id(); $this->switch_to_blog( $blog_id ); // Opt-in with network user. $this->install_with_user( $this->get_network_user(), false, false, false, false ); $site = $this->_site; $this->switch_to_blog( $current_blog_id ); } else { /** * If the super-admin mixed different options (connect, skip, delegated): * a) If at least one site connection was delegated, then automatically delegate connection. * b) Otherwise, it means that at least one site was skipped and at least one site was connected. For a simplified UX in the initial release of the multisite network integration, skip the connection for the newly created site. If the super-admin will want to opt-in they can still do that from the network level Account page. */ $has_delegated_site = false; $sites = self::get_sites(); foreach ( $sites as $wp_site ) { $blog_id = self::get_site_blog_id( $wp_site ); if ( $this->is_site_delegated_connection( $blog_id ) ) { $has_delegated_site = true; break; } } if ( $has_delegated_site ) { $this->delegate_site_connection( $blog_id ); } else { $this->skip_site_connection( $blog_id ); } } /** * Store the new blog's information even if there's no install so that when a clone install is stored in the new blog's storage, we can try to resolve it automatically. * * @author Leo Fajardo (@leorw) * @since 2.5.0 */ FS_Clone_Manager::instance()->store_blog_install_info( $new_blog_id, $site ); } /** * @author Vova Feldman (@svovaf) * @since 2.5.0 * * @param \WP_Site $new_site * @param array $args */ public function _after_wp_initialize_site_callback( WP_Site $new_site, $args ) { $this->_logger->entrance(); $this->_after_new_blog_callback( $new_site->id, // Dummy user ID (not in use). 0, $new_site->domain, $new_site->path, $new_site->network_id, // Dummy meta, not in use. array() ); } /** * @author Vova Feldman (@svovaf) * @since 1.1.3 * * @param bool|int|int[] $network_or_blog_ids Since 2.0.0. */ private function reset_anonymous_mode( $network_or_blog_ids = false ) { if ( true === $network_or_blog_ids ) { $this->unset_anonymous_mode( true ); if ( fs_is_network_admin() ) { $this->_is_anonymous = null; } // Rest anonymous mode for all non-delegated sub-sites. $blog_ids = $this->get_non_delegated_blog_ids(); } else { if ( false === $network_or_blog_ids ) { $network_or_blog_ids = 0; } $blog_ids = is_array( $network_or_blog_ids ) ? $network_or_blog_ids : array( $network_or_blog_ids ); foreach ( $blog_ids as $blog_id ) { if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) { $this->_is_anonymous = null; } } } foreach ( $blog_ids as $blog_id ) { $this->unset_anonymous_mode( $blog_id ); } /** * Ensure that this field is also "false", otherwise, if the current module's type is "theme" and the module * has no menus, the opt-in popup will not be shown immediately (in this case, the user will have to click * on the admin notice that contains the opt-in link in order to trigger the opt-in popup). * * @author Leo Fajardo (@leorw) * @since 1.2.2 */ if ( ! $this->_is_network_active ) { $this->_is_anonymous = null; } } /** * @author Leo Fajardo (@leorw) * @since 2.5.3 */ private function update_license_required_permissions_if_anonymous() { if ( ! $this->is_anonymous() ) { return; } $this->reset_anonymous_mode( fs_is_network_admin() ); FS_Permission_Manager::instance( $this )->update_permissions_tracking_flag( array( 'essentials' => true, 'events' => true, 'diagnostic' => false, 'extensions' => false, 'site' => false, ) ); } /** * This is used to ensure that before redirecting to the opt-in page after resetting the anonymous mode or * deleting the account in the network level, the URL of the page to redirect to is correct. * * @author Leo Fajardo (@leorw) * * @since 2.1.3 */ private function maybe_set_slug_and_network_menu_exists_flag() { if ( ! empty( $this->_dynamically_added_top_level_page_hook_name ) ) { $this->_menu->set_slug_and_network_menu_exists_flag( $this->_menu->has_menu() ? $this->_menu->get_slug() : $this->_slug ); } } /** * Clears the anonymous mode and redirects to the opt-in screen. * * @author Vova Feldman (@svovaf) * @since 1.1.7 */ function connect_again() { if ( ! $this->is_anonymous() && ! $this->is_pending_activation() ) { return; } if ( $this->is_anonymous() ) { $this->reset_anonymous_mode( fs_is_network_admin() ); } $activation_url_params = array(); if ( $this->is_pending_activation() ) { $this->clear_pending_activation_mode(); if ( fs_request_get_bool( 'require_license' ) ) { $activation_url_params['require_license'] = true; } } $this->maybe_set_slug_and_network_menu_exists_flag(); fs_redirect( $this->get_activation_url( $activation_url_params ) ); } /** * Skip account connect, and set anonymous mode. * * @author Vova Feldman (@svovaf) * @since 1.1.1 * * @param bool|int|int[] $network_or_blog_ids Since 2.5.1 */ function skip_connection( $network_or_blog_ids = false ) { $this->_logger->entrance(); $this->_admin_notices->remove_sticky( 'connect_account' ); if ( true === $network_or_blog_ids ) { $this->set_anonymous_mode( true, true ); if ( fs_is_network_admin() ) { $this->_is_anonymous = null; } // Rest anonymous mode for all non-delegated sub-sites. $blog_ids = $this->get_non_delegated_blog_ids(); } else { if ( false === $network_or_blog_ids ) { $network_or_blog_ids = 0; } $blog_ids = is_array( $network_or_blog_ids ) ? $network_or_blog_ids : array( $network_or_blog_ids ); foreach ( $blog_ids as $blog_id ) { if ( 0 === $blog_id || get_current_blog_id() == $blog_id ) { $this->_is_anonymous = null; } } } foreach ( $blog_ids as $blog_id ) { $this->skip_site_connection( $blog_id ); } $this->network_upgrade_mode_completed(); } /** * Skip connection for specific site in the network. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param int|null $blog_id * @param bool $send_skip */ private function skip_site_connection( $blog_id = null ) { $this->_logger->entrance(); $this->_admin_notices->remove_sticky( 'connect_account', $blog_id ); $this->set_anonymous_mode( true, $blog_id ); } /** * Plugin version update hook. * * @author Vova Feldman (@svovaf) * @since 1.0.4 */ private function update_plugin_version_event() { $this->_logger->entrance(); if ( ! $this->is_registered() ) { return; } $this->schedule_install_sync(); // $this->sync_install( array(), true ); } /** * Generate an MD5 signature of a plugins collection. * This helper methods used to identify changes in a plugins collection. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param array [string]array $plugins * * @return string */ private function get_plugins_thumbprint( $plugins ) { ksort( $plugins ); $thumbprint = ''; foreach ( $plugins as $basename => $data ) { $thumbprint .= $data['slug'] . ',' . $data['Version'] . ',' . ( $data['is_active'] ? '1' : '0' ) . ';'; } return md5( $thumbprint ); } /** * Return a list of modified plugins since the last sync. * * Note: * There's no point to store a plugins counter since even if the number of * plugins didn't change, we still need to check if the versions are all the * same and the activity state is similar. * * @author Vova Feldman (@svovaf) * @since 1.1.8 * * @return array|false */ private function get_plugins_data_for_api() { // Alias. $site_active_plugins_option_name = 'active_plugins'; $network_plugins_option_name = 'all_plugins'; /** * Collection of all site level active plugins. */ $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name ); if ( ! is_object( $site_active_plugins_cache ) ) { $site_active_plugins_cache = (object) array( 'timestamp' => '', 'md5' => '', 'plugins' => array(), ); } $time = time(); if ( ! empty( $site_active_plugins_cache->timestamp ) && ( $time - $site_active_plugins_cache->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC ) { // Don't send plugin updates if last update was in the past 5 min. return false; } // Write timestamp to lock the logic. $site_active_plugins_cache->timestamp = $time; self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true ); // Reload options from DB. self::$_accounts->load( true ); $site_active_plugins_cache = self::$_accounts->get_option( $site_active_plugins_option_name ); if ( $time != $site_active_plugins_cache->timestamp ) { // If timestamp is different, then another thread captured the lock. return false; } /** * Collection of all plugins (network level). */ $network_plugins_cache = self::$_accounts->get_option( $network_plugins_option_name ); if ( ! is_object( $network_plugins_cache ) ) { $network_plugins_cache = (object) array( 'timestamp' => '', 'md5' => '', 'plugins' => array(), ); } // Check if there's a change in plugins. $network_plugins = self::get_network_plugins(); $site_active_plugins = self::get_site_active_plugins(); $network_plugins_thumbprint = $this->get_plugins_thumbprint( $network_plugins ); $site_active_plugins_thumbprint = $this->get_plugins_thumbprint( $site_active_plugins ); // Check if plugins status changed (version or active/inactive). $network_plugins_changed = ( $network_plugins_cache->md5 !== $network_plugins_thumbprint ); $site_active_plugins_changed = ( $site_active_plugins_cache->md5 !== $site_active_plugins_thumbprint ); if ( ! $network_plugins_changed && ! $site_active_plugins_changed ) { // No changes. return array(); } $plugins_update_data = array(); foreach ( $network_plugins_cache->plugins as $basename => $data ) { if ( ! isset( $network_plugins[ $basename ] ) ) { // Plugin uninstalled. $uninstalled_plugin_data = $data; $uninstalled_plugin_data['is_active'] = false; $uninstalled_plugin_data['is_uninstalled'] = true; $plugins_update_data[] = $uninstalled_plugin_data; unset( $network_plugins[ $basename ] ); unset( $network_plugins_cache->plugins[ $basename ] ); unset( $site_active_plugins_cache->plugins[ $basename ] ); continue; } $was_active = $data['is_active'] || ( isset( $site_active_plugins_cache->plugins[ $basename ] ) && true === $site_active_plugins_cache->plugins[ $basename ]['is_active'] ); $is_active = $network_plugins[ $basename ]['is_active'] || ( isset( $site_active_plugins[ $basename ] ) && $site_active_plugins[ $basename ]['is_active'] ); if ( ! isset( $site_active_plugins_cache->plugins[ $basename ] ) && isset( $site_active_plugins[ $basename ] ) ) { // Plugin was site level activated. $site_active_plugins_cache->plugins[ $basename ] = $network_plugins[ $basename ]; $site_active_plugins_cache->plugins[ $basename ]['is_active'] = true; } else if ( isset( $site_active_plugins_cache->plugins[ $basename ] ) && ! isset( $site_active_plugins[ $basename ] ) ) { // Plugin was site level deactivated. unset( $site_active_plugins_cache->plugins[ $basename ] ); } $prev_version = $data['version']; $current_version = $network_plugins[ $basename ]['Version']; if ( $was_active !== $is_active || $prev_version !== $current_version ) { // Plugin activated or deactivated, or version changed. if ( $was_active !== $is_active ) { if ( $data['is_active'] != $network_plugins[ $basename ]['is_active'] ) { $network_plugins_cache->plugins[ $basename ]['is_active'] = $data['is_active']; } } if ( $prev_version !== $current_version ) { $network_plugins_cache->plugins[ $basename ]['Version'] = $current_version; } $updated_plugin_data = $data; $updated_plugin_data['is_active'] = $is_active; $updated_plugin_data['version'] = $current_version; $updated_plugin_data['title'] = $network_plugins[ $basename ]['Name']; $plugins_update_data[] = $updated_plugin_data; } } // Find new plugins that weren't yet seen before. foreach ( $network_plugins as $basename => $data ) { if ( ! isset( $network_plugins_cache->plugins[ $basename ] ) ) { // New plugin. $new_plugin = array( 'slug' => $data['slug'], 'version' => $data['Version'], 'title' => $data['Name'], 'is_active' => $data['is_active'], 'is_uninstalled' => false, ); $network_plugins_cache->plugins[ $basename ] = $new_plugin; $is_site_level_active = ( isset( $site_active_plugins[ $basename ] ) && $site_active_plugins[ $basename ]['is_active'] ); /** * If not network active, set the activity status based on the site-level plugin status. */ if ( ! $new_plugin['is_active'] ) { $new_plugin['is_active'] = $is_site_level_active; } $plugins_update_data[] = $new_plugin; if ( isset( $site_active_plugins[ $basename ] ) ) { $site_active_plugins_cache->plugins[ $basename ] = $new_plugin; $site_active_plugins_cache->plugins[ $basename ]['is_active'] = $is_site_level_active; } } } $site_active_plugins_cache->md5 = $site_active_plugins_thumbprint; $site_active_plugins_cache->timestamp = $time; self::$_accounts->set_option( $site_active_plugins_option_name, $site_active_plugins_cache, true ); $network_plugins_cache->md5 = $network_plugins_thumbprint; $network_plugins_cache->timestamp = $time; self::$_accounts->set_option( $network_plugins_option_name, $network_plugins_cache, true ); return $plugins_update_data; } /** * Return a list of modified themes since the last sync. * * Note: * There's no point to store a themes counter since even if the number of * themes didn't change, we still need to check if the versions are all the * same and the activity state is similar. * * @author Vova Feldman (@svovaf) * @since 1.1.8 * * @return array|false */ private function get_themes_data_for_api() { // Alias. $option_name = 'all_themes'; $all_cached_themes = self::$_accounts->get_option( $option_name ); if ( ! is_object( $all_cached_themes ) ) { $all_cached_themes = (object) array( 'timestamp' => '', 'md5' => '', 'themes' => array(), ); } $time = time(); if ( ! empty( $all_cached_themes->timestamp ) && ( $time - $all_cached_themes->timestamp ) < WP_FS__TIME_5_MIN_IN_SEC ) { // Don't send theme updates if last update was in the past 5 min. return false; } // Write timestamp to lock the logic. $all_cached_themes->timestamp = $time; self::$_accounts->set_option( $option_name, $all_cached_themes, true ); // Reload options from DB. self::$_accounts->load( true ); $all_cached_themes = self::$_accounts->get_option( $option_name ); if ( $time != $all_cached_themes->timestamp ) { // If timestamp is different, then another thread captured the lock. return false; } // Get active theme. $active_theme = wp_get_theme(); $active_theme_stylesheet = $active_theme->get_stylesheet(); // Check if there's a change in themes. $all_themes = wp_get_themes(); // Check if themes changed. ksort( $all_themes ); $themes_signature = ''; foreach ( $all_themes as $slug => $data ) { $is_active = ( $slug === $active_theme_stylesheet ); $themes_signature .= $slug . ',' . $data->version . ',' . ( $is_active ? '1' : '0' ) . ';'; } // Check if themes status changed (version or active/inactive). $themes_changed = ( $all_cached_themes->md5 !== md5( $themes_signature ) ); $themes_update_data = array(); if ( $themes_changed ) { // Change in themes, report changes. // Update existing themes info. foreach ( $all_cached_themes->themes as $slug => $data ) { $is_active = ( $slug === $active_theme_stylesheet ); if ( ! isset( $all_themes[ $slug ] ) ) { // Plugin uninstalled. $uninstalled_theme_data = $data; $uninstalled_theme_data['is_active'] = false; $uninstalled_theme_data['is_uninstalled'] = true; $themes_update_data[] = $uninstalled_theme_data; unset( $all_themes[ $slug ] ); unset( $all_cached_themes->themes[ $slug ] ); } else if ( $data['is_active'] !== $is_active || $data['version'] !== $all_themes[ $slug ]->version ) { // Plugin activated or deactivated, or version changed. $all_cached_themes->themes[ $slug ]['is_active'] = $is_active; $all_cached_themes->themes[ $slug ]['version'] = $all_themes[ $slug ]->version; $themes_update_data[] = $all_cached_themes->themes[ $slug ]; } } // Find new themes that weren't yet seen before. foreach ( $all_themes as $slug => $data ) { if ( ! isset( $all_cached_themes->themes[ $slug ] ) ) { $is_active = ( $slug === $active_theme_stylesheet ); // New plugin. $new_plugin = array( 'slug' => $slug, 'version' => $data->version, 'title' => $data->name, 'is_active' => $is_active, 'is_uninstalled' => false, ); $themes_update_data[] = $new_plugin; $all_cached_themes->themes[ $slug ] = $new_plugin; } } $all_cached_themes->md5 = md5( $themes_signature ); $all_cached_themes->timestamp = time(); self::$_accounts->set_option( $option_name, $all_cached_themes, true ); } return $themes_update_data; } /** * Get site data for API install request. * * @author Vova Feldman (@svovaf) * @since 1.1.2 * * @param string[] $override * @param bool $include_plugins Since 1.1.8 by default include plugin changes. * @param bool $include_themes Since 1.1.8 by default include plugin changes. * @param bool $include_blog_data Since 2.3.0 by default include the current blog's data (language, title, and URL). * * @return array */ private function get_install_data_for_api( array $override, $include_plugins = true, $include_themes = true, $include_blog_data = true ) { // Alias. $permissions = FS_Permission_Manager::instance( $this ); if ( $permissions->is_extensions_tracking_allowed() ) { if ( ! defined( 'WP_FS__TRACK_PLUGINS' ) || false !== WP_FS__TRACK_PLUGINS ) { /** * @since 1.1.8 Also send plugin updates. */ if ( $include_plugins && ! isset( $override['plugins'] ) ) { $plugins = $this->get_plugins_data_for_api(); if ( ! empty( $plugins ) ) { $override['plugins'] = $plugins; } } } if ( ! defined( 'WP_FS__TRACK_THEMES' ) || false !== WP_FS__TRACK_THEMES ) { /** * @since 1.1.8 Also send themes updates. */ if ( $include_themes && ! isset( $override['themes'] ) ) { $themes = $this->get_themes_data_for_api(); if ( ! empty( $themes ) ) { $override['themes'] = $themes; } } } } $versions = $this->get_versions(); $blog_data = array(); if ( $include_blog_data ) { $blog_data['url'] = self::get_unfiltered_site_url(); if ( $permissions->is_diagnostic_tracking_allowed() ) { $blog_data = array_merge( $blog_data, array( 'language' => self::get_sanitized_language(), 'title' => get_bloginfo( 'name' ), ) ); } } return array_merge( $versions, $blog_data, array( 'version' => $this->get_plugin_version(), 'is_premium' => $this->is_premium(), // Special params. 'is_active' => true, 'is_uninstalled' => false, ), $override ); } /** * Update installs details. * * @todo V1 of multiste network support doesn't support plugin and theme data sending. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string[] string $override * @param bool $only_diff * @param bool $is_keepalive * @param bool $include_plugins Since 1.1.8 by default include plugin changes. * @param bool $include_themes Since 1.1.8 by default include plugin changes. * * @return array */ private function get_installs_data_for_api( array $override, $only_diff = false, $is_keepalive = false, $include_plugins = true, $include_themes = true ) { /** * @since 1.1.8 Also send plugin updates. */ // if ( $include_plugins && ! isset( $override['plugins'] ) ) { // $plugins = $this->get_plugins_data_for_api(); // if ( ! empty( $plugins ) ) { // $override['plugins'] = $plugins; // } // } /** * @since 1.1.8 Also send themes updates. */ // if ( $include_themes && ! isset( $override['themes'] ) ) { // $themes = $this->get_themes_data_for_api(); // if ( ! empty( $themes ) ) { // $override['themes'] = $themes; // } // } // Common properties. $versions = $this->get_versions(); $common = array_merge( $versions, array( 'version' => $this->get_plugin_version(), 'is_premium' => $this->is_premium(), ), $override ); $is_common_diff_for_any_site = false; $common_diff_union = array(); $installs_data = array(); $sites = self::get_sites(); $subsite_data_for_api_by_install_id = array(); $install_url_by_install_id = array(); $subsite_registration_date_by_install_id = array(); foreach ( $sites as $site ) { $blog_id = self::get_site_blog_id( $site ); $install = $this->get_install_by_blog_id( $blog_id ); if ( is_object( $install ) ) { if ( $install->user_id != $this->_user->id ) { // Install belongs to a different owner. continue; } if ( ! $this->is_tracking_allowed( $blog_id, $install ) ) { // Don't send updates regarding opted-out installs. continue; } $install_data = $this->get_site_info( $site, true ); if ( FS_Clone_Manager::instance()->is_temporary_duplicate_by_blog_id( $install_data['blog_id'] ) ) { continue; } $uid = $install_data['uid']; $url = $install_data['url']; $registration_date = $install_data['registration_date']; if ( isset( $subsite_data_for_api_by_install_id[ $install->id ] ) ) { $clone_subsite_data = $subsite_data_for_api_by_install_id[ $install->id ]; $clone_install_url = $install_url_by_install_id[ $install->id ]; $clone_subsite_registration_date = $subsite_registration_date_by_install_id[ $install->id ]; $skip = false; if ( ! empty( $install_data['registration_date'] ) && ! empty( $clone_subsite_registration_date ) ) { /** * If the current subsite was created after the other subsite that is also linked to the same install ID, we assume that it's a clone (not the original), and therefore, would skip its processing. * * @author Leo Fajardo (@leorw) * @since 2.5.1 */ $skip = ( strtotime( $install_data['registration_date'] ) > strtotime( $clone_subsite_registration_date ) ); } else if ( /** * If we already have an install with the same URL as the subsite it's stored in, skip the current subsite. Otherwise, replace the existing install's data with the current subsite's install's data if the URLs match. * * @author Leo Fajardo (@leorw) * @since 2.5.0 */ fs_strip_url_protocol( untrailingslashit( $clone_install_url ) ) === fs_strip_url_protocol( untrailingslashit( $clone_subsite_data['url'] ) ) || fs_strip_url_protocol( untrailingslashit( $install->url ) ) !== fs_strip_url_protocol( untrailingslashit( $url ) ) ) { $skip = true; } if ( $skip ) { // Store the skipped subsite's ID so that the clone resolution manager can try to resolve the clone install that is stored in that subsite later on. FS_Clone_Manager::instance()->store_blog_install_info( $blog_id ); continue; } } unset( $install_data['blog_id'] ); unset( $install_data['uid'] ); unset( $install_data['url'] ); unset( $install_data['registration_date'] ); $install_data['is_active'] = $this->is_active_for_site( $blog_id ); $install_data['is_uninstalled'] = $install->is_uninstalled; $common_diff = null; $is_common_diff = false; if ( $only_diff ) { $install_data = $this->get_install_diff_for_api( $install_data, $install, $override ); $common_diff = $this->get_install_diff_for_api( $common, $install, $override ); $is_common_diff = ! empty( $common_diff ); if ( $is_common_diff ) { foreach ( $common_diff as $k => $v ) { if ( ! isset( $common_diff_union[ $k ] ) ) { $common_diff_union[ $k ] = $v; } } } $is_common_diff_for_any_site = $is_common_diff_for_any_site || $is_common_diff; } if ( ! empty( $install_data ) || $is_common_diff || $is_keepalive ) { // Add install ID and site unique ID. $install_data['id'] = $install->id; $install_data['uid'] = $uid; $install_data['url'] = $url; $subsite_data_for_api_by_install_id[ $install->id ] = $install_data; $install_url_by_install_id[ $install->id ] = $install->url; $subsite_registration_date_by_install_id[ $install->id ] = $registration_date; } } } restore_current_blog(); $installs_data = array_merge( $installs_data, array_values( $subsite_data_for_api_by_install_id ) ); if ( 0 < count( $installs_data ) && ( $is_common_diff_for_any_site || ! $only_diff ) ) { if ( ! $only_diff ) { $installs_data[] = $common; } else if ( ! empty( $common_diff_union ) ) { $installs_data[] = $common_diff_union; } } foreach ( $installs_data as &$data ) { $data = (object) $data; } return $installs_data; } /** * Compare site actual data to the stored install data and return the differences for an API data sync. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param array $site * @param FS_Site $install * @param string[] string $override * * @return array */ private function get_install_diff_for_api( $site, $install, $override = array() ) { $diff = array(); $special = array(); $special_override = false; foreach ( $site as $p => $v ) { if ( property_exists( $install, $p ) ) { if ( ( is_bool( $install->{$p} ) || ! empty( $install->{$p} ) ) && $install->{$p} != $v ) { $val = self::get_api_sanitized_property( $p, $v ); if ( $install->{$p} != $val ) { $install->{$p} = $val; $diff[ $p ] = $val; } } } else { $special[ $p ] = $v; if ( isset( $override[ $p ] ) || 'plugins' === $p || 'themes' === $p ) { $special_override = true; } } } if ( $special_override || 0 < count( $diff ) ) { // Add special params only if has at least one // standard param, or if explicitly requested to // override a special param or a param which is not exist // in the install object. $diff = array_merge( $diff, $special ); } return $diff; } /** * @author Leo Fajardo (@leorw) * @since 2.5.1 */ private function send_pending_clone_update_once() { $this->_logger->entrance(); if ( ! empty( $this->_storage->clone_id ) ) { return; } $install_clone = $this->get_api_site_scope()->call( '/clones', 'post', array( 'site_url' => self::get_unfiltered_site_url() ) ); if ( $this->is_api_result_entity( $install_clone ) ) { $this->_storage->clone_id = $install_clone->id; } } /** * @author Leo Fajardo (@leorw) * @since 2.5.1 * * @param string $resolution_type * @param FS_Site $clone_context_install */ function send_clone_resolution_update( $resolution_type, $clone_context_install ) { $this->_logger->entrance(); if ( empty( $this->_storage->clone_id ) ) { return; } $new_install_id = null; $current_site = null; $flush = false; /** * If the current site is now different from the context install before the clone resolution, we need to override `$this->_site` so that the API call below will be made with the right install scope entity. */ if ( $clone_context_install->id != $this->_site->id ) { $new_install_id = $this->_site->id; $current_site = $this->_site; $this->_site = $clone_context_install; $flush = true; } $this->get_api_site_scope( $flush )->call( "/clones/{$this->_storage->clone_id}", 'put', array( 'resolution' => $resolution_type, 'new_install_id' => $new_install_id, ) ); if ( is_object( $current_site ) ) { /** * Ensure that the install scope entity is updated back to the previous install entity. */ $this->_site = $current_site; // Restore the previous install scope entity of the API. $this->get_api_site_scope( true ); } } /** * Update install only if changed. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param string[] string $override * @param bool $flush * @param bool $is_two_way_sync @since 2.5.0 If true and there's a successful API request, the install sync cron will be cleared. * * @return false|object|string */ private function send_install_update( $override = array(), $flush = false, $is_two_way_sync = false ) { $this->_logger->entrance(); $check_properties = $this->get_install_data_for_api( $override ); if ( $flush ) { $params = $check_properties; } else { $params = $this->get_install_diff_for_api( $check_properties, $this->_site, $override ); } if ( empty( $params ) ) { $keepalive_only_update = $this->should_send_keepalive_update(); if ( ! $keepalive_only_update ) { /** * There are no updates to send including keepalive. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ return false; } } if ( $is_two_way_sync ) { /** * Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ if ( ! is_multisite() ) { // Update last install sync timestamp. $this->set_cron_execution_timestamp( 'install_sync' ); } $params['uid'] = $this->get_anonymous_id(); } $this->set_keepalive_timestamp(); // Send updated values to FS. $site = $this->api_site_call( '/', 'put', $params, true ); if ( $is_two_way_sync && $this->is_api_result_entity( $site ) ) { /** * Clear scheduled install sync after a two-way sync call. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ if ( ! is_multisite() ) { // I successfully sent install update, clear scheduled sync if exist. $this->clear_install_sync_cron(); } } return $site; } /** * Update installs only if changed. * * @author Vova Feldman (@svovaf) * @since 2.0.0 * * @param string[] string $override * @param bool $flush * @param bool $is_two_way_sync @since 2.5.0 If true and there's a successful API request, the install sync cron will be cleared. * * @return false|object|string */ private function send_installs_update( $override = array(), $flush = false, $is_two_way_sync = false ) { $this->_logger->entrance(); /** * Pass `true` to use the network level storage since the update is for many installs. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ $should_send_keepalive = $this->should_send_keepalive_update( true ); $installs_data = $this->get_installs_data_for_api( $override, ! $flush, $should_send_keepalive ); if ( empty( $installs_data ) ) { return false; } if ( $is_two_way_sync ) { // Update last install sync timestamp during a two-way sync call as we expect that updates are sent during this call. $this->set_cron_execution_timestamp( 'install_sync' ); } /** * Pass `true` to use the network level storage since the update is for many installs. * * @author Leo Fajardo (@leorw) * @since 2.2.3 */ $this->set_keepalive_timestamp( true ); // Send updated values to FS. $result = $this->get_api_user_scope()->call( "/plugins/{$this->_plugin->id}/installs.json", 'put', $installs_data ); if ( $is_two_way_sync && $this->is_api_result_object( $result, 'installs' ) ) { // I successfully sent a two-way installs update, clear the scheduled install sync if it exists. $this->clear_install_sync_cron(); } return $result; } /** * @author Leo Fajardo (@leorw) * * @param bool|null $use_network_level_storage * * @return bool */ private function should_send_keepalive_update( $use_network_level_storage = null ) { $keepalive_timestamp = $this->_storage->get( 'keepalive_timestamp', 0, $use_network_level_storage ); if ( $keepalive_timestamp < ( time() - WP_FS__TIME_WEEK_IN_SEC ) ) { // If updated more than 7 days ago, trigger a keepalive and update the time it was triggered. return true; } else { // If updated 7 days ago or less, "flip a coin", if the value is 7 trigger a keepalive and update the last time it was triggered. return ( 7 == rand( 1, 7 ) ); } } /** * Syncs the install owner's data if needed (i.e., if the install owner is different from the loaded user). * * @author Leo Fajardo (@leorw) * @since 2.3.2 */ private function maybe_sync_install_user() { if ( $this->_user->id == $this->_site->user_id ) { return; } // Fetch user data and store if found. $this->sync_user_by_current_install(); } /** * Update install only if changed. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param string[] string $override * @param bool $flush */ function sync_install( $override = array(), $flush = false ) { $this->_logger->entrance(); $site = $this->send_install_update( $override, $flush, true ); if ( false === $site ) { // No sync required. return; } if ( ! $this->is_api_result_entity( $site ) ) { // Failed to sync, don't update locally. return; } $this->_site = new FS_Site( $site ); $this->_store_site( true ); } /** * Update install only if changed. * * @author Vova Feldman (@svovaf) * @since 1.0.9 * * @param string[] string $override * @param bool $flush */ private function sync_installs( $override = array(), $flush = false ) { $this->_logger->entrance(); $result = $this->send_installs_update( $override, $flush, true ); if ( false === $result ) { // No sync required. return; } if ( ! $this->is_api_result_object( $result, 'installs' ) ) { // Failed to sync, don't update locally. return; } $address_to_blog_map = $this->get_address_to_blog_map(); foreach ( $result->installs as $install ) { $this->_site = new FS_Site( $install ); $address = trailingslashit( fs_strip_url_protocol( $install->url ) ); $blog_id = $address_to_blog_map[ $address ]; $this->_store_site( true, $blog_id ); } } /** * Track install's custom event. * * IMPORTANT: * Custom event tracking is currently only supported for specific clients. * If you are not one of them, please don't use this method. If you will, * the API will simply ignore your request based on the plugin ID. * * Need custom tracking for your plugin or theme? * If you are interested in custom event tracking please contact yo@freemius.com * for further details. * * @author Vova Feldman (@svovaf) * @since 1.2.1 * * @param string $name Event name. * @param array $properties Associative key/value array with primitive values only * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s. * @param bool $once If true, event will be tracked only once. IMPORTANT: Still trigger the API call. * * @return object|false Event data or FALSE on failure. * * @throws \Freemius_InvalidArgumentException */ public function track_event( $name, $properties = array(), $process_at = false, $once = false ) { $this->_logger->entrance( http_build_query( array( 'name' => $name, 'once' => $once ) ) ); if ( ! $this->is_registered() ) { return false; } $event = array( 'type' => $name ); if ( is_numeric( $process_at ) && $process_at > time() ) { $event['process_at'] = $process_at; } if ( $once ) { $event['once'] = true; } if ( ! empty( $properties ) ) { // Verify associative array values are primitive. foreach ( $properties as $k => $v ) { if ( ! is_scalar( $v ) ) { throw new Freemius_InvalidArgumentException( 'The $properties argument must be an associative key/value array with primitive values only.' ); } } $event['properties'] = $properties; } $result = $this->get_api_site_scope()->call( 'events.json', 'post', $event ); return $this->is_api_error( $result ) ? false : $result; } /** * Track install's custom event only once, but it still triggers the API call. * * IMPORTANT: * Custom event tracking is currently only supported for specific clients. * If you are not one of them, please don't use this method. If you will, * the API will simply ignore your request based on the plugin ID. * * Need custom tracking for your plugin or theme? * If you are interested in custom event tracking please contact yo@freemius.com * for further details. * * @author Vova Feldman (@svovaf) * @since 1.2.1 * * @param string $name Event name. * @param array $properties Associative key/value array with primitive values only * @param bool $process_at A valid future date-time in the following format Y-m-d H:i:s. * * @return object|false Event data or FALSE on failure. * * @throws \Freemius_InvalidArgumentException * * @user Freemius::track_event() */ public function track_event_once( $name, $properties = array(), $process_at = false ) { return $this->track_event( $name, $properties, $process_at, true ); } /** * Plugin uninstall hook. * * @author Vova Feldman (@svovaf) * @since 1.0.1 * * @param bool $check_user Enforce checking if user have plugins activation privileges. */ function _uninstall_plugin_event( $check_user = true ) {
•
Search:
•
Replace:
1
2
3
Function
Edit by line
Download
Information
Rename
Copy
Move
Delete
Chmod
List