This commit is contained in:
2024-05-20 15:37:46 +03:00
commit 00b7dbd0b7
10404 changed files with 3285853 additions and 0 deletions

View File

@ -0,0 +1,597 @@
<?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.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* - Each instance of Freemius class represents a single plugin
* install by a single user (the installer of the plugin).
*
* - Each website can only have one install of the same plugin.
*
* - Install entity is only created after a user connects his account with Freemius.
*
* Class Freemius_Abstract
*/
abstract class Freemius_Abstract {
#----------------------------------------------------------------------------------
#region Identity
#----------------------------------------------------------------------------------
/**
* Check if user has connected his account (opted-in).
*
* Note:
* If the user opted-in and opted-out on a later stage,
* this will still return true. If you want to check if the
* user is currently opted-in, use:
* `$fs->is_registered() && $fs->is_tracking_allowed()`
*
* @since 1.0.1
* @return bool
*/
abstract function is_registered();
/**
* Check if the user skipped connecting the account with Freemius.
*
* @since 1.0.7
*
* @return bool
*/
abstract function is_anonymous();
/**
* Check if the user currently in activation mode.
*
* @since 1.0.7
*
* @return bool
*/
abstract function is_activation_mode();
#endregion
#----------------------------------------------------------------------------------
#region Usage Tracking
#----------------------------------------------------------------------------------
/**
* Returns TRUE if the user opted-in and didn't disconnect (opt-out).
*
* @author Leo Fajardo (@leorw)
* @since 1.2.1.5
*
* @return bool
*/
abstract function is_tracking_allowed();
/**
* Returns TRUE if the user never opted-in or manually opted-out.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @return bool
*/
function is_tracking_prohibited() {
return ! $this->is_registered() || ! $this->is_tracking_allowed();
}
/**
* Opt-out from usage tracking.
*
* Note: This will not delete the account information but will stop all tracking.
*
* Returns:
* 1. FALSE - If the user never opted-in.
* 2. TRUE - If successfully opted-out.
* 3. object - API Result on failure.
*
* @author Leo Fajardo (@leorw)
* @since 1.2.1.5
*
* @return bool|object
*/
abstract function stop_tracking();
/**
* 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
*
* @return bool|object
*/
abstract function allow_tracking();
#endregion
#----------------------------------------------------------------------------------
#region Module Type
#----------------------------------------------------------------------------------
/**
* Checks if the plugin's type is "plugin". The other type is "theme".
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*
* @return bool
*/
abstract function is_plugin();
/**
* Checks if the module type is "theme". The other type is "plugin".
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*
* @return bool
*/
function is_theme() {
return ( ! $this->is_plugin() );
}
#endregion
#----------------------------------------------------------------------------------
#region Permissions
#----------------------------------------------------------------------------------
/**
* Check if plugin must be WordPress.org compliant.
*
* @since 1.0.7
*
* @return bool
*/
abstract function is_org_repo_compliant();
/**
* Check if plugin is allowed to install executable files.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.5
*
* @return bool
*/
function is_allowed_to_install() {
return ( $this->is_premium() || ! $this->is_org_repo_compliant() );
}
#endregion
/**
* Check if user in trial or in free plan (not paying).
*
* @author Vova Feldman (@svovaf)
* @since 1.0.4
*
* @return bool
*/
function is_not_paying() {
return ( $this->is_trial() || $this->is_free_plan() );
}
/**
* Check if the user has an activated and valid paid license on current plugin's install.
*
* @since 1.0.9
*
* @return bool
*/
abstract function is_paying();
/**
* Check if the user is paying or in trial.
*
* @since 1.0.9
*
* @return bool
*/
function is_paying_or_trial() {
return ( $this->is_paying() || $this->is_trial() );
}
/**
* Check if user in a trial or have feature enabled license.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.7
*
* @return bool
*/
abstract function can_use_premium_code();
#----------------------------------------------------------------------------------
#region Premium Only
#----------------------------------------------------------------------------------
/**
* All logic wrapped in methods with "__premium_only()" suffix will be only
* included in the premium code.
*
* Example:
* if ( freemius()->is__premium_only() ) {
* ...
* }
*/
/**
* Returns true when running premium plugin code.
*
* @since 1.0.9
*
* @return bool
*/
function is__premium_only() {
return $this->is_premium();
}
/**
* Check if the user has an activated and valid paid license on current plugin's install.
*
* @since 1.0.9
*
* @return bool
*
*/
function is_paying__premium_only() {
return ( $this->is__premium_only() && $this->is_paying() );
}
/**
* All code wrapped in this statement will be only included in the premium code.
*
* @since 1.0.9
*
* @param string $plan Plan name.
* @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
*
* @return bool
*/
function is_plan__premium_only( $plan, $exact = false ) {
return ( $this->is_premium() && $this->is_plan( $plan, $exact ) );
}
/**
* Check if plan matches active license' plan or active trial license' plan.
*
* All code wrapped in this statement will be only included in the premium code.
*
* @since 1.0.9
*
* @param string $plan Plan name.
* @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
*
* @return bool
*/
function is_plan_or_trial__premium_only( $plan, $exact = false ) {
return ( $this->is_premium() && $this->is_plan_or_trial( $plan, $exact ) );
}
/**
* Check if the user is paying or in trial.
*
* All code wrapped in this statement will be only included in the premium code.
*
* @since 1.0.9
*
* @return bool
*/
function is_paying_or_trial__premium_only() {
return $this->is_premium() && $this->is_paying_or_trial();
}
/**
* Check if the user has an activated and valid paid license on current plugin's install.
*
* @since 1.0.4
*
* @return bool
*
* @deprecated Method name is confusing since it's not clear from the name the code will be removed.
* @using Alias to is_paying__premium_only()
*/
function is_paying__fs__() {
return $this->is_paying__premium_only();
}
/**
* Check if user in a trial or have feature enabled license.
*
* All code wrapped in this statement will be only included in the premium code.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.9
*
* @return bool
*/
function can_use_premium_code__premium_only() {
return $this->is_premium() && $this->can_use_premium_code();
}
#endregion
#----------------------------------------------------------------------------------
#region Trial
#----------------------------------------------------------------------------------
/**
* Check if the user in a trial.
*
* @since 1.0.3
*
* @return bool
*/
abstract function is_trial();
/**
* Check if trial already utilized.
*
* @since 1.0.9
*
* @return bool
*/
abstract function is_trial_utilized();
#endregion
#----------------------------------------------------------------------------------
#region Plans
#----------------------------------------------------------------------------------
/**
* Check if the user is on the free plan of the product.
*
* @since 1.0.4
*
* @return bool
*/
abstract function is_free_plan();
/**
* @since 1.0.2
*
* @param string $plan Plan name.
* @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
*
* @return bool
*/
abstract function is_plan( $plan, $exact = false );
/**
* Check if plan based on trial. If not in trial mode, should return false.
*
* @since 1.0.9
*
* @param string $plan Plan name.
* @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
*
* @return bool
*/
abstract function is_trial_plan( $plan, $exact = false );
/**
* Check if plan matches active license' plan or active trial license' plan.
*
* @since 1.0.9
*
* @param string $plan Plan name.
* @param bool $exact If true, looks for exact plan. If false, also check "higher" plans.
*
* @return bool
*/
function is_plan_or_trial( $plan, $exact = false ) {
return $this->is_plan( $plan, $exact ) ||
$this->is_trial_plan( $plan, $exact );
}
/**
* Check if plugin has any paid plans.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @return bool
*/
abstract function has_paid_plan();
/**
* Check if plugin has any free plan, or is it premium only.
*
* Note: If no plans configured, assume plugin is free.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @return bool
*/
abstract function has_free_plan();
/**
* Check if plugin is premium only (no free plans).
*
* NOTE: is__premium_only() is very different method, don't get confused.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.9
*
* @return bool
*/
abstract function is_only_premium();
/**
* Check if module has a premium code version.
*
* Serviceware module might be freemium without any
* premium code version, where the paid features
* are all part of the service.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @return bool
*/
abstract function has_premium_version();
/**
* Check if module has any release on Freemius,
* or all plugin's code is on WordPress.org (Serviceware).
*
* @return bool
*/
function has_release_on_freemius() {
return ! $this->is_org_repo_compliant() ||
$this->has_premium_version();
}
/**
* Checks if it's a freemium plugin.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.9
*
* @return bool
*/
function is_freemium() {
return $this->has_paid_plan() &&
$this->has_free_plan();
}
/**
* Check if module has only one plan.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.7
*
* @return bool
*/
abstract function is_single_plan();
#endregion
/**
* Check if running payments in sandbox mode.
*
* @since 1.0.4
*
* @return bool
*/
abstract function is_payments_sandbox();
/**
* Check if running test vs. live plugin.
*
* @since 1.0.5
*
* @return bool
*/
abstract function is_live();
/**
* Check if running premium plugin code.
*
* @since 1.0.5
*
* @return bool
*/
abstract function is_premium();
/**
* Get upgrade URL.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.2
*
* @param string $period Billing cycle.
*
* @return string
*/
abstract function get_upgrade_url( $period = WP_FS__PERIOD_ANNUALLY );
/**
* Check if Freemius was first added in a plugin update.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.5
*
* @return bool
*/
function is_plugin_update() {
return ! $this->is_plugin_new_install();
}
/**
* Check if Freemius was part of the plugin when the user installed it first.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.5
*
* @return bool
*/
abstract function is_plugin_new_install();
#----------------------------------------------------------------------------------
#region Marketing
#----------------------------------------------------------------------------------
/**
* Check if current user purchased any other plugins before.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
abstract function has_purchased_before();
/**
* Check if current user classified as an agency.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
abstract function is_agency();
/**
* Check if current user classified as a developer.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
abstract function is_developer();
/**
* Check if current user classified as a business.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
abstract function is_business();
#endregion
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,321 @@
<?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 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WP Admin notices manager both for site level and network level.
*
* Class FS_Admin_Notices
*/
class FS_Admin_Notices {
/**
* @since 1.2.2
*
* @var string
*/
protected $_module_unique_affix;
/**
* @var string
*/
protected $_id;
/**
* @var string
*/
protected $_title;
/**
* @var FS_Admin_Notice_Manager
*/
protected $_notices;
/**
* @var FS_Admin_Notice_Manager
*/
protected $_network_notices;
/**
* @var int The ID of the blog that is associated with the current site level options.
*/
private $_blog_id = 0;
/**
* @var bool
*/
private $_is_multisite;
/**
* @var FS_Admin_Notices[]
*/
private static $_instances = array();
/**
* @param string $id
* @param string $title
* @param string $module_unique_affix
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network and
* blog admin pages.
*
* @return FS_Admin_Notices
*/
static function instance( $id, $title = '', $module_unique_affix = '', $is_network_and_blog_admins = false ) {
if ( ! isset( self::$_instances[ $id ] ) ) {
self::$_instances[ $id ] = new FS_Admin_Notices( $id, $title, $module_unique_affix, $is_network_and_blog_admins );
}
return self::$_instances[ $id ];
}
/**
* @param string $id
* @param string $title
* @param string $module_unique_affix
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network and
* blog admin pages.
*/
protected function __construct( $id, $title = '', $module_unique_affix = '', $is_network_and_blog_admins = false ) {
$this->_id = $id;
$this->_title = $title;
$this->_module_unique_affix = $module_unique_affix;
$this->_is_multisite = is_multisite();
if ( $this->_is_multisite ) {
$this->_blog_id = get_current_blog_id();
$this->_network_notices = FS_Admin_Notice_Manager::instance(
$id,
$title,
$module_unique_affix,
$is_network_and_blog_admins,
true
);
}
$this->_notices = FS_Admin_Notice_Manager::instance(
$id,
$title,
$module_unique_affix,
false,
$this->_blog_id
);
}
/**
* Add admin message to admin messages queue, and hook to admin_notices / all_admin_notices if not yet hooked.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.4
*
* @param string $message
* @param string $title
* @param string $type
* @param bool $is_sticky
* @param string $id Message ID
* @param bool $store_if_sticky
* @param int|null $network_level_or_blog_id
*
* @uses add_action()
*/
function add(
$message,
$title = '',
$type = 'success',
$is_sticky = false,
$id = '',
$store_if_sticky = true,
$network_level_or_blog_id = null
) {
if ( $this->should_use_network_notices( $id, $network_level_or_blog_id ) ) {
$notices = $this->_network_notices;
} else {
$notices = $this->get_site_notices( $network_level_or_blog_id );
}
$notices->add(
$message,
$title,
$type,
$is_sticky,
$id,
$store_if_sticky
);
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string|string[] $ids
* @param int|null $network_level_or_blog_id
*/
function remove_sticky( $ids, $network_level_or_blog_id = null ) {
if ( ! is_array( $ids ) ) {
$ids = array( $ids );
}
if ( $this->should_use_network_notices( $ids[0], $network_level_or_blog_id ) ) {
$notices = $this->_network_notices;
} else {
$notices = $this->get_site_notices( $network_level_or_blog_id );
}
return $notices->remove_sticky( $ids );
}
/**
* Check if sticky message exists by id.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param string $id
* @param int|null $network_level_or_blog_id
*
* @return bool
*/
function has_sticky( $id, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_notices( $id, $network_level_or_blog_id ) ) {
$notices = $this->_network_notices;
} else {
$notices = $this->get_site_notices( $network_level_or_blog_id );
}
return $notices->has_sticky( $id );
}
/**
* Adds sticky admin notification.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string $message
* @param string $id Message ID
* @param string $title
* @param string $type
* @param int|null $network_level_or_blog_id
* @param number|null $wp_user_id
* @param string|null $plugin_title
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network and
* blog admin pages.
*/
function add_sticky(
$message,
$id,
$title = '',
$type = 'success',
$network_level_or_blog_id = null,
$wp_user_id = null,
$plugin_title = null,
$is_network_and_blog_admins = false
) {
if ( $this->should_use_network_notices( $id, $network_level_or_blog_id ) ) {
$notices = $this->_network_notices;
} else {
$notices = $this->get_site_notices( $network_level_or_blog_id );
}
$notices->add_sticky( $message, $id, $title, $type, $wp_user_id, $plugin_title, $is_network_and_blog_admins );
}
/**
* Clear all sticky messages.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int|null $network_level_or_blog_id
*/
function clear_all_sticky( $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ||
false === $network_level_or_blog_id ||
0 == $network_level_or_blog_id ||
is_null( $network_level_or_blog_id )
) {
$notices = $this->get_site_notices( $network_level_or_blog_id );
$notices->clear_all_sticky();
}
if ( $this->_is_multisite &&
( true === $network_level_or_blog_id || is_null( $network_level_or_blog_id ) )
) {
$this->_network_notices->clear_all_sticky();
}
}
/**
* Add admin message to all admin messages queue, and hook to all_admin_notices if not yet hooked.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.4
*
* @param string $message
* @param string $title
* @param string $type
* @param bool $is_sticky
* @param string $id Message ID
*/
function add_all( $message, $title = '', $type = 'success', $is_sticky = false, $id = '' ) {
$this->add( $message, $title, $type, $is_sticky, true, $id );
}
#--------------------------------------------------------------------------------
#region Helper Methods
#--------------------------------------------------------------------------------
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $blog_id
*
* @return FS_Admin_Notice_Manager
*/
private function get_site_notices( $blog_id = 0 ) {
if ( 0 == $blog_id || $blog_id == $this->_blog_id ) {
return $this->_notices;
}
return FS_Admin_Notice_Manager::instance(
$this->_id,
$this->_title,
$this->_module_unique_affix,
false,
$blog_id
);
}
/**
* Check if the network notices should be used.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $id
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite notices (if there's a network). When `false`, use the current context blog notices. When `null`, the decision which notices manager to use (MS vs. Current S) will be handled internally and determined based on the $id and the context admin (blog admin vs. network level admin).
*
* @return bool
*/
private function should_use_network_notices( $id = '', $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ) {
// Not a multisite environment.
return false;
}
if ( is_numeric( $network_level_or_blog_id ) ) {
// Explicitly asked to use a specified blog storage.
return false;
}
if ( is_bool( $network_level_or_blog_id ) ) {
// Explicitly specified whether should use the network or blog level storage.
return $network_level_or_blog_id;
}
return fs_is_network_admin();
}
#endregion
}

View File

@ -0,0 +1,664 @@
<?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.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Api
*
* Wraps Freemius API SDK to handle:
* 1. Clock sync.
* 2. Fallback to HTTP when HTTPS fails.
* 3. Adds caching layer to GET requests.
* 4. Adds consistency for failed requests by using last cached version.
*/
class FS_Api {
/**
* @var FS_Api[]
*/
private static $_instances = array();
/**
* @var FS_Option_Manager Freemius options, options-manager.
*/
private static $_options;
/**
* @var FS_Cache_Manager API Caching layer
*/
private static $_cache;
/**
* @var int Clock diff in seconds between current server to API server.
*/
private static $_clock_diff;
/**
* @var Freemius_Api_WordPress
*/
private $_api;
/**
* @var string
*/
private $_slug;
/**
* @var FS_Logger
* @since 1.0.4
*/
private $_logger;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @var string
*/
private $_sdk_version;
/**
* @param string $slug
* @param string $scope 'app', 'developer', 'user' or 'install'.
* @param number $id Element's id.
* @param string $public_key Public key.
* @param bool $is_sandbox
* @param bool|string $secret_key Element's secret key.
* @param null|string $sdk_version
*
* @return FS_Api
*/
static function instance(
$slug,
$scope,
$id,
$public_key,
$is_sandbox,
$secret_key = false,
$sdk_version = null
) {
$identifier = md5( $slug . $scope . $id . $public_key . ( is_string( $secret_key ) ? $secret_key : '' ) . json_encode( $is_sandbox ) );
if ( ! isset( self::$_instances[ $identifier ] ) ) {
self::_init();
self::$_instances[ $identifier ] = new FS_Api( $slug, $scope, $id, $public_key, $secret_key, $is_sandbox, $sdk_version );
}
return self::$_instances[ $identifier ];
}
private static function _init() {
if ( isset( self::$_options ) ) {
return;
}
if ( ! class_exists( 'Freemius_Api_WordPress' ) ) {
require_once WP_FS__DIR_SDK . '/FreemiusWordPress.php';
}
self::$_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true );
self::$_cache = FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME );
self::$_clock_diff = self::$_options->get_option( 'api_clock_diff', 0 );
Freemius_Api_WordPress::SetClockDiff( self::$_clock_diff );
if ( self::$_options->get_option( 'api_force_http', false ) ) {
Freemius_Api_WordPress::SetHttp();
}
}
/**
* @param string $slug
* @param string $scope 'app', 'developer', 'user' or 'install'.
* @param number $id Element's id.
* @param string $public_key Public key.
* @param bool|string $secret_key Element's secret key.
* @param bool $is_sandbox
* @param null|string $sdk_version
*/
private function __construct(
$slug,
$scope,
$id,
$public_key,
$secret_key,
$is_sandbox,
$sdk_version
) {
$this->_api = new Freemius_Api_WordPress( $scope, $id, $public_key, $secret_key, $is_sandbox );
$this->_slug = $slug;
$this->_sdk_version = $sdk_version;
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $slug . '_api', WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
}
/**
* Find clock diff between server and API server, and store the diff locally.
*
* @param bool|int $diff
*
* @return bool|int False if clock diff didn't change, otherwise returns the clock diff in seconds.
*/
private function _sync_clock_diff( $diff = false ) {
$this->_logger->entrance();
// Sync clock and store.
$new_clock_diff = ( false === $diff ) ?
Freemius_Api_WordPress::FindClockDiff() :
$diff;
if ( $new_clock_diff === self::$_clock_diff ) {
return false;
}
self::$_clock_diff = $new_clock_diff;
// Update API clock's diff.
Freemius_Api_WordPress::SetClockDiff( self::$_clock_diff );
// Store new clock diff in storage.
self::$_options->set_option( 'api_clock_diff', self::$_clock_diff, true );
return $new_clock_diff;
}
/**
* Override API call to enable retry with servers' clock auto sync method.
*
* @param string $path
* @param string $method
* @param array $params
* @param bool $retry Is in retry or first call attempt.
*
* @return array|mixed|string|void
*/
private function _call( $path, $method = 'GET', $params = array(), $retry = false ) {
$this->_logger->entrance( $method . ':' . $path );
if ( self::is_temporary_down() ) {
$result = $this->get_temporary_unavailable_error();
} else {
/**
* @since 2.3.0 Include the SDK version with all API requests that going through the API manager. IMPORTANT: Only pass the SDK version if the caller didn't include it yet.
*/
if ( ! empty( $this->_sdk_version ) ) {
if ( false === strpos( $path, 'sdk_version=' ) &&
! isset( $params['sdk_version'] )
) {
// Always add the sdk_version param in the querystring. DO NOT INCLUDE IT IN THE BODY PARAMS, OTHERWISE, IT MAY LEAD TO AN UNEXPECTED PARAMS PARSING IN CASES WHERE THE $params IS A REGULAR NON-ASSOCIATIVE ARRAY.
$path = add_query_arg( 'sdk_version', $this->_sdk_version, $path );
}
}
$result = $this->_api->Api( $path, $method, $params );
if ( null !== $result &&
isset( $result->error ) &&
isset( $result->error->code ) &&
'request_expired' === $result->error->code
) {
if ( ! $retry ) {
$diff = isset( $result->error->timestamp ) ?
( time() - strtotime( $result->error->timestamp ) ) :
false;
// Try to sync clock diff.
if ( false !== $this->_sync_clock_diff( $diff ) ) {
// Retry call with new synced clock.
return $this->_call( $path, $method, $params, true );
}
}
}
}
if ( $this->_logger->is_on() && self::is_api_error( $result ) ) {
// Log API errors.
$this->_logger->api_error( $result );
}
return $result;
}
/**
* Override API call to wrap it in servers' clock sync method.
*
* @param string $path
* @param string $method
* @param array $params
*
* @return array|mixed|string|void
* @throws Freemius_Exception
*/
function call( $path, $method = 'GET', $params = array() ) {
return $this->_call( $path, $method, $params );
}
/**
* Get API request URL signed via query string.
*
* @param string $path
*
* @return string
*/
function get_signed_url( $path ) {
return $this->_api->GetSignedUrl( $path );
}
/**
* @param string $path
* @param bool $flush
* @param int $expiration (optional) Time until expiration in seconds from now, defaults to 24 hours
*
* @return stdClass|mixed
*/
function get( $path = '/', $flush = false, $expiration = WP_FS__TIME_24_HOURS_IN_SEC ) {
$this->_logger->entrance( $path );
$cache_key = $this->get_cache_key( $path );
// Always flush during development.
if ( WP_FS__DEV_MODE || $this->_api->IsSandbox() ) {
$flush = true;
}
$cached_result = self::$_cache->get( $cache_key );
if ( $flush || ! self::$_cache->has_valid( $cache_key, $expiration ) ) {
$result = $this->call( $path );
if ( ! is_object( $result ) || isset( $result->error ) ) {
// Api returned an error.
if ( is_object( $cached_result ) &&
! isset( $cached_result->error )
) {
// If there was an error during a newer data fetch,
// fallback to older data version.
$result = $cached_result;
if ( $this->_logger->is_on() ) {
$this->_logger->warn( 'Fallback to cached API result: ' . var_export( $cached_result, true ) );
}
} else {
if ( is_object( $result ) && isset( $result->error->http ) && 404 == $result->error->http ) {
/**
* If the response code is 404, cache the result for half of the `$expiration`.
*
* @author Leo Fajardo (@leorw)
* @since 2.2.4
*/
$expiration /= 2;
} else {
// If no older data version and the response code is not 404, return result without
// caching the error.
return $result;
}
}
}
self::$_cache->set( $cache_key, $result, $expiration );
$cached_result = $result;
} else {
$this->_logger->log( 'Using cached API result.' );
}
return $cached_result;
}
/**
* Check if there's a cached version of the API request.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1
*
* @param string $path
* @param string $method
* @param array $params
*
* @return bool
*/
function is_cached( $path, $method = 'GET', $params = array() ) {
$cache_key = $this->get_cache_key( $path, $method, $params );
return self::$_cache->has_valid( $cache_key );
}
/**
* Invalidate a cached version of the API request.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @param string $path
* @param string $method
* @param array $params
*/
function purge_cache( $path, $method = 'GET', $params = array() ) {
$this->_logger->entrance( "{$method}:{$path}" );
$cache_key = $this->get_cache_key( $path, $method, $params );
self::$_cache->purge( $cache_key );
}
/**
* Invalidate a cached version of the API request.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $path
* @param int $expiration
* @param string $method
* @param array $params
*/
function update_cache_expiration( $path, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $method = 'GET', $params = array() ) {
$this->_logger->entrance( "{$method}:{$path}:{$expiration}" );
$cache_key = $this->get_cache_key( $path, $method, $params );
self::$_cache->update_expiration( $cache_key, $expiration );
}
/**
* @param string $path
* @param string $method
* @param array $params
*
* @return string
* @throws \Freemius_Exception
*/
private function get_cache_key( $path, $method = 'GET', $params = array() ) {
$canonized = $this->_api->CanonizePath( $path );
// $exploded = explode('/', $canonized);
// return $method . '_' . array_pop($exploded) . '_' . md5($canonized . json_encode($params));
return strtolower( $method . ':' . $canonized ) . ( ! empty( $params ) ? '#' . md5( json_encode( $params ) ) : '' );
}
/**
* Test API connectivity.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9 If fails, try to fallback to HTTP.
* @since 1.1.6 Added a 5-min caching mechanism, to prevent from overloading the server if the API if
* temporary down.
*
* @return bool True if successful connectivity to the API.
*/
static function test() {
self::_init();
$cache_key = 'ping_test';
$test = self::$_cache->get_valid( $cache_key, null );
if ( is_null( $test ) ) {
$test = Freemius_Api_WordPress::Test();
if ( false === $test && Freemius_Api_WordPress::IsHttps() ) {
// Fallback to HTTP, since HTTPS fails.
Freemius_Api_WordPress::SetHttp();
self::$_options->set_option( 'api_force_http', true, true );
$test = Freemius_Api_WordPress::Test();
if ( false === $test ) {
/**
* API connectivity test fail also in HTTP request, therefore,
* fallback to HTTPS to keep connection secure.
*
* @since 1.1.6
*/
self::$_options->set_option( 'api_force_http', false, true );
}
}
self::$_cache->set( $cache_key, $test, WP_FS__TIME_5_MIN_IN_SEC );
}
return $test;
}
/**
* Check if API is temporary down.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @return bool
*/
static function is_temporary_down() {
self::_init();
$test = self::$_cache->get_valid( 'ping_test', null );
return ( false === $test );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @return object
*/
private function get_temporary_unavailable_error() {
return (object) array(
'error' => (object) array(
'type' => 'TemporaryUnavailable',
'message' => 'API is temporary unavailable, please retry in ' . ( self::$_cache->get_record_expiration( 'ping_test' ) - WP_FS__SCRIPT_START_TIME ) . ' sec.',
'code' => 'temporary_unavailable',
'http' => 503
)
);
}
/**
* Ping API for connectivity test, and return result object.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param null|string $unique_anonymous_id
* @param array $params
*
* @return object
*/
function ping( $unique_anonymous_id = null, $params = array() ) {
$this->_logger->entrance();
if ( self::is_temporary_down() ) {
return $this->get_temporary_unavailable_error();
}
$pong = is_null( $unique_anonymous_id ) ?
Freemius_Api_WordPress::Ping() :
$this->_call( 'ping.json?' . http_build_query( array_merge(
array( 'uid' => $unique_anonymous_id ),
$params
) ) );
if ( $this->is_valid_ping( $pong ) ) {
return $pong;
}
if ( self::should_try_with_http( $pong ) ) {
// Fallback to HTTP, since HTTPS fails.
Freemius_Api_WordPress::SetHttp();
self::$_options->set_option( 'api_force_http', true, true );
$pong = is_null( $unique_anonymous_id ) ?
Freemius_Api_WordPress::Ping() :
$this->_call( 'ping.json?' . http_build_query( array_merge(
array( 'uid' => $unique_anonymous_id ),
$params
) ) );
if ( ! $this->is_valid_ping( $pong ) ) {
self::$_options->set_option( 'api_force_http', false, true );
}
}
return $pong;
}
/**
* Check if based on the API result we should try
* to re-run the same request with HTTP instead of HTTPS.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param $result
*
* @return bool
*/
private static function should_try_with_http( $result ) {
if ( ! Freemius_Api_WordPress::IsHttps() ) {
return false;
}
return ( ! is_object( $result ) ||
! isset( $result->error ) ||
! isset( $result->error->code ) ||
! in_array( $result->error->code, array(
'curl_missing',
'cloudflare_ddos_protection',
'maintenance_mode',
'squid_cache_block',
'too_many_requests',
) ) );
}
/**
* Check if valid ping request result.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.1
*
* @param mixed $pong
*
* @return bool
*/
function is_valid_ping( $pong ) {
return Freemius_Api_WordPress::Test( $pong );
}
function get_url( $path = '' ) {
return Freemius_Api_WordPress::GetUrl( $path, $this->_api->IsSandbox() );
}
/**
* Clear API cache.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*/
static function clear_cache() {
self::_init();
self::$_cache = FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME );
self::$_cache->clear();
}
#----------------------------------------------------------------------------------
#region Error Handling
#----------------------------------------------------------------------------------
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @param mixed $result
*
* @return bool Is API result contains an error.
*/
static function is_api_error( $result ) {
return ( is_object( $result ) && isset( $result->error ) ) ||
is_string( $result );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param mixed $result
*
* @return bool Is API result contains an error.
*/
static function is_api_error_object( $result ) {
return (
is_object( $result ) &&
isset( $result->error ) &&
isset( $result->error->message )
);
}
/**
* Checks if given API result is a non-empty and not an error object.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @param mixed $result
* @param string|null $required_property Optional property we want to verify that is set.
*
* @return bool
*/
static function is_api_result_object( $result, $required_property = null ) {
return (
is_object( $result ) &&
! isset( $result->error ) &&
( empty( $required_property ) || isset( $result->{$required_property} ) )
);
}
/**
* Checks if given API result is a non-empty entity object with non-empty ID.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @param mixed $result
*
* @return bool
*/
static function is_api_result_entity( $result ) {
return self::is_api_result_object( $result, 'id' ) &&
FS_Entity::is_valid_id( $result->id );
}
/**
* Get API result error code. If failed to get code, returns an empty string.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param mixed $result
*
* @return string
*/
static function get_error_code( $result ) {
if ( is_object( $result ) &&
isset( $result->error ) &&
is_object( $result->error ) &&
! empty( $result->error->code )
) {
return $result->error->code;
}
return '';
}
#endregion
}

View File

@ -0,0 +1,691 @@
<?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;
}
class FS_Logger {
private $_id;
private $_on = false;
private $_echo = false;
private $_file_start = 0;
/**
* @var int PHP Process ID.
*/
private static $_processID;
/**
* @var string PHP Script user name.
*/
private static $_ownerName;
/**
* @var bool Is storage logging turned on.
*/
private static $_isStorageLoggingOn;
/**
* @var int ABSPATH length.
*/
private static $_abspathLength;
private static $LOGGERS = array();
private static $LOG = array();
private static $CNT = 0;
private static $_HOOKED_FOOTER = false;
private function __construct( $id, $on = false, $echo = false ) {
$this->_id = $id;
$bt = debug_backtrace();
$caller = $bt[2];
if ( false !== strpos( $caller['file'], 'plugins' ) ) {
$this->_file_start = strpos( $caller['file'], 'plugins' ) + strlen( 'plugins/' );
} else {
$this->_file_start = strpos( $caller['file'], 'themes' ) + strlen( 'themes/' );
}
if ( $on ) {
$this->on();
}
if ( $echo ) {
$this->echo_on();
}
}
/**
* @param string $id
* @param bool $on
* @param bool $echo
*
* @return FS_Logger
*/
public static function get_logger( $id, $on = false, $echo = false ) {
$id = strtolower( $id );
if ( ! isset( self::$_processID ) ) {
self::init();
}
if ( ! isset( self::$LOGGERS[ $id ] ) ) {
self::$LOGGERS[ $id ] = new FS_Logger( $id, $on, $echo );
}
return self::$LOGGERS[ $id ];
}
/**
* Initialize logging global info.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*/
private static function init() {
self::$_ownerName = function_exists( 'get_current_user' ) ?
get_current_user() :
'unknown';
self::$_isStorageLoggingOn = ( 1 == get_option( 'fs_storage_logger', 0 ) );
self::$_abspathLength = strlen( ABSPATH );
self::$_processID = mt_rand( 0, 32000 );
// Process ID may be `false` on errors.
if ( ! is_numeric( self::$_processID ) ) {
self::$_processID = 0;
}
}
private static function hook_footer() {
if ( self::$_HOOKED_FOOTER ) {
return;
}
if ( is_admin() ) {
add_action( 'admin_footer', 'FS_Logger::dump', 100 );
} else {
add_action( 'wp_footer', 'FS_Logger::dump', 100 );
}
}
function is_on() {
return $this->_on;
}
function on() {
$this->_on = true;
if ( ! function_exists( 'dbDelta' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
self::hook_footer();
}
function echo_on() {
$this->on();
$this->_echo = true;
}
function is_echo_on() {
return $this->_echo;
}
function get_id() {
return $this->_id;
}
function get_file() {
return $this->_file_start;
}
private function _log( &$message, $type, $wrapper = false ) {
if ( ! $this->is_on() ) {
return;
}
$bt = debug_backtrace();
$depth = $wrapper ? 3 : 2;
while ( $depth < count( $bt ) - 1 && 'eval' === $bt[ $depth ]['function'] ) {
$depth ++;
}
$caller = $bt[ $depth ];
/**
* Retrieve the correct call file & line number from backtrace
* when logging from a wrapper method.
*
* @author Vova Feldman
* @since 1.2.1.6
*/
if ( empty( $caller['line'] ) ) {
$depth --;
while ( $depth >= 0 ) {
if ( ! empty( $bt[ $depth ]['line'] ) ) {
$caller['line'] = $bt[ $depth ]['line'];
$caller['file'] = $bt[ $depth ]['file'];
break;
}
}
}
$log = array_merge( $caller, array(
'cnt' => self::$CNT ++,
'logger' => $this,
'timestamp' => microtime( true ),
'log_type' => $type,
'msg' => $message,
) );
if ( self::$_isStorageLoggingOn ) {
$this->db_log( $type, $message, self::$CNT, $caller );
}
self::$LOG[] = $log;
if ( $this->is_echo_on() && ! Freemius::is_ajax() ) {
echo self::format_html( $log ) . "\n";
}
}
function log( $message, $wrapper = false ) {
$this->_log( $message, 'log', $wrapper );
}
function info( $message, $wrapper = false ) {
$this->_log( $message, 'info', $wrapper );
}
function warn( $message, $wrapper = false ) {
$this->_log( $message, 'warn', $wrapper );
}
function error( $message, $wrapper = false ) {
$this->_log( $message, 'error', $wrapper );
}
/**
* Log API error.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.5
*
* @param mixed $api_result
* @param bool $wrapper
*/
function api_error( $api_result, $wrapper = false ) {
$message = '';
if ( is_object( $api_result ) &&
! empty( $api_result->error ) &&
! empty( $api_result->error->message )
) {
$message = $api_result->error->message;
} else if ( is_object( $api_result ) ) {
$message = var_export( $api_result, true );
} else if ( is_string( $api_result ) ) {
$message = $api_result;
} else if ( empty( $api_result ) ) {
$message = 'Empty API result.';
}
$message = 'API Error: ' . $message;
$this->_log( $message, 'error', $wrapper );
}
function entrance( $message = '', $wrapper = false ) {
$msg = 'Entrance' . ( empty( $message ) ? '' : ' > ' ) . $message;
$this->_log( $msg, 'log', $wrapper );
}
function departure( $message = '', $wrapper = false ) {
$msg = 'Departure' . ( empty( $message ) ? '' : ' > ' ) . $message;
$this->_log( $msg, 'log', $wrapper );
}
#--------------------------------------------------------------------------------
#region Log Formatting
#--------------------------------------------------------------------------------
private static function format( $log, $show_type = true ) {
return '[' . str_pad( $log['cnt'], strlen( self::$CNT ), '0', STR_PAD_LEFT ) . '] [' . $log['logger']->_id . '] ' . ( $show_type ? '[' . $log['log_type'] . ']' : '' ) . ( ! empty( $log['class'] ) ? $log['class'] . $log['type'] : '' ) . $log['function'] . ' >> ' . $log['msg'] . ( isset( $log['file'] ) ? ' (' . substr( $log['file'], $log['logger']->_file_start ) . ' ' . $log['line'] . ') ' : '' ) . ' [' . $log['timestamp'] . ']';
}
private static function format_html( $log ) {
return '<div style="font-size: 13px; font-family: monospace; color: #7da767; padding: 8px 3px; background: #000; border-bottom: 1px solid #555;">[' . $log['cnt'] . '] [' . $log['logger']->_id . '] [' . $log['log_type'] . '] <b><code style="color: #c4b1e0;">' . ( ! empty( $log['class'] ) ? $log['class'] . $log['type'] : '' ) . $log['function'] . '</code> >> <b style="color: #f59330;">' . esc_html( $log['msg'] ) . '</b></b>' . ( isset( $log['file'] ) ? ' (' . substr( $log['file'], $log['logger']->_file_start ) . ' ' . $log['line'] . ')' : '' ) . ' [' . $log['timestamp'] . ']</div>';
}
#endregion
static function dump() {
?>
<!-- BEGIN: Freemius PHP Console Log -->
<script type="text/javascript">
<?php
foreach ( self::$LOG as $log ) {
echo 'console.' . $log['log_type'] . '(' . json_encode( self::format( $log, false ) ) . ')' . "\n";
}
?>
</script>
<!-- END: Freemius PHP Console Log -->
<?php
}
static function get_log() {
return self::$LOG;
}
#--------------------------------------------------------------------------------
#region Database Logging
#--------------------------------------------------------------------------------
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @return bool
*/
public static function is_storage_logging_on() {
if ( ! isset( self::$_isStorageLoggingOn ) ) {
self::$_isStorageLoggingOn = ( 1 == get_option( 'fs_storage_logger', 0 ) );
}
return self::$_isStorageLoggingOn;
}
/**
* Turns on/off database persistent debugging to capture
* multi-session logs to debug complex flows like
* plugin auto-deactivate on premium version activation.
*
* @todo Check if Theme Check has issues with DB tables for themes.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param bool $is_on
*
* @return bool
*/
public static function _set_storage_logging( $is_on = true ) {
global $wpdb;
$table = "{$wpdb->prefix}fs_logger";
if ( $is_on ) {
/**
* Create logging table.
*
* NOTE:
* dbDelta must use KEY and not INDEX for indexes.
*
* @link https://core.trac.wordpress.org/ticket/2695
*/
$result = $wpdb->query( "CREATE TABLE {$table} (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`process_id` INT UNSIGNED NOT NULL,
`user_name` VARCHAR(64) NOT NULL,
`logger` VARCHAR(128) NOT NULL,
`log_order` INT UNSIGNED NOT NULL,
`type` ENUM('log','info','warn','error') NOT NULL DEFAULT 'log',
`message` TEXT NOT NULL,
`file` VARCHAR(256) NOT NULL,
`line` INT UNSIGNED NOT NULL,
`function` VARCHAR(256) NOT NULL,
`request_type` ENUM('call','ajax','cron') NOT NULL DEFAULT 'call',
`request_url` VARCHAR(1024) NOT NULL,
`created` DECIMAL(16, 6) NOT NULL,
PRIMARY KEY (`id`),
KEY `process_id` (`process_id` ASC),
KEY `process_logger` (`process_id` ASC, `logger` ASC),
KEY `function` (`function` ASC),
KEY `type` (`type` ASC))" );
} else {
/**
* Drop logging table.
*/
$result = $wpdb->query( "DROP TABLE IF EXISTS $table;" );
}
if ( false !== $result ) {
update_option( 'fs_storage_logger', ( $is_on ? 1 : 0 ) );
}
return ( false !== $result );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param string $type
* @param string $message
* @param int $log_order
* @param array $caller
*
* @return false|int
*/
private function db_log(
&$type,
&$message,
&$log_order,
&$caller
) {
global $wpdb;
$request_type = 'call';
if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
$request_type = 'cron';
} else if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
$request_type = 'ajax';
}
$request_url = WP_FS__IS_HTTP_REQUEST ?
$_SERVER['REQUEST_URI'] :
'';
return $wpdb->insert(
"{$wpdb->prefix}fs_logger",
array(
'process_id' => self::$_processID,
'user_name' => self::$_ownerName,
'logger' => $this->_id,
'log_order' => $log_order,
'type' => $type,
'request_type' => $request_type,
'request_url' => $request_url,
'message' => $message,
'file' => isset( $caller['file'] ) ?
substr( $caller['file'], self::$_abspathLength ) :
'',
'line' => $caller['line'],
'function' => ( ! empty( $caller['class'] ) ? $caller['class'] . $caller['type'] : '' ) . $caller['function'],
'created' => microtime( true ),
)
);
}
/**
* Persistent DB logger columns.
*
* @var array
*/
private static $_log_columns = array(
'id',
'process_id',
'user_name',
'logger',
'log_order',
'type',
'message',
'file',
'line',
'function',
'request_type',
'request_url',
'created',
);
/**
* Create DB logs query.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param bool $filters
* @param int $limit
* @param int $offset
* @param bool $order
* @param bool $escape_eol
*
* @return string
*/
private static function build_db_logs_query(
$filters = false,
$limit = 200,
$offset = 0,
$order = false,
$escape_eol = false
) {
global $wpdb;
$select = '*';
if ( $escape_eol ) {
$select = '';
for ( $i = 0, $len = count( self::$_log_columns ); $i < $len; $i ++ ) {
if ( $i > 0 ) {
$select .= ', ';
}
if ( 'message' !== self::$_log_columns[ $i ] ) {
$select .= self::$_log_columns[ $i ];
} else {
$select .= 'REPLACE(message , \'\n\', \' \') AS message';
}
}
}
$query = "SELECT {$select} FROM {$wpdb->prefix}fs_logger";
if ( is_array( $filters ) ) {
$criteria = array();
if ( ! empty( $filters['type'] ) && 'all' !== $filters['type'] ) {
$filters['type'] = strtolower( $filters['type'] );
switch ( $filters['type'] ) {
case 'warn_error':
$criteria[] = array( 'col' => 'type', 'val' => array( 'warn', 'error' ) );
break;
case 'error':
case 'warn':
$criteria[] = array( 'col' => 'type', 'val' => $filters['type'] );
break;
case 'info':
default:
$criteria[] = array( 'col' => 'type', 'val' => array( 'info', 'log' ) );
break;
}
}
if ( ! empty( $filters['request_type'] ) ) {
$filters['request_type'] = strtolower( $filters['request_type'] );
if ( in_array( $filters['request_type'], array( 'call', 'ajax', 'cron' ) ) ) {
$criteria[] = array( 'col' => 'request_type', 'val' => $filters['request_type'] );
}
}
if ( ! empty( $filters['file'] ) ) {
$criteria[] = array(
'col' => 'file',
'op' => 'LIKE',
'val' => '%' . esc_sql( $filters['file'] ),
);
}
if ( ! empty( $filters['function'] ) ) {
$criteria[] = array(
'col' => 'function',
'op' => 'LIKE',
'val' => '%' . esc_sql( $filters['function'] ),
);
}
if ( ! empty( $filters['process_id'] ) && is_numeric( $filters['process_id'] ) ) {
$criteria[] = array( 'col' => 'process_id', 'val' => $filters['process_id'] );
}
if ( ! empty( $filters['logger'] ) ) {
$criteria[] = array(
'col' => 'logger',
'op' => 'LIKE',
'val' => '%' . esc_sql( $filters['logger'] ) . '%',
);
}
if ( ! empty( $filters['message'] ) ) {
$criteria[] = array(
'col' => 'message',
'op' => 'LIKE',
'val' => '%' . esc_sql( $filters['message'] ) . '%',
);
}
if ( 0 < count( $criteria ) ) {
$query .= "\nWHERE\n";
$first = true;
foreach ( $criteria as $c ) {
if ( ! $first ) {
$query .= "AND\n";
}
if ( is_array( $c['val'] ) ) {
$operator = 'IN';
for ( $i = 0, $len = count( $c['val'] ); $i < $len; $i ++ ) {
$c['val'][ $i ] = "'" . esc_sql( $c['val'][ $i ] ) . "'";
}
$val = '(' . implode( ',', $c['val'] ) . ')';
} else {
$operator = ! empty( $c['op'] ) ? $c['op'] : '=';
$val = "'" . esc_sql( $c['val'] ) . "'";
}
$query .= "`{$c['col']}` {$operator} {$val}\n";
$first = false;
}
}
}
if ( ! is_array( $order ) ) {
$order = array(
'col' => 'id',
'order' => 'desc'
);
}
$query .= " ORDER BY {$order['col']} {$order['order']} LIMIT {$offset},{$limit}";
return $query;
}
/**
* Load logs from DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param bool $filters
* @param int $limit
* @param int $offset
* @param bool $order
*
* @return object[]|null
*/
public static function load_db_logs(
$filters = false,
$limit = 200,
$offset = 0,
$order = false
) {
global $wpdb;
$query = self::build_db_logs_query(
$filters,
$limit,
$offset,
$order
);
return $wpdb->get_results( $query );
}
/**
* Load logs from DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param bool $filters
* @param string $filename
* @param int $limit
* @param int $offset
* @param bool $order
*
* @return false|string File download URL or false on failure.
*/
public static function download_db_logs(
$filters = false,
$filename = '',
$limit = 10000,
$offset = 0,
$order = false
) {
global $wpdb;
$query = self::build_db_logs_query(
$filters,
$limit,
$offset,
$order,
true
);
$upload_dir = wp_upload_dir();
if ( empty( $filename ) ) {
$filename = 'fs-logs-' . date( 'Y-m-d_H-i-s', WP_FS__SCRIPT_START_TIME ) . '.csv';
}
$filepath = rtrim( $upload_dir['path'], '/' ) . "/{$filename}";
$query .= " INTO OUTFILE '{$filepath}' FIELDS TERMINATED BY '\t' ESCAPED BY '\\\\' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n'";
$columns = '';
for ( $i = 0, $len = count( self::$_log_columns ); $i < $len; $i ++ ) {
if ( $i > 0 ) {
$columns .= ', ';
}
$columns .= "'" . self::$_log_columns[ $i ] . "'";
}
$query = "SELECT {$columns} UNION ALL " . $query;
$result = $wpdb->query( $query );
if ( false === $result ) {
return false;
}
return rtrim( $upload_dir['url'], '/' ) . '/' . $filename;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.1.6
*
* @param string $filename
*
* @return string
*/
public static function get_logs_download_url( $filename = '' ) {
$upload_dir = wp_upload_dir();
if ( empty( $filename ) ) {
$filename = 'fs-logs-' . date( 'Y-m-d_H-i-s', WP_FS__SCRIPT_START_TIME ) . '.csv';
}
return rtrim( $upload_dir['url'], '/' ) . $filename;
}
#endregion
}

View File

@ -0,0 +1,431 @@
<?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.2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Options
*
* A wrapper class for handling network level and single site level options.
*/
class FS_Options {
/**
* @var string
*/
private $_id;
/**
* @var array[string]FS_Options {
* @key string
* @value FS_Options
* }
*/
private static $_instances;
/**
* @var FS_Option_Manager Site level options.
*/
private $_options;
/**
* @var FS_Option_Manager Network level options.
*/
private $_network_options;
/**
* @var int The ID of the blog that is associated with the current site level options.
*/
private $_blog_id = 0;
/**
* @var bool
*/
private $_is_multisite;
/**
* @var string[] Lazy collection of params on the site level.
*/
private static $_SITE_OPTIONS_MAP;
/**
* @author Leo Fajardo (@leorw)
* @since 2.0.0
*
* @param string $id
* @param bool $load
*
* @return FS_Options
*/
static function instance( $id, $load = false ) {
if ( ! isset( self::$_instances[ $id ] ) ) {
self::$_instances[ $id ] = new FS_Options( $id, $load );
}
return self::$_instances[ $id ];
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.0.0
*
* @param string $id
* @param bool $load
*/
private function __construct( $id, $load = false ) {
$this->_id = $id;
$this->_is_multisite = is_multisite();
if ( $this->_is_multisite ) {
$this->_blog_id = get_current_blog_id();
$this->_network_options = FS_Option_Manager::get_manager( $id, $load, true );
}
$this->_options = FS_Option_Manager::get_manager( $id, $load, $this->_blog_id );
}
/**
* Switch the context of the site level options manager.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param $blog_id
*/
function set_site_blog_context( $blog_id ) {
$this->_blog_id = $blog_id;
$this->_options = FS_Option_Manager::get_manager( $this->_id, false, $this->_blog_id );
}
/**
* @author Leo Fajardo (@leorw)
*
* @param string $option
* @param mixed $default
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_SITE_LEVEL_PARAMS).
*
* @return mixed
*/
function get_option( $option, $default = null, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_storage( $option, $network_level_or_blog_id ) ) {
return $this->_network_options->get_option( $option, $default );
}
$site_options = $this->get_site_options( $network_level_or_blog_id );
return $site_options->get_option( $option, $default );
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.0.0
*
* @param string $option
* @param mixed $value
* @param bool $flush
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_SITE_LEVEL_PARAMS).
*/
function set_option( $option, $value, $flush = false, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_storage( $option, $network_level_or_blog_id ) ) {
$this->_network_options->set_option( $option, $value, $flush );
} else {
$site_options = $this->get_site_options( $network_level_or_blog_id );
$site_options->set_option( $option, $value, $flush );
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $option
* @param bool $flush
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_SITE_LEVEL_PARAMS).
*/
function unset_option( $option, $flush = false, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_storage( $option, $network_level_or_blog_id ) ) {
$this->_network_options->unset_option( $option, $flush );
} else {
$site_options = $this->get_site_options( $network_level_or_blog_id );
$site_options->unset_option( $option, $flush );
}
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.0.0
*
* @param bool $flush
* @param bool $network_level
*/
function load( $flush = false, $network_level = true ) {
if ( $this->_is_multisite && $network_level ) {
$this->_network_options->load( $flush );
} else {
$this->_options->load( $flush );
}
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.0.0
*
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, store both network storage and the current context blog storage.
*/
function store( $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ||
false === $network_level_or_blog_id ||
0 == $network_level_or_blog_id ||
is_null( $network_level_or_blog_id )
) {
$site_options = $this->get_site_options( $network_level_or_blog_id );
$site_options->store();
}
if ( $this->_is_multisite &&
( is_null( $network_level_or_blog_id ) || true === $network_level_or_blog_id )
) {
$this->_network_options->store();
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int|null|bool $network_level_or_blog_id
* @param bool $flush
*/
function clear( $network_level_or_blog_id = null, $flush = false ) {
if ( ! $this->_is_multisite ||
false === $network_level_or_blog_id ||
is_null( $network_level_or_blog_id ) ||
is_numeric( $network_level_or_blog_id )
) {
$site_options = $this->get_site_options( $network_level_or_blog_id );
$site_options->clear( $flush );
}
if ( $this->_is_multisite &&
( true === $network_level_or_blog_id || is_null( $network_level_or_blog_id ) )
) {
$this->_network_options->clear( $flush );
}
}
/**
* Migration script to the new storage data structure that is network compatible.
*
* IMPORTANT:
* This method should be executed only after it is determined if this is a network
* level compatible product activation.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $blog_id
*/
function migrate_to_network( $blog_id = 0 ) {
if ( ! $this->_is_multisite ) {
return;
}
$updated = false;
$site_options = $this->get_site_options( $blog_id );
$keys = $site_options->get_options_keys();
foreach ( $keys as $option ) {
if ( $this->is_site_option( $option ) ||
// Don't move admin notices to the network storage.
in_array($option, array(
// Don't move admin notices to the network storage.
'admin_notices',
// Don't migrate the module specific data, it will be migrated by the FS_Storage.
'plugin_data',
'theme_data',
))
) {
continue;
}
$option_updated = false;
// Migrate option to the network storage.
$site_option = $site_options->get_option( $option );
if ( ! $this->_network_options->has_option( $option ) ) {
// Option not set on the network level, so just set it.
$this->_network_options->set_option( $option, $site_option, false );
$option_updated = true;
} else {
// Option already set on the network level, so we need to merge it inelegantly.
$network_option = $this->_network_options->get_option( $option );
if ( is_array( $network_option ) && is_array( $site_option ) ) {
// Option is an array.
foreach ( $site_option as $key => $value ) {
if ( ! isset( $network_option[ $key ] ) ) {
$network_option[ $key ] = $value;
$option_updated = true;
} else if ( is_array( $network_option[ $key ] ) && is_array( $value ) ) {
if ( empty( $network_option[ $key ] ) ) {
$network_option[ $key ] = $value;
$option_updated = true;
} else if ( empty( $value ) ) {
// Do nothing.
} else {
reset($value);
$first_key = key($value);
if ( $value[$first_key] instanceof FS_Entity ) {
// Merge entities by IDs.
$network_entities_ids = array();
foreach ( $network_option[ $key ] as $entity ) {
$network_entities_ids[ $entity->id ] = true;
}
foreach ( $value as $entity ) {
if ( ! isset( $network_entities_ids[ $entity->id ] ) ) {
$network_option[ $key ][] = $entity;
$option_updated = true;
}
}
}
}
}
}
}
if ( $option_updated ) {
$this->_network_options->set_option( $option, $network_option, false );
}
}
/**
* Remove the option from site level storage.
*
* IMPORTANT:
* The line below is intentionally commented since we want to preserve the option
* on the site storage level for "downgrade compatibility". Basically, if the user
* will downgrade to an older version of the plugin with the prev storage structure,
* it will continue working.
*
* @todo After a few releases we can remove this.
*/
// $site_options->unset_option($option, false);
if ( $option_updated ) {
$updated = true;
}
}
if ( ! $updated ) {
return;
}
// Update network level storage.
$this->_network_options->store();
// $site_options->store();
}
#--------------------------------------------------------------------------------
#region Helper Methods
#--------------------------------------------------------------------------------
/**
* We don't want to load the map right away since it's not even needed in a non-MS environment.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
private static function load_site_options_map() {
self::$_SITE_OPTIONS_MAP = array(
'sites' => true,
'theme_sites' => true,
'unique_id' => true,
'active_plugins' => true,
);
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $option
*
* @return bool
*/
private function is_site_option( $option ) {
if ( WP_FS__ACCOUNTS_OPTION_NAME != $this->_id ) {
return false;
}
if ( ! isset( self::$_SITE_OPTIONS_MAP ) ) {
self::load_site_options_map();
}
return isset( self::$_SITE_OPTIONS_MAP[ $option ] );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $blog_id
*
* @return FS_Option_Manager
*/
private function get_site_options( $blog_id = 0 ) {
if ( 0 == $blog_id || $blog_id == $this->_blog_id ) {
return $this->_options;
}
return FS_Option_Manager::get_manager( $this->_id, true, $blog_id );
}
/**
* Check if an option should be stored on the MS network storage.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $option
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_SITE_LEVEL_PARAMS).
*
* @return bool
*/
private function should_use_network_storage( $option, $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ) {
// Not a multisite environment.
return false;
}
if ( is_numeric( $network_level_or_blog_id ) ) {
// Explicitly asked to use a specified blog storage.
return false;
}
if ( is_bool( $network_level_or_blog_id ) ) {
// Explicitly specified whether should use the network or blog level storage.
return $network_level_or_blog_id;
}
// Determine which storage to use based on the option.
return ! $this->is_site_option( $option );
}
#endregion
}

View File

@ -0,0 +1,85 @@
<?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;
}
define( 'WP_FS__SECURITY_PARAMS_PREFIX', 's_' );
/**
* Class FS_Security
*/
class FS_Security {
/**
* @var FS_Security
* @since 1.0.3
*/
private static $_instance;
/**
* @var FS_Logger
* @since 1.0.3
*/
private static $_logger;
/**
* @return \FS_Security
*/
public static function instance() {
if ( ! isset( self::$_instance ) ) {
self::$_instance = new FS_Security();
self::$_logger = FS_Logger::get_logger(
WP_FS__SLUG,
WP_FS__DEBUG_SDK,
WP_FS__ECHO_DEBUG_SDK
);
}
return self::$_instance;
}
private function __construct() {
}
/**
* @param \FS_Scope_Entity $entity
* @param int $timestamp
* @param string $action
*
* @return string
*/
function get_secure_token( FS_Scope_Entity $entity, $timestamp, $action = '' ) {
return md5(
$timestamp .
$entity->id .
$entity->secret_key .
$entity->public_key .
$action
);
}
/**
* @param \FS_Scope_Entity $entity
* @param int|bool $timestamp
* @param string $action
*
* @return array
*/
function get_context_params( FS_Scope_Entity $entity, $timestamp = false, $action = '' ) {
if ( false === $timestamp ) {
$timestamp = time();
}
return array(
's_ctx_type' => $entity->get_type(),
's_ctx_id' => $entity->id,
's_ctx_ts' => $timestamp,
's_ctx_secure' => $this->get_secure_token( $entity, $timestamp, $action ),
);
}
}

View File

@ -0,0 +1,532 @@
<?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.2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Storage
*
* A wrapper class for handling network level and single site level storage.
*
* @property bool $is_network_activation
* @property int $network_install_blog_id
* @property object $sync_cron
*/
class FS_Storage {
/**
* @var FS_Storage[]
*/
private static $_instances = array();
/**
* @var FS_Key_Value_Storage Site level storage.
*/
private $_storage;
/**
* @var FS_Key_Value_Storage Network level storage.
*/
private $_network_storage;
/**
* @var string
*/
private $_module_type;
/**
* @var string
*/
private $_module_slug;
/**
* @var int The ID of the blog that is associated with the current site level options.
*/
private $_blog_id = 0;
/**
* @var bool
*/
private $_is_multisite;
/**
* @var bool
*/
private $_is_network_active = false;
/**
* @var bool
*/
private $_is_delegated_connection = false;
/**
* @var array {
* @key string Option name.
* @value int If 0 store on the network level. If 1, store on the network level only if module was network level activated. If 2, store on the network level only if network activated and NOT delegated the connection.
* }
*/
private static $_NETWORK_OPTIONS_MAP;
/**
* @author Leo Fajardo (@leorw)
*
* @param string $module_type
* @param string $slug
*
* @return FS_Storage
*/
static function instance( $module_type, $slug ) {
$key = $module_type . ':' . $slug;
if ( ! isset( self::$_instances[ $key ] ) ) {
self::$_instances[ $key ] = new FS_Storage( $module_type, $slug );
}
return self::$_instances[ $key ];
}
/**
* @author Leo Fajardo (@leorw)
*
* @param string $module_type
* @param string $slug
*/
private function __construct( $module_type, $slug ) {
$this->_module_type = $module_type;
$this->_module_slug = $slug;
$this->_is_multisite = is_multisite();
if ( $this->_is_multisite ) {
$this->_blog_id = get_current_blog_id();
$this->_network_storage = FS_Key_Value_Storage::instance( $module_type . '_data', $slug, true );
}
$this->_storage = FS_Key_Value_Storage::instance( $module_type . '_data', $slug, $this->_blog_id );
}
/**
* Tells this storage wrapper class that the context plugin is network active. This flag will affect how values
* are retrieved/stored from/into the storage.
*
* @author Leo Fajardo (@leorw)
*
* @param bool $is_network_active
* @param bool $is_delegated_connection
*/
function set_network_active( $is_network_active = true, $is_delegated_connection = false ) {
$this->_is_network_active = $is_network_active;
$this->_is_delegated_connection = $is_delegated_connection;
}
/**
* Switch the context of the site level storage manager.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $blog_id
*/
function set_site_blog_context( $blog_id ) {
$this->_storage = $this->get_site_storage( $blog_id );
$this->_blog_id = $blog_id;
}
/**
* @author Leo Fajardo (@leorw)
*
* @param string $key
* @param mixed $value
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_BINARY_MAP).
* @param bool $flush
*/
function store( $key, $value, $network_level_or_blog_id = null, $flush = true ) {
if ( $this->should_use_network_storage( $key, $network_level_or_blog_id ) ) {
$this->_network_storage->store( $key, $value, $flush );
} else {
$storage = $this->get_site_storage( $network_level_or_blog_id );
$storage->store( $key, $value, $flush );
}
}
/**
* @author Leo Fajardo (@leorw)
*
* @param bool $store
* @param string[] $exceptions Set of keys to keep and not clear.
* @param int|null|bool $network_level_or_blog_id
*/
function clear_all( $store = true, $exceptions = array(), $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ||
false === $network_level_or_blog_id ||
is_null( $network_level_or_blog_id ) ||
is_numeric( $network_level_or_blog_id )
) {
$storage = $this->get_site_storage( $network_level_or_blog_id );
$storage->clear_all( $store, $exceptions );
}
if ( $this->_is_multisite &&
( true === $network_level_or_blog_id || is_null( $network_level_or_blog_id ) )
) {
$this->_network_storage->clear_all( $store, $exceptions );
}
}
/**
* @author Leo Fajardo (@leorw)
*
* @param string $key
* @param bool $store
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_BINARY_MAP).
*/
function remove( $key, $store = true, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_storage( $key, $network_level_or_blog_id ) ) {
$this->_network_storage->remove( $key, $store );
} else {
$storage = $this->get_site_storage( $network_level_or_blog_id );
$storage->remove( $key, $store );
}
}
/**
* @author Leo Fajardo (@leorw)
*
* @param string $key
* @param mixed $default
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_BINARY_MAP).
*
* @return mixed
*/
function get( $key, $default = false, $network_level_or_blog_id = null ) {
if ( $this->should_use_network_storage( $key, $network_level_or_blog_id ) ) {
return $this->_network_storage->get( $key, $default );
} else {
$storage = $this->get_site_storage( $network_level_or_blog_id );
return $storage->get( $key, $default );
}
}
/**
* Multisite activated:
* true: Save network storage.
* int: Save site specific storage.
* false|0: Save current site storage.
* null: Save network and current site storage.
* Site level activated:
* Save site storage.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param bool|int|null $network_level_or_blog_id
*/
function save( $network_level_or_blog_id = null ) {
if ( $this->_is_network_active &&
( true === $network_level_or_blog_id || is_null( $network_level_or_blog_id ) )
) {
$this->_network_storage->save();
}
if ( ! $this->_is_network_active || true !== $network_level_or_blog_id ) {
$storage = $this->get_site_storage( $network_level_or_blog_id );
$storage->save();
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return string
*/
function get_module_slug() {
return $this->_module_slug;
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return string
*/
function get_module_type() {
return $this->_module_type;
}
/**
* Migration script to the new storage data structure that is network compatible.
*
* IMPORTANT:
* This method should be executed only after it is determined if this is a network
* level compatible product activation.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
function migrate_to_network() {
if ( ! $this->_is_multisite ) {
return;
}
$updated = false;
if ( ! isset( self::$_NETWORK_OPTIONS_MAP ) ) {
self::load_network_options_map();
}
foreach ( self::$_NETWORK_OPTIONS_MAP as $option => $storage_level ) {
if ( ! $this->is_multisite_option( $option ) ) {
continue;
}
if ( isset( $this->_storage->{$option} ) && ! isset( $this->_network_storage->{$option} ) ) {
// Migrate option to the network storage.
$this->_network_storage->store( $option, $this->_storage->{$option}, false );
/**
* Remove the option from site level storage.
*
* IMPORTANT:
* The line below is intentionally commented since we want to preserve the option
* on the site storage level for "downgrade compatibility". Basically, if the user
* will downgrade to an older version of the plugin with the prev storage structure,
* it will continue working.
*
* @todo After a few releases we can remove this.
*/
// $this->_storage->remove($option, false);
$updated = true;
}
}
if ( ! $updated ) {
return;
}
// Update network level storage.
$this->_network_storage->save();
// $this->_storage->save();
}
#--------------------------------------------------------------------------------
#region Helper Methods
#--------------------------------------------------------------------------------
/**
* We don't want to load the map right away since it's not even needed in a non-MS environment.
*
* Example:
* array(
* 'option1' => 0, // Means that the option should always be stored on the network level.
* 'option2' => 1, // Means that the option should be stored on the network level only when the module was network level activated.
* 'option2' => 2, // Means that the option should be stored on the network level only when the module was network level activated AND the connection was NOT delegated.
* 'option3' => 3, // Means that the option should always be stored on the site level.
* )
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
private static function load_network_options_map() {
self::$_NETWORK_OPTIONS_MAP = array(
// Network level options.
'affiliate_application_data' => 0,
'beta_data' => 0,
'connectivity_test' => 0,
'handle_gdpr_admin_notice' => 0,
'has_trial_plan' => 0,
'install_sync_timestamp' => 0,
'install_sync_cron' => 0,
'is_anonymous_ms' => 0,
'is_network_activated' => 0,
'is_on' => 0,
'is_plugin_new_install' => 0,
'network_install_blog_id' => 0,
'pending_sites_info' => 0,
'plugin_last_version' => 0,
'plugin_main_file' => 0,
'plugin_version' => 0,
'sdk_downgrade_mode' => 0,
'sdk_last_version' => 0,
'sdk_upgrade_mode' => 0,
'sdk_version' => 0,
'sticky_optin_added_ms' => 0,
'subscriptions' => 0,
'sync_timestamp' => 0,
'sync_cron' => 0,
'was_plugin_loaded' => 0,
'network_user_id' => 0,
'plugin_upgrade_mode' => 0,
'plugin_downgrade_mode' => 0,
'is_network_connected' => 0,
/**
* Special flag that is used when a super-admin upgrades to the new version of the SDK that
* supports network level integration, when the connection decision wasn't made for all of the
* sites in the network.
*/
'is_network_activation' => 0,
'license_migration' => 0,
// When network activated, then network level.
'install_timestamp' => 1,
'prev_is_premium' => 1,
'require_license_activation' => 1,
// If not network activated OR delegated, then site level.
'activation_timestamp' => 2,
'expired_license_notice_shown' => 2,
'is_whitelabeled' => 2,
'last_license_key' => 2,
'last_license_user_id' => 2,
'prev_user_id' => 2,
'sticky_optin_added' => 2,
'uninstall_reason' => 2,
'is_pending_activation' => 2,
'pending_license_key' => 2,
'is_extensions_tracking_allowed' => 2,
// Site level options.
'is_anonymous' => 3,
);
}
/**
* This method will and should only be executed when is_multisite() is true.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $key
*
* @return bool|mixed
*/
private function is_multisite_option( $key ) {
if ( ! isset( self::$_NETWORK_OPTIONS_MAP ) ) {
self::load_network_options_map();
}
if ( ! isset( self::$_NETWORK_OPTIONS_MAP[ $key ] ) ) {
// Option not found -> use site level storage.
return false;
}
if ( 0 === self::$_NETWORK_OPTIONS_MAP[ $key ] ) {
// Option found and set to always use the network level storage on a multisite.
return true;
}
if ( 3 === self::$_NETWORK_OPTIONS_MAP[ $key ] ) {
// Option found and set to always use the site level storage on a multisite.
return false;
}
if ( ! $this->_is_network_active ) {
return false;
}
if ( 1 === self::$_NETWORK_OPTIONS_MAP[ $key ] ) {
// Network activated.
return true;
}
if ( 2 === self::$_NETWORK_OPTIONS_MAP[ $key ] && ! $this->_is_delegated_connection ) {
// Network activated and not delegated.
return true;
}
return false;
}
/**
* @author Leo Fajardo
*
* @param string $key
* @param null|bool|int $network_level_or_blog_id When an integer, use the given blog storage. When `true` use the multisite storage (if there's a network). When `false`, use the current context blog storage. When `null`, the decision which storage to use (MS vs. Current S) will be handled internally and determined based on the $option (based on self::$_BINARY_MAP).
*
* @return bool
*/
private function should_use_network_storage( $key, $network_level_or_blog_id = null ) {
if ( ! $this->_is_multisite ) {
// Not a multisite environment.
return false;
}
if ( is_numeric( $network_level_or_blog_id ) ) {
// Explicitly asked to use a specified blog storage.
return false;
}
if ( is_bool( $network_level_or_blog_id ) ) {
// Explicitly specified whether should use the network or blog level storage.
return $network_level_or_blog_id;
}
// Determine which storage to use based on the option.
return $this->is_multisite_option( $key );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $blog_id
*
* @return \FS_Key_Value_Storage
*/
private function get_site_storage( $blog_id = 0 ) {
if ( ! is_numeric( $blog_id ) ||
$blog_id == $this->_blog_id ||
0 == $blog_id
) {
return $this->_storage;
}
return FS_Key_Value_Storage::instance(
$this->_module_type . '_data',
$this->_storage->get_secondary_id(),
$blog_id
);
}
#endregion
#--------------------------------------------------------------------------------
#region Magic methods
#--------------------------------------------------------------------------------
function __set( $k, $v ) {
if ( $this->should_use_network_storage( $k ) ) {
$this->_network_storage->{$k} = $v;
} else {
$this->_storage->{$k} = $v;
}
}
function __isset( $k ) {
return $this->should_use_network_storage( $k ) ?
isset( $this->_network_storage->{$k} ) :
isset( $this->_storage->{$k} );
}
function __unset( $k ) {
if ( $this->should_use_network_storage( $k ) ) {
unset( $this->_network_storage->{$k} );
} else {
unset( $this->_storage->{$k} );
}
}
function __get( $k ) {
return $this->should_use_network_storage( $k ) ?
$this->_network_storage->{$k} :
$this->_storage->{$k};
}
#endregion
}

View File

@ -0,0 +1,126 @@
<?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 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_User_Lock
*/
class FS_User_Lock {
/**
* @var int
*/
private $_wp_user_id;
/**
* @var int
*/
private $_thread_id;
#--------------------------------------------------------------------------------
#region Singleton
#--------------------------------------------------------------------------------
/**
* @var FS_User_Lock
*/
private static $_instance;
/**
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @return FS_User_Lock
*/
static function instance() {
if ( ! isset( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
#endregion
private function __construct() {
$this->_wp_user_id = Freemius::get_current_wp_user_id();
$this->_thread_id = mt_rand( 0, 32000 );
}
/**
* Try to acquire lock. If the lock is already set or is being acquired by another locker, don't do anything.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @param int $expiration
*
* @return bool TRUE if successfully acquired lock.
*/
function try_lock( $expiration = 0 ) {
if ( $this->is_locked() ) {
// Already locked.
return false;
}
set_site_transient( "locked_{$this->_wp_user_id}", $this->_thread_id, $expiration );
if ( $this->has_lock() ) {
set_site_transient( "locked_{$this->_wp_user_id}", true, $expiration );
return true;
}
return false;
}
/**
* Acquire lock regardless if it's already acquired by another locker or not.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @param int $expiration
*/
function lock( $expiration = 0 ) {
set_site_transient( "locked_{$this->_wp_user_id}", true, $expiration );
}
/**
* Checks if lock is currently acquired.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @return bool
*/
function is_locked() {
return ( false !== get_site_transient( "locked_{$this->_wp_user_id}" ) );
}
/**
* Unlock the lock.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*/
function unlock() {
delete_site_transient( "locked_{$this->_wp_user_id}" );
}
/**
* Checks if lock is currently acquired by the current locker.
*
* @return bool
*/
private function has_lock() {
return ( $this->_thread_id == get_site_transient( "locked_{$this->_wp_user_id}" ) );
}
}

View File

@ -0,0 +1,102 @@
<?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.2.2.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class Zerif_Customizer_Theme_Info_Main
*
* @since 1.0.0
* @access public
*/
class FS_Customizer_Support_Section extends WP_Customize_Section {
function __construct( $manager, $id, $args = array() ) {
$manager->register_section_type( 'FS_Customizer_Support_Section' );
parent::__construct( $manager, $id, $args );
}
/**
* The type of customize section being rendered.
*
* @since 1.0.0
* @access public
* @var string
*/
public $type = 'freemius-support-section';
/**
* @var Freemius
*/
public $fs = null;
/**
* Add custom parameters to pass to the JS via JSON.
*
* @since 1.0.0
*/
public function json() {
$json = parent::json();
$is_contact_visible = $this->fs->is_page_visible( 'contact' );
$is_support_visible = $this->fs->is_page_visible( 'support' );
$json['theme_title'] = $this->fs->get_plugin_name();
if ( $is_contact_visible && $is_support_visible ) {
$json['theme_title'] .= ' ' . $this->fs->get_text_inline( 'Support', 'support' );
}
if ( $is_contact_visible ) {
$json['contact'] = array(
'label' => $this->fs->get_text_inline( 'Contact Us', 'contact-us' ),
'url' => $this->fs->contact_url(),
);
}
if ( $is_support_visible ) {
$json['support'] = array(
'label' => $this->fs->get_text_inline( 'Support Forum', 'support-forum' ),
'url' => $this->fs->get_support_forum_url()
);
}
return $json;
}
/**
* Outputs the Underscore.js template.
*
* @since 1.0.0
*/
protected function render_template() {
?>
<li id="fs_customizer_support"
class="accordion-section control-section control-section-{{ data.type }} cannot-expand">
<h3 class="accordion-section-title">
<span>{{ data.theme_title }}</span>
<# if ( data.contact && data.support ) { #>
<div class="button-group">
<# } #>
<# if ( data.contact ) { #>
<a class="button" href="{{ data.contact.url }}" target="_blank" rel="noopener noreferrer">{{ data.contact.label }} </a>
<# } #>
<# if ( data.support ) { #>
<a class="button" href="{{ data.support.url }}" target="_blank" rel="noopener noreferrer">{{ data.support.label }} </a>
<# } #>
<# if ( data.contact && data.support ) { #>
</div>
<# } #>
</h3>
</li>
<?php
}
}

View File

@ -0,0 +1,161 @@
<?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.2.2.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Customizer_Upsell_Control
*/
class FS_Customizer_Upsell_Control extends WP_Customize_Control {
/**
* Control type
*
* @var string control type
*/
public $type = 'freemius-upsell-control';
/**
* @var Freemius
*/
public $fs = null;
/**
* @param WP_Customize_Manager $manager the customize manager class.
* @param string $id id.
* @param array $args customizer manager parameters.
*/
public function __construct( WP_Customize_Manager $manager, $id, array $args ) {
$manager->register_control_type( 'FS_Customizer_Upsell_Control' );
parent::__construct( $manager, $id, $args );
}
/**
* Enqueue resources for the control.
*/
public function enqueue() {
fs_enqueue_local_style( 'fs_customizer', 'customizer.css' );
}
/**
* Json conversion
*/
public function to_json() {
$pricing_cta = esc_html( $this->fs->get_pricing_cta_label() ) . '&nbsp;&nbsp;' . ( is_rtl() ? '&#x2190;' : '&#x27a4;' );
parent::to_json();
$this->json['button_text'] = $pricing_cta;
$this->json['button_url'] = $this->fs->is_in_trial_promotion() ?
$this->fs->get_trial_url() :
$this->fs->get_upgrade_url();
$api = FS_Plugin::is_valid_id( $this->fs->get_bundle_id() ) ?
$this->fs->get_api_bundle_scope() :
$this->fs->get_api_plugin_scope();
// Load features.
$pricing = $api->get( $this->fs->add_show_pending( "pricing.json" ) );
if ( $this->fs->is_api_result_object( $pricing, 'plans' ) ) {
// Add support features.
if ( is_array( $pricing->plans ) && 0 < count( $pricing->plans ) ) {
$support_features = array(
'kb' => 'Help Center',
'forum' => 'Support Forum',
'email' => 'Priority Email Support',
'phone' => 'Phone Support',
'skype' => 'Skype Support',
'is_success_manager' => 'Personal Success Manager',
);
for ( $i = 0, $len = count( $pricing->plans ); $i < $len; $i ++ ) {
if ( 'free' == $pricing->plans[$i]->name ) {
continue;
}
if ( ! isset( $pricing->plans[ $i ]->features ) ||
! is_array( $pricing->plans[ $i ]->features ) ) {
$pricing->plans[$i]->features = array();
}
foreach ( $support_features as $key => $label ) {
$key = ( 'is_success_manager' !== $key ) ?
"support_{$key}" :
$key;
if ( ! empty( $pricing->plans[ $i ]->{$key} ) ) {
$support_feature = new stdClass();
$support_feature->title = $label;
$pricing->plans[ $i ]->features[] = $support_feature;
}
}
}
}
}
$this->json['plans'] = $pricing->plans;
$this->json['strings'] = array(
'plan' => $this->fs->get_text_x_inline( 'Plan', 'as product pricing plan', 'plan' ),
);
}
/**
* Control content
*/
public function content_template() {
?>
<div id="fs_customizer_upsell">
<# if ( data.plans ) { #>
<ul class="fs-customizer-plans">
<# for (i in data.plans) { #>
<# if ( 'free' != data.plans[i].name && (null != data.plans[i].features && 0 < data.plans[i].features.length) ) { #>
<li class="fs-customizer-plan">
<div class="fs-accordion-section-open">
<h2 class="fs-accordion-section-title menu-item">
<span>{{ data.plans[i].title }}</span>
<button type="button" class="button-link item-edit" aria-expanded="true">
<span class="screen-reader-text">Toggle section: {{ data.plans[i].title }} {{ data.strings.plan }}</span>
<span class="toggle-indicator" aria-hidden="true"></span>
</button>
</h2>
<div class="fs-accordion-section-content">
<# if ( data.plans[i].description ) { #>
<h3>{{ data.plans[i].description }}</h3>
<# } #>
<# if ( data.plans[i].features ) { #>
<ul>
<# for ( j in data.plans[i].features ) { #>
<li><div class="fs-feature">
<span class="dashicons dashicons-yes"></span><span><# if ( data.plans[i].features[j].value ) { #>{{ data.plans[i].features[j].value }} <# } #>{{ data.plans[i].features[j].title }}</span>
<# if ( data.plans[i].features[j].description ) { #>
<span class="dashicons dashicons-editor-help"><span class="fs-feature-desc">{{ data.plans[i].features[j].description }}</span></span>
<# } #>
</div></li>
<# } #>
</ul>
<# } #>
<# if ( 'free' != data.plans[i].name ) { #>
<a href="{{ data.button_url }}" class="button button-primary" target="_blank">{{{ data.button_text }}}</a>
<# } #>
</div>
</div>
</li>
<# } #>
<# } #>
</ul>
<# } #>
</div>
<?php }
}

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,64 @@
<?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.1.7.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Extends Debug Bar plugin by adding a panel to show all Freemius API requests.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.7.3
*
* Class Freemius_Debug_Bar_Panel
*/
class Freemius_Debug_Bar_Panel extends Debug_Bar_Panel {
function init() {
$this->title( 'Freemius' );
}
static function requests_count() {
if ( class_exists( 'Freemius_Api_WordPress' ) ) {
$logger = Freemius_Api_WordPress::GetLogger();
} else {
$logger = array();
}
return number_format( count( $logger ) );
}
static function total_time() {
if ( class_exists( 'Freemius_Api_WordPress' ) ) {
$logger = Freemius_Api_WordPress::GetLogger();
} else {
$logger = array();
}
$total_time = .0;
foreach ( $logger as $l ) {
$total_time += $l['total'];
}
return number_format( 100 * $total_time, 2 ) . ' ' . fs_text_x_inline( 'ms', 'milliseconds' );
}
function render() {
?>
<div id='debug-bar-php'>
<?php fs_require_template( '/debug/api-calls.php' ) ?>
<br>
<?php fs_require_template( '/debug/scheduled-crons.php' ) ?>
<br>
<?php fs_require_template( '/debug/plugins-themes-sync.php' ) ?>
<br>
<?php fs_require_template( '/debug/logger.php' ) ?>
</div>
<?php
}
}

View File

@ -0,0 +1,52 @@
<?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.1.7.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! WP_FS__DEBUG_SDK ) {
return;
}
/**
* Initialize Freemius custom debug panels.
*
* @param array $panels Debug bar panels objects
*
* @return array Debug bar panels with your custom panels
*/
function fs_custom_panels_init( $panels ) {
if ( class_exists( 'Debug_Bar_Panel' ) ) {
if ( FS_API__LOGGER_ON ) {
require_once dirname( __FILE__ ) . '/class-fs-debug-bar-panel.php';
$panels[] = new Freemius_Debug_Bar_Panel();
}
}
return $panels;
}
function fs_custom_status_init( $statuses ) {
if ( class_exists( 'Debug_Bar_Panel' ) ) {
if ( FS_API__LOGGER_ON ) {
require_once dirname( __FILE__ ) . '/class-fs-debug-bar-panel.php';
$statuses[] = array(
'fs_api_requests',
fs_text_inline( 'Freemius API' ),
Freemius_Debug_Bar_Panel::requests_count() . ' ' . fs_text_inline( 'Requests' ) .
' (' . Freemius_Debug_Bar_Panel::total_time() . ')'
);
}
}
return $statuses;
}
add_filter( 'debug_bar_panels', 'fs_custom_panels_init' );
add_filter( 'debug_bar_statuses', 'fs_custom_status_init' );

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,128 @@
<?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.2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_AffiliateTerms extends FS_Scope_Entity {
#region Properties
/**
* @var bool
*/
public $is_active;
/**
* @var string Enum: `affiliation` or `rewards`. Defaults to `affiliation`.
*/
public $type;
/**
* @var string Enum: `payout` or `credit`. Defaults to `payout`.
*/
public $reward_type;
/**
* If `first`, the referral will be attributed to the first visited source containing the affiliation link that
* was clicked.
*
* @var string Enum: `first` or `last`. Defaults to `first`.
*/
public $referral_attribution;
/**
* @var int Defaults to `30`, `0` for session cookie, and `null` for endless cookie (until cookies are cleaned).
*/
public $cookie_days;
/**
* @var int
*/
public $commission;
/**
* @var string Enum: `percentage` or `dollar`. Defaults to `percentage`.
*/
public $commission_type;
/**
* @var null|int Defaults to `0` (affiliate only on first payment). `null` for commission for all renewals. If
* greater than `0`, affiliate will get paid for all renewals for `commission_renewals_days` days after
* the initial upgrade/purchase.
*/
public $commission_renewals_days;
/**
* @var int Only cents and no percentage. In US cents, e.g.: 100 = $1.00. Defaults to `null`.
*/
public $install_commission;
/**
* @var string Required default target link, e.g.: pricing page.
*/
public $default_url;
/**
* @var string One of the following: 'all', 'new_customer', 'new_user'.
* If 'all' - reward for any user type.
* If 'new_customer' - reward only for new customers.
* If 'new_user' - reward only for new users.
*/
public $reward_customer_type;
/**
* @var int Defaults to `0` (affiliate only on directly affiliated links). `null` if an affiliate will get
* paid for all customers' lifetime payments. If greater than `0`, an affiliate will get paid for all
* customer payments for `future_payments_days` days after the initial payment.
*/
public $future_payments_days;
/**
* @var bool If `true`, allow referrals from social sites.
*/
public $is_social_allowed;
/**
* @var bool If `true`, allow conversions without HTTP referrer header at all.
*/
public $is_app_allowed;
/**
* @var bool If `true`, allow referrals from any site.
*/
public $is_any_site_allowed;
#endregion Properties
/**
* @author Leo Fajardo (@leorw)
*
* @return string
*/
function get_formatted_commission()
{
return ( 'dollar' === $this->commission_type ) ?
( '$' . $this->commission ) :
( $this->commission . '%' );
}
/**
* @author Leo Fajardo (@leorw)
*
* @return bool
*/
function has_lifetime_commission() {
return ( 0 !== $this->future_payments_days );
}
/**
* @author Leo Fajardo (@leorw)
*
* @return bool
*/
function is_session_cookie() {
return ( 0 == $this->cookie_days );
}
/**
* @author Leo Fajardo (@leorw)
*
* @return bool
*/
function has_renewals_commission() {
return ( is_null( $this->commission_renewals_days ) || $this->commission_renewals_days > 0 );
}
}

View File

@ -0,0 +1,84 @@
<?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.2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Affiliate extends FS_Scope_Entity {
#region Properties
/**
* @var string
*/
public $paypal_email;
/**
* @var number
*/
public $custom_affiliate_terms_id;
/**
* @var boolean
*/
public $is_using_custom_terms;
/**
* @var string status Enum: `pending`, `rejected`, `suspended`, or `active`. Defaults to `pending`.
*/
public $status;
/**
* @var string
*/
public $domain;
#endregion Properties
/**
* @author Leo Fajardo
*
* @return bool
*/
function is_active() {
return ( 'active' === $this->status );
}
/**
* @author Leo Fajardo
*
* @return bool
*/
function is_pending() {
return ( 'pending' === $this->status );
}
/**
* @author Leo Fajardo
*
* @return bool
*/
function is_suspended() {
return ( 'suspended' === $this->status );
}
/**
* @author Leo Fajardo
*
* @return bool
*/
function is_rejected() {
return ( 'rejected' === $this->status );
}
/**
* @author Leo Fajardo
*
* @return bool
*/
function is_blocked() {
return ( 'blocked' === $this->status );
}
}

View File

@ -0,0 +1,95 @@
<?php
/**
* @package Freemius for EDD Add-On
* @copyright Copyright (c) 2016, Freemius, Inc.
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Billing extends FS_Entity {
#region Properties
/**
* @var int
*/
public $entity_id;
/**
* @var string (Enum) Linked entity type. One of: developer, plugin, user, install
*/
public $entity_type;
/**
* @var string
*/
public $business_name;
/**
* @var string
*/
public $first;
/**
* @var string
*/
public $last;
/**
* @var string
*/
public $email;
/**
* @var string
*/
public $phone;
/**
* @var string
*/
public $website;
/**
* @var string Tax or VAT ID.
*/
public $tax_id;
/**
* @var string
*/
public $address_street;
/**
* @var string
*/
public $address_apt;
/**
* @var string
*/
public $address_city;
/**
* @var string
*/
public $address_country;
/**
* @var string Two chars country code.
*/
public $address_country_code;
/**
* @var string
*/
public $address_state;
/**
* @var number Numeric ZIP code (cab be with leading zeros).
*/
public $address_zip;
#endregion Properties
/**
* @param object|bool $event
*/
function __construct( $event = false ) {
parent::__construct( $event );
}
static function get_type() {
return 'billing';
}
}

View File

@ -0,0 +1,159 @@
<?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;
}
/**
* Get object's public variables.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.0
*
* @param object $object
*
* @return array
*/
function fs_get_object_public_vars( $object ) {
return get_object_vars( $object );
}
class FS_Entity {
/**
* @var number
*/
public $id;
/**
* @var string Datetime value in 'YYYY-MM-DD HH:MM:SS' format.
*/
public $updated;
/**
* @var string Datetime value in 'YYYY-MM-DD HH:MM:SS' format.
*/
public $created;
/**
* @param bool|object $entity
*/
function __construct( $entity = false ) {
if ( ! ( $entity instanceof stdClass ) && ! ( $entity instanceof FS_Entity ) ) {
return;
}
$props = fs_get_object_public_vars( $this );
foreach ( $props as $key => $def_value ) {
$this->{$key} = isset( $entity->{$key} ) ?
$entity->{$key} :
$def_value;
}
}
static function get_type() {
return 'type';
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param FS_Entity $entity1
* @param FS_Entity $entity2
*
* @return bool
*/
static function equals( $entity1, $entity2 ) {
if ( is_null( $entity1 ) && is_null( $entity2 ) ) {
return true;
} else if ( is_object( $entity1 ) && is_object( $entity2 ) ) {
return ( $entity1->id == $entity2->id );
} else if ( is_object( $entity1 ) ) {
return is_null( $entity1->id );
} else {
return is_null( $entity2->id );
}
}
private $_is_updated = false;
/**
* Update object property.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param string|array[string]mixed $key
* @param string|bool $val
*
* @return bool
*/
function update( $key, $val = false ) {
if ( ! is_array( $key ) ) {
$key = array( $key => $val );
}
$is_updated = false;
foreach ( $key as $k => $v ) {
if ( $this->{$k} === $v ) {
continue;
}
if ( ( is_string( $this->{$k} ) && is_numeric( $v ) ||
( is_numeric( $this->{$k} ) && is_string( $v ) ) ) &&
$this->{$k} == $v
) {
continue;
}
// Update value.
$this->{$k} = $v;
$is_updated = true;
}
$this->_is_updated = $is_updated;
return $is_updated;
}
/**
* Checks if entity was updated.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_updated() {
return $this->_is_updated;
}
/**
* @param $id
*
* @author Vova Feldman (@svovaf)
* @since 1.1.2
*
* @return bool
*/
static function is_valid_id($id){
return is_numeric($id);
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.1
*
* @return string
*/
public static function get_class_name() {
return get_called_class();
}
}

View File

@ -0,0 +1,168 @@
<?php
/**
* @package Freemius
* @copyright Copyright (c) 2016, Freemius, Inc.
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
* @since 1.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Payment extends FS_Entity {
#region Properties
/**
* @var number
*/
public $plugin_id;
/**
* @var number
*/
public $user_id;
/**
* @var number
*/
public $install_id;
/**
* @var number
*/
public $subscription_id;
/**
* @var number
*/
public $plan_id;
/**
* @var number
*/
public $license_id;
/**
* @var float
*/
public $gross;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @var string One of the following: `usd`, `gbp`, `eur`.
*/
public $currency;
/**
* @var number
*/
public $bound_payment_id;
/**
* @var string
*/
public $external_id;
/**
* @var string
*/
public $gateway;
/**
* @var string ISO 3166-1 alpha-2 - two-letter country code.
*
* @link http://www.wikiwand.com/en/ISO_3166-1_alpha-2
*/
public $country_code;
/**
* @var string
*/
public $vat_id;
/**
* @var float Actual Tax / VAT in $$$
*/
public $vat;
/**
* @var int Payment source.
*/
public $source = 0;
#endregion Properties
const CURRENCY_USD = 'usd';
const CURRENCY_GBP = 'gbp';
const CURRENCY_EUR = 'eur';
/**
* @param object|bool $payment
*/
function __construct( $payment = false ) {
parent::__construct( $payment );
}
static function get_type() {
return 'payment';
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.0
*
* @return bool
*/
function is_refund() {
return ( parent::is_valid_id( $this->bound_payment_id ) && 0 > $this->gross );
}
/**
* Checks if the payment was migrated from another platform.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.2
*
* @return bool
*/
function is_migrated() {
return ( 0 != $this->source );
}
/**
* Returns the gross in this format:
* `{symbol}{amount | 2 decimal digits} {currency | uppercase}`
*
* Examples: £9.99 GBP, -£9.99 GBP.
*
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @return string
*/
function formatted_gross()
{
return (
( $this->gross < 0 ? '-' : '' ) .
$this->get_symbol() .
number_format( abs( $this->gross ), 2, '.', ',' ) . ' ' .
strtoupper( $this->currency )
);
}
/**
* A map between supported currencies with their symbols.
*
* @var array<string,string>
*/
static $CURRENCY_2_SYMBOL;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @return string
*/
private function get_symbol() {
if ( ! isset( self::$CURRENCY_2_SYMBOL ) ) {
// Lazy load.
self::$CURRENCY_2_SYMBOL = array(
self::CURRENCY_USD => '$',
self::CURRENCY_GBP => '&pound;',
self::CURRENCY_EUR => '&euro;',
);
}
return self::$CURRENCY_2_SYMBOL[ $this->currency ];
}
}

View File

@ -0,0 +1,34 @@
<?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;
}
class FS_Plugin_Info extends FS_Entity {
public $plugin_id;
public $description;
public $short_description;
public $banner_url;
public $card_banner_url;
public $selling_point_0;
public $selling_point_1;
public $selling_point_2;
public $screenshots;
/**
* @param stdClass|bool $plugin_info
*/
function __construct( $plugin_info = false ) {
parent::__construct( $plugin_info );
}
static function get_type() {
return 'plugin';
}
}

View File

@ -0,0 +1,330 @@
<?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.5
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Plugin_License
*/
class FS_Plugin_License extends FS_Entity {
#region Properties
/**
* @var number
*/
public $plugin_id;
/**
* @var number
*/
public $user_id;
/**
* @var number
*/
public $plan_id;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @var string
*/
public $parent_plan_name;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @var string
*/
public $parent_plan_title;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @var number
*/
public $parent_license_id;
/**
* @author Leo Fajardo (@leorw)
* @since 2.4.0
*
* @var array
*/
public $products;
/**
* @var number
*/
public $pricing_id;
/**
* @var int|null
*/
public $quota;
/**
* @var int
*/
public $activated;
/**
* @var int
*/
public $activated_local;
/**
* @var string
*/
public $expiration;
/**
* @var string
*/
public $secret_key;
/**
* @var bool
*/
public $is_whitelabeled;
/**
* @var bool $is_free_localhost Defaults to true. If true, allow unlimited localhost installs with the same
* license.
*/
public $is_free_localhost;
/**
* @var bool $is_block_features Defaults to true. If false, don't block features after license expiry - only
* block updates and support.
*/
public $is_block_features;
/**
* @var bool
*/
public $is_cancelled;
#endregion Properties
/**
* @param stdClass|bool $license
*/
function __construct( $license = false ) {
parent::__construct( $license );
}
/**
* Get entity type.
*
* @return string
*/
static function get_type() {
return 'license';
}
/**
* Check how many site activations left.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.5
*
* @return int
*/
function left() {
if ( ! $this->is_features_enabled() ) {
return 0;
}
if ( $this->is_unlimited() ) {
return 999;
}
return ( $this->quota - $this->activated - ( $this->is_free_localhost ? 0 : $this->activated_local ) );
}
/**
* Check if single site license.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.8.1
*
* @return bool
*/
function is_single_site() {
return ( is_numeric( $this->quota ) && 1 == $this->quota );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.5
*
* @return bool
*/
function is_expired() {
return ! $this->is_lifetime() && ( strtotime( $this->expiration ) < WP_FS__SCRIPT_START_TIME );
}
/**
* Check if license is not expired.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.1
*
* @return bool
*/
function is_valid() {
return ! $this->is_expired();
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @return bool
*/
function is_lifetime() {
return is_null( $this->expiration );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.0
*
* @return bool
*/
function is_unlimited() {
return is_null( $this->quota );
}
/**
* Check if license is fully utilized.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param bool|null $is_localhost
*
* @return bool
*/
function is_utilized( $is_localhost = null ) {
if ( is_null( $is_localhost ) ) {
$is_localhost = WP_FS__IS_LOCALHOST_FOR_SERVER;
}
if ( $this->is_unlimited() ) {
return false;
}
return ! ( $this->is_free_localhost && $is_localhost ) &&
( $this->quota <= $this->activated + ( $this->is_free_localhost ? 0 : $this->activated_local ) );
}
/**
* Check if license can be activated.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param bool|null $is_localhost
*
* @return bool
*/
function can_activate( $is_localhost = null ) {
return ! $this->is_utilized( $is_localhost ) && $this->is_features_enabled();
}
/**
* Check if license can be activated on a given number of production and localhost sites.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param int $production_count
* @param int $localhost_count
*
* @return bool
*/
function can_activate_bulk( $production_count, $localhost_count ) {
if ( $this->is_unlimited() ) {
return true;
}
/**
* For simplicity, the logic will work as following: when given X sites to activate the license on, if it's
* possible to activate on ALL of them, do the activation. If it's not possible to activate on ALL of them,
* do NOT activate on any of them.
*/
return ( $this->quota >= $this->activated + $production_count + ( $this->is_free_localhost ? 0 : $this->activated_local + $localhost_count ) );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.2.1
*
* @return bool
*/
function is_active() {
return ( ! $this->is_cancelled );
}
/**
* Check if license's plan features are enabled.
*
* - Either if plan not expired
* - If expired, based on the configuration to block features or not.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @return bool
*/
function is_features_enabled() {
return $this->is_active() && ( ! $this->is_block_features || ! $this->is_expired() );
}
/**
* Subscription considered to be new without any payments
* if the license expires in less than 24 hours
* from the license creation.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_first_payment_pending() {
return ( WP_FS__TIME_24_HOURS_IN_SEC >= strtotime( $this->expiration ) - strtotime( $this->created ) );
}
/**
* @return int
*/
function total_activations() {
return ( $this->activated + $this->activated_local );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.3.1
*
* @return string
*/
function get_html_escaped_masked_secret_key() {
return self::mask_secret_key_for_html( $this->secret_key );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.3.1
*
* @param string $secret_key
*
* @return string
*/
static function mask_secret_key_for_html( $secret_key ) {
return (
// Initial 6 chars - sk_ABC
htmlspecialchars( substr( $secret_key, 0, 6 ) ) .
// Masking
str_pad( '', ( strlen( $secret_key ) - 9 ) * 6, '&bull;' ) .
// Last 3 chars.
htmlspecialchars( substr( $secret_key, - 3 ) )
);
}
}

View File

@ -0,0 +1,145 @@
<?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.5
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Plugin_Plan
*
* @property FS_Pricing[] $pricing
*/
class FS_Plugin_Plan extends FS_Entity {
#region Properties
/**
* @var number
*/
public $plugin_id;
/**
* @var string
*/
public $name;
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $description;
/**
* @var bool Defaults to true. If true, allow unlimited localhost installs with the same license.
*/
public $is_free_localhost;
/**
* @var bool Defaults to true. If false, don't block features after license expiry - only block updates and
* support.
*/
public $is_block_features;
/**
* @var int
*/
public $license_type;
/**
* @var bool
*/
public $is_https_support;
/**
* @var int Trial days.
*/
public $trial_period;
/**
* @var string If true, require payment for trial.
*/
public $is_require_subscription;
/**
* @var string Knowledge Base URL.
*/
public $support_kb;
/**
* @var string Support Forum URL.
*/
public $support_forum;
/**
* @var string Support email address.
*/
public $support_email;
/**
* @var string Support phone.
*/
public $support_phone;
/**
* @var string Support skype username.
*/
public $support_skype;
/**
* @var bool Is personal success manager supported with the plan.
*/
public $is_success_manager;
/**
* @var bool Is featured plan.
*/
public $is_featured;
#endregion Properties
/**
* @param object|bool $plan
*/
function __construct( $plan = false ) {
parent::__construct( $plan );
if ( is_object( $plan ) ) {
$this->name = strtolower( $plan->name );
}
}
static function get_type() {
return 'plan';
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_free() {
return ( 'free' === $this->name );
}
/**
* Checks if this plan supports "Technical Support".
*
* @author Leo Fajardo (leorw)
* @since 1.2.0
*
* @return bool
*/
function has_technical_support() {
return ( ! empty( $this->support_email ) ||
! empty( $this->support_skype ) ||
! empty( $this->support_phone ) ||
! empty( $this->is_success_manager )
);
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function has_trial() {
return ! $this->is_free() &&
is_numeric( $this->trial_period ) && ( $this->trial_period > 0 );
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* @package Freemius
* @copyright Copyright (c) 2018, Freemius, Inc.
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
* @since 2.0.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Plugin_Tag extends FS_Entity {
/**
* @var string
*/
public $version;
/**
* @var string
*/
public $url;
/**
* @var string
*/
public $requires_platform_version;
/**
* @var string
*/
public $tested_up_to_version;
/**
* @var bool
*/
public $has_free;
/**
* @var bool
*/
public $has_premium;
/**
* @var string One of the following: `pending`, `beta`, `unreleased`.
*/
public $release_mode;
function __construct( $tag = false ) {
parent::__construct( $tag );
}
static function get_type() {
return 'tag';
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.0
*
* @return bool
*/
function is_beta() {
return ( 'beta' === $this->release_mode );
}
}

View File

@ -0,0 +1,159 @@
<?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;
}
class FS_Plugin extends FS_Scope_Entity {
/**
* @since 1.0.6
* @var null|number
*/
public $parent_plugin_id;
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $slug;
/**
* @author Leo Fajardo (@leorw)
* @since 2.2.1
*
* @var string
*/
public $premium_slug;
/**
* @since 1.2.2
*
* @var string 'plugin' or 'theme'
*/
public $type;
/**
* @author Leo Fajardo (@leorw)
*
* @since 1.2.3
*
* @var string|false false if the module doesn't have an affiliate program or one of the following: 'selected', 'customers', or 'all'.
*/
public $affiliate_moderation;
/**
* @var bool Set to true if the free version of the module is hosted on WordPress.org. Defaults to true.
*/
public $is_wp_org_compliant = true;
/**
* @author Leo Fajardo (@leorw)
* @since 2.2.5
*
* @var int
*/
public $premium_releases_count;
#region Install Specific Properties
/**
* @var string
*/
public $file;
/**
* @var string
*/
public $version;
/**
* @var bool
*/
public $auto_update;
/**
* @var FS_Plugin_Info
*/
public $info;
/**
* @since 1.0.9
*
* @var bool
*/
public $is_premium;
/**
* @author Leo Fajardo (@leorw)
* @since 2.2.1
*
* @var string
*/
public $premium_suffix;
/**
* @since 1.0.9
*
* @var bool
*/
public $is_live;
/**
* @since 2.2.3
* @var null|number
*/
public $bundle_id;
/**
* @since 2.3.1
* @var null|string
*/
public $bundle_public_key;
const AFFILIATE_MODERATION_CUSTOMERS = 'customers';
#endregion Install Specific Properties
/**
* @param stdClass|bool $plugin
*/
function __construct( $plugin = false ) {
parent::__construct( $plugin );
$this->is_premium = false;
$this->is_live = true;
if ( empty( $this->premium_slug ) && ! empty( $plugin->slug ) ) {
$this->premium_slug = "{$this->slug}-premium";
}
if ( empty( $this->premium_suffix ) ) {
$this->premium_suffix = '(Premium)';
}
if ( isset( $plugin->info ) && is_object( $plugin->info ) ) {
$this->info = new FS_Plugin_Info( $plugin->info );
}
}
/**
* Check if plugin is an add-on (has parent).
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @return bool
*/
function is_addon() {
return isset( $this->parent_plugin_id ) && is_numeric( $this->parent_plugin_id );
}
/**
* @author Leo Fajardo (@leorw)
* @since 1.2.3
*
* @return bool
*/
function has_affiliate_program() {
return ( ! empty( $this->affiliate_moderation ) );
}
static function get_type() {
return 'plugin';
}
}

View File

@ -0,0 +1,157 @@
<?php
/**
* @package Freemius for EDD Add-On
* @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.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Pricing extends FS_Entity {
#region Properties
/**
* @var number
*/
public $plan_id;
/**
* @var int
*/
public $licenses;
/**
* @var null|float
*/
public $monthly_price;
/**
* @var null|float
*/
public $annual_price;
/**
* @var null|float
*/
public $lifetime_price;
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.1
*
* @var string One of the following: `usd`, `gbp`, `eur`.
*/
public $currency;
#endregion Properties
/**
* @param object|bool $pricing
*/
function __construct( $pricing = false ) {
parent::__construct( $pricing );
}
static function get_type() {
return 'pricing';
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return bool
*/
function has_monthly() {
return ( is_numeric( $this->monthly_price ) && $this->monthly_price > 0 );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return bool
*/
function has_annual() {
return ( is_numeric( $this->annual_price ) && $this->annual_price > 0 );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return bool
*/
function has_lifetime() {
return ( is_numeric( $this->lifetime_price ) && $this->lifetime_price > 0 );
}
/**
* Check if unlimited licenses pricing.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return bool
*/
function is_unlimited() {
return is_null( $this->licenses );
}
/**
* Check if pricing has more than one billing cycle.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return bool
*/
function is_multi_cycle() {
$cycles = 0;
if ( $this->has_monthly() ) {
$cycles ++;
}
if ( $this->has_annual() ) {
$cycles ++;
}
if ( $this->has_lifetime() ) {
$cycles ++;
}
return $cycles > 1;
}
/**
* Get annual over monthly discount.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return int
*/
function annual_discount_percentage() {
return floor( $this->annual_savings() / ( $this->monthly_price * 12 * ( $this->is_unlimited() ? 1 : $this->licenses ) ) * 100 );
}
/**
* Get annual over monthly savings.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.8
*
* @return float
*/
function annual_savings() {
return ( $this->monthly_price * 12 - $this->annual_price ) * ( $this->is_unlimited() ? 1 : $this->licenses );
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.3.1
*
* @return bool
*/
function is_usd() {
return ( 'usd' === $this->currency );
}
}

View File

@ -0,0 +1,29 @@
<?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.4
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Scope_Entity extends FS_Entity {
/**
* @var string
*/
public $public_key;
/**
* @var string
*/
public $secret_key;
/**
* @param bool|stdClass $scope_entity
*/
function __construct( $scope_entity = false ) {
parent::__construct( $scope_entity );
}
}

View File

@ -0,0 +1,253 @@
<?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;
}
class FS_Site extends FS_Scope_Entity {
/**
* @var number
*/
public $site_id;
/**
* @var number
*/
public $plugin_id;
/**
* @var number
*/
public $user_id;
/**
* @var string
*/
public $title;
/**
* @var string
*/
public $url;
/**
* @var string
*/
public $version;
/**
* @var string E.g. en-GB
*/
public $language;
/**
* @var string E.g. UTF-8
*/
public $charset;
/**
* @var string Platform version (e.g WordPress version).
*/
public $platform_version;
/**
* Freemius SDK version
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*
* @var string SDK version (e.g.: 1.2.2)
*/
public $sdk_version;
/**
* @var string Programming language version (e.g PHP version).
*/
public $programming_language_version;
/**
* @var number|null
*/
public $plan_id;
/**
* @var number|null
*/
public $license_id;
/**
* @var number|null
*/
public $trial_plan_id;
/**
* @var string|null
*/
public $trial_ends;
/**
* @since 1.0.9
*
* @var bool
*/
public $is_premium = false;
/**
* @author Leo Fajardo (@leorw)
*
* @since 1.2.1.5
*
* @var bool
*/
public $is_disconnected = false;
/**
* @since 2.0.0
*
* @var bool
*/
public $is_active = true;
/**
* @since 2.0.0
*
* @var bool
*/
public $is_uninstalled = false;
/**
* @author Edgar Melkonyan
*
* @since 2.4.2
*
* @var bool
*/
public $is_beta;
/**
* @param stdClass|bool $site
*/
function __construct( $site = false ) {
parent::__construct( $site );
if ( is_object( $site ) ) {
$this->plan_id = $site->plan_id;
}
if ( ! is_bool( $this->is_disconnected ) ) {
$this->is_disconnected = false;
}
}
static function get_type() {
return 'install';
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $url
*
* @return bool
*/
static function is_localhost_by_address( $url ) {
if ( false !== strpos( $url, '127.0.0.1' ) ||
false !== strpos( $url, 'localhost' )
) {
return true;
}
if ( ! fs_starts_with( $url, 'http' ) ) {
$url = 'http://' . $url;
}
$url_parts = parse_url( $url );
$subdomain = $url_parts['host'];
return (
// Starts with.
fs_starts_with( $subdomain, 'local.' ) ||
fs_starts_with( $subdomain, 'dev.' ) ||
fs_starts_with( $subdomain, 'test.' ) ||
fs_starts_with( $subdomain, 'stage.' ) ||
fs_starts_with( $subdomain, 'staging.' ) ||
// Ends with.
fs_ends_with( $subdomain, '.dev' ) ||
fs_ends_with( $subdomain, '.test' ) ||
fs_ends_with( $subdomain, '.staging' ) ||
fs_ends_with( $subdomain, '.local' ) ||
fs_ends_with( $subdomain, '.example' ) ||
fs_ends_with( $subdomain, '.invalid' ) ||
// GoDaddy test/dev.
fs_ends_with( $subdomain, '.myftpupload.com' ) ||
// ngrok tunneling.
fs_ends_with( $subdomain, '.ngrok.io' ) ||
// wpsandbox.
fs_ends_with( $subdomain, '.wpsandbox.pro' ) ||
// SiteGround staging.
fs_starts_with( $subdomain, 'staging' ) ||
// WPEngine staging.
fs_ends_with( $subdomain, '.staging.wpengine.com' ) ||
fs_ends_with( $subdomain, '.dev.wpengine.com' ) ||
fs_ends_with( $subdomain, '.wpengine.com' ) ||
// Pantheon
( fs_ends_with( $subdomain, 'pantheonsite.io' ) &&
( fs_starts_with( $subdomain, 'test-' ) || fs_starts_with( $subdomain, 'dev-' ) ) ) ||
// Cloudways
fs_ends_with( $subdomain, '.cloudwaysapps.com' ) ||
// Kinsta
( fs_starts_with( $subdomain, 'staging-' ) && ( fs_ends_with( $subdomain, '.kinsta.com' ) || fs_ends_with( $subdomain, '.kinsta.cloud' ) ) ) ||
// DesktopServer
fs_ends_with( $subdomain, '.dev.cc' ) ||
// Pressable
fs_ends_with( $subdomain, '.mystagingwebsite.com' )
);
}
function is_localhost() {
return ( WP_FS__IS_LOCALHOST_FOR_SERVER || self::is_localhost_by_address( $this->url ) );
}
/**
* Check if site in trial.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_trial() {
return is_numeric( $this->trial_plan_id ) && ( strtotime( $this->trial_ends ) > WP_FS__SCRIPT_START_TIME );
}
/**
* Check if user already utilized the trial with the current install.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_trial_utilized() {
return is_numeric( $this->trial_plan_id );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return bool
*/
function is_tracking_allowed() {
return ( true !== $this->is_disconnected );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return bool
*/
function is_tracking_prohibited() {
return ! $this->is_tracking_allowed();
}
/**
* @author Edgar Melkonyan
*
* @return bool
*/
function is_beta() {
return ( isset( $this->is_beta ) && true === $this->is_beta );
}
}

View File

@ -0,0 +1,147 @@
<?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.9
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Subscription extends FS_Entity {
#region Properties
/**
* @var number
*/
public $user_id;
/**
* @var number
*/
public $install_id;
/**
* @var number
*/
public $plan_id;
/**
* @var number
*/
public $license_id;
/**
* @var float
*/
public $total_gross;
/**
* @var float
*/
public $amount_per_cycle;
/**
* @var int # of months
*/
public $billing_cycle;
/**
* @var float
*/
public $outstanding_balance;
/**
* @var int
*/
public $failed_payments;
/**
* @var string
*/
public $gateway;
/**
* @var string
*/
public $external_id;
/**
* @var string|null
*/
public $trial_ends;
/**
* @var string|null Datetime of the next payment, or null if cancelled.
*/
public $next_payment;
/**
* @since 2.3.1
*
* @var string|null Datetime of the cancellation.
*/
public $canceled_at;
/**
* @var string|null
*/
public $vat_id;
/**
* @var string Two characters country code
*/
public $country_code;
#endregion Properties
/**
* @param object|bool $subscription
*/
function __construct( $subscription = false ) {
parent::__construct( $subscription );
}
static function get_type() {
return 'subscription';
}
/**
* Check if subscription is active.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_active() {
if ( $this->is_canceled() ) {
return false;
}
return (
! empty( $this->next_payment ) &&
strtotime( $this->next_payment ) > WP_FS__SCRIPT_START_TIME
);
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.3.1
*
* @return bool
*/
function is_canceled() {
return ! is_null( $this->canceled_at );
}
/**
* Subscription considered to be new without any payments
* if the next payment should be made within less than 24 hours
* from the subscription creation.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @return bool
*/
function is_first_payment_pending() {
return ( WP_FS__TIME_24_HOURS_IN_SEC >= strtotime( $this->next_payment ) - strtotime( $this->created ) );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.7
*/
function has_trial() {
return ! is_null( $this->trial_ends );
}
}

View File

@ -0,0 +1,62 @@
<?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;
}
class FS_User extends FS_Scope_Entity {
#region Properties
/**
* @var string
*/
public $email;
/**
* @var string
*/
public $first;
/**
* @var string
*/
public $last;
/**
* @var bool
*/
public $is_verified;
/**
* @var string|null
*/
public $customer_id;
/**
* @var float
*/
public $gross;
#endregion Properties
/**
* @param object|bool $user
*/
function __construct( $user = false ) {
parent::__construct( $user );
}
function get_name() {
return trim( ucfirst( trim( is_string( $this->first ) ? $this->first : '' ) ) . ' ' . ucfirst( trim( is_string( $this->last ) ? $this->last : '' ) ) );
}
function is_verified() {
return ( isset( $this->is_verified ) && true === $this->is_verified );
}
static function get_type() {
return 'user';
}
}

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,500 @@
<?php
/**
* IMPORTANT:
* This file will be loaded based on the order of the plugins/themes load.
* If there's a theme and a plugin using Freemius, the plugin's essential
* file will always load first.
*
* @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.1.5
*/
if ( ! function_exists( 'fs_normalize_path' ) ) {
if ( function_exists( 'wp_normalize_path' ) ) {
/**
* Normalize a filesystem path.
*
* Replaces backslashes with forward slashes for Windows systems, and ensures
* no duplicate slashes exist.
*
* @param string $path Path to normalize.
*
* @return string Normalized path.
*/
function fs_normalize_path( $path ) {
return wp_normalize_path( $path );
}
} else {
function fs_normalize_path( $path ) {
$path = str_replace( '\\', '/', $path );
$path = preg_replace( '|/+|', '/', $path );
return $path;
}
}
}
require_once dirname( __FILE__ ) . '/supplements/fs-essential-functions-2.2.1.php';
#region Core Redirect (copied from BuddyPress) -----------------------------------------
if ( ! function_exists( 'fs_redirect' ) ) {
/**
* Redirects to another page, with a workaround for the IIS Set-Cookie bug.
*
* @link http://support.microsoft.com/kb/q176113/
* @since 1.5.1
* @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
*
* @param string $location The path to redirect to.
* @param bool $exit If true, exit after redirect (Since 1.2.1.5).
* @param int $status Status code to use.
*
* @return bool False if $location is not set
*/
function fs_redirect( $location, $exit = true, $status = 302 ) {
global $is_IIS;
$file = '';
$line = '';
if ( headers_sent($file, $line) ) {
if ( WP_FS__DEBUG_SDK && class_exists( 'FS_Admin_Notices' ) ) {
$notices = FS_Admin_Notices::instance( 'global' );
$notices->add( "Freemius failed to redirect the page because the headers have been already sent from line <b><code>{$line}</code></b> in file <b><code>{$file}</code></b>. If it's unexpected, it usually happens due to invalid space and/or EOL character(s).", 'Oops...', 'error' );
}
return false;
}
if ( defined( 'DOING_AJAX' ) ) {
// Don't redirect on AJAX calls.
return false;
}
if ( ! $location ) // allows the wp_redirect filter to cancel a redirect
{
return false;
}
$location = fs_sanitize_redirect( $location );
if ( $is_IIS ) {
header( "Refresh: 0;url=$location" );
} else {
if ( php_sapi_name() != 'cgi-fcgi' ) {
status_header( $status );
} // This causes problems on IIS and some FastCGI setups
header( "Location: $location" );
}
if ( $exit ) {
exit();
}
return true;
}
if ( ! function_exists( 'fs_sanitize_redirect' ) ) {
/**
* Sanitizes a URL for use in a redirect.
*
* @since 2.3
*
* @param string $location
*
* @return string redirect-sanitized URL
*/
function fs_sanitize_redirect( $location ) {
$location = preg_replace( '|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location );
$location = fs_kses_no_null( $location );
// remove %0d and %0a from location
$strip = array( '%0d', '%0a' );
$found = true;
while ( $found ) {
$found = false;
foreach ( (array) $strip as $val ) {
while ( strpos( $location, $val ) !== false ) {
$found = true;
$location = str_replace( $val, '', $location );
}
}
}
return $location;
}
}
if ( ! function_exists( 'fs_kses_no_null' ) ) {
/**
* Removes any NULL characters in $string.
*
* @since 1.0.0
*
* @param string $string
*
* @return string
*/
function fs_kses_no_null( $string ) {
$string = preg_replace( '/\0+/', '', $string );
$string = preg_replace( '/(\\\\0)+/', '', $string );
return $string;
}
}
}
#endregion Core Redirect (copied from BuddyPress) -----------------------------------------
if ( ! function_exists( '__fs' ) ) {
global $fs_text_overrides;
if ( ! isset( $fs_text_overrides ) ) {
$fs_text_overrides = array();
}
/**
* Retrieve a translated text by key.
*
* @deprecated Use `fs_text()` instead since methods starting with `__` trigger warnings in Php 7.
* @todo Remove this method in the future.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.4
*
* @param string $key
* @param string $slug
*
* @return string
*
* @global $fs_text, $fs_text_overrides
*/
function __fs( $key, $slug = 'freemius' ) {
_deprecated_function( __FUNCTION__, '2.0.0', 'fs_text()' );
global $fs_text,
$fs_module_info_text,
$fs_text_overrides;
if ( isset( $fs_text_overrides[ $slug ] ) ) {
if ( isset( $fs_text_overrides[ $slug ][ $key ] ) ) {
return $fs_text_overrides[ $slug ][ $key ];
}
$lower_key = strtolower( $key );
if ( isset( $fs_text_overrides[ $slug ][ $lower_key ] ) ) {
return $fs_text_overrides[ $slug ][ $lower_key ];
}
}
if ( ! isset( $fs_text ) ) {
$dir = defined( 'WP_FS__DIR_INCLUDES' ) ?
WP_FS__DIR_INCLUDES :
dirname( __FILE__ );
require_once $dir . '/i18n.php';
}
if ( isset( $fs_text[ $key ] ) ) {
return $fs_text[ $key ];
}
if ( isset( $fs_module_info_text[ $key ] ) ) {
return $fs_module_info_text[ $key ];
}
return $key;
}
/**
* Output a translated text by key.
*
* @deprecated Use `fs_echo()` instead for consistency with `fs_text()`.
*
* @todo Remove this method in the future.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.4
*
* @param string $key
* @param string $slug
*/
function _efs( $key, $slug = 'freemius' ) {
fs_echo( $key, $slug );
}
}
if ( ! function_exists( 'fs_get_ip' ) ) {
/**
* Get client IP.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.2
*
* @return string|null
*/
function fs_get_ip() {
$fields = array(
'HTTP_CF_CONNECTING_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ( $fields as $ip_field ) {
if ( ! empty( $_SERVER[ $ip_field ] ) ) {
return $_SERVER[ $ip_field ];
}
}
return null;
}
}
/**
* Leverage backtrace to find caller plugin main file path.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @return string
*/
function fs_find_caller_plugin_file() {
/**
* All the code below will be executed once on activation.
* If the user changes the main plugin's file name, the file_exists()
* will catch it.
*/
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$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 ) {
$all_plugins_paths[] = fs_normalize_path( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) );
}
$plugin_file = null;
for ( $i = 1, $bt = debug_backtrace(), $len = count( $bt ); $i < $len; $i ++ ) {
if ( empty( $bt[ $i ]['file'] ) ) {
continue;
}
if ( in_array( fs_normalize_path( $bt[ $i ]['file'] ), $all_plugins_paths ) ) {
$plugin_file = $bt[ $i ]['file'];
break;
}
}
if ( is_null( $plugin_file ) ) {
// Throw an error to the developer in case of some edge case dev environment.
wp_die(
'Freemius SDK couldn\'t find the plugin\'s main file. Please contact sdk@freemius.com with the current error.',
'Error',
array( 'back_link' => true )
);
}
return $plugin_file;
}
require_once dirname( __FILE__ ) . '/supplements/fs-essential-functions-1.1.7.1.php';
/**
* Update SDK newest version reference.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $sdk_relative_path
* @param string|bool $plugin_file
*
* @global $fs_active_plugins
*/
function fs_update_sdk_newest_version( $sdk_relative_path, $plugin_file = false ) {
/**
* If there is a plugin running an older version of FS (1.2.1 or below), the `fs_update_sdk_newest_version()`
* function in the older version will be used instead of this one. But since the older version is using
* the `is_plugin_active` function to check if a plugin is active, passing the theme's `plugin_path` to the
* `is_plugin_active` function will return false since the path is not a plugin path, so `in_activation` will be
* `true` for theme modules and the upgrading of the SDK version to 1.2.2 or newer version will work fine.
*
* Future versions that will call this function will use the proper logic here instead of just relying on the
* `is_plugin_active` function to fail for themes.
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*/
global $fs_active_plugins;
$newest_sdk = $fs_active_plugins->plugins[ $sdk_relative_path ];
if ( ! is_string( $plugin_file ) ) {
$plugin_file = plugin_basename( fs_find_caller_plugin_file() );
}
if ( ! isset( $newest_sdk->type ) || 'theme' !== $newest_sdk->type ) {
if ( ! function_exists( 'is_plugin_active' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$in_activation = ( ! is_plugin_active( $plugin_file ) );
} else {
$theme = wp_get_theme();
$in_activation = ( $newest_sdk->plugin_path == $theme->stylesheet );
}
$fs_active_plugins->newest = (object) array(
'plugin_path' => $plugin_file,
'sdk_path' => $sdk_relative_path,
'version' => $newest_sdk->version,
'in_activation' => $in_activation,
'timestamp' => time(),
);
// Update DB with latest SDK version and path.
update_option( 'fs_active_plugins', $fs_active_plugins );
}
/**
* Reorder the plugins load order so the plugin with the newest Freemius SDK is loaded first.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @return bool Was plugin order changed. Return false if plugin was loaded first anyways.
*
* @global $fs_active_plugins
*/
function fs_newest_sdk_plugin_first() {
global $fs_active_plugins;
/**
* @todo Multi-site network activated plugin are always loaded prior to site plugins so if there's a plugin activated in the network mode that has an older version of the SDK of another plugin which is site activated that has new SDK version, the fs-essential-functions.php will be loaded from the older SDK. Same thing about MU plugins (loaded even before network activated plugins).
*
* @link https://github.com/Freemius/wordpress-sdk/issues/26
*/
$newest_sdk_plugin_path = $fs_active_plugins->newest->plugin_path;
$active_plugins = get_option( 'active_plugins', array() );
$updated_active_plugins = array( $newest_sdk_plugin_path );
$plugin_found = false;
$is_first_path = true;
foreach ( $active_plugins as $key => $plugin_path ) {
if ( $plugin_path === $newest_sdk_plugin_path ) {
if ( $is_first_path ) {
// if it's the first plugin already, no need to continue
return false;
}
$plugin_found = true;
// Skip the plugin (it is already added as the 1st item of $updated_active_plugins).
continue;
}
$updated_active_plugins[] = $plugin_path;
if ( $is_first_path ) {
$is_first_path = false;
}
}
if ( $plugin_found ) {
update_option( 'active_plugins', $updated_active_plugins );
return true;
}
if ( is_multisite() ) {
// Plugin is network active.
$network_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if ( isset( $network_active_plugins[ $newest_sdk_plugin_path ] ) ) {
reset( $network_active_plugins );
if ( $newest_sdk_plugin_path === key( $network_active_plugins ) ) {
// Plugin is already activated first on the network level.
return false;
} else {
$time = $network_active_plugins[ $newest_sdk_plugin_path ];
// Remove plugin from its current position.
unset( $network_active_plugins[ $newest_sdk_plugin_path ] );
// Set it to be included first.
$network_active_plugins = array( $newest_sdk_plugin_path => $time ) + $network_active_plugins;
update_site_option( 'active_sitewide_plugins', $network_active_plugins );
return true;
}
}
}
return false;
}
/**
* Go over all Freemius SDKs in the system and find and "remember"
* the newest SDK which is associated with an active plugin.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @global $fs_active_plugins
*/
function fs_fallback_to_newest_active_sdk() {
global $fs_active_plugins;
/**
* @var object $newest_sdk_data
*/
$newest_sdk_data = null;
$newest_sdk_path = null;
foreach ( $fs_active_plugins->plugins as $sdk_relative_path => $data ) {
if ( is_null( $newest_sdk_data ) || version_compare( $data->version, $newest_sdk_data->version, '>' )
) {
// If plugin inactive or SDK starter file doesn't exist, remove SDK reference.
if ( 'plugin' === $data->type ) {
$is_module_active = is_plugin_active( $data->plugin_path );
} else {
$active_theme = wp_get_theme();
$is_module_active = ( $data->plugin_path === $active_theme->get_template() );
}
$is_sdk_exists = file_exists( fs_normalize_path( WP_PLUGIN_DIR . '/' . $sdk_relative_path . '/start.php' ) );
if ( ! $is_module_active || ! $is_sdk_exists ) {
unset( $fs_active_plugins->plugins[ $sdk_relative_path ] );
// No need to store the data since it will be stored in fs_update_sdk_newest_version()
// or explicitly with update_option().
} else {
$newest_sdk_data = $data;
$newest_sdk_path = $sdk_relative_path;
}
}
}
if ( is_null( $newest_sdk_data ) ) {
// Couldn't find any SDK reference.
$fs_active_plugins = new stdClass();
update_option( 'fs_active_plugins', $fs_active_plugins );
} else {
fs_update_sdk_newest_version( $newest_sdk_path, $newest_sdk_data->plugin_path );
}
}

View File

@ -0,0 +1,605 @@
<?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.1.4
*
* @deprecated This file is no longer in use. It's still in the project for backward compatibility.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once dirname( __FILE__ ) . '/l10n.php';
/**
* All strings can now be overridden.
*
* For example, if we want to override:
* 'you-are-step-away' => 'You are just one step away - %s',
*
* We can use the filter:
* fs_override_i18n( array(
* 'opt-in-connect' => __( "Yes - I'm in!", '{your-text_domain}' ),
* 'skip' => __( 'Not today', '{your-text_domain}' ),
* ), '{plugin_slug}' );
*
* Or with the Freemius instance:
*
* my_freemius->override_i18n( array(
* 'opt-in-connect' => __( "Yes - I'm in!", '{your-text_domain}' ),
* 'skip' => __( 'Not today', '{your-text_domain}' ),
* ) );
*/
global $fs_text;
$fs_text = array(
'account' => _fs_text( 'Account' ),
'addon' => _fs_text( 'Add-On' ),
'contact-us' => _fs_text( 'Contact Us' ),
'contact-support' => _fs_text( 'Contact Support' ),
'change-ownership' => _fs_text( 'Change Ownership' ),
'support' => _fs_text( 'Support' ),
'support-forum' => _fs_text( 'Support Forum' ),
'add-ons' => _fs_text( 'Add-Ons' ),
'upgrade' => _fs_x( 'Upgrade', 'verb' ),
'awesome' => _fs_text( 'Awesome' ),
'pricing' => _fs_x( 'Pricing', 'noun' ),
'price' => _fs_x( 'Price', 'noun' ),
'unlimited-updates' => _fs_text( 'Unlimited Updates' ),
'downgrade' => _fs_x( 'Downgrade', 'verb' ),
'cancel-subscription' => _fs_x( 'Cancel Subscription', 'verb' ),
'cancel-trial' => _fs_text( 'Cancel Trial' ),
'free-trial' => _fs_text( 'Free Trial' ),
'start-free-x' => _fs_text( 'Start my free %s' ),
'no-commitment-x' => _fs_text( 'No commitment for %s - cancel anytime' ),
'after-x-pay-as-little-y' => _fs_text( 'After your free %s, pay as little as %s' ),
'details' => _fs_text( 'Details' ),
'account-details' => _fs_text( 'Account Details' ),
'delete' => _fs_x( 'Delete', 'verb' ),
'show' => _fs_x( 'Show', 'verb' ),
'hide' => _fs_x( 'Hide', 'verb' ),
'edit' => _fs_x( 'Edit', 'verb' ),
'update' => _fs_x( 'Update', 'verb' ),
'date' => _fs_text( 'Date' ),
'amount' => _fs_text( 'Amount' ),
'invoice' => _fs_text( 'Invoice' ),
'billing' => _fs_text( 'Billing' ),
'payments' => _fs_text( 'Payments' ),
'delete-account' => _fs_text( 'Delete Account' ),
'dismiss' => _fs_x( 'Dismiss', 'as close a window' ),
'plan' => _fs_x( 'Plan', 'as product pricing plan' ),
'change-plan' => _fs_text( 'Change Plan' ),
'download-x-version' => _fs_x( 'Download %s Version', 'as download professional version' ),
'download-x-version-now' => _fs_x( 'Download %s version now', 'as download professional version now' ),
'download-latest' => _fs_x( 'Download Latest', 'as download latest version' ),
'you-have-x-license' => _fs_x( 'You have a %s license.', 'E.g. you have a professional license.' ),
'new' => _fs_text( 'New' ),
'free' => _fs_text( 'Free' ),
'trial' => _fs_x( 'Trial', 'as trial plan' ),
'start-trial' => _fs_x( 'Start Trial', 'as starting a trial plan' ),
'purchase' => _fs_x( 'Purchase', 'verb' ),
'purchase-license' => _fs_text( 'Purchase License' ),
'buy' => _fs_x( 'Buy', 'verb' ),
'buy-license' => _fs_text( 'Buy License' ),
'license-single-site' => _fs_text( 'Single Site License' ),
'license-unlimited' => _fs_text( 'Unlimited Licenses' ),
'license-x-sites' => _fs_text( 'Up to %s Sites' ),
'renew-license-now' => _fs_text( '%sRenew your license now%s to access version %s security & feature updates, and support.' ),
'ask-for-upgrade-email-address' => _fs_text( "Enter the email address you've used for the upgrade below and we will resend you the license key." ),
'x-plan' => _fs_x( '%s Plan', 'e.g. Professional Plan' ),
'you-are-step-away' => _fs_text( 'You are just one step away - %s' ),
'activate-x-now' => _fs_x( 'Complete "%s" Activation Now',
'%s - plugin name. As complete "Jetpack" activation now' ),
'few-plugin-tweaks' => _fs_text( 'We made a few tweaks to the %s, %s' ),
'optin-x-now' => _fs_text( 'Opt in to make "%s" better!' ),
'error' => _fs_text( 'Error' ),
'failed-finding-main-path' => _fs_text( 'Freemius SDK couldn\'t find the plugin\'s main file. Please contact sdk@freemius.com with the current error.' ),
'learn-more' => _fs_text( 'Learn more' ),
'license_not_whitelabeled' => _fs_text( "Is this your client's site? %s if you wish to hide sensitive info like your billing address and invoices from the WP Admin."),
'license_whitelabeled' => _fs_text( 'Your %s license was flagged as white-labeled to hide sensitive information from the WP Admin (e.g. your billing address and invoices). If you ever wish to revert it back, you can easily do it through your %s. If this was a mistake you can also %s.'),
#region Affiliation
'affiliation' => _fs_text( 'Affiliation' ),
'affiliate' => _fs_text( 'Affiliate' ),
'affiliate-tracking' => _fs_text( '%s tracking cookie after the first visit to maximize earnings potential.' ),
'renewals-commission' => _fs_text( 'Get commission for automated subscription renewals.' ),
'affiliate-application-accepted' => _fs_text( "Your affiliate application for %s has been accepted! Log in to your affiliate area at: %s." ),
'affiliate-application-thank-you' => _fs_text( "Thank you for applying for our affiliate program, we'll review your details during the next 14 days and will get back to you with further information." ),
'affiliate-application-rejected' => _fs_text( "Thank you for applying for our affiliate program, unfortunately, we've decided at this point to reject your application. Please try again in 30 days." ),
'affiliate-account-suspended' => _fs_text( 'Your affiliation account was temporarily suspended.' ),
'affiliate-account-blocked' => _fs_text( 'Due to violation of our affiliation terms, we decided to temporarily block your affiliation account. If you have any questions, please contact support.' ),
'become-an-ambassador' => _fs_text( 'Like the %s? Become our ambassador and earn cash ;-)' ),
'become-an-ambassador-admin-notice' => _fs_text( 'Hey there, did you know that %s has an affiliate program? If you like the %s you can become our ambassador and earn some cash!' ),
'refer-new-customers' => _fs_text( 'Refer new customers to our %s and earn %s commission on each successful sale you refer!' ),
'program-summary' => _fs_text( 'Program Summary' ),
'commission-on-new-license-purchase' => _fs_text( '%s commission when a customer purchases a new license.' ),
'unlimited-commissions' => _fs_text( 'Unlimited commissions.' ),
'minimum-payout-amount' => _fs_text( '%s minimum payout amount.' ),
'payouts-unit-and-processing' => _fs_text( 'Payouts are in USD and processed monthly via PayPal.' ),
'commission-payment' => _fs_text( 'As we reserve 30 days for potential refunds, we only pay commissions that are older than 30 days.' ),
'become-an-affiliate' => _fs_text( 'Become an affiliate' ),
'apply-to-become-an-affiliate' => _fs_text( 'Apply to become an affiliate' ),
'full-name' => _fs_text( 'Full name' ),
'paypal-account-email-address' => _fs_text( 'PayPal account email address' ),
'promotion-methods' => _fs_text( 'Promotion methods' ),
'social-media' => _fs_text( 'Social media (Facebook, Twitter, etc.)' ),
'mobile-apps' => _fs_text( 'Mobile apps' ),
'statistics-information-field-label' => _fs_text( 'Website, email, and social media statistics (optional)' ),
'statistics-information-field-desc' => _fs_text( 'Please feel free to provide any relevant website or social media statistics, e.g. monthly unique site visits, number of email subscribers, followers, etc. (we will keep this information confidential).' ),
'promotion-method-desc-field-label' => _fs_text( 'How will you promote us?' ),
'promotion-method-desc-field-desc' => _fs_text( 'Please provide details on how you intend to promote %s (please be as specific as possible).' ),
'domain-field-label' => _fs_text( 'Where are you going to promote the %s?' ),
'domain-field-desc' => _fs_text( 'Enter the domain of your website or other websites from where you plan to promote the %s.' ),
'extra-domain-fields-label' => _fs_text( 'Extra Domains' ),
'extra-domain-fields-desc' => _fs_text( 'Extra domains where you will be marketing the product from.' ),
'add-another-domain' => _fs_text( 'Add another domain' ),
'remove' => _fs_x( 'Remove', 'Remove domain' ),
'email-address-is-required' => _fs_text( 'Email address is required.' ),
'domain-is-required' => _fs_text( 'Domain is required.' ),
'invalid-domain' => _fs_text( 'Invalid domain' ),
'paypal-email-address-is-required' => _fs_text( 'PayPal email address is required.' ),
'processing' => _fs_text( 'Processing...' ),
'non-expiring' => _fs_text( 'Non-expiring' ),
'account-is-pending-activation' => _fs_text( 'Account is pending activation.' ),
#endregion Affiliation
#region Account
'expiration' => _fs_x( 'Expiration', 'as expiration date' ),
'license' => _fs_x( 'License', 'as software license' ),
'not-verified' => _fs_text( 'not verified' ),
'verify-email' => _fs_text( 'Verify Email' ),
'expires-in' => _fs_x( 'Expires in %s', 'e.g. expires in 2 months' ),
'renews-in' => _fs_x( 'Auto renews in %s', 'e.g. auto renews in 2 months' ),
'no-expiration' => _fs_text( 'No expiration' ),
'expired' => _fs_text( 'Expired' ),
'cancelled' => _fs_text( 'Cancelled' ),
'in-x' => _fs_x( 'In %s', 'e.g. In 2 hours' ),
'x-ago' => _fs_x( '%s ago', 'e.g. 2 min ago' ),
/* translators: %s: Version number (e.g. 4.6 or higher) */
'x-or-higher' => _fs_text( '%s or higher' ),
'version' => _fs_x( 'Version', 'as plugin version' ),
'name' => _fs_text( 'Name' ),
'email' => _fs_text( 'Email' ),
'email-address' => _fs_text( 'Email address' ),
'verified' => _fs_text( 'Verified' ),
'module' => _fs_text( 'Module' ),
'module-type' => _fs_text( 'Module Type' ),
'plugin' => _fs_text( 'Plugin' ),
'plugins' => _fs_text( 'Plugins' ),
'theme' => _fs_text( 'Theme' ),
'themes' => _fs_text( 'Themes' ),
'path' => _fs_x( 'Path', 'as file/folder path' ),
'title' => _fs_text( 'Title' ),
'free-version' => _fs_text( 'Free version' ),
'premium-version' => _fs_text( 'Premium version' ),
'slug' => _fs_x( 'Slug', 'as WP plugin slug' ),
'id' => _fs_text( 'ID' ),
'users' => _fs_text( 'Users' ),
'module-installs' => _fs_text( '%s Installs' ),
'sites' => _fs_x( 'Sites', 'like websites' ),
'user-id' => _fs_text( 'User ID' ),
'site-id' => _fs_text( 'Site ID' ),
'public-key' => _fs_text( 'Public Key' ),
'secret-key' => _fs_text( 'Secret Key' ),
'no-secret' => _fs_x( 'No Secret', 'as secret encryption key missing' ),
'no-id' => _fs_text( 'No ID' ),
'sync-license' => _fs_x( 'Sync License', 'as synchronize license' ),
'sync' => _fs_x( 'Sync', 'as synchronize' ),
'activate-license' => _fs_text( 'Activate License' ),
'activate-free-version' => _fs_text( 'Activate Free Version' ),
'activate-license-message' => _fs_text( 'Please enter the license key that you received in the email right after the purchase:' ),
'activating-license' => _fs_text( 'Activating license...' ),
'change-license' => _fs_text( 'Change License' ),
'update-license' => _fs_text( 'Update License' ),
'deactivate-license' => _fs_text( 'Deactivate License' ),
'activate' => _fs_text( 'Activate' ),
'deactivate' => _fs_text( 'Deactivate' ),
'skip-deactivate' => _fs_text( 'Skip & Deactivate' ),
'skip-and-x' => _fs_text( 'Skip & %s' ),
'no-deactivate' => _fs_text( 'No - just deactivate' ),
'yes-do-your-thing' => _fs_text( 'Yes - do your thing' ),
'active' => _fs_x( 'Active', 'active mode' ),
'is-active' => _fs_x( 'Is Active', 'is active mode?' ),
'install-now' => _fs_text( 'Install Now' ),
'install-update-now' => _fs_text( 'Install Update Now' ),
'more-information-about-x' => _fs_text( 'More information about %s' ),
'localhost' => _fs_text( 'Localhost' ),
'activate-x-plan' => _fs_x( 'Activate %s Plan', 'as activate Professional plan' ),
'x-left' => _fs_x( '%s left', 'as 5 licenses left' ),
'last-license' => _fs_text( 'Last license' ),
'what-is-your-x' => _fs_text( 'What is your %s?' ),
'activate-this-addon' => _fs_text( 'Activate this add-on' ),
'deactivate-license-confirm' => _fs_text( 'Deactivating your license will block all premium features, but will enable you to activate the license on another site. Are you sure you want to proceed?' ),
'delete-account-x-confirm' => _fs_text( 'Deleting the account will automatically deactivate your %s plan license so you can use it on other sites. If you want to terminate the recurring payments as well, click the "Cancel" button, and first "Downgrade" your account. Are you sure you would like to continue with the deletion?' ),
'delete-account-confirm' => _fs_text( 'Deletion is not temporary. Only delete if you no longer want to use this %s anymore. Are you sure you would like to continue with the deletion?' ),
'downgrade-x-confirm' => _fs_text( 'Downgrading your plan will immediately stop all future recurring payments and your %s plan license will expire in %s.' ),
'cancel-trial-confirm' => _fs_text( 'Cancelling the trial will immediately block access to all premium features. Are you sure?' ),
'after-downgrade-non-blocking' => _fs_text( 'You can still enjoy all %s features but you will not have access to %s security & feature updates, nor support.' ),
'after-downgrade-blocking' => _fs_text( 'Once your license expires you can still use the Free version but you will NOT have access to the %s features.' ),
'proceed-confirmation' => _fs_text( 'Are you sure you want to proceed?' ),
#endregion Account
'add-ons-for-x' => _fs_text( 'Add Ons for %s' ),
'add-ons-missing' => _fs_text( 'We could\'nt load the add-ons list. It\'s probably an issue on our side, please try to come back in few minutes.' ),
#region Plugin Deactivation
'anonymous-feedback' => _fs_text( 'Anonymous feedback' ),
'quick-feedback' => _fs_text( 'Quick feedback' ),
'deactivation-share-reason' => _fs_text( 'If you have a moment, please let us know why you are %s' ),
'deactivating' => _fs_text( 'deactivating' ),
'deactivation' => _fs_text( 'Deactivation' ),
'theme-switch' => _fs_text( 'Theme Switch' ),
'switching' => _fs_text( 'switching' ),
'switch' => _fs_text( 'Switch' ),
'activate-x' => _fs_text( 'Activate %s' ),
'deactivation-modal-button-confirm' => _fs_text( 'Yes - %s' ),
'deactivation-modal-button-submit' => _fs_text( 'Submit & %s' ),
'cancel' => _fs_text( 'Cancel' ),
'reason-no-longer-needed' => _fs_text( 'I no longer need the %s' ),
'reason-found-a-better-plugin' => _fs_text( 'I found a better %s' ),
'reason-needed-for-a-short-period' => _fs_text( 'I only needed the %s for a short period' ),
'reason-broke-my-site' => _fs_text( 'The %s broke my site' ),
'reason-suddenly-stopped-working' => _fs_text( 'The %s suddenly stopped working' ),
'reason-cant-pay-anymore' => _fs_text( "I can't pay for it anymore" ),
'reason-temporary-deactivation' => _fs_text( "It's a temporary deactivation. I'm just debugging an issue." ),
'reason-temporary-x' => _fs_text( "It's a temporary %s. I'm just debugging an issue." ),
'reason-other' => _fs_x( 'Other',
'the text of the "other" reason for deactivating the module that is shown in the modal box.' ),
'ask-for-reason-message' => _fs_text( 'Kindly tell us the reason so we can improve.' ),
'placeholder-plugin-name' => _fs_text( "What's the %s's name?" ),
'placeholder-comfortable-price' => _fs_text( 'What price would you feel comfortable paying?' ),
'reason-couldnt-make-it-work' => _fs_text( "I couldn't understand how to make it work" ),
'reason-great-but-need-specific-feature' => _fs_text( "The %s is great, but I need specific feature that you don't support" ),
'reason-not-working' => _fs_text( 'The %s is not working' ),
'reason-not-what-i-was-looking-for' => _fs_text( "It's not what I was looking for" ),
'reason-didnt-work-as-expected' => _fs_text( "The %s didn't work as expected" ),
'placeholder-feature' => _fs_text( 'What feature?' ),
'placeholder-share-what-didnt-work' => _fs_text( "Kindly share what didn't work so we can fix it for future users..." ),
'placeholder-what-youve-been-looking-for' => _fs_text( "What you've been looking for?" ),
'placeholder-what-did-you-expect' => _fs_text( "What did you expect?" ),
'reason-didnt-work' => _fs_text( "The %s didn't work" ),
'reason-dont-like-to-share-my-information' => _fs_text( "I don't like to share my information with you" ),
'dont-have-to-share-any-data' => _fs_text( "You might have missed it, but you don't have to share any data and can just %s the opt-in." ),
#endregion Plugin Deactivation
#region Connect
'hey-x' => _fs_x( 'Hey %s,', 'greeting' ),
'thanks-x' => _fs_x( 'Thanks %s!', 'a greeting. E.g. Thanks John!' ),
'connect-message' => _fs_text( 'Never miss an important update - opt in to our security and feature updates notifications, and non-sensitive diagnostic tracking with %4$s.' ),
'connect-message_on-update' => _fs_text( 'Please help us improve %1$s! If you opt in, some data about your usage of %1$s will be sent to %4$s. If you skip this, that\'s okay! %1$s will still work just fine.' ),
'pending-activation-message' => _fs_text( 'You should receive an activation email for %s to your mailbox at %s. Please make sure you click the activation button in that email to %s.' ),
'complete-the-install' => _fs_text( 'complete the install' ),
'start-the-trial' => _fs_text( 'start the trial' ),
'thanks-for-purchasing' => _fs_text( 'Thanks for purchasing %s! To get started, please enter your license key:' ),
'license-sync-disclaimer' => _fs_text( 'The %1$s will be periodically sending data to %2$s to check for security and feature updates, and verify the validity of your license.' ),
'what-permissions' => _fs_text( 'What permissions are being granted?' ),
'permissions-profile' => _fs_text( 'Your Profile Overview' ),
'permissions-profile_desc' => _fs_text( 'Name and email address' ),
'permissions-site' => _fs_text( 'Your Site Overview' ),
'permissions-site_desc' => _fs_text( 'Site URL, WP version, PHP info, plugins & themes' ),
'permissions-events' => _fs_text( 'Current %s Events' ),
'permissions-events_desc' => _fs_text( 'Activation, deactivation and uninstall' ),
'permissions-plugins_themes' => _fs_text( 'Plugins & Themes' ),
'permissions-plugins_themes_desc' => _fs_text( 'Titles, versions and state.' ),
'permissions-admin-notices' => _fs_text( 'Admin Notices' ),
'permissions-newsletter' => _fs_text( 'Newsletter' ),
'permissions-newsletter_desc' => _fs_text( 'Updates, announcements, marketing, no spam' ),
'privacy-policy' => _fs_text( 'Privacy Policy' ),
'tos' => _fs_text( 'Terms of Service' ),
'activating' => _fs_x( 'Activating', 'as activating plugin' ),
'sending-email' => _fs_x( 'Sending email', 'as in the process of sending an email' ),
'opt-in-connect' => _fs_x( 'Allow & Continue', 'button label' ),
'agree-activate-license' => _fs_x( 'Agree & Activate License', 'button label' ),
'skip' => _fs_x( 'Skip', 'verb' ),
'click-here-to-use-plugin-anonymously' => _fs_text( 'Click here to use the plugin anonymously' ),
'resend-activation-email' => _fs_text( 'Re-send activation email' ),
'license-key' => _fs_text( 'License key' ),
'send-license-key' => _fs_text( 'Send License Key' ),
'sending-license-key' => _fs_text( 'Sending license key' ),
'have-license-key' => _fs_text( 'Have a license key?' ),
'dont-have-license-key' => _fs_text( 'Don\'t have a license key?' ),
'cant-find-license-key' => _fs_text( "Can't find your license key?" ),
'email-not-found' => _fs_text( "We couldn't find your email address in the system, are you sure it's the right address?" ),
'no-active-licenses' => _fs_text( "We can't see any active licenses associated with that email address, are you sure it's the right address?" ),
'opt-in' => _fs_text( 'Opt In' ),
'opt-out' => _fs_text( 'Opt Out' ),
'opt-out-cancel' => _fs_text( 'On second thought - I want to continue helping' ),
'opting-out' => _fs_text( 'Opting out...' ),
'opting-in' => _fs_text( 'Opting in...' ),
'opt-out-message-appreciation' => _fs_text( 'We appreciate your help in making the %s better by letting us track some usage data.' ),
'opt-out-message-usage-tracking' => _fs_text( "Usage tracking is done in the name of making %s better. Making a better user experience, prioritizing new features, and more good things. We'd really appreciate if you'll reconsider letting us continue with the tracking." ),
'opt-out-message-clicking-opt-out' => _fs_text( 'By clicking "Opt Out", we will no longer be sending any data from %s to %s.' ),
'apply-on-all-sites-in-the-network' => _fs_text( 'Apply on all sites in the network.' ),
'delegate-to-site-admins' => _fs_text( 'Delegate to Site Admins' ),
'delegate-to-site-admins-and-continue' => _fs_text( 'Delegate to Site Admins & Continue' ),
'continue' => _fs_text( 'Continue' ),
'allow' => _fs_text( 'allow' ),
'delegate' => _fs_text( 'delegate' ),
#endregion Connect
#region Screenshots
'screenshots' => _fs_text( 'Screenshots' ),
'view-full-size-x' => _fs_text( 'Click to view full-size screenshot %d' ),
#endregion Screenshots
#region Debug
'freemius-debug' => _fs_text( 'Freemius Debug' ),
'on' => _fs_x( 'On', 'as turned on' ),
'off' => _fs_x( 'Off', 'as turned off' ),
'debugging' => _fs_x( 'Debugging', 'as code debugging' ),
'freemius-state' => _fs_text( 'Freemius State' ),
'connected' => _fs_x( 'Connected', 'as connection was successful' ),
'blocked' => _fs_x( 'Blocked', 'as connection blocked' ),
'api' => _fs_x( 'API', 'as application program interface' ),
'sdk' => _fs_x( 'SDK', 'as software development kit versions' ),
'sdk-versions' => _fs_x( 'SDK Versions', 'as software development kit versions' ),
'plugin-path' => _fs_x( 'Plugin Path', 'as plugin folder path' ),
'sdk-path' => _fs_x( 'SDK Path', 'as sdk path' ),
'addons-of-x' => _fs_text( 'Add Ons of Plugin %s' ),
'delete-all-confirm' => _fs_text( 'Are you sure you want to delete all Freemius data?' ),
'actions' => _fs_text( 'Actions' ),
'delete-all-accounts' => _fs_text( 'Delete All Accounts' ),
'start-fresh' => _fs_text( 'Start Fresh' ),
'clear-api-cache' => _fs_text( 'Clear API Cache' ),
'sync-data-from-server' => _fs_text( 'Sync Data From Server' ),
'scheduled-crons' => _fs_text( 'Scheduled Crons' ),
'cron-type' => _fs_text( 'Cron Type' ),
'plugins-themes-sync' => _fs_text( 'Plugins & Themes Sync' ),
'module-licenses' => _fs_text( '%s Licenses' ),
'debug-log' => _fs_text( 'Debug Log' ),
'all' => _fs_text( 'All' ),
'file' => _fs_text( 'File' ),
'function' => _fs_text( 'Function' ),
'process-id' => _fs_text( 'Process ID' ),
'logger' => _fs_text( 'Logger' ),
'message' => _fs_text( 'Message' ),
'download' => _fs_text( 'Download' ),
'filter' => _fs_text( 'Filter' ),
'type' => _fs_text( 'Type' ),
'all-types' => _fs_text( 'All Types' ),
'all-requests' => _fs_text( 'All Requests' ),
#endregion Debug
#region Expressions
'congrats' => _fs_x( 'Congrats', 'as congratulations' ),
'oops' => _fs_x( 'Oops', 'exclamation' ),
'yee-haw' => _fs_x( 'Yee-haw', 'interjection expressing joy or exuberance' ),
'woot' => _fs_x( 'W00t',
'(especially in electronic communication) used to express elation, enthusiasm, or triumph.' ),
'right-on' => _fs_x( 'Right on', 'a positive response' ),
'hmm' => _fs_x( 'Hmm',
'something somebody says when they are thinking about what you have just said. ' ),
'ok' => _fs_text( 'O.K' ),
'hey' => _fs_x( 'Hey', 'exclamation' ),
'heads-up' => _fs_x( 'Heads up',
'advance notice of something that will need attention.' ),
#endregion Expressions
#region Admin Notices
'you-have-latest' => _fs_text( 'Seems like you got the latest release.' ),
'you-are-good' => _fs_text( 'You are all good!' ),
'user-exist-message' => _fs_text( 'Sorry, we could not complete the email update. Another user with the same email is already registered.' ),
'user-exist-message_ownership' => _fs_text( 'If you would like to give up the ownership of the %s\'s account to %s click the Change Ownership button.' ),
'email-updated-message' => _fs_text( 'Your email was successfully updated. You should receive an email with confirmation instructions in few moments.' ),
'name-updated-message' => _fs_text( 'Your name was successfully updated.' ),
'x-updated' => _fs_text( 'You have successfully updated your %s.' ),
'name-update-failed-message' => _fs_text( 'Please provide your full name.' ),
'verification-email-sent-message' => _fs_text( 'Verification mail was just sent to %s. If you can\'t find it after 5 min, please check your spam box.' ),
'addons-info-external-message' => _fs_text( 'Just letting you know that the add-ons information of %s is being pulled from an external server.' ),
'no-cc-required' => _fs_text( 'No credit card required' ),
'premium-activated-message' => _fs_text( 'Premium %s version was successfully activated.' ),
'successful-version-upgrade-message' => _fs_text( 'The upgrade of %s was successfully completed.' ),
'activation-with-plan-x-message' => _fs_text( 'Your account was successfully activated with the %s plan.' ),
'download-latest-x-version-now' => _fs_text( 'Download the latest %s version now' ),
'follow-steps-to-complete-upgrade' => _fs_text( 'Please follow these steps to complete the upgrade' ),
'download-latest-x-version' => _fs_text( 'Download the latest %s version' ),
'download-latest-version' => _fs_text( 'Download the latest version' ),
'deactivate-free-version' => _fs_text( 'Deactivate the free version' ),
'upload-and-activate' => _fs_text( 'Upload and activate the downloaded version' ),
'howto-upload-activate' => _fs_text( 'How to upload and activate?' ),
'addon-successfully-purchased-message' => _fs_x( '%s Add-on was successfully purchased.',
'%s - product name, e.g. Facebook add-on was successfully...' ),
'addon-successfully-upgraded-message' => _fs_text( 'Your %s Add-on plan was successfully upgraded.' ),
'email-verified-message' => _fs_text( 'Your email has been successfully verified - you are AWESOME!' ),
'plan-upgraded-message' => _fs_text( 'Your plan was successfully upgraded.' ),
'plan-changed-to-x-message' => _fs_text( 'Your plan was successfully changed to %s.' ),
'license-expired-blocking-message' => _fs_text( 'Your license has expired. You can still continue using the free %s forever.' ),
'license-cancelled' => _fs_text( 'Your license has been cancelled. If you think it\'s a mistake, please contact support.' ),
'trial-started-message' => _fs_text( 'Your trial has been successfully started.' ),
'license-activated-message' => _fs_text( 'Your license was successfully activated.' ),
'no-active-license-message' => _fs_text( 'It looks like your site currently doesn\'t have an active license.' ),
'license-deactivation-message' => _fs_text( 'Your license was successfully deactivated, you are back to the %s plan.' ),
'license-deactivation-failed-message' => _fs_text( 'It looks like the license deactivation failed.' ),
'license-activation-failed-message' => _fs_text( 'It looks like the license could not be activated.' ),
'server-error-message' => _fs_text( 'Error received from the server:' ),
'trial-expired-message' => _fs_text( 'Your trial has expired. You can still continue using all our free features.' ),
'plan-x-downgraded-message' => _fs_text( 'Your plan was successfully downgraded. Your %s plan license will expire in %s.' ),
'plan-downgraded-failure-message' => _fs_text( 'Seems like we are having some temporary issue with your plan downgrade. Please try again in few minutes.' ),
'trial-cancel-no-trial-message' => _fs_text( 'It looks like you are not in trial mode anymore so there\'s nothing to cancel :)' ),
'trial-cancel-message' => _fs_text( 'Your %s free trial was successfully cancelled.' ),
'version-x-released' => _fs_x( 'Version %s was released.', '%s - numeric version number' ),
'please-download-x' => _fs_text( 'Please download %s.' ),
'latest-x-version' => _fs_x( 'the latest %s version here',
'%s - plan name, as the latest professional version here' ),
'trial-x-promotion-message' => _fs_text( 'How do you like %s so far? Test all our %s premium features with a %d-day free trial.' ),
'start-free-trial' => _fs_x( 'Start free trial', 'call to action' ),
'starting-trial' => _fs_text( 'Starting trial' ),
'please-wait' => _fs_text( 'Please wait' ),
'trial-cancel-failure-message' => _fs_text( 'Seems like we are having some temporary issue with your trial cancellation. Please try again in few minutes.' ),
'trial-utilized' => _fs_text( 'You already utilized a trial before.' ),
'in-trial-mode' => _fs_text( 'You are already running the %s in a trial mode.' ),
'trial-plan-x-not-exist' => _fs_text( 'Plan %s do not exist, therefore, can\'t start a trial.' ),
'plan-x-no-trial' => _fs_text( 'Plan %s does not support a trial period.' ),
'no-trials' => _fs_text( 'None of the %s\'s plans supports a trial period.' ),
'unexpected-api-error' => _fs_text( 'Unexpected API error. Please contact the %s\'s author with the following error.' ),
'no-commitment-for-x-days' => _fs_text( 'No commitment for %s days - cancel anytime!' ),
'license-expired-non-blocking-message' => _fs_text( 'Your license has expired. You can still continue using all the %s features, but you\'ll need to renew your license to continue getting updates and support.' ),
'could-not-activate-x' => _fs_text( 'Couldn\'t activate %s.' ),
'contact-us-with-error-message' => _fs_text( 'Please contact us with the following message:' ),
'plan-did-not-change-message' => _fs_text( 'It looks like you are still on the %s plan. If you did upgrade or change your plan, it\'s probably an issue on our side - sorry.' ),
'contact-us-here' => _fs_text( 'Please contact us here' ),
'plan-did-not-change-email-message' => _fs_text( 'I have upgraded my account but when I try to Sync the License, the plan remains %s.' ),
#endregion Admin Notices
#region Connectivity Issues
'connectivity-test-fails-message' => _fs_text( 'From unknown reason, the API connectivity test failed.' ),
'connectivity-test-maybe-temporary' => _fs_text( 'It\'s probably a temporary issue on our end. Just to be sure, with your permission, would it be o.k to run another connectivity test?' ),
'curl-missing-message' => _fs_text( 'We use PHP cURL library for the API calls, which is a very common library and usually installed and activated out of the box. Unfortunately, cURL is not activated (or disabled) on your server.' ),
'curl-disabled-methods' => _fs_text( 'Disabled method(s):' ),
'cloudflare-blocks-connection-message' => _fs_text( 'From unknown reason, CloudFlare, the firewall we use, blocks the connection.' ),
'x-requires-access-to-api' => _fs_x( '%s requires an access to our API.',
'as pluginX requires an access to our API' ),
'squid-blocks-connection-message' => _fs_text( 'It looks like your server is using Squid ACL (access control lists), which blocks the connection.' ),
'squid-no-clue-title' => _fs_text( 'I don\'t know what is Squid or ACL, help me!' ),
'squid-no-clue-desc' => _fs_text( 'We\'ll make sure to contact your hosting company and resolve the issue. You will get a follow-up email to %s once we have an update.' ),
'sysadmin-title' => _fs_text( 'I\'m a system administrator' ),
'squid-sysadmin-desc' => _fs_text( 'Great, please whitelist the following domains: %s. Once you are done, deactivate the %s and activate it again.' ),
'curl-missing-no-clue-title' => _fs_text( 'I don\'t know what is cURL or how to install it, help me!' ),
'curl-missing-no-clue-desc' => _fs_text( 'We\'ll make sure to contact your hosting company and resolve the issue. You will get a follow-up email to %s once we have an update.' ),
'curl-missing-sysadmin-desc' => _fs_text( 'Great, please install cURL and enable it in your php.ini file. In addition, search for the \'disable_functions\' directive in your php.ini file and remove any disabled methods starting with \'curl_\'. To make sure it was successfully activated, use \'phpinfo()\'. Once activated, deactivate the %s and reactivate it back again.' ),
'happy-to-resolve-issue-asap' => _fs_text( 'We are sure it\'s an issue on our side and more than happy to resolve it for you ASAP if you give us a chance.' ),
'contact-support-before-deactivation' => _fs_text( 'Sorry for the inconvenience and we are here to help if you give us a chance.' ),
'fix-issue-title' => _fs_text( 'Yes - I\'m giving you a chance to fix it' ),
'fix-issue-desc' => _fs_text( 'We will do our best to whitelist your server and resolve this issue ASAP. You will get a follow-up email to %s once we have an update.' ),
'install-previous-title' => _fs_text( 'Let\'s try your previous version' ),
'install-previous-desc' => _fs_text( 'Uninstall this version and install the previous one.' ),
'deactivate-plugin-title' => _fs_text( 'That\'s exhausting, please deactivate' ),
'deactivate-plugin-desc' => _fs_text( 'We feel your frustration and sincerely apologize for the inconvenience. Hope to see you again in the future.' ),
'fix-request-sent-message' => _fs_text( 'Thank for giving us the chance to fix it! A message was just sent to our technical staff. We will get back to you as soon as we have an update to %s. Appreciate your patience.' ),
'server-blocking-access' => _fs_x( 'Your server is blocking the access to Freemius\' API, which is crucial for %1$s synchronization. Please contact your host to whitelist %2$s',
'%1$s - plugin title, %2$s - API domain' ),
'wrong-authentication-param-message' => _fs_text( 'It seems like one of the authentication parameters is wrong. Update your Public Key, Secret Key & User ID, and try again.' ),
#endregion Connectivity Issues
#region Change Owner
'change-owner-request-sent-x' => _fs_text( 'Please check your mailbox, you should receive an email via %s to confirm the ownership change. From security reasons, you must confirm the change within the next 15 min. If you cannot find the email, please check your spam folder.' ),
'change-owner-request_owner-confirmed' => _fs_text( 'Thanks for confirming the ownership change. An email was just sent to %s for final approval.' ),
'change-owner-request_candidate-confirmed' => _fs_text( '%s is the new owner of the account.' ),
#endregion Change Owner
'addon-x-cannot-run-without-y' => _fs_x( '%s cannot run without %s.',
'addonX cannot run without pluginY' ),
'addon-x-cannot-run-without-parent' => _fs_x( '%s cannot run without the plugin.', 'addonX cannot run...' ),
'plugin-x-activation-message' => _fs_x( '%s activation was successfully completed.',
'pluginX activation was successfully...' ),
'features-and-pricing' => _fs_x( 'Features & Pricing', 'Plugin installer section title' ),
'free-addon-not-deployed' => _fs_text( 'Add-on must be deployed to WordPress.org or Freemius.' ),
'paid-addon-not-deployed' => _fs_text( 'Paid add-on must be deployed to Freemius.' ),
#--------------------------------------------------------------------------------
#region Add-On Licensing
#--------------------------------------------------------------------------------
'addon-no-license-message' => _fs_text( '%s is a premium only add-on. You have to purchase a license first before activating the plugin.' ),
'addon-trial-cancelled-message' => _fs_text( '%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.' ),
#endregion
#--------------------------------------------------------------------------------
#region Billing Cycles
#--------------------------------------------------------------------------------
'monthly' => _fs_x( 'Monthly', 'as every month' ),
'mo' => _fs_x( 'mo', 'as monthly period' ),
'annual' => _fs_x( 'Annual', 'as once a year' ),
'annually' => _fs_x( 'Annually', 'as once a year' ),
'once' => _fs_x( 'Once', 'as once a year' ),
'year' => _fs_x( 'year', 'as annual period' ),
'lifetime' => _fs_text( 'Lifetime' ),
'best' => _fs_x( 'Best', 'e.g. the best product' ),
'billed-x' => _fs_x( 'Billed %s', 'e.g. billed monthly' ),
'save-x' => _fs_x( 'Save %s', 'as a discount of $5 or 10%' ),
#endregion Billing Cycles
'view-details' => _fs_text( 'View details' ),
#--------------------------------------------------------------------------------
#region Trial
#--------------------------------------------------------------------------------
'approve-start-trial' => _fs_x( 'Approve & Start Trial', 'button label' ),
/* translators: %1$s: Number of trial days; %2$s: Plan name; */
'start-trial-prompt-header' => _fs_text( 'You are 1-click away from starting your %1$s-day free trial of the %2$s plan.' ),
/* translators: %s: Link to freemius.com */
'start-trial-prompt-message' => _fs_text( 'For compliance with the WordPress.org guidelines, before we start the trial we ask that you opt in with your user and non-sensitive site information, allowing the %s to periodically send data to %s to check for version updates and to validate your trial.' ),
#endregion
#--------------------------------------------------------------------------------
#region Billing Details
#--------------------------------------------------------------------------------
'business-name' => _fs_text( 'Business name' ),
'tax-vat-id' => _fs_text( 'Tax / VAT ID' ),
'address-line-n' => _fs_text( 'Address Line %d' ),
'country' => _fs_text( 'Country' ),
'select-country' => _fs_text( 'Select Country' ),
'city' => _fs_text( 'City' ),
'town' => _fs_text( 'Town' ),
'state' => _fs_text( 'State' ),
'province' => _fs_text( 'Province' ),
'zip-postal-code' => _fs_text( 'ZIP / Postal Code' ),
#endregion
#--------------------------------------------------------------------------------
#region Module Installation
#--------------------------------------------------------------------------------
'installing-plugin-x' => _fs_text( 'Installing plugin: %s' ),
'auto-installation' => _fs_text( 'Automatic Installation' ),
/* translators: %s: Number of seconds */
'x-sec' => _fs_text( '%s sec' ),
'installing-in-n' => _fs_text( 'An automated download and installation of %s (paid version) from %s will start in %s. If you would like to do it manually - click the cancellation button now.' ),
'installing-module-x' => _fs_text( 'The installation process has started and may take a few minutes to complete. Please wait until it is done - do not refresh this page.' ),
'cancel-installation' => _fs_text( 'Cancel Installation' ),
'module-package-rename-failure' => _fs_text( 'The remote plugin package does not contain a folder with the desired slug and renaming did not work.' ),
'auto-install-error-invalid-id' => _fs_text( 'Invalid module ID.' ),
'auto-install-error-not-opted-in' => _fs_text( 'Auto installation only works for opted-in users.' ),
'auto-install-error-premium-activated' => _fs_text( 'Premium version already active.' ),
'auto-install-error-premium-addon-activated' => _fs_text( 'Premium add-on version already installed.' ),
'auto-install-error-invalid-license' => _fs_text( 'You do not have a valid license to access the premium version.' ),
'auto-install-error-serviceware' => _fs_text( 'Plugin is a "Serviceware" which means it does not have a premium code version.' ),
#endregion
/* translators: %s: Page name */
'secure-x-page-header' => _fs_text( 'Secure HTTPS %s page, running from an external domain' ),
'pci-compliant' => _fs_text( 'PCI compliant' ),
'view-paid-features' => _fs_text( 'View paid features' ),
);
/**
* Localization of the strings in the plugin/theme info dialog box.
*
* $fs_module_info_text should ONLY include strings that are not located in $fs_text.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.2
*/
global $fs_module_info_text;
$fs_module_info_text = array(
'description' => _fs_x( 'Description', 'Plugin installer section title' ),
'installation' => _fs_x( 'Installation', 'Plugin installer section title' ),
'faq' => _fs_x( 'FAQ', 'Plugin installer section title' ),
'changelog' => _fs_x( 'Changelog', 'Plugin installer section title' ),
'reviews' => _fs_x( 'Reviews', 'Plugin installer section title' ),
'other_notes' => _fs_x( 'Other Notes', 'Plugin installer section title' ),
/* translators: %s: 1 or One */
'x-star' => _fs_text( '%s star' ),
/* translators: %s: Number larger than 1 */
'x-stars' => _fs_text( '%s stars' ),
/* translators: %s: 1 or One */
'x-rating' => _fs_text( '%s rating' ),
/* translators: %s: Number larger than 1 */
'x-ratings' => _fs_text( '%s ratings' ),
/* translators: %s: 1 or One (Number of times downloaded) */
'x-time' => _fs_text( '%s time' ),
/* translators: %s: Number of times downloaded */
'x-times' => _fs_text( '%s times' ),
/* translators: %s: # of stars (e.g. 5 stars) */
'click-to-reviews' => _fs_text( 'Click to see reviews that provided a rating of %s' ),
'last-updated:' => _fs_text( 'Last Updated' ),
'requires-wordpress-version:' => _fs_text( 'Requires WordPress Version:' ),
'author:' => _fs_x( 'Author:', 'as the plugin author' ),
'compatible-up-to:' => _fs_text( 'Compatible up to:' ),
'downloaded:' => _fs_text( 'Downloaded:' ),
'wp-org-plugin-page' => _fs_text( 'WordPress.org Plugin Page' ),
'plugin-homepage' => _fs_text( 'Plugin Homepage' ),
'donate-to-plugin' => _fs_text( 'Donate to this plugin' ),
'average-rating' => _fs_text( 'Average Rating' ),
'based-on-x' => _fs_text( 'based on %s' ),
'warning:' => _fs_text( 'Warning:' ),
'contributors' => _fs_text( 'Contributors' ),
'plugin-install' => _fs_text( 'Plugin Install' ),
'not-tested-warning' => _fs_text( 'This plugin has not been tested with your current version of WordPress.' ),
'not-compatible-warning' => _fs_text( 'This plugin has not been marked as compatible with your version of WordPress.' ),
'newer-installed' => _fs_text( 'Newer Version (%s) Installed' ),
'latest-installed' => _fs_text( 'Latest Version Installed' ),
);

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,48 @@
<?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.2.1.6
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Retrieve the translation of $text.
*
* @since 1.2.1.6
*
* @param string $text
*
* @return string
*/
function _fs_text( $text ) {
// Avoid misleading Theme Check warning.
$fn = 'translate';
return $fn( $text, 'freemius' );
}
/**
* Retrieve translated string with gettext context.
*
* Quite a few times, there will be collisions with similar translatable text
* found in more than two places, but with different translated context.
*
* By including the context in the pot file, translators can translate the two
* strings differently.
*
* @since 1.2.1.6
*
* @param string $text
* @param string $context
*
* @return string
*/
function _fs_x( $text, $context ) {
// Avoid misleading Theme Check warning.
$fn = 'translate_with_gettext_context';
return $fn( $text, $context, 'freemius' );
}

View File

@ -0,0 +1,477 @@
<?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.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Admin_Notice_Manager {
/**
* @since 1.2.2
*
* @var string
*/
protected $_module_unique_affix;
/**
* @var string
*/
protected $_id;
/**
* @var string
*/
protected $_title;
/**
* @var array[string]array
*/
private $_notices = array();
/**
* @var FS_Key_Value_Storage
*/
private $_sticky_storage;
/**
* @var FS_Logger
*/
protected $_logger;
/**
* @since 2.0.0
* @var int The ID of the blog that is associated with the current site level admin notices.
*/
private $_blog_id = 0;
/**
* @since 2.0.0
* @var bool
*/
private $_is_network_notices;
/**
* @var FS_Admin_Notice_Manager[]
*/
private static $_instances = array();
/**
* @param string $id
* @param string $title
* @param string $module_unique_affix
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on
* network and blog admin pages.
* @param bool $network_level_or_blog_id Since 2.0.0
*
* @return \FS_Admin_Notice_Manager
*/
static function instance(
$id,
$title = '',
$module_unique_affix = '',
$is_network_and_blog_admins = false,
$network_level_or_blog_id = false
) {
if ( $is_network_and_blog_admins ) {
$network_level_or_blog_id = true;
}
$key = strtolower( $id );
if ( is_multisite() ) {
if ( true === $network_level_or_blog_id ) {
$key .= ':ms';
} else if ( is_numeric( $network_level_or_blog_id ) && $network_level_or_blog_id > 0 ) {
$key .= ":{$network_level_or_blog_id}";
} else {
$network_level_or_blog_id = get_current_blog_id();
$key .= ":{$network_level_or_blog_id}";
}
}
if ( ! isset( self::$_instances[ $key ] ) ) {
self::$_instances[ $key ] = new FS_Admin_Notice_Manager(
$id,
$title,
$module_unique_affix,
$is_network_and_blog_admins,
$network_level_or_blog_id
);
}
return self::$_instances[ $key ];
}
/**
* @param string $id
* @param string $title
* @param string $module_unique_affix
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network and
* blog admin pages.
* @param bool|int $network_level_or_blog_id
*/
protected function __construct(
$id,
$title = '',
$module_unique_affix = '',
$is_network_and_blog_admins = false,
$network_level_or_blog_id = false
) {
$this->_id = $id;
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $this->_id . '_data', WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
$this->_title = ! empty( $title ) ? $title : '';
$this->_module_unique_affix = $module_unique_affix;
$this->_sticky_storage = FS_Key_Value_Storage::instance( 'admin_notices', $this->_id, $network_level_or_blog_id );
if ( is_multisite() ) {
$this->_is_network_notices = ( true === $network_level_or_blog_id );
if ( is_numeric( $network_level_or_blog_id ) ) {
$this->_blog_id = $network_level_or_blog_id;
}
} else {
$this->_is_network_notices = false;
}
$is_network_admin = fs_is_network_admin();
$is_blog_admin = fs_is_blog_admin();
if ( ( $this->_is_network_notices && $is_network_admin ) ||
( ! $this->_is_network_notices && $is_blog_admin ) ||
( $is_network_and_blog_admins && ( $is_network_admin || $is_blog_admin ) )
) {
if ( 0 < count( $this->_sticky_storage ) ) {
$ajax_action_suffix = str_replace( ':', '-', $this->_id );
// If there are sticky notices for the current slug, add a callback
// to the AJAX action that handles message dismiss.
add_action( "wp_ajax_fs_dismiss_notice_action_{$ajax_action_suffix}", array(
&$this,
'dismiss_notice_ajax_callback'
) );
foreach ( $this->_sticky_storage as $msg ) {
// Add admin notice.
$this->add(
$msg['message'],
$msg['title'],
$msg['type'],
true,
$msg['id'],
false,
isset( $msg['wp_user_id'] ) ? $msg['wp_user_id'] : null,
! empty( $msg['plugin'] ) ? $msg['plugin'] : null,
$is_network_and_blog_admins
);
}
}
}
}
/**
* Remove sticky message by ID.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
*/
function dismiss_notice_ajax_callback() {
check_admin_referer( 'fs_dismiss_notice_action' );
if ( ! is_numeric( $_POST['message_id'] ) ) {
$this->_sticky_storage->remove( $_POST['message_id'] );
}
wp_die();
}
/**
* Rendered sticky message dismiss JavaScript.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*/
static function _add_sticky_dismiss_javascript() {
$params = array();
fs_require_once_template( 'sticky-admin-notice-js.php', $params );
}
private static $_added_sticky_javascript = false;
/**
* Hook to the admin_footer to add sticky message dismiss JavaScript handler.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*/
private static function has_sticky_messages() {
if ( ! self::$_added_sticky_javascript ) {
add_action( 'admin_footer', array( 'FS_Admin_Notice_Manager', '_add_sticky_dismiss_javascript' ) );
}
}
/**
* Handle admin_notices by printing the admin messages stacked in the queue.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.4
*
*/
function _admin_notices_hook() {
if ( function_exists( 'current_user_can' ) &&
! current_user_can( 'manage_options' )
) {
// Only show messages to admins.
return;
}
$show_admin_notices = ( ! $this->is_gutenberg_page() );
foreach ( $this->_notices as $id => $msg ) {
if ( isset( $msg['wp_user_id'] ) && is_numeric( $msg['wp_user_id'] ) ) {
if ( get_current_user_id() != $msg['wp_user_id'] ) {
continue;
}
}
/**
* Added a filter to control the visibility of admin notices.
*
* Usage example:
*
* /**
* * @param bool $show
* * @param array $msg {
* * @var string $message The actual message.
* * @var string $title An optional message title.
* * @var string $type The type of the message ('success', 'update', 'warning', 'promotion').
* * @var string $id The unique identifier of the message.
* * @var string $manager_id The unique identifier of the notices manager. For plugins it would be the plugin's slug, for themes - `<slug>-theme`.
* * @var string $plugin The product's title.
* * @var string $wp_user_id An optional WP user ID that this admin notice is for.
* * }
* *
* * @return bool
* *\/
* function my_custom_show_admin_notice( $show, $msg ) {
* if ('trial_promotion' != $msg['id']) {
* return false;
* }
*
* return $show;
* }
*
* my_fs()->add_filter( 'show_admin_notice', 'my_custom_show_admin_notice', 10, 2 );
*
* @author Vova Feldman
* @since 2.2.0
*/
$show_notice = call_user_func_array( 'fs_apply_filter', array(
$this->_module_unique_affix,
'show_admin_notice',
$show_admin_notices,
$msg
) );
if ( true !== $show_notice ) {
continue;
}
fs_require_template( 'admin-notice.php', $msg );
if ( $msg['sticky'] ) {
self::has_sticky_messages();
}
}
}
/**
* Enqueue common stylesheet to style admin notice.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*/
function _enqueue_styles() {
fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
}
/**
* Check if the current page is the Gutenberg block editor.
*
* @author Vova Feldman (@svovaf)
* @since 2.2.3
*
* @return bool
*/
function is_gutenberg_page() {
if ( function_exists( 'is_gutenberg_page' ) &&
is_gutenberg_page()
) {
// The Gutenberg plugin is on.
return true;
}
$current_screen = get_current_screen();
if ( method_exists( $current_screen, 'is_block_editor' ) &&
$current_screen->is_block_editor()
) {
// Gutenberg page on 5+.
return true;
}
return false;
}
/**
* Add admin message to admin messages queue, and hook to admin_notices / all_admin_notices if not yet hooked.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.4
*
* @param string $message
* @param string $title
* @param string $type
* @param bool $is_sticky
* @param string $id Message ID
* @param bool $store_if_sticky
* @param number|null $wp_user_id
* @param string|null $plugin_title
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network
* and blog admin pages.
*
* @uses add_action()
*/
function add(
$message,
$title = '',
$type = 'success',
$is_sticky = false,
$id = '',
$store_if_sticky = true,
$wp_user_id = null,
$plugin_title = null,
$is_network_and_blog_admins = false
) {
$notices_type = $this->get_notices_type();
if ( empty( $this->_notices ) ) {
if ( ! $is_network_and_blog_admins ) {
add_action( $notices_type, array( &$this, "_admin_notices_hook" ) );
} else {
add_action( 'network_admin_notices', array( &$this, "_admin_notices_hook" ) );
add_action( 'admin_notices', array( &$this, "_admin_notices_hook" ) );
}
add_action( 'admin_enqueue_scripts', array( &$this, '_enqueue_styles' ) );
}
if ( '' === $id ) {
$id = md5( $title . ' ' . $message . ' ' . $type );
}
$message_object = array(
'message' => $message,
'title' => $title,
'type' => $type,
'sticky' => $is_sticky,
'id' => $id,
'manager_id' => $this->_id,
'plugin' => ( ! is_null( $plugin_title ) ? $plugin_title : $this->_title ),
'wp_user_id' => $wp_user_id,
);
if ( $is_sticky && $store_if_sticky ) {
$this->_sticky_storage->{$id} = $message_object;
}
$this->_notices[ $id ] = $message_object;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string|string[] $ids
*/
function remove_sticky( $ids ) {
if ( ! is_array( $ids ) ) {
$ids = array( $ids );
}
foreach ( $ids as $id ) {
// Remove from sticky storage.
$this->_sticky_storage->remove( $id );
if ( isset( $this->_notices[ $id ] ) ) {
unset( $this->_notices[ $id ] );
}
}
}
/**
* Check if sticky message exists by id.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param $id
*
* @return bool
*/
function has_sticky( $id ) {
return isset( $this->_sticky_storage[ $id ] );
}
/**
* Adds sticky admin notification.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string $message
* @param string $id Message ID
* @param string $title
* @param string $type
* @param number|null $wp_user_id
* @param string|null $plugin_title
* @param bool $is_network_and_blog_admins Whether or not the message should be shown both on network
* and blog admin pages.
*/
function add_sticky( $message, $id, $title = '', $type = 'success', $wp_user_id = null, $plugin_title = null, $is_network_and_blog_admins = false ) {
if ( ! empty( $this->_module_unique_affix ) ) {
$message = fs_apply_filter( $this->_module_unique_affix, "sticky_message_{$id}", $message );
$title = fs_apply_filter( $this->_module_unique_affix, "sticky_title_{$id}", $title );
}
$this->add( $message, $title, $type, true, $id, true, $wp_user_id, $plugin_title, $is_network_and_blog_admins );
}
/**
* Clear all sticky messages.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.8
*/
function clear_all_sticky() {
$this->_sticky_storage->clear_all();
}
#--------------------------------------------------------------------------------
#region Helper Method
#--------------------------------------------------------------------------------
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return string
*/
private function get_notices_type() {
return $this->_is_network_notices ?
'network_admin_notices' :
'admin_notices';
}
#endregion
}

View File

@ -0,0 +1,326 @@
<?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.1.6
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Cache_Manager {
/**
* @var FS_Option_Manager
*/
private $_options;
/**
* @var FS_Logger
*/
private $_logger;
/**
* @var FS_Cache_Manager[]
*/
private static $_MANAGERS = array();
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.3
*
* @param string $id
*/
private function __construct( $id ) {
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_cach_mngr_' . $id, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
$this->_logger->entrance();
$this->_logger->log( 'id = ' . $id );
$this->_options = FS_Option_Manager::get_manager( $id, true, true, false );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param $id
*
* @return FS_Cache_Manager
*/
static function get_manager( $id ) {
$id = strtolower( $id );
if ( ! isset( self::$_MANAGERS[ $id ] ) ) {
self::$_MANAGERS[ $id ] = new FS_Cache_Manager( $id );
}
return self::$_MANAGERS[ $id ];
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @return bool
*/
function is_empty() {
$this->_logger->entrance();
return $this->_options->is_empty();
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*/
function clear() {
$this->_logger->entrance();
$this->_options->clear( true );
}
/**
* Delete cache manager from DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*/
function delete() {
$this->_options->delete();
}
/**
* Check if there's a cached item.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
*
* @return bool
*/
function has( $key ) {
$cache_entry = $this->_options->get_option( $key, false );
return ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp )
);
}
/**
* Check if there's a valid cached item.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
* @param null|int $expiration Since 1.2.2.7
*
* @return bool
*/
function has_valid( $key, $expiration = null ) {
$cache_entry = $this->_options->get_option( $key, false );
$is_valid = ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp ) &&
$cache_entry->timestamp > WP_FS__SCRIPT_START_TIME
);
if ( $is_valid &&
is_numeric( $expiration ) &&
isset( $cache_entry->created ) &&
is_numeric( $cache_entry->created ) &&
$cache_entry->created + $expiration < WP_FS__SCRIPT_START_TIME
) {
/**
* Even if the cache is still valid, since we are checking for validity
* with an explicit expiration period, if the period has past, return
* `false` as if the cache is invalid.
*
* @since 1.2.2.7
*/
$is_valid = false;
}
return $is_valid;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
function get( $key, $default = null ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = $this->_options->get_option( $key, false );
if ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp )
) {
return $cache_entry->result;
}
return is_object( $default ) ? clone $default : $default;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
function get_valid( $key, $default = null ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = $this->_options->get_option( $key, false );
if ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp ) &&
$cache_entry->timestamp > WP_FS__SCRIPT_START_TIME
) {
return $cache_entry->result;
}
return is_object( $default ) ? clone $default : $default;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
* @param mixed $value
* @param int $expiration
* @param int $created Since 2.0.0 Cache creation date.
*/
function set( $key, $value, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $created = WP_FS__SCRIPT_START_TIME ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = new stdClass();
$cache_entry->result = $value;
$cache_entry->created = $created;
$cache_entry->timestamp = $created + $expiration;
$this->_options->set_option( $key, $cache_entry, true );
}
/**
* Get cached record expiration, or false if not cached or expired.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.7.3
*
* @param string $key
*
* @return bool|int
*/
function get_record_expiration( $key ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = $this->_options->get_option( $key, false );
if ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp ) &&
$cache_entry->timestamp > WP_FS__SCRIPT_START_TIME
) {
return $cache_entry->timestamp;
}
return false;
}
/**
* Purge cached item.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.6
*
* @param string $key
*/
function purge( $key ) {
$this->_logger->entrance( 'key = ' . $key );
$this->_options->unset_option( $key, true );
}
/**
* Extend cached item caching period.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @param string $key
* @param int $expiration
*
* @return bool
*/
function update_expiration( $key, $expiration = WP_FS__TIME_24_HOURS_IN_SEC ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = $this->_options->get_option( $key, false );
if ( ! is_object( $cache_entry ) ||
! isset( $cache_entry->timestamp ) ||
! is_numeric( $cache_entry->timestamp )
) {
return false;
}
$this->set( $key, $cache_entry->result, $expiration, $cache_entry->created );
return true;
}
/**
* Set cached item as expired.
*
* @author Vova Feldman (@svovaf)
* @since 1.2.2.7
*
* @param string $key
*/
function expire( $key ) {
$this->_logger->entrance( 'key = ' . $key );
$cache_entry = $this->_options->get_option( $key, false );
if ( is_object( $cache_entry ) &&
isset( $cache_entry->timestamp ) &&
is_numeric( $cache_entry->timestamp )
) {
// Set to expired.
$cache_entry->timestamp = WP_FS__SCRIPT_START_TIME;
$this->_options->set_option( $key, $cache_entry, true );
}
}
#--------------------------------------------------------------------------------
#region Migration
#--------------------------------------------------------------------------------
/**
* Migrate options from site level.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
function migrate_to_network() {
$this->_options->migrate_to_network();
}
#endregion
}

View File

@ -0,0 +1,202 @@
<?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 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_GDPR_Manager {
/**
* @var FS_Option_Manager
*/
private $_storage;
/**
* @var array {
* @type bool $required Are GDPR rules apply on the current context admin.
* @type bool $show_opt_in_notice Should the marketing and offers opt-in message be shown to the admin or not. If not set, defaults to `true`.
* @type int $notice_shown_at Last time the special GDPR opt-in message was shown to the current admin.
* }
*/
private $_data;
/**
* @var int
*/
private $_wp_user_id;
/**
* @var string
*/
private $_option_name;
/**
* @var FS_Admin_Notices
*/
private $_notices;
#--------------------------------------------------------------------------------
#region Singleton
#--------------------------------------------------------------------------------
/**
* @var FS_GDPR_Manager
*/
private static $_instance;
/**
* @return FS_GDPR_Manager
*/
public static function instance() {
if ( ! isset( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
#endregion
private function __construct() {
$this->_storage = FS_Option_Manager::get_manager( WP_FS__GDPR_OPTION_NAME, true, true );
$this->_wp_user_id = Freemius::get_current_wp_user_id();
$this->_option_name = "u{$this->_wp_user_id}";
$this->_data = $this->_storage->get_option( $this->_option_name, array() );
$this->_notices = FS_Admin_Notices::instance( 'all_admins', '', '', true );
if ( ! is_array( $this->_data ) ) {
$this->_data = array();
}
}
/**
* Update a GDPR option for the current admin and store it.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @param string $name
* @param mixed $value
*/
private function update_option( $name, $value ) {
$this->_data[ $name ] = $value;
$this->_storage->set_option( $this->_option_name, $this->_data, true );
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.1.0
*
* @return bool|null
*/
public function is_required() {
return isset( $this->_data['required'] ) ?
$this->_data['required'] :
null;
}
/**
* @author Leo Fajardo (@leorw)
* @since 2.1.0
*
* @param bool $is_required
*/
public function store_is_required( $is_required ) {
$this->update_option( 'required', $is_required );
}
/**
* Checks if the GDPR opt-in sticky notice is currently shown.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @return bool
*/
public function is_opt_in_notice_shown() {
return $this->_notices->has_sticky( "gdpr_optin_actions_{$this->_wp_user_id}", true );
}
/**
* Remove the GDPR opt-in sticky notice.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*/
public function remove_opt_in_notice() {
$this->_notices->remove_sticky( "gdpr_optin_actions_{$this->_wp_user_id}", true );
$this->disable_opt_in_notice();
}
/**
* Prevents the opt-in message from being added/shown.
*
* @author Leo Fajardo (@leorw)
* @since 2.1.0
*/
public function disable_opt_in_notice() {
$this->update_option( 'show_opt_in_notice', false );
}
/**
* Checks if a GDPR opt-in message needs to be shown to the current admin.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @return bool
*/
public function should_show_opt_in_notice() {
return (
! isset( $this->_data['show_opt_in_notice'] ) ||
true === $this->_data['show_opt_in_notice']
);
}
/**
* Get the last time the GDPR opt-in notice was shown.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*
* @return false|int
*/
public function last_time_notice_was_shown() {
return isset( $this->_data['notice_shown_at'] ) ?
$this->_data['notice_shown_at'] :
false;
}
/**
* Update the timestamp of the last time the GDPR opt-in message was shown to now.
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*/
public function notice_was_just_shown() {
$this->update_option( 'notice_shown_at', WP_FS__SCRIPT_START_TIME );
}
/**
* @param string $message
* @param string|null $plugin_title
*
* @author Vova Feldman (@svovaf)
* @since 2.1.0
*/
public function add_opt_in_sticky_notice( $message, $plugin_title = null ) {
$this->_notices->add_sticky(
$message,
"gdpr_optin_actions_{$this->_wp_user_id}",
'',
'promotion',
true,
$this->_wp_user_id,
$plugin_title,
true
);
}
}

View File

@ -0,0 +1,392 @@
<?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.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class FS_Key_Value_Storage
*
* @property int $install_timestamp
* @property int $activation_timestamp
* @property int $sync_timestamp
* @property object $sync_cron
* @property int $install_sync_timestamp
* @property array $connectivity_test
* @property array $is_on
* @property object $trial_plan
* @property bool $has_trial_plan
* @property bool $trial_promotion_shown
* @property string $sdk_version
* @property string $sdk_last_version
* @property bool $sdk_upgrade_mode
* @property bool $sdk_downgrade_mode
* @property bool $plugin_upgrade_mode
* @property bool $plugin_downgrade_mode
* @property string $plugin_version
* @property string $plugin_last_version
* @property bool $is_plugin_new_install
* @property bool $was_plugin_loaded
* @property object $plugin_main_file
* @property bool $prev_is_premium
* @property array $is_anonymous
* @property bool $is_pending_activation
* @property bool $sticky_optin_added
* @property object $uninstall_reason
* @property object $subscription
*/
class FS_Key_Value_Storage implements ArrayAccess, Iterator, Countable {
/**
* @var string
*/
protected $_id;
/**
* @since 1.2.2
*
* @var string
*/
protected $_secondary_id;
/**
* @since 2.0.0
* @var int The ID of the blog that is associated with the current site level options.
*/
private $_blog_id = 0;
/**
* @since 2.0.0
* @var bool
*/
private $_is_multisite_storage;
/**
* @var array
*/
protected $_data;
/**
* @var FS_Key_Value_Storage[]
*/
private static $_instances = array();
/**
* @var FS_Logger
*/
protected $_logger;
/**
* @param string $id
* @param string $secondary_id
* @param bool $network_level_or_blog_id
*
* @return FS_Key_Value_Storage
*/
static function instance( $id, $secondary_id, $network_level_or_blog_id = false ) {
$key = $id . ':' . $secondary_id;
if ( is_multisite() ) {
if ( true === $network_level_or_blog_id ) {
$key .= ':ms';
} else if ( is_numeric( $network_level_or_blog_id ) && $network_level_or_blog_id > 0 ) {
$key .= ":{$network_level_or_blog_id}";
} else {
$network_level_or_blog_id = get_current_blog_id();
$key .= ":{$network_level_or_blog_id}";
}
}
if ( ! isset( self::$_instances[ $key ] ) ) {
self::$_instances[ $key ] = new FS_Key_Value_Storage( $id, $secondary_id, $network_level_or_blog_id );
}
return self::$_instances[ $key ];
}
protected function __construct( $id, $secondary_id, $network_level_or_blog_id = false ) {
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $secondary_id . '_' . $id, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
$this->_id = $id;
$this->_secondary_id = $secondary_id;
if ( is_multisite() ) {
$this->_is_multisite_storage = ( true === $network_level_or_blog_id );
if ( is_numeric( $network_level_or_blog_id ) ) {
$this->_blog_id = $network_level_or_blog_id;
}
} else {
$this->_is_multisite_storage = false;
}
$this->load();
}
protected function get_option_manager() {
return FS_Option_Manager::get_manager(
WP_FS__ACCOUNTS_OPTION_NAME,
true,
$this->_is_multisite_storage ?
true :
( $this->_blog_id > 0 ? $this->_blog_id : false )
);
}
protected function get_all_data() {
return $this->get_option_manager()->get_option( $this->_id, array() );
}
/**
* Load plugin data from local DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*/
function load() {
$all_plugins_data = $this->get_all_data();
$this->_data = isset( $all_plugins_data[ $this->_secondary_id ] ) ?
$all_plugins_data[ $this->_secondary_id ] :
array();
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string $key
* @param mixed $value
* @param bool $flush
*/
function store( $key, $value, $flush = true ) {
if ( $this->_logger->is_on() ) {
$this->_logger->entrance( $key . ' = ' . var_export( $value, true ) );
}
if ( array_key_exists( $key, $this->_data ) && $value === $this->_data[ $key ] ) {
// No need to store data if the value wasn't changed.
return;
}
$all_data = $this->get_all_data();
$this->_data[ $key ] = $value;
$all_data[ $this->_secondary_id ] = $this->_data;
$options_manager = $this->get_option_manager();
$options_manager->set_option( $this->_id, $all_data, $flush );
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
function save() {
$this->get_option_manager()->store();
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param bool $store
* @param string[] $exceptions Set of keys to keep and not clear.
*/
function clear_all( $store = true, $exceptions = array() ) {
$new_data = array();
foreach ( $exceptions as $key ) {
if ( isset( $this->_data[ $key ] ) ) {
$new_data[ $key ] = $this->_data[ $key ];
}
}
$this->_data = $new_data;
if ( $store ) {
$all_data = $this->get_all_data();
$all_data[ $this->_secondary_id ] = $this->_data;
$options_manager = $this->get_option_manager();
$options_manager->set_option( $this->_id, $all_data, true );
}
}
/**
* Delete key-value storage.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*/
function delete() {
$this->_data = array();
$all_data = $this->get_all_data();
unset( $all_data[ $this->_secondary_id ] );
$options_manager = $this->get_option_manager();
$options_manager->set_option( $this->_id, $all_data, true );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string $key
* @param bool $store
*/
function remove( $key, $store = true ) {
if ( ! array_key_exists( $key, $this->_data ) ) {
return;
}
unset( $this->_data[ $key ] );
if ( $store ) {
$all_data = $this->get_all_data();
$all_data[ $this->_secondary_id ] = $this->_data;
$options_manager = $this->get_option_manager();
$options_manager->set_option( $this->_id, $all_data, true );
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param string $key
* @param mixed $default
*
* @return bool|\FS_Plugin
*/
function get( $key, $default = false ) {
return array_key_exists( $key, $this->_data ) ?
$this->_data[ $key ] :
$default;
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return string
*/
function get_secondary_id() {
return $this->_secondary_id;
}
/* ArrayAccess + Magic Access (better for refactoring)
-----------------------------------------------------------------------------------*/
function __set( $k, $v ) {
$this->store( $k, $v );
}
function __isset( $k ) {
return array_key_exists( $k, $this->_data );
}
function __unset( $k ) {
$this->remove( $k );
}
function __get( $k ) {
return $this->get( $k, null );
}
function offsetSet( $k, $v ) {
if ( is_null( $k ) ) {
throw new Exception( 'Can\'t append value to request params.' );
} else {
$this->{$k} = $v;
}
}
function offsetExists( $k ) {
return array_key_exists( $k, $this->_data );
}
function offsetUnset( $k ) {
unset( $this->$k );
}
function offsetGet( $k ) {
return $this->get( $k, null );
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the current element
*
* @link http://php.net/manual/en/iterator.current.php
* @return mixed Can return any type.
*/
public function current() {
return current( $this->_data );
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Move forward to next element
*
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next() {
next( $this->_data );
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the key of the current element
*
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key() {
return key( $this->_data );
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Checks if current position is valid
*
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid() {
$key = key( $this->_data );
return ( $key !== null && $key !== false );
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Rewind the Iterator to the first element
*
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind() {
reset( $this->_data );
}
/**
* (PHP 5 &gt;= 5.1.0)<br/>
* Count elements of an object
*
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
*/
public function count() {
return count( $this->_data );
}
}

View File

@ -0,0 +1,104 @@
<?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.6
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_License_Manager /*extends FS_Abstract_Manager*/
{
//
//
// /**
// * @var FS_License_Manager[]
// */
// private static $_instances = array();
//
// static function instance( Freemius $fs ) {
// $slug = strtolower( $fs->get_slug() );
//
// if ( ! isset( self::$_instances[ $slug ] ) ) {
// self::$_instances[ $slug ] = new FS_License_Manager( $slug, $fs );
// }
//
// return self::$_instances[ $slug ];
// }
//
//// private function __construct($slug) {
//// parent::__construct($slug);
//// }
//
// function entry_id() {
// return 'licenses';
// }
//
// function sync( $id ) {
//
// }
//
// /**
// * @author Vova Feldman (@svovaf)
// * @since 1.0.5
// * @uses FS_Api
// *
// * @param number|bool $plugin_id
// *
// * @return FS_Plugin_License[]|stdClass Licenses or API error.
// */
// function api_get_user_plugin_licenses( $plugin_id = false ) {
// $api = $this->_fs->get_api_user_scope();
//
// if ( ! is_numeric( $plugin_id ) ) {
// $plugin_id = $this->_fs->get_id();
// }
//
// $result = $api->call( "/plugins/{$plugin_id}/licenses.json" );
//
// if ( ! isset( $result->error ) ) {
// for ( $i = 0, $len = count( $result->licenses ); $i < $len; $i ++ ) {
// $result->licenses[ $i ] = new FS_Plugin_License( $result->licenses[ $i ] );
// }
//
// $result = $result->licenses;
// }
//
// return $result;
// }
//
// function api_get_many() {
//
// }
//
// function api_activate( $id ) {
//
// }
//
// function api_deactivate( $id ) {
//
// }
/**
* @param FS_Plugin_License[] $licenses
*
* @return bool
*/
static function has_premium_license( $licenses ) {
if ( is_array( $licenses ) ) {
foreach ( $licenses as $license ) {
/**
* @var FS_Plugin_License $license
*/
if ( ! $license->is_utilized() && $license->is_features_enabled() ) {
return true;
}
}
}
return false;
}
}

View File

@ -0,0 +1,521 @@
<?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;
}
/**
* 3-layer lazy options manager.
* layer 3: Memory
* layer 2: Cache (if there's any caching plugin and if WP_FS__DEBUG_SDK is FALSE)
* layer 1: Database (options table). All options stored as one option record in the DB to reduce number of DB
* queries.
*
* If load() is not explicitly called, starts as empty manager. Same thing about saving the data - you have to
* explicitly call store().
*
* Class Freemius_Option_Manager
*/
class FS_Option_Manager {
/**
* @var string
*/
private $_id;
/**
* @var array|object
*/
private $_options;
/**
* @var FS_Logger
*/
private $_logger;
/**
* @since 2.0.0
* @var int The ID of the blog that is associated with the current site level options.
*/
private $_blog_id = 0;
/**
* @since 2.0.0
* @var bool
*/
private $_is_network_storage;
/**
* @var bool|null
*/
private $_autoload;
/**
* @var array[string]FS_Option_Manager {
* @key string
* @value FS_Option_Manager
* }
*/
private static $_MANAGERS = array();
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param string $id
* @param bool $load
* @param bool|int $network_level_or_blog_id Since 2.0.0
* @param bool|null $autoload
*/
private function __construct(
$id,
$load = false,
$network_level_or_blog_id = false,
$autoload = null
) {
$id = strtolower( $id );
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_opt_mngr_' . $id, WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
$this->_logger->entrance();
$this->_logger->log( 'id = ' . $id );
$this->_id = $id;
$this->_autoload = $autoload;
if ( is_multisite() ) {
$this->_is_network_storage = ( true === $network_level_or_blog_id );
if ( is_numeric( $network_level_or_blog_id ) ) {
$this->_blog_id = $network_level_or_blog_id;
}
} else {
$this->_is_network_storage = false;
}
if ( $load ) {
$this->load();
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param string $id
* @param bool $load
* @param bool|int $network_level_or_blog_id Since 2.0.0
* @param bool|null $autoload
*
* @return \FS_Option_Manager
*/
static function get_manager(
$id,
$load = false,
$network_level_or_blog_id = false,
$autoload = null
) {
$key = strtolower( $id );
if ( is_multisite() ) {
if ( true === $network_level_or_blog_id ) {
$key .= ':ms';
} else if ( is_numeric( $network_level_or_blog_id ) && $network_level_or_blog_id > 0 ) {
$key .= ":{$network_level_or_blog_id}";
} else {
$network_level_or_blog_id = get_current_blog_id();
$key .= ":{$network_level_or_blog_id}";
}
}
if ( ! isset( self::$_MANAGERS[ $key ] ) ) {
self::$_MANAGERS[ $key ] = new FS_Option_Manager(
$id,
$load,
$network_level_or_blog_id,
$autoload
);
} // If load required but not yet loaded, load.
else if ( $load && ! self::$_MANAGERS[ $key ]->is_loaded() ) {
self::$_MANAGERS[ $key ]->load();
}
return self::$_MANAGERS[ $key ];
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param bool $flush
*/
function load( $flush = false ) {
$this->_logger->entrance();
$option_name = $this->get_option_manager_name();
if ( $flush || ! isset( $this->_options ) ) {
if ( isset( $this->_options ) ) {
// Clear prev options.
$this->clear();
}
$cache_group = $this->get_cache_group();
if ( WP_FS__DEBUG_SDK ) {
// Don't use cache layer in DEBUG mode.
$load_options = empty( $this->_options );
} else {
$this->_options = wp_cache_get(
$option_name,
$cache_group
);
$load_options = ( false === $this->_options );
}
$cached = true;
if ( $load_options ) {
if ( $this->_is_network_storage ) {
$this->_options = get_site_option( $option_name );
} else if ( $this->_blog_id > 0 ) {
$this->_options = get_blog_option( $this->_blog_id, $option_name );
} else {
$this->_options = get_option( $option_name );
}
if ( is_string( $this->_options ) ) {
$this->_options = json_decode( $this->_options );
}
// $this->_logger->info('get_option = ' . var_export($this->_options, true));
if ( false === $this->_options ) {
$this->clear();
}
$cached = false;
}
if ( ! WP_FS__DEBUG_SDK && ! $cached ) {
// Set non encoded cache.
wp_cache_set( $option_name, $this->_options, $cache_group );
}
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @return bool
*/
function is_loaded() {
return isset( $this->_options );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @return bool
*/
function is_empty() {
return ( $this->is_loaded() && false === $this->_options );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param bool $flush
*/
function clear( $flush = false ) {
$this->_logger->entrance();
$this->_options = array();
if ( $flush ) {
$this->store();
}
}
/**
* Delete options manager from DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*/
function delete() {
$option_name = $this->get_option_manager_name();
if ( $this->_is_network_storage ) {
delete_site_option( $option_name );
} else if ( $this->_blog_id > 0 ) {
delete_blog_option( $this->_blog_id, $option_name );
} else {
delete_option( $option_name );
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param string $option
*
* @return bool
*/
function has_option( $option ) {
return array_key_exists( $option, $this->_options );
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param string $option
* @param mixed $default
*
* @return mixed
*/
function get_option( $option, $default = null ) {
$this->_logger->entrance( 'option = ' . $option );
if ( ! $this->is_loaded() ) {
$this->load();
}
if ( is_array( $this->_options ) ) {
$value = isset( $this->_options[ $option ] ) ?
$this->_options[ $option ] :
$default;
} else if ( is_object( $this->_options ) ) {
$value = isset( $this->_options->{$option} ) ?
$this->_options->{$option} :
$default;
} else {
$value = $default;
}
/**
* If it's an object, return a clone of the object, otherwise,
* external changes of the object will actually change the value
* of the object in the options manager which may lead to an unexpected
* behaviour and data integrity when a store() call is triggered.
*
* Example:
* $object1 = $options->get_option( 'object1' );
* $object1->x = 123;
*
* $object2 = $options->get_option( 'object2' );
* $object2->y = 'dummy';
*
* $options->set_option( 'object2', $object2, true );
*
* If we don't return a clone of option 'object1', setting 'object2'
* will also store the updated value of 'object1' which is quite not
* an expected behaviour.
*
* @author Vova Feldman
*/
return is_object( $value ) ? clone $value : $value;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param string $option
* @param mixed $value
* @param bool $flush
*/
function set_option( $option, $value, $flush = false ) {
$this->_logger->entrance( 'option = ' . $option );
if ( ! $this->is_loaded() ) {
$this->clear();
}
/**
* If it's an object, store a clone of the object, otherwise,
* external changes of the object will actually change the value
* of the object in the options manager which may lead to an unexpected
* behaviour and data integrity when a store() call is triggered.
*
* Example:
* $object1 = new stdClass();
* $object1->x = 123;
*
* $options->set_option( 'object1', $object1 );
*
* $object1->x = 456;
*
* $options->set_option( 'object2', $object2, true );
*
* If we don't set the option as a clone of option 'object1', setting 'object2'
* will also store the updated value of 'object1' ($object1->x = 456 instead of
* $object1->x = 123) which is quite not an expected behaviour.
*
* @author Vova Feldman
*/
$copy = is_object( $value ) ? clone $value : $value;
if ( is_array( $this->_options ) ) {
$this->_options[ $option ] = $copy;
} else if ( is_object( $this->_options ) ) {
$this->_options->{$option} = $copy;
}
if ( $flush ) {
$this->store();
}
}
/**
* Unset option.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @param string $option
* @param bool $flush
*/
function unset_option( $option, $flush = false ) {
$this->_logger->entrance( 'option = ' . $option );
if ( is_array( $this->_options ) ) {
if ( ! isset( $this->_options[ $option ] ) ) {
return;
}
unset( $this->_options[ $option ] );
} else if ( is_object( $this->_options ) ) {
if ( ! isset( $this->_options->{$option} ) ) {
return;
}
unset( $this->_options->{$option} );
}
if ( $flush ) {
$this->store();
}
}
/**
* Dump options to database.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*/
function store() {
$this->_logger->entrance();
$option_name = $this->get_option_manager_name();
if ( $this->_logger->is_on() ) {
$this->_logger->info( $option_name . ' = ' . var_export( $this->_options, true ) );
}
// Update DB.
if ( $this->_is_network_storage ) {
update_site_option( $option_name, $this->_options );
} else if ( $this->_blog_id > 0 ) {
update_blog_option( $this->_blog_id, $option_name, $this->_options );
} else {
update_option( $option_name, $this->_options, $this->_autoload );
}
if ( ! WP_FS__DEBUG_SDK ) {
wp_cache_set( $option_name, $this->_options, $this->get_cache_group() );
}
}
/**
* Get options keys.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.3
*
* @return string[]
*/
function get_options_keys() {
if ( is_array( $this->_options ) ) {
return array_keys( $this->_options );
} else if ( is_object( $this->_options ) ) {
return array_keys( get_object_vars( $this->_options ) );
}
return array();
}
#--------------------------------------------------------------------------------
#region Migration
#--------------------------------------------------------------------------------
/**
* Migrate options from site level.
*
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*/
function migrate_to_network() {
$site_options = FS_Option_Manager::get_manager($this->_id, true, false);
$options = is_object( $site_options->_options ) ?
get_object_vars( $site_options->_options ) :
$site_options->_options;
if ( ! empty( $options ) ) {
foreach ( $options as $key => $val ) {
$this->set_option( $key, $val, false );
}
$this->store();
}
}
#endregion
#--------------------------------------------------------------------------------
#region Helper Methods
#--------------------------------------------------------------------------------
/**
* @return string
*/
private function get_option_manager_name() {
return $this->_id;
}
/**
* @author Vova Feldman (@svovaf)
* @since 2.0.0
*
* @return string
*/
private function get_cache_group() {
$group = WP_FS__SLUG;
if ( $this->_is_network_storage ) {
$group .= '_ms';
} else if ( $this->_blog_id > 0 ) {
$group .= "_s{$this->_blog_id}";
}
return $group;
}
#endregion
}

View File

@ -0,0 +1,162 @@
<?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.6
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Plan_Manager {
/**
* @var FS_Plan_Manager
*/
private static $_instance;
/**
* @return FS_Plan_Manager
*/
static function instance() {
if ( ! isset( self::$_instance ) ) {
self::$_instance = new FS_Plan_Manager();
}
return self::$_instance;
}
private function __construct() {
}
/**
* @param FS_Plugin_License[] $licenses
*
* @return bool
*/
function has_premium_license( $licenses ) {
if ( is_array( $licenses ) ) {
/**
* @var FS_Plugin_License[] $licenses
*/
foreach ( $licenses as $license ) {
if ( ! $license->is_utilized() && $license->is_features_enabled() ) {
return true;
}
}
}
return false;
}
/**
* Check if plugin has any paid plans.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param FS_Plugin_Plan[] $plans
*
* @return bool
*/
function has_paid_plan( $plans ) {
if ( ! is_array( $plans ) || 0 === count( $plans ) ) {
return false;
}
/**
* @var FS_Plugin_Plan[] $plans
*/
for ( $i = 0, $len = count( $plans ); $i < $len; $i ++ ) {
if ( ! $plans[ $i ]->is_free() ) {
return true;
}
}
return false;
}
/**
* Check if plugin has any free plan, or is it premium only.
*
* Note: If no plans configured, assume plugin is free.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.7
*
* @param FS_Plugin_Plan[] $plans
*
* @return bool
*/
function has_free_plan( $plans ) {
if ( ! is_array( $plans ) || 0 === count( $plans ) ) {
return true;
}
/**
* @var FS_Plugin_Plan[] $plans
*/
for ( $i = 0, $len = count( $plans ); $i < $len; $i ++ ) {
if ( $plans[ $i ]->is_free() ) {
return true;
}
}
return false;
}
/**
* Find all plans that have trial.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param FS_Plugin_Plan[] $plans
*
* @return FS_Plugin_Plan[]
*/
function get_trial_plans( $plans ) {
$trial_plans = array();
if ( is_array( $plans ) && 0 < count( $plans ) ) {
/**
* @var FS_Plugin_Plan[] $plans
*/
for ( $i = 0, $len = count( $plans ); $i < $len; $i ++ ) {
if ( $plans[ $i ]->has_trial() ) {
$trial_plans[] = $plans[ $i ];
}
}
}
return $trial_plans;
}
/**
* Check if plugin has any trial plan.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.9
*
* @param FS_Plugin_Plan[] $plans
*
* @return bool
*/
function has_trial_plan( $plans ) {
if ( ! is_array( $plans ) || 0 === count( $plans ) ) {
return true;
}
/**
* @var FS_Plugin_Plan[] $plans
*/
for ( $i = 0, $len = count( $plans ); $i < $len; $i ++ ) {
if ( $plans[ $i ]->has_trial() ) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,220 @@
<?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.6
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class FS_Plugin_Manager {
/**
* @since 1.2.2
*
* @var string|number
*/
protected $_module_id;
/**
* @since 1.2.2
*
* @var FS_Plugin
*/
protected $_module;
/**
* @var FS_Plugin_Manager[]
*/
private static $_instances = array();
/**
* @var FS_Logger
*/
protected $_logger;
/**
* Option names
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*/
const OPTION_NAME_PLUGINS = 'plugins';
const OPTION_NAME_THEMES = 'themes';
/**
* @param string|number $module_id
*
* @return FS_Plugin_Manager
*/
static function instance( $module_id ) {
$key = 'm_' . $module_id;
if ( ! isset( self::$_instances[ $key ] ) ) {
self::$_instances[ $key ] = new FS_Plugin_Manager( $module_id );
}
return self::$_instances[ $key ];
}
/**
* @param string|number $module_id
*/
protected function __construct( $module_id ) {
$this->_logger = FS_Logger::get_logger( WP_FS__SLUG . '_' . $module_id . '_' . 'plugins', WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
$this->_module_id = $module_id;
$this->load();
}
protected function get_option_manager() {
return FS_Option_Manager::get_manager( WP_FS__ACCOUNTS_OPTION_NAME, true, true );
}
/**
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*
* @param string|bool $module_type "plugin", "theme", or "false" for all modules.
*
* @return array
*/
protected function get_all_modules( $module_type = false ) {
$option_manager = $this->get_option_manager();
if ( false !== $module_type ) {
return fs_get_entities( $option_manager->get_option( $module_type . 's', array() ), FS_Plugin::get_class_name() );
}
return array(
self::OPTION_NAME_PLUGINS => fs_get_entities( $option_manager->get_option( self::OPTION_NAME_PLUGINS, array() ), FS_Plugin::get_class_name() ),
self::OPTION_NAME_THEMES => fs_get_entities( $option_manager->get_option( self::OPTION_NAME_THEMES, array() ), FS_Plugin::get_class_name() ),
);
}
/**
* Load plugin data from local DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*/
function load() {
$all_modules = $this->get_all_modules();
if ( ! is_numeric( $this->_module_id ) ) {
unset( $all_modules[ self::OPTION_NAME_THEMES ] );
}
foreach ( $all_modules as $modules ) {
/**
* @since 1.2.2
*
* @var $modules FS_Plugin[]
*/
foreach ( $modules as $module ) {
$found_module = false;
/**
* If module ID is not numeric, it must be a plugin's slug.
*
* @author Leo Fajardo (@leorw)
* @since 1.2.2
*/
if ( ! is_numeric( $this->_module_id ) ) {
if ( $this->_module_id === $module->slug ) {
$this->_module_id = $module->id;
$found_module = true;
}
} else if ( $this->_module_id == $module->id ) {
$found_module = true;
}
if ( $found_module ) {
$this->_module = $module;
break;
}
}
}
}
/**
* Store plugin on local DB.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param bool|FS_Plugin $module
* @param bool $flush
*
* @return bool|\FS_Plugin
*/
function store( $module = false, $flush = true ) {
if ( false !== $module ) {
$this->_module = $module;
}
$all_modules = $this->get_all_modules( $this->_module->type );
$all_modules[ $this->_module->slug ] = $this->_module;
$options_manager = $this->get_option_manager();
$options_manager->set_option( $this->_module->type . 's', $all_modules, $flush );
return $this->_module;
}
/**
* Update local plugin data if different.
*
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param \FS_Plugin $plugin
* @param bool $store
*
* @return bool True if plugin was updated.
*/
function update( FS_Plugin $plugin, $store = true ) {
if ( ! ($this->_module instanceof FS_Plugin ) ||
$this->_module->slug != $plugin->slug ||
$this->_module->public_key != $plugin->public_key ||
$this->_module->secret_key != $plugin->secret_key ||
$this->_module->parent_plugin_id != $plugin->parent_plugin_id ||
$this->_module->title != $plugin->title
) {
$this->store( $plugin, $store );
return true;
}
return false;
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @param FS_Plugin $plugin
* @param bool $store
*/
function set( FS_Plugin $plugin, $store = false ) {
$this->_module = $plugin;
if ( $store ) {
$this->store();
}
}
/**
* @author Vova Feldman (@svovaf)
* @since 1.0.6
*
* @return bool|\FS_Plugin
*/
function get() {
return isset( $this->_module ) ?
$this->_module :
false;
}
}

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,13 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_InvalidArgumentException' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_ArgumentNotExistException' ) ) {
class Freemius_ArgumentNotExistException extends Freemius_InvalidArgumentException {
}
}

View File

@ -0,0 +1,13 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_InvalidArgumentException' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_EmptyArgumentException' ) ) {
class Freemius_EmptyArgumentException extends Freemius_InvalidArgumentException {
}
}

View File

@ -0,0 +1,78 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_Exception' ) ) {
/**
* Thrown when an API call returns an exception.
*
*/
class Freemius_Exception extends Exception {
protected $_result;
protected $_type;
protected $_code;
/**
* Make a new API Exception with the given result.
*
* @param array $result The result from the API server.
*/
public function __construct( $result ) {
$this->_result = $result;
$code = 0;
$message = 'Unknown error, please check GetResult().';
$type = '';
if ( isset( $result['error'] ) && is_array( $result['error'] ) ) {
if ( isset( $result['error']['code'] ) ) {
$code = $result['error']['code'];
}
if ( isset( $result['error']['message'] ) ) {
$message = $result['error']['message'];
}
if ( isset( $result['error']['type'] ) ) {
$type = $result['error']['type'];
}
}
$this->_type = $type;
$this->_code = $code;
parent::__construct( $message, is_numeric( $code ) ? $code : 0 );
}
/**
* Return the associated result object returned by the API server.
*
* @return array The result from the API server
*/
public function getResult() {
return $this->_result;
}
public function getStringCode() {
return $this->_code;
}
public function getType() {
return $this->_type;
}
/**
* To make debugging easier.
*
* @return string The string representation of the error
*/
public function __toString() {
$str = $this->getType() . ': ';
if ( $this->code != 0 ) {
$str .= $this->getStringCode() . ': ';
}
return $str . $this->getMessage();
}
}
}

View File

@ -0,0 +1,12 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_Exception' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_InvalidArgumentException' ) ) {
class Freemius_InvalidArgumentException extends Freemius_Exception { }
}

View File

@ -0,0 +1,16 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_Exception' ) ) {
exit;
}
if ( ! class_exists( 'Freemius_OAuthException' ) ) {
class Freemius_OAuthException extends Freemius_Exception {
public function __construct( $pResult ) {
parent::__construct( $pResult );
}
}
}

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,219 @@
<?php
/**
* Copyright 2014 Freemius, Inc.
*
* Licensed under the GPL v2 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://choosealicense.com/licenses/gpl-v2/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'FS_API__VERSION' ) ) {
define( 'FS_API__VERSION', '1' );
}
if ( ! defined( 'FS_SDK__PATH' ) ) {
define( 'FS_SDK__PATH', dirname( __FILE__ ) );
}
if ( ! defined( 'FS_SDK__EXCEPTIONS_PATH' ) ) {
define( 'FS_SDK__EXCEPTIONS_PATH', FS_SDK__PATH . '/Exceptions/' );
}
if ( ! function_exists( 'json_decode' ) ) {
throw new Exception( 'Freemius needs the JSON PHP extension.' );
}
// Include all exception files.
$exceptions = array(
'Exception',
'InvalidArgumentException',
'ArgumentNotExistException',
'EmptyArgumentException',
'OAuthException'
);
foreach ( $exceptions as $e ) {
require_once FS_SDK__EXCEPTIONS_PATH . $e . '.php';
}
if ( class_exists( 'Freemius_Api_Base' ) ) {
return;
}
abstract class Freemius_Api_Base {
const VERSION = '1.0.4';
const FORMAT = 'json';
protected $_id;
protected $_public;
protected $_secret;
protected $_scope;
protected $_isSandbox;
/**
* @param string $pScope 'app', 'developer', 'plugin', 'user' or 'install'.
* @param number $pID Element's id.
* @param string $pPublic Public key.
* @param string $pSecret Element's secret key.
* @param bool $pIsSandbox Whether or not to run API in sandbox mode.
*/
public function Init( $pScope, $pID, $pPublic, $pSecret, $pIsSandbox = false ) {
$this->_id = $pID;
$this->_public = $pPublic;
$this->_secret = $pSecret;
$this->_scope = $pScope;
$this->_isSandbox = $pIsSandbox;
}
public function IsSandbox() {
return $this->_isSandbox;
}
function CanonizePath( $pPath ) {
$pPath = trim( $pPath, '/' );
$query_pos = strpos( $pPath, '?' );
$query = '';
if ( false !== $query_pos ) {
$query = substr( $pPath, $query_pos );
$pPath = substr( $pPath, 0, $query_pos );
}
// Trim '.json' suffix.
$format_length = strlen( '.' . self::FORMAT );
$start = $format_length * ( - 1 ); //negative
if ( substr( strtolower( $pPath ), $start ) === ( '.' . self::FORMAT ) ) {
$pPath = substr( $pPath, 0, strlen( $pPath ) - $format_length );
}
switch ( $this->_scope ) {
case 'app':
$base = '/apps/' . $this->_id;
break;
case 'developer':
$base = '/developers/' . $this->_id;
break;
case 'user':
$base = '/users/' . $this->_id;
break;
case 'plugin':
$base = '/plugins/' . $this->_id;
break;
case 'install':
$base = '/installs/' . $this->_id;
break;
default:
throw new Freemius_Exception( 'Scope not implemented.' );
}
return '/v' . FS_API__VERSION . $base .
( ! empty( $pPath ) ? '/' : '' ) . $pPath .
( ( false === strpos( $pPath, '.' ) ) ? '.' . self::FORMAT : '' ) . $query;
}
abstract function MakeRequest( $pCanonizedPath, $pMethod = 'GET', $pParams = array() );
/**
* @param string $pPath
* @param string $pMethod
* @param array $pParams
*
* @return object[]|object|null
*/
private function _Api( $pPath, $pMethod = 'GET', $pParams = array() ) {
$pMethod = strtoupper( $pMethod );
try {
$result = $this->MakeRequest( $pPath, $pMethod, $pParams );
} catch ( Freemius_Exception $e ) {
// Map to error object.
$result = (object) $e->getResult();
} catch ( Exception $e ) {
// Map to error object.
$result = (object) array(
'error' => (object) array(
'type' => 'Unknown',
'message' => $e->getMessage() . ' (' . $e->getFile() . ': ' . $e->getLine() . ')',
'code' => 'unknown',
'http' => 402
)
);
}
return $result;
}
public function Api( $pPath, $pMethod = 'GET', $pParams = array() ) {
return $this->_Api( $this->CanonizePath( $pPath ), $pMethod, $pParams );
}
/**
* Base64 decoding that does not need to be urldecode()-ed.
*
* Exactly the same as PHP base64 encode except it uses
* `-` instead of `+`
* `_` instead of `/`
* No padded =
*
* @param string $input Base64UrlEncoded() string
*
* @return string
*/
protected static function Base64UrlDecode( $input ) {
/**
* IMPORTANT NOTE:
* This is a hack suggested by @otto42 and @greenshady from
* the theme's review team. The usage of base64 for API
* signature encoding was approved in a Slack meeting
* held on Tue (10/25 2016).
*
* @todo Remove this hack once the base64 error is removed from the Theme Check.
*
* @since 1.2.2
* @author Vova Feldman (@svovaf)
*/
$fn = 'base64' . '_decode';
return $fn( strtr( $input, '-_', '+/' ) );
}
/**
* Base64 encoding that does not need to be urlencode()ed.
*
* Exactly the same as base64 encode except it uses
* `-` instead of `+
* `_` instead of `/`
*
* @param string $input string
*
* @return string Base64 encoded string
*/
protected static function Base64UrlEncode( $input ) {
/**
* IMPORTANT NOTE:
* This is a hack suggested by @otto42 and @greenshady from
* the theme's review team. The usage of base64 for API
* signature encoding was approved in a Slack meeting
* held on Tue (10/25 2016).
*
* @todo Remove this hack once the base64 error is removed from the Theme Check.
*
* @since 1.2.2
* @author Vova Feldman (@svovaf)
*/
$fn = 'base64' . '_encode';
$str = strtr( $fn( $input ), '+/', '-_' );
$str = str_replace( '=', '', $str );
return $str;
}
}

View File

@ -0,0 +1,715 @@
<?php
/**
* Copyright 2016 Freemius, Inc.
*
* Licensed under the GPL v2 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://choosealicense.com/licenses/gpl-v2/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once dirname( __FILE__ ) . '/FreemiusBase.php';
if ( ! defined( 'FS_SDK__USER_AGENT' ) ) {
define( 'FS_SDK__USER_AGENT', 'fs-php-' . Freemius_Api_Base::VERSION );
}
if ( ! defined( 'FS_SDK__SIMULATE_NO_CURL' ) ) {
define( 'FS_SDK__SIMULATE_NO_CURL', false );
}
if ( ! defined( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE' ) ) {
define( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE', false );
}
if ( ! defined( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL' ) ) {
define( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL', false );
}
if ( ! defined( 'FS_SDK__HAS_CURL' ) ) {
if ( FS_SDK__SIMULATE_NO_CURL ) {
define( 'FS_SDK__HAS_CURL', false );
} else {
$curl_required_methods = array(
'curl_version',
'curl_exec',
'curl_init',
'curl_close',
'curl_setopt',
'curl_setopt_array',
'curl_error',
);
$has_curl = true;
foreach ( $curl_required_methods as $m ) {
if ( ! function_exists( $m ) ) {
$has_curl = false;
break;
}
}
define( 'FS_SDK__HAS_CURL', $has_curl );
}
}
if ( ! defined( 'FS_SDK__SSLVERIFY' ) ) {
define( 'FS_SDK__SSLVERIFY', false );
}
$curl_version = FS_SDK__HAS_CURL ?
curl_version() :
array( 'version' => '7.37' );
if ( ! defined( 'FS_API__PROTOCOL' ) ) {
define( 'FS_API__PROTOCOL', version_compare( $curl_version['version'], '7.37', '>=' ) ? 'https' : 'http' );
}
if ( ! defined( 'FS_API__LOGGER_ON' ) ) {
define( 'FS_API__LOGGER_ON', false );
}
if ( ! defined( 'FS_API__ADDRESS' ) ) {
define( 'FS_API__ADDRESS', '://api.freemius.com' );
}
if ( ! defined( 'FS_API__SANDBOX_ADDRESS' ) ) {
define( 'FS_API__SANDBOX_ADDRESS', '://sandbox-api.freemius.com' );
}
if ( class_exists( 'Freemius_Api_WordPress' ) ) {
return;
}
class Freemius_Api_WordPress extends Freemius_Api_Base {
private static $_logger = array();
/**
* @param string $pScope 'app', 'developer', 'user' or 'install'.
* @param number $pID Element's id.
* @param string $pPublic Public key.
* @param string|bool $pSecret Element's secret key.
* @param bool $pSandbox Whether or not to run API in sandbox mode.
*/
public function __construct( $pScope, $pID, $pPublic, $pSecret = false, $pSandbox = false ) {
// If secret key not provided, use public key encryption.
if ( is_bool( $pSecret ) ) {
$pSecret = $pPublic;
}
parent::Init( $pScope, $pID, $pPublic, $pSecret, $pSandbox );
}
public static function GetUrl( $pCanonizedPath = '', $pIsSandbox = false ) {
$address = ( $pIsSandbox ? FS_API__SANDBOX_ADDRESS : FS_API__ADDRESS );
if ( ':' === $address[0] ) {
$address = self::$_protocol . $address;
}
return $address . $pCanonizedPath;
}
#----------------------------------------------------------------------------------
#region Servers Clock Diff
#----------------------------------------------------------------------------------
/**
* @var int Clock diff in seconds between current server to API server.
*/
private static $_clock_diff = 0;
/**
* Set clock diff for all API calls.
*
* @since 1.0.3
*
* @param $pSeconds
*/
public static function SetClockDiff( $pSeconds ) {
self::$_clock_diff = $pSeconds;
}
/**
* Find clock diff between current server to API server.
*
* @since 1.0.2
* @return int Clock diff in seconds.
*/
public static function FindClockDiff() {
$time = time();
$pong = self::Ping();
return ( $time - strtotime( $pong->timestamp ) );
}
#endregion
/**
* @var string http or https
*/
private static $_protocol = FS_API__PROTOCOL;
/**
* Set API connection protocol.
*
* @since 1.0.4
*/
public static function SetHttp() {
self::$_protocol = 'http';
}
/**
* @since 1.0.4
*
* @return bool
*/
public static function IsHttps() {
return ( 'https' === self::$_protocol );
}
/**
* Sign request with the following HTTP headers:
* Content-MD5: MD5(HTTP Request body)
* Date: Current date (i.e Sat, 14 Feb 2016 20:24:46 +0000)
* Authorization: FS {scope_entity_id}:{scope_entity_public_key}:base64encode(sha256(string_to_sign,
* {scope_entity_secret_key}))
*
* @param string $pResourceUrl
* @param array $pWPRemoteArgs
*
* @return array
*/
function SignRequest( $pResourceUrl, $pWPRemoteArgs ) {
$auth = $this->GenerateAuthorizationParams(
$pResourceUrl,
$pWPRemoteArgs['method'],
! empty( $pWPRemoteArgs['body'] ) ? $pWPRemoteArgs['body'] : ''
);
$pWPRemoteArgs['headers']['Date'] = $auth['date'];
$pWPRemoteArgs['headers']['Authorization'] = $auth['authorization'];
if ( ! empty( $auth['content_md5'] ) ) {
$pWPRemoteArgs['headers']['Content-MD5'] = $auth['content_md5'];
}
return $pWPRemoteArgs;
}
/**
* Generate Authorization request headers:
*
* Content-MD5: MD5(HTTP Request body)
* Date: Current date (i.e Sat, 14 Feb 2016 20:24:46 +0000)
* Authorization: FS {scope_entity_id}:{scope_entity_public_key}:base64encode(sha256(string_to_sign,
* {scope_entity_secret_key}))
*
* @author Vova Feldman
*
* @param string $pResourceUrl
* @param string $pMethod
* @param string $pPostParams
*
* @return array
* @throws Freemius_Exception
*/
function GenerateAuthorizationParams(
$pResourceUrl,
$pMethod = 'GET',
$pPostParams = ''
) {
$pMethod = strtoupper( $pMethod );
$eol = "\n";
$content_md5 = '';
$content_type = '';
$now = ( time() - self::$_clock_diff );
$date = date( 'r', $now );
if ( in_array( $pMethod, array( 'POST', 'PUT' ) ) ) {
$content_type = 'application/json';
if ( ! empty( $pPostParams ) ) {
$content_md5 = md5( $pPostParams );
}
}
$string_to_sign = implode( $eol, array(
$pMethod,
$content_md5,
$content_type,
$date,
$pResourceUrl
) );
// If secret and public keys are identical, it means that
// the signature uses public key hash encoding.
$auth_type = ( $this->_secret !== $this->_public ) ? 'FS' : 'FSP';
$auth = array(
'date' => $date,
'authorization' => $auth_type . ' ' . $this->_id . ':' .
$this->_public . ':' .
self::Base64UrlEncode( hash_hmac(
'sha256', $string_to_sign, $this->_secret
) )
);
if ( ! empty( $content_md5 ) ) {
$auth['content_md5'] = $content_md5;
}
return $auth;
}
/**
* Get API request URL signed via query string.
*
* @since 1.2.3 Stopped using http_build_query(). Instead, use urlencode(). In some environments the encoding of http_build_query() can generate a URL that once used with a redirect, the `&` querystring separator is escaped to `&amp;` which breaks the URL (Added by @svovaf).
*
* @param string $pPath
*
* @throws Freemius_Exception
*
* @return string
*/
function GetSignedUrl( $pPath ) {
$resource = explode( '?', $this->CanonizePath( $pPath ) );
$pResourceUrl = $resource[0];
$auth = $this->GenerateAuthorizationParams( $pResourceUrl );
return Freemius_Api_WordPress::GetUrl(
$pResourceUrl . '?' .
( 1 < count( $resource ) && ! empty( $resource[1] ) ? $resource[1] . '&' : '' ) .
'authorization=' . urlencode( $auth['authorization'] ) .
'&auth_date=' . urlencode( $auth['date'] )
, $this->_isSandbox );
}
/**
* @author Vova Feldman
*
* @param string $pUrl
* @param array $pWPRemoteArgs
*
* @return mixed
*/
private static function ExecuteRequest( $pUrl, &$pWPRemoteArgs ) {
$start = microtime( true );
$response = wp_remote_request( $pUrl, $pWPRemoteArgs );
if ( FS_API__LOGGER_ON ) {
$end = microtime( true );
$has_body = ( isset( $pWPRemoteArgs['body'] ) && ! empty( $pWPRemoteArgs['body'] ) );
$is_http_error = is_wp_error( $response );
self::$_logger[] = array(
'id' => count( self::$_logger ),
'start' => $start,
'end' => $end,
'total' => ( $end - $start ),
'method' => $pWPRemoteArgs['method'],
'path' => $pUrl,
'body' => $has_body ? $pWPRemoteArgs['body'] : null,
'result' => ! $is_http_error ?
$response['body'] :
json_encode( $response->get_error_messages() ),
'code' => ! $is_http_error ? $response['response']['code'] : null,
'backtrace' => debug_backtrace(),
);
}
return $response;
}
/**
* @return array
*/
static function GetLogger() {
return self::$_logger;
}
/**
* @param string $pCanonizedPath
* @param string $pMethod
* @param array $pParams
* @param null|array $pWPRemoteArgs
* @param bool $pIsSandbox
* @param null|callable $pBeforeExecutionFunction
*
* @return object[]|object|null
*
* @throws \Freemius_Exception
*/
private static function MakeStaticRequest(
$pCanonizedPath,
$pMethod = 'GET',
$pParams = array(),
$pWPRemoteArgs = null,
$pIsSandbox = false,
$pBeforeExecutionFunction = null
) {
// Connectivity errors simulation.
if ( FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE ) {
self::ThrowCloudFlareDDoSException();
} else if ( FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL ) {
self::ThrowSquidAclException();
}
if ( empty( $pWPRemoteArgs ) ) {
$user_agent = 'Freemius/WordPress-SDK/' . Freemius_Api_Base::VERSION . '; ' .
home_url();
$pWPRemoteArgs = array(
'method' => strtoupper( $pMethod ),
'connect_timeout' => 10,
'timeout' => 60,
'follow_redirects' => true,
'redirection' => 5,
'user-agent' => $user_agent,
'blocking' => true,
);
}
if ( ! isset( $pWPRemoteArgs['headers'] ) ||
! is_array( $pWPRemoteArgs['headers'] )
) {
$pWPRemoteArgs['headers'] = array();
}
if ( in_array( $pMethod, array( 'POST', 'PUT' ) ) ) {
$pWPRemoteArgs['headers']['Content-type'] = 'application/json';
if ( is_array( $pParams ) && 0 < count( $pParams ) ) {
$pWPRemoteArgs['body'] = json_encode( $pParams );
}
}
$request_url = self::GetUrl( $pCanonizedPath, $pIsSandbox );
$resource = explode( '?', $pCanonizedPath );
if ( FS_SDK__HAS_CURL ) {
// Disable the 'Expect: 100-continue' behaviour. This causes cURL to wait
// for 2 seconds if the server does not support this header.
$pWPRemoteArgs['headers']['Expect'] = '';
}
if ( 'https' === substr( strtolower( $request_url ), 0, 5 ) ) {
$pWPRemoteArgs['sslverify'] = FS_SDK__SSLVERIFY;
}
if ( false !== $pBeforeExecutionFunction &&
is_callable( $pBeforeExecutionFunction )
) {
$pWPRemoteArgs = call_user_func( $pBeforeExecutionFunction, $resource[0], $pWPRemoteArgs );
}
$result = self::ExecuteRequest( $request_url, $pWPRemoteArgs );
if ( is_wp_error( $result ) ) {
/**
* @var WP_Error $result
*/
if ( self::IsCurlError( $result ) ) {
/**
* With dual stacked DNS responses, it's possible for a server to
* have IPv6 enabled but not have IPv6 connectivity. If this is
* the case, cURL will try IPv4 first and if that fails, then it will
* fall back to IPv6 and the error EHOSTUNREACH is returned by the
* operating system.
*/
$matches = array();
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if ( preg_match( $regex, $result->get_error_message( 'http_request_failed' ), $matches ) ) {
/**
* Validate IP before calling `inet_pton()` to avoid PHP un-catchable warning.
* @author Vova Feldman (@svovaf)
*/
if ( filter_var( $matches[1], FILTER_VALIDATE_IP ) ) {
if ( strlen( inet_pton( $matches[1] ) ) === 16 ) {
// error_log('Invalid IPv6 configuration on server, Please disable or get native IPv6 on your server.');
// Hook to an action triggered just before cURL is executed to resolve the IP version to v4.
add_action( 'http_api_curl', 'Freemius_Api_WordPress::CurlResolveToIPv4', 10, 1 );
// Re-run request.
$result = self::ExecuteRequest( $request_url, $pWPRemoteArgs );
}
}
}
}
if ( is_wp_error( $result ) ) {
self::ThrowWPRemoteException( $result );
}
}
$response_body = $result['body'];
if ( empty( $response_body ) ) {
return null;
}
$decoded = json_decode( $response_body );
if ( is_null( $decoded ) ) {
if ( preg_match( '/Please turn JavaScript on/i', $response_body ) &&
preg_match( '/text\/javascript/', $response_body )
) {
self::ThrowCloudFlareDDoSException( $response_body );
} else if ( preg_match( '/Access control configuration prevents your request from being allowed at this time. Please contact your service provider if you feel this is incorrect./', $response_body ) &&
preg_match( '/squid/', $response_body )
) {
self::ThrowSquidAclException( $response_body );
} else {
$decoded = (object) array(
'error' => (object) array(
'type' => 'Unknown',
'message' => $response_body,
'code' => 'unknown',
'http' => 402
)
);
}
}
return $decoded;
}
/**
* Makes an HTTP request. This method can be overridden by subclasses if
* developers want to do fancier things or use something other than wp_remote_request()
* to make the request.
*
* @param string $pCanonizedPath The URL to make the request to
* @param string $pMethod HTTP method
* @param array $pParams The parameters to use for the POST body
* @param null|array $pWPRemoteArgs wp_remote_request options.
*
* @return object[]|object|null
*
* @throws Freemius_Exception
*/
public function MakeRequest(
$pCanonizedPath,
$pMethod = 'GET',
$pParams = array(),
$pWPRemoteArgs = null
) {
$resource = explode( '?', $pCanonizedPath );
// Only sign request if not ping.json connectivity test.
$sign_request = ( '/v1/ping.json' !== strtolower( substr( $resource[0], - strlen( '/v1/ping.json' ) ) ) );
return self::MakeStaticRequest(
$pCanonizedPath,
$pMethod,
$pParams,
$pWPRemoteArgs,
$this->_isSandbox,
$sign_request ? array( &$this, 'SignRequest' ) : null
);
}
/**
* Sets CURLOPT_IPRESOLVE to CURL_IPRESOLVE_V4 for cURL-Handle provided as parameter
*
* @param resource $handle A cURL handle returned by curl_init()
*
* @return resource $handle A cURL handle returned by curl_init() with CURLOPT_IPRESOLVE set to
* CURL_IPRESOLVE_V4
*
* @link https://gist.github.com/golderweb/3a2aaec2d56125cc004e
*/
static function CurlResolveToIPv4( $handle ) {
curl_setopt( $handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
return $handle;
}
#----------------------------------------------------------------------------------
#region Connectivity Test
#----------------------------------------------------------------------------------
/**
* If successful connectivity to the API endpoint using ping.json endpoint.
*
* - OR -
*
* Validate if ping result object is valid.
*
* @param mixed $pPong
*
* @return bool
*/
public static function Test( $pPong = null ) {
$pong = is_null( $pPong ) ?
self::Ping() :
$pPong;
return (
is_object( $pong ) &&
isset( $pong->api ) &&
'pong' === $pong->api
);
}
/**
* Ping API to test connectivity.
*
* @return object
*/
public static function Ping() {
try {
$result = self::MakeStaticRequest( '/v' . FS_API__VERSION . '/ping.json' );
} catch ( Freemius_Exception $e ) {
// Map to error object.
$result = (object) $e->getResult();
} catch ( Exception $e ) {
// Map to error object.
$result = (object) array(
'error' => (object) array(
'type' => 'Unknown',
'message' => $e->getMessage() . ' (' . $e->getFile() . ': ' . $e->getLine() . ')',
'code' => 'unknown',
'http' => 402
)
);
}
return $result;
}
#endregion
#----------------------------------------------------------------------------------
#region Connectivity Exceptions
#----------------------------------------------------------------------------------
/**
* @param \WP_Error $pError
*
* @return bool
*/
private static function IsCurlError( WP_Error $pError ) {
$message = $pError->get_error_message( 'http_request_failed' );
return ( 0 === strpos( $message, 'cURL' ) );
}
/**
* @param WP_Error $pError
*
* @throws Freemius_Exception
*/
private static function ThrowWPRemoteException( WP_Error $pError ) {
if ( self::IsCurlError( $pError ) ) {
$message = $pError->get_error_message( 'http_request_failed' );
#region Check if there are any missing cURL methods.
$curl_required_methods = array(
'curl_version',
'curl_exec',
'curl_init',
'curl_close',
'curl_setopt',
'curl_setopt_array',
'curl_error',
);
// Find all missing methods.
$missing_methods = array();
foreach ( $curl_required_methods as $m ) {
if ( ! function_exists( $m ) ) {
$missing_methods[] = $m;
}
}
if ( ! empty( $missing_methods ) ) {
throw new Freemius_Exception( array(
'error' => (object) array(
'type' => 'cUrlMissing',
'message' => $message,
'code' => 'curl_missing',
'http' => 402
),
'missing_methods' => $missing_methods,
) );
}
#endregion
// cURL error - "cURL error {{errno}}: {{error}}".
$parts = explode( ':', substr( $message, strlen( 'cURL error ' ) ), 2 );
$code = ( 0 < count( $parts ) ) ? $parts[0] : 'http_request_failed';
$message = ( 1 < count( $parts ) ) ? $parts[1] : $message;
$e = new Freemius_Exception( array(
'error' => (object) array(
'code' => $code,
'message' => $message,
'type' => 'CurlException',
),
) );
} else {
$e = new Freemius_Exception( array(
'error' => (object) array(
'code' => $pError->get_error_code(),
'message' => $pError->get_error_message(),
'type' => 'WPRemoteException',
),
) );
}
throw $e;
}
/**
* @param string $pResult
*
* @throws Freemius_Exception
*/
private static function ThrowCloudFlareDDoSException( $pResult = '' ) {
throw new Freemius_Exception( array(
'error' => (object) array(
'type' => 'CloudFlareDDoSProtection',
'message' => $pResult,
'code' => 'cloudflare_ddos_protection',
'http' => 402
)
) );
}
/**
* @param string $pResult
*
* @throws Freemius_Exception
*/
private static function ThrowSquidAclException( $pResult = '' ) {
throw new Freemius_Exception( array(
'error' => (object) array(
'type' => 'SquidCacheBlock',
'message' => $pResult,
'code' => 'squid_cache_block',
'http' => 402
)
) );
}
#endregion
}

View File

@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{description}
Copyright (C) {year} {fullname}
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.

View File

@ -0,0 +1,43 @@
<?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.1.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Find the plugin main file path based on any given file inside the plugin's folder.
*
* @author Vova Feldman (@svovaf)
* @since 1.1.7.1
*
* @param string $file Absolute path to a file inside a plugin's folder.
*
* @return string
*/
function fs_find_direct_caller_plugin_file( $file ) {
/**
* All the code below will be executed once on activation.
* If the user changes the main plugin's file name, the file_exists()
* will catch it.
*/
$all_plugins = fs_get_plugins( true );
$file_real_path = fs_normalize_path( realpath( $file ) );
// Get active plugin's main files real full names (might be symlinks).
foreach ( $all_plugins as $relative_path => $data ) {
if ( 0 === strpos( $file_real_path, fs_normalize_path( dirname( realpath( WP_PLUGIN_DIR . '/' . $relative_path ) ) . '/' ) ) ) {
if ( '.' !== dirname( trailingslashit( $relative_path ) ) ) {
return $relative_path;
}
}
}
return null;
}

View File

@ -0,0 +1,45 @@
<?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 2.2.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! function_exists( 'fs_get_plugins' ) ) {
/**
* @author Leo Fajardo (@leorw)
* @since 2.2.1
*
* @param bool $delete_cache
*
* @return array
*/
function fs_get_plugins( $delete_cache = false ) {
$cached_plugins = wp_cache_get( 'plugins', 'plugins' );
if ( ! is_array( $cached_plugins ) ) {
$cached_plugins = array();
}
$plugin_folder = '';
if ( isset( $cached_plugins[ $plugin_folder ] ) ) {
$plugins = $cached_plugins[ $plugin_folder ];
} else {
if ( ! function_exists( 'get_plugins' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$plugins = get_plugins();
if ( $delete_cache && is_plugin_active( 'woocommerce/woocommerce.php' ) ) {
wp_cache_delete( 'plugins', 'plugins' );
}
}
return $plugins;
}
}

View File

@ -0,0 +1,3 @@
<?php
// Silence is golden.
// Hide file structure from users on unprotected servers.