first commit

This commit is contained in:
2026-03-05 13:07:40 +01:00
commit 64ba0721ee
25709 changed files with 4691006 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
{
"name": "wpdesk\/wp-wpdesk-license",
"authors": [
{
"name": "Krzysiek",
"email": "krzysiek@wpdesk.pl"
}
],
"prefer-stable": true,
"minimum-stability": "dev",
"require": {
"php": ">=7.0",
"ext-curl": "*",
"ext-json": "*",
"wpdesk\/wp-builder": "^2.0.0",
"wpdesk\/wp-notice": "^3.1.4"
},
"require-dev": {
"phpunit\/phpunit": "<7",
"wp-coding-standards\/wpcs": "^0.14.1",
"squizlabs\/php_codesniffer": "^3.0.2",
"mockery\/mockery": "*",
"10up\/wp_mock": "*"
},
"suggest": {
"wpdesk\/wp-logs": "^1.10"
},
"autoload": {
"classmap": [
"src\/ApiManager"
],
"psr-4": {
"VendorDHL\\WPDesk\\License\\": "src\/"
}
},
"autoload-dev": {},
"extra": {
"text-domain": "wp-wpdesk-license",
"translations-folder": "lang",
"po-files": {
"pl_PL": "pl_PL.po",
"de_DE": "de_DE.po"
}
},
"scripts": {
"phpunit-unit": "phpunit --configuration phpunit-unit.xml --coverage-text --colors=never",
"phpunit-unit-fast": "phpunit --configuration phpunit-unit.xml --no-coverage",
"phpunit-integration": "phpunit --configuration phpunit-integration.xml --coverage-text --colors=never",
"phpunit-integration-fast": "phpunit --configuration phpunit-integration.xml --no-coverage"
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace VendorDHL\WPDesk\License\ActivationForm;
use VendorDHL\WPDesk\License\LicenseManager;
use VendorDHL\WPDesk\License\Page\LicensePageActions;
use VendorDHL\WPDesk\License\PluginLicense;
use VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Handles License Activation Ajax requests.
*/
class AjaxHandler implements \VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable
{
const AJAX_ACTION = 'license_activation';
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @param WPDesk_Plugin_Info $plugin_info .
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
$this->plugin_info = $plugin_info;
}
/**
* Hooks.
*/
public function hooks()
{
\add_action('wp_ajax_wpdesk_license_activation_' . $this->plugin_info->get_plugin_file_name(), [$this, 'handle_ajax_action']);
}
/**
* Handles ajax action.
*/
public function handle_ajax_action()
{
\check_ajax_referer(self::AJAX_ACTION, 'security');
$license_manager = new \VendorDHL\WPDesk\License\LicenseManager($this->plugin_info);
$license_action = $this->get_post_value_as_string('license_action');
$plugin_info = ['plugin' => $this->plugin_info->get_plugin_file_name(), 'product_id' => $this->plugin_info->get_product_id(), 'api_manager' => $license_manager->create_api_manager(\false)];
$license_page_action = (new \VendorDHL\WPDesk\License\Page\LicensePageActions())->create_action($license_action, \false);
$license_page_action->execute($plugin_info);
\delete_site_transient('update_plugins');
\wp_update_plugins();
$update_plugins = \get_site_transient('update_plugins');
$update_plugins = \is_array($update_plugins) ? $update_plugins : [$this->plugin_info->get_plugin_file_name() => new \stdClass()];
$plugin_license = new \VendorDHL\WPDesk\License\PluginLicense($this->plugin_info);
$form_content_renderer = new \VendorDHL\WPDesk\License\ActivationForm\FormContentRenderer($this->plugin_info, $this->is_update_possible(isset($update_plugins[$this->plugin_info->get_plugin_file_name()]) ?? new \stdClass()), $license_page_action->get_errors());
\wp_send_json_success(['activation_form_content' => $form_content_renderer->render(), 'is_active' => $plugin_license->is_active(), 'errors' => $license_page_action->get_errors()]);
}
/**
* @param \stdClass $plugin_data .
*
* @return bool
*/
private function is_update_possible($plugin_data)
{
if (isset($plugin_data->Version) && isset($plugin_data->new_version) && $plugin_data->Version !== $plugin_data->new_version && empty($plugin_data->package)) {
return \false;
}
return \true;
}
/**
* @param string $key .
*
* @return string
*/
private function get_post_value_as_string(string $key) : string
{
$value = \wp_unslash($_POST[$key]);
// phpcs:ignore.
return \is_array($value) ? '' : $value;
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace VendorDHL\WPDesk\License\ActivationForm;
use VendorDHL\WPDesk\License\Page\License\Action\ActionError;
use VendorDHL\WPDesk\License\PluginLicense;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Can render License Activation form content.
*/
class FormContentRenderer
{
const SHOP_WWW_WPDESK_PL = 'https://www.wpdesk.pl/';
const MY_ACCOUNT_API_KEYS_EN = 'my-account/api-keys/';
const MY_ACCOUNT_API_KEYS_PL = 'moje-konto/api-keys/';
const DOCS_EN = 'docs/how-to-activate-licenses';
const DOCS_PL = 'docs/licencje-wtyczek/';
const DOCS_URLS = ['octolize.com' => 'https://octol.io/how-to-activate-plugin'];
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @var \stdClass
*/
private $update_possible;
/**
* @var ActionError[]
*/
private $errors;
/**
* @param WPDesk_Plugin_Info $plugin_info .
* @param bool $update_possible .
* @param ActionError[] $errors .
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info, bool $update_possible, array $errors = [])
{
$this->plugin_info = $plugin_info;
$this->update_possible = $update_possible;
$this->errors = $errors;
}
/**
* @return string
*/
public function render() : string
{
\ob_start();
$this->output_render();
return \ob_get_clean();
}
public function output_render()
{
$plugin_license = new \VendorDHL\WPDesk\License\PluginLicense($this->plugin_info);
$is_active = $plugin_license->is_active();
$plugin_slug = $this->plugin_info->get_plugin_slug();
$api_key = $plugin_license->get_api_key();
$activation_email = $plugin_license->get_activation_email();
$plugin_file = $this->plugin_info->get_plugin_file_name();
$errors = $this->errors;
$my_account_link = $this->prapare_my_account_link_according_to_locale_and_shop(\get_locale(), $this->plugin_info->get_plugin_shops());
$docs_link = $this->prapare_docs_link_according_to_locale_and_shop(\get_locale(), $this->plugin_info->get_plugin_shops());
$update_possible = $this->update_possible;
$renew_subscription_link = $this->prepare_renew_subscription_link_according_to_shop($plugin_license->get_upgrade_url());
include __DIR__ . '/views/activation-form-content.php';
}
/**
* @param string $upgrade_url .
*
* @return string
*/
private function prepare_renew_subscription_link_according_to_shop($upgrade_url)
{
$utms = '?utm_source=renew&utm_medium=plugin-list&utm_campaign=subscriptions';
return \trailingslashit($upgrade_url) . '/my-account/' . $utms;
}
/**
* @param string $locale .
* @param array<string,string> $plugin_shops .
*
* @return string
*/
private function prapare_my_account_link_according_to_locale_and_shop(string $locale, array $plugin_shops) : string
{
$default = 'default';
$default_shop = $plugin_shops[$default] ?? '';
$shop_url = $plugin_shops[$locale] ?? $default_shop;
$my_account = self::SHOP_WWW_WPDESK_PL !== $shop_url ? self::MY_ACCOUNT_API_KEYS_EN : self::MY_ACCOUNT_API_KEYS_PL;
$utms = '?utm_source=my-account-list&utm_medium=link&utm_campaign=licenses';
return isset($shop_url) ? \trailingslashit($shop_url) . $my_account . $utms : '';
}
/**
* @param string $locale .
* @param array<string,string> $plugin_shops .
*
* @return string
*/
private function prapare_docs_link_according_to_locale_and_shop(string $locale, array $plugin_shops) : string
{
$default = 'default';
$default_shop = $plugin_shops[$default] ?? '';
$shop_url = $plugin_shops[$locale] ?? $default_shop;
$shop_domain = $this->get_shop_domain($shop_url);
if (isset(self::DOCS_URLS[$shop_domain])) {
return self::DOCS_URLS[$shop_domain];
}
$docs = self::SHOP_WWW_WPDESK_PL !== $shop_url ? self::DOCS_EN : self::DOCS_PL;
$utms = '?utm_source=docs&utm_medium=link&utm_campaign=licenses';
return isset($shop_url) ? \trailingslashit($shop_url) . $docs . $utms : '';
}
/**
* @param string $shop_url .
*
* @return string
*/
private function get_shop_domain(string $shop_url) : string
{
return \parse_url($shop_url, \PHP_URL_HOST) ?? '';
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace VendorDHL\WPDesk\License\ActivationForm;
use VendorDHL\WPDesk\License\PluginLicense;
use VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Can render activation form on plugins page.
*/
class PluginsPageRenderer implements \VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable
{
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @param WPDesk_Plugin_Info $plugin_info .
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
$this->plugin_info = $plugin_info;
}
public function hooks()
{
\add_action('after_plugin_row_' . $this->plugin_info->get_plugin_file_name(), [$this, 'display_activation_form_in_table_row'], 10, 3);
}
/**
* Displays activation form.
*
* @param string $plugin_file .
* @param array $plugin_data .
* @param string $status .
*/
public function display_activation_form_in_table_row($plugin_file, $plugin_data, $status)
{
$this->output_render($plugin_file, $plugin_data);
}
/**
* @param string $plugin_file .
* @param array $plugin_data .
*
* @return string
*/
public function render(string $plugin_file, $plugin_data)
{
\ob_start();
$this->output_render($plugin_file, $plugin_data);
return \ob_get_clean();
}
/**
* @param string $plugin_file .
* @param array $plugin_data .
*/
public function output_render(string $plugin_file, $plugin_data)
{
$plugin_license = new \VendorDHL\WPDesk\License\PluginLicense($this->plugin_info);
$plugin_slug = $this->plugin_info->get_plugin_slug();
$is_active = $plugin_license->is_active();
$update_possible = $this->is_update_possible($plugin_data);
$form_content = new \VendorDHL\WPDesk\License\ActivationForm\Renderer($this->plugin_info, $update_possible);
include __DIR__ . '/views/plugins-page-row.php';
}
/**
* @param array $plugin_data .
*
* @return bool
*/
private function is_update_possible(array $plugin_data)
{
if (isset($plugin_data['Version']) && isset($plugin_data['new_version']) && $plugin_data['Version'] !== $plugin_data['new_version'] && empty($plugin_data['package'])) {
return \false;
}
return \true;
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace VendorDHL\WPDesk\License\ActivationForm;
use VendorDHL\WPDesk_Plugin_Info;
class Renderer
{
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @var bool
*/
private $update_possible;
/**
* @param WPDesk_Plugin_Info $plugin_info .
* @param bool $update_possible .
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info, bool $update_possible)
{
$this->plugin_info = $plugin_info;
$this->update_possible = $update_possible;
}
/**
* @return string
*/
public function render()
{
\ob_start();
$this->output_render();
return \ob_get_clean();
}
public function output_render()
{
$form_content = new \VendorDHL\WPDesk\License\ActivationForm\FormContentRenderer($this->plugin_info, $this->update_possible);
$plugin_slug = $this->plugin_info->get_plugin_slug();
$plugin_file = $this->plugin_info->get_plugin_file_name();
include __DIR__ . '/views/activation-form.php';
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace VendorDHL;
use VendorDHL\WPDesk\License\Page\License\Action\ActionError;
/**
* @var $plugin_slug string
* @var $api_key string
* @var $activation_email string
* @var $is_active bool
* @var $errors ActionError[]
* @var $my_account_link string
* @var $docs_link string
* @var $update_possible bool
* @var $renew_subscription_link string
*/
foreach ($errors as $error) {
?>
<div class="wpdesk-license-notice notice inline notice-alt <?php
echo \esc_html($error->get_type());
?>">
<?php
echo \wp_kses_post($error->get_message());
?>
</div>
<?php
}
?><p class="introduction">
<?php
if ($is_active) {
if ($update_possible) {
\esc_html_e(\__('Plugin\'s API key has been successfully activated. You are now fully eligible to receive plugin updates and support.', 'woocommerce-dhl'));
} else {
\esc_html_e(\__('Plugin\'s API key has been successfully activated, but your subscription has expired. In order to receive the upcoming updates and support please renew your subscription.', 'woocommerce-dhl'));
}
} else {
echo \esc_html(\__('In order to receive the upcoming updates and support please enter the plugin\'s API key obtained after the purchase.', 'woocommerce-dhl'));
if ($my_account_link && $docs_link) {
// Translators: my account link.
echo \wp_kses_post(' ' . \sprintf(
// Translators: my account link and docs link.
\__('You can find it in %1$sMy Account / API Keys%2$s tab. %3$sLearn more about activating the API key →%4$s', 'woocommerce-dhl'),
\sprintf('<a href="%1$s" target="_blank">', $my_account_link),
'</a>',
\sprintf('<a href="%1$s" target="_blank">', $docs_link),
'</a>'
));
}
}
?>
</p>
<div class="api-key">
<?php
echo \esc_html(\__('Key: ', 'woocommerce-dhl'));
?> <input type="text" name="api_key" value="<?php
echo \esc_html($api_key);
?>" placeholder="" <?php
\disabled($is_active);
?> />
</div>
<div class="activation-button">
<?php
if ($is_active) {
?>
<button class="deactivate button"><?php
echo \esc_html(\__('Deactivate license', 'woocommerce-dhl'));
?></button><span class="spinner"></span>
<?php
if (!$update_possible) {
?>
<a href="<?php
echo \esc_url($renew_subscription_link);
?>" class="button-primary" target="_blank" style="text-decoration: none;"><?php
echo \esc_html(\__('Renew subscription →', 'woocommerce-dhl'));
?></a>
<?php
}
?>
<?php
} else {
?>
<button class="activate button button-primary"><?php
echo \esc_html(\__('Activate license', 'woocommerce-dhl'));
?></button><span class="spinner"></span>
<?php
}
?>
</div>
<?php

View File

@@ -0,0 +1,136 @@
<?php
namespace VendorDHL;
/**
* @var string $plugin_slug
* @var string $plugin_file
* @var \WPDesk\License\ActivationForm\FormContentRenderer $form_content
*/
use VendorDHL\WPDesk\License\ActivationForm\AjaxHandler;
?>
<div id="<?php
echo \esc_attr($plugin_slug);
?>-activation-form" class="wpdesk-license-activation-form">
<style>
#<?php
echo \esc_html($plugin_slug);
?>-activation-form {
overflow: hidden;
}
#<?php
echo \esc_html($plugin_slug);
?>-activation-form div {
float: left;
margin-right: 10px;
margin-bottom: 3px;
}
#<?php
echo \esc_html($plugin_slug);
?>-activation-form div input[type=text] {
min-width: 350px;
box-shadow: 0 0 0 transparent;
border-radius: 4px;
border: 1px solid #8c8f94;
background-color: #fff;
color: #2c3338;
}
#<?php
echo \esc_html($plugin_slug);
?>-activation-form div input[type=text]:disabled {
background: rgba(255,255,255,.5);
border-color: rgba(220,220,222,.75);
box-shadow: inset 0 1px 2px rgb(0 0 0 / 4%);
color: rgba(44,51,56,.5);
}
#<?php
echo \esc_html($plugin_slug);
?>-activation-form div.wpdesk-license-notice {
float: none;
margin-left: 0px;
font-weight: bold;
padding: 10px 10px 10px 20px;
color: rgb(60, 67, 74);
}
</style>
<div class="wpdesk-license-activation-form-content">
<?php
$form_content->output_render();
?>
</div>
<script type="text/javascript">
jQuery(function(){
let plugin_slug = "<?php
echo \esc_html($plugin_slug);
?>";
let admin_ajax_url = "<?php
echo \esc_url(\admin_url('admin-ajax.php'));
?>";
let plugin_file = "<?php
echo \esc_attr($plugin_file);
?>";
let nonce = "<?php
echo \esc_attr(\wp_create_nonce(\VendorDHL\WPDesk\License\ActivationForm\AjaxHandler::AJAX_ACTION));
?>";
let alert_text = "<?php
echo \esc_attr(\__('The action failed with an error: ', 'woocommerce-dhl'));
?>";
let enter_license_key = "<?php
echo \esc_attr(\__('Enter license key', 'woocommerce-dhl'));
?>";
/**
* Sends AJAX request.
* @param {string} action
* @param {object} $button
*/
function send_ajax_request( action, $button ) {
$button.prop( "disabled", true );
$button.parent().find( "span.spinner" ).addClass( 'is-active' );
let api_key = jQuery( "#" + plugin_slug + "-activation-form input[name='api_key']" ).val();
let activation_email = ' ';
jQuery.ajax({
type : "post",
dataType : "json",
url : admin_ajax_url,
data : {
action: "wpdesk_license_activation_" + plugin_file,
license_action: action,
api_key : api_key,
activation_email: activation_email,
security: nonce,
},
success: function( response ) {
if ( response.success ) {
let $form_content = jQuery( "#" + plugin_slug + "-activation-form div.wpdesk-license-activation-form-content" );
$form_content.html( response.data.activation_form_content );
$form_content.parent().trigger( "license-updated", response.data );
}
jQuery( "#" + plugin_slug + "-update" ).remove();
},
error: function ( xhr, ajaxOptions, thrownError ) {
alert( alert_text + thrownError );
$button.prop( "disabled", false );
$button.parent().find( "span.spinner" ).removeClass( "is-active" );
}
});
}
jQuery(document).on( "click", "#" + plugin_slug + "-activation-form button.deactivate", function (event) {
event.preventDefault();
send_ajax_request( 'deactivate', jQuery( this ) );
});
jQuery(document).on( "click", "#" + plugin_slug + "-activation-form button.activate", function (event) {
event.preventDefault();
let $api_key = jQuery( "#" + plugin_slug + "-activation-form input[name='api_key']" );
let api_key_val = $api_key.val();
if ( "" !== api_key_val ) {
send_ajax_request( "activate", jQuery( this ) );
} else {
$api_key.focus();
$api_key.attr( "placeholder", enter_license_key );
}
});
});
</script>
</div>
<?php

View File

@@ -0,0 +1,57 @@
<?php
namespace VendorDHL;
/**
* @var string $status
* @var bool $is_active
* @var string $plugin_slug
* @var string $plugin_file
* @var bool $update_possible
* @var WPDesk\License\ActivationForm\Renderer $form_content
*/
?><tr class="plugin-update-tr plugin-wpdesk-license-tr active" id="<?php
echo \esc_attr($plugin_slug);
?>-wpdesk-license" data-slug="<?php
echo \esc_attr($plugin_slug);
?>" data-plugin="<?php
echo \esc_attr($plugin_file);
?>">
<td colspan="10" class="plugin-update colspanchange">
<div id="<?php
echo \esc_attr($plugin_slug);
?>-wpdesk-license-activation-notice" class="notice inline notice-alt <?php
echo \esc_html($is_active && $update_possible ? 'notice-success' : 'notice-warning');
?>">
<?php
$form_content->output_render();
?>
</div>
<script type="text/javascript">
jQuery(function() {
let plugin_slug = "<?php
echo \esc_html($plugin_slug);
?>";
let plugin_file = "<?php
echo \esc_attr($plugin_file);
?>";
let $plugin_tr = jQuery("tr[data-plugin='" + plugin_file + "']");
if ( $plugin_tr.hasClass('update') ) {
jQuery( "#" + plugin_slug + "-wpdesk-license" ).find( 'td' ).css( 'box-shadow', 'none' );
}
$plugin_tr.addClass('update');
jQuery( "#" + plugin_slug + "-wpdesk-license-activation-notice" ).on( 'license-updated', function( event, data ){
let $notice_div = jQuery( this );
if ( data.is_active ) {
$notice_div.addClass( 'notice-success' );
$notice_div.removeClass( 'notice-warning' );
} else {
$notice_div.addClass( 'notice-warning' );
$notice_div.removeClass( 'notice-success' );
}
});
});
</script>
</td>
</tr>
<?php

View File

@@ -0,0 +1,316 @@
<?php
namespace VendorDHL;
/**
* Admin Menu Class
*
* @package Update API Manager/Admin
* @author Todd Lahman LLC, WPDesk
* @copyright Copyright (c) Todd Lahman LLC
* @since 1.3
*
*/
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
if (!\class_exists('VendorDHL\\WPDesk_API_MENU')) {
class WPDesk_API_MENU
{
private $api_manager;
// Load admin menu
public function __construct($api_manager)
{
$this->api_manager = $api_manager;
}
// Draw option page
public function config_page()
{
$settings_tabs = [$this->api_manager->activation_tab_key => \__($this->api_manager->menu_tab_activation_title, $this->api_manager->text_domain), $this->api_manager->deactivation_tab_key => \__($this->api_manager->menu_tab_deactivation_title, $this->api_manager->text_domain)];
$current_tab = isset($_GET['tab']) ? \sanitize_key($_GET['tab']) : $this->api_manager->activation_tab_key;
$tab = isset($_GET['tab']) ? \sanitize_key($_GET['tab']) : $this->api_manager->activation_tab_key;
?>
<div class='wrap'>
<?php
/* screen_icon(); */
?>
<h2><?php
echo \wp_kses_post(\__($this->api_manager->settings_title, $this->api_manager->text_domain));
?></h2>
<?php
\settings_errors();
?>
<h2 class="nav-tab-wrapper">
<?php
foreach ($settings_tabs as $tab_page => $tab_name) {
$active_tab = $current_tab == $tab_page ? 'nav-tab-active' : '';
echo \wp_kses_post('<a class="nav-tab ' . $active_tab . '" href="?page=' . $this->api_manager->activation_tab_key . '&tab=' . $tab_page . '">' . $tab_name . '</a>');
}
?>
</h2>
<form action='options.php' method='post'>
<div class="main">
<?php
if ($tab == $this->api_manager->activation_tab_key) {
\settings_fields($this->api_manager->data_key);
\do_settings_sections($this->api_manager->activation_tab_key);
//if (get_option( $this->api_manager->activated_key, '0' ) != 'Activated') {
\submit_button(\__('Save Changes', $this->api_manager->text_domain));
//}
} else {
\settings_fields($this->api_manager->deactivate_checkbox);
\do_settings_sections($this->api_manager->deactivation_tab_key);
\submit_button(\__('Save Changes', $this->api_manager->text_domain));
}
?>
</div>
</form>
</div>
<?php
}
// Register settings
public function load_settings()
{
\register_setting($this->api_manager->data_key, $this->api_manager->data_key, [$this, 'validate_options']);
// API Key
\add_settings_section($this->api_manager->api_key, \__('API Key Activation', $this->api_manager->text_domain), [$this, 'wc_am_api_key_text'], $this->api_manager->activation_tab_key);
\add_settings_field('status', \__('API Key Status', $this->api_manager->text_domain), [$this, 'wc_am_api_key_status'], $this->api_manager->activation_tab_key, $this->api_manager->api_key);
\add_settings_field($this->api_manager->api_key, \__('API Subscription Key', $this->api_manager->text_domain), [$this, 'wc_am_api_key_field'], $this->api_manager->activation_tab_key, $this->api_manager->api_key);
\add_settings_field($this->api_manager->activation_email, \__('API Subscription email', $this->api_manager->text_domain), [$this, 'wc_am_api_email_field'], $this->api_manager->activation_tab_key, $this->api_manager->api_key);
// Activation settings
\register_setting($this->api_manager->deactivate_checkbox, $this->api_manager->deactivate_checkbox, [$this, 'wc_am_license_key_deactivation']);
\add_settings_section('deactivate_button', \__('API Key Deactivation', $this->api_manager->text_domain), [$this, 'wc_am_deactivate_text'], $this->api_manager->deactivation_tab_key);
\add_settings_field('deactivate_button', \__('Deactivate API Key', $this->api_manager->text_domain), [$this, 'wc_am_deactivate_textarea'], $this->api_manager->deactivation_tab_key, 'deactivate_button');
}
// Provides text for api key section
public function wc_am_api_key_text()
{
//
}
// Returns the API License Key status from the WooCommerce API Manager on the server
public function wc_am_api_key_status()
{
$license_status = $this->license_key_status();
$license_status_check = !empty($license_status['status_check']) && $license_status['status_check'] == 'active' ? 'Activated' : 'Deactivated';
if (!empty($license_status_check)) {
echo \esc_html($license_status_check);
}
}
// Returns API License text field
public function wc_am_api_key_field()
{
echo \wp_kses_post("<input id='api_key' name='" . $this->api_manager->data_key . "[" . $this->api_manager->api_key . "]' size='55' type='text' value='" . $this->api_manager->options[$this->api_manager->api_key] . "' />");
if ($this->api_manager->options[$this->api_manager->api_key]) {
echo \wp_kses_post("<span class='icon-pos'><img src='" . \plugins_url("wpdesk-helper/assets/images/complete.png") . "' title='' style='padding-bottom: 4px; vertical-align: middle; margin-right:3px;' /></span>");
} else {
echo \wp_kses_post("<span class='icon-pos'><img src='" . \plugins_url("wpdesk-helper/assets/images/warn.png") . "' title='' style='padding-bottom: 4px; vertical-align: middle; margin-right:3px;' /></span>");
}
}
// Returns API License email text field
public function wc_am_api_email_field()
{
echo \wp_kses_post("<input id='activation_email' name='" . $this->api_manager->data_key . "[" . $this->api_manager->activation_email . "]' size='55' type='text' value='" . $this->api_manager->options[$this->api_manager->activation_email] . "' />");
if ($this->api_manager->options[$this->api_manager->activation_email]) {
echo \wp_kses_post("<span class='icon-pos'><img src='" . \plugins_url("wpdesk-helper/assets/images/complete.png") . "' title='' style='padding-bottom: 4px; vertical-align: middle; margin-right:3px;' /></span>");
} else {
echo \wp_kses_post("<span class='icon-pos'><img src='" . \plugins_url("wpdesk-helper/assets/images/warn.png") . "' title='' style='padding-bottom: 4px; vertical-align: middle; margin-right:3px;' /></span>");
}
}
// Sanitizes and validates all input and output for Dashboard
public function validate_options($input)
{
// Load existing options, validate, and update with changes from input before returning
$options = $this->api_manager->options;
$options[$this->api_manager->api_key] = \trim($input[$this->api_manager->api_key]);
$options[$this->api_manager->activation_email] = \trim($input[$this->api_manager->activation_email]);
/**
* Plugin Activation
*/
$api_email = \trim($input[$this->api_manager->activation_email]);
$api_key = \trim($input[$this->api_manager->api_key]);
$activation_status = \get_option($this->api_manager->activated_key);
$checkbox_status = \get_option($this->api_manager->deactivate_checkbox);
$current_api_key = $this->api_manager->options[$this->api_manager->api_key];
// Should match the settings_fields() value
if ($_REQUEST['option_page'] != $this->api_manager->deactivate_checkbox) {
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
if ($activation_status == 'Deactivated' || $activation_status == '' || $api_key == '' || $api_email == '' || $checkbox_status == 'on' || $current_api_key != $api_key) {
/**
* If this is a new key, and an existing key already exists in the database,
* deactivate the existing key before activating the new key.
*/
if ($current_api_key != $api_key) {
$this->replace_license_key($current_api_key);
}
$args = ['email' => $api_email, 'licence_key' => $api_key];
$activate_results = \json_decode($this->api_manager->key()->activate($args), \true);
if ($activate_results['activated'] === \true) {
\add_settings_error('activate_text', 'activate_msg', \__('Plugin activated. ', $this->api_manager->text_domain) . "{$activate_results['message']}.", 'updated');
\update_option($this->api_manager->activated_key, 'Activated');
\update_option($this->api_manager->deactivate_checkbox, 'off');
}
if ($activate_results == \false) {
\add_settings_error('api_key_check_text', 'api_key_check_error', \__('Connection failed to the API Key server. Try again later.', $this->api_manager->text_domain), 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
}
if (isset($activate_results['code'])) {
switch ($activate_results['code']) {
case '100':
\add_settings_error('api_email_text', 'api_email_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->activation_email] = '';
$options[$this->api_manager->api_key] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '101':
\add_settings_error('api_key_text', 'api_key_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '102':
\add_settings_error('api_key_purchase_incomplete_text', 'api_key_purchase_incomplete_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '103':
\add_settings_error('api_key_exceeded_text', 'api_key_exceeded_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '104':
\add_settings_error('api_key_not_activated_text', 'api_key_not_activated_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '105':
\add_settings_error('api_key_invalid_text', 'api_key_invalid_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '106':
\add_settings_error('sub_not_active_text', 'sub_not_active_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
}
}
}
// End Plugin Activation
}
return $options;
}
// Returns the API License Key status from the WooCommerce API Manager on the server
public function license_key_status()
{
$activation_status = \get_option($this->api_manager->activated_key);
$args = ['email' => $this->api_manager->options[$this->api_manager->activation_email], 'licence_key' => $this->api_manager->options[$this->api_manager->api_key]];
return \json_decode($this->api_manager->key()->status($args), \true);
}
// Deactivate the current license key before activating the new license key
public function replace_license_key($current_api_key)
{
$args = ['email' => $this->api_manager->options[$this->api_manager->activation_email], 'licence_key' => $current_api_key];
$reset = $this->api_manager->key()->deactivate($args);
// reset license key activation
if ($reset == \true) {
return \true;
}
return \add_settings_error('not_deactivated_text', 'not_deactivated_error', \__('The subscription could not be deactivated. Use the Subscription Deactivation tab to manually deactivate the subscription before activating a new subscription.', $this->api_manager->text_domain), 'updated');
}
// Deactivates the license key to allow key to be used on another blog
public function wc_am_license_key_deactivation($input)
{
$activation_status = \get_option($this->api_manager->activated_key);
$args = ['email' => $this->api_manager->options[$this->api_manager->activation_email], 'licence_key' => $this->api_manager->options[$this->api_manager->api_key]];
// For testing activation status_extra data
// $activate_results = json_decode( $this->api_manager->key()->status( $args ), true );
// print_r($activate_results); exit;
$options = $input == 'on' ? 'on' : 'off';
if ($options == 'on' && $activation_status == 'Activated' && $this->api_manager->options[$this->api_manager->api_key] != '' && $this->api_manager->options[$this->api_manager->activation_email] != '') {
// deactivates license key activation
$activate_results = \json_decode($this->api_manager->key()->deactivate($args), \true);
// Used to display results for development
//print_r($activate_results); exit();
if ($activate_results['deactivated'] === \true) {
$update = [$this->api_manager->api_key => '', $this->api_manager->activation_email => ''];
$merge_options = \array_merge($this->api_manager->options, $update);
\update_option($this->api_manager->data_key, $merge_options);
\update_option($this->api_manager->activated_key, 'Deactivated');
\add_settings_error('wc_am_deactivate_text', 'deactivate_msg', \__('Plugin subscription deactivated. ', $this->api_manager->text_domain) . "{$activate_results['activations_remaining']}.", 'updated');
return $options;
}
if (isset($activate_results['code'])) {
switch ($activate_results['code']) {
case '100':
\add_settings_error('api_email_text', 'api_email_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->activation_email] = '';
$options[$this->api_manager->api_key] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '101':
\add_settings_error('api_key_text', 'api_key_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '102':
\add_settings_error('api_key_purchase_incomplete_text', 'api_key_purchase_incomplete_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '103':
\add_settings_error('api_key_exceeded_text', 'api_key_exceeded_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '104':
\add_settings_error('api_key_not_activated_text', 'api_key_not_activated_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '105':
\add_settings_error('api_key_invalid_text', 'api_key_invalid_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
case '106':
\add_settings_error('sub_not_active_text', 'sub_not_active_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$this->api_manager->api_key] = '';
$options[$this->api_manager->activation_email] = '';
\update_option($this->api_manager->options[$this->api_manager->activated_key], 'Deactivated');
break;
}
}
} else {
return $options;
}
}
public function wc_am_deactivate_text()
{
}
public function wc_am_deactivate_textarea()
{
echo \wp_kses_post('<input type="checkbox" id="' . $this->api_manager->deactivate_checkbox . '" name="' . $this->api_manager->deactivate_checkbox . '" value="on"');
echo \wp_kses_post(\checked(\get_option($this->api_manager->deactivate_checkbox), 'on'));
echo \wp_kses_post('/>');
?><span class="description"><?php
\wp_kses_post(\__('Deactivates an API Key so it can be used on another blog.', $this->api_manager->text_domain));
?></span>
<?php
}
}
// class WPDesk_API_MENU
}
// if (!class_exists('WPDesk_API_MENU'))

View File

@@ -0,0 +1,74 @@
<?php
namespace VendorDHL;
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
/**
* WooCommerce API Manager Passwords Class
*
* @package Update API Manager/Passwords
* @author Todd Lahman LLC, WPDesk
* @copyright Copyright (c) Todd Lahman LLC
* @since 1.0.0
*
*/
if (!\class_exists('VendorDHL\\WPDesk_API_Password_Management')) {
class WPDesk_API_Password_Management
{
private function rand($min = 0, $max = 0)
{
static $rnd_value = '';
// Reset $rnd_value after 14 uses
// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
if (\strlen($rnd_value) < 8) {
if (\defined('VendorDHL\\WP_SETUP_CONFIG')) {
static $seed = '';
} else {
$seed = \get_transient('random_seed');
}
$rnd_value = \md5(\uniqid(\microtime() . \mt_rand(), \true) . $seed);
$rnd_value .= \sha1($rnd_value);
$rnd_value .= \sha1($rnd_value . $seed);
$seed = \md5($seed . $rnd_value);
if (!\defined('VendorDHL\\WP_SETUP_CONFIG')) {
\set_transient('random_seed', $seed);
}
}
// Take the first 8 digits for our value
$value = \substr($rnd_value, 0, 8);
// Strip the first eight, leaving the remainder for the next call to wp_rand().
$rnd_value = \substr($rnd_value, 8);
$value = \abs(\hexdec($value));
// Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
$max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295;
// 4294967295 = 0xffffffff
// Reduce the value to be within the min - max range
if ($max != 0) {
$value = $min + ($max - $min + 1) * $value / ($max_random_number + 1);
}
return \abs(\intval($value));
}
// Creates a unique instance ID
public function generate_password($length = 12, $special_chars = \true, $extra_special_chars = \false)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ($special_chars) {
$chars .= '!@#$%^&*()';
}
if ($extra_special_chars) {
$chars .= '-_ []{}<>~`+=,.;:/?|';
}
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= \substr($chars, self::rand(0, \strlen($chars) - 1), 1);
}
// random_password filter was previously in random_password function which was deprecated
return $password;
}
}
// class Ilabs_API_Password_Management
}
// if (!class_exists('Ilabs_API_Password_Management'))

View File

@@ -0,0 +1,386 @@
<?php
namespace VendorDHL;
// Exit if accessed directly
use VendorDHL\WPDesk\Notice\AjaxHandler;
use VendorDHL\WPDesk\Notice\PermanentDismissibleNotice;
if (!\defined('ABSPATH')) {
exit;
}
if (!\class_exists('VendorDHL\\WPDesk_API_Manager_With_Update_Flag')) {
class WPDesk_API_Manager_With_Update_Flag
{
const ACTIVATED = 'Activated';
/**
* Self Upgrade Values
*/
// Base URL to the remote upgrade API Manager server. If not set then the Author URI is used.
public $upgrade_url;
/**
* @var string
*/
//public $version = '4.0';
public $version;
/**
* @var string
* This version is saved after an upgrade to compare this db version to $version
*/
public $api_version_name;
/**
* Software Product ID is the product title string
* This value must be unique, and it must match the API tab for the product in WooCommerce
*/
private $software_product_id;
public $plugin_dir;
/**
* @var string
*/
private $plugin_title;
/**
* @var string
* used to defined localization for translation, but a string literal is preferred
*
* https://github.com/tommcfarlin/WordPress-Plugin-Boilerplate/issues/59
* http://markjaquith.wordpress.com/2011/10/06/translating-wordpress-plugins-and-themes-dont-get-clever/
* http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/
*/
public $text_domain = 'woocommerce-dhl';
/**
* @var string
*/
public $plugin_url;
/**
* Data defaults
* @var mixed
*/
public $data_key;
public $api_key;
public $activation_email;
public $product_id_key;
public $instance_key;
public $deactivate_checkbox_key;
public $activated_key;
public $upgrade_url_key;
public $deactivate_checkbox;
public $activation_tab_key;
public $deactivation_tab_key;
public $menu_tab_activation_title;
public $menu_tab_deactivation_title;
public $options;
public $plugin_name;
public $product_id;
public $renew_license_url;
public $instance_id;
public $domain;
public $software_version;
public $plugin_or_theme;
public $update_version;
/**
* Used to send any extra information.
* @var mixed array, object, string, etc.
*/
public $extra;
/**
*/
private $key_insance = null;
private $update_check_insance = null;
/**
* Cloning is forbidden.
*
* @since 1.2
*/
private function __clone()
{
}
/**
* Unserializing instances of this class is forbidden.
*
* @since 1.2
*/
public function __wakeup()
{
}
public function __construct($upgrade_url, $version, $name, $product_id, $plugin_file, $plugin_dir, $hook_to_updates = \true, $plugin_title = null)
{
global $wpdesk_installed_plugins;
if (!$wpdesk_installed_plugins) {
$wpdesk_installed_plugins = [];
}
$wpdesk_installed_plugins[\trailingslashit($plugin_dir) . $plugin_file] = $this;
//
$this->upgrade_url_key = "api_{$plugin_dir}_upgrade_url";
$tmp_upgrade_url = \get_option($this->upgrade_url_key, '');
if ($tmp_upgrade_url == '') {
$tmp_upgrade_url = $upgrade_url;
\update_option($this->upgrade_url_key, $tmp_upgrade_url);
}
$this->upgrade_url = $tmp_upgrade_url;
$this->version = $version;
$this->api_version_name = 'plugin_' . $name . '_version';
$this->software_product_id = $product_id;
$this->plugin_dir = $plugin_dir;
$this->plugin_title = $plugin_title;
$this->plugin_url = \plugins_url('/', $plugin_file);
if (\is_admin()) {
// Check for external connection blocking
\add_action('admin_notices', [$this, 'check_external_blocking']);
/**
* Set all data defaults here
*/
$this->data_key = 'api_' . $plugin_dir;
$this->api_key = "api_{$plugin_dir}_key";
$this->activation_email = "api_{$plugin_dir}_activation_email";
$this->product_id_key = "api_{$plugin_dir}_product_id";
$this->instance_key = "api_{$plugin_dir}_instance";
$this->deactivate_checkbox_key = "api_{$plugin_dir}_deactivate_checkbox";
$this->activated_key = "api_{$plugin_dir}_activated";
/**
* Set all admin menu data
*/
$this->deactivate_checkbox = 'am_deactivate_example_checkbox';
$this->activation_tab_key = "api_{$plugin_dir}_dashboard";
$this->deactivation_tab_key = "api_{$plugin_dir}_deactivation";
$this->menu_tab_activation_title = \__('Subscription Activation', $this->text_domain);
$this->menu_tab_deactivation_title = \__('Subscription Deactivation', $this->text_domain);
/**
* Set all software update data here
*/
$this->options = \get_option($this->data_key);
//$this->plugin_name = untrailingslashit( dirname( $plugin_file) ); // same as plugin slug. if a theme use a theme name like 'twentyeleven'
$this->plugin_name = $name;
// same as plugin slug. if a theme use a theme name like 'twentyeleven'
$this->product_id = $this->software_product_id;
//get_option( $this->product_id_key ); // Software Title
$this->renew_license_url = $this->upgrade_url . '/my-account';
// URL to renew a license. Trailing slash in the upgrade_url is required.
$this->instance_id = \get_option($this->instance_key);
// Instance ID (unique to each blog activation)
if (\get_option($this->activated_key, '0') != self::ACTIVATED) {
$this->inactive_notice();
}
/* grola */
if (!$this->instance_id) {
$this->create_instance_id();
}
/**
* Some web hosts have security policies that block the : (colon) and // (slashes) in http://,
* so only the host portion of the URL can be sent. For example the host portion might be
* www.example.com or example.com. http://www.example.com includes the scheme http,
* and the host www.example.com.
* Sending only the host also eliminates issues when a client site changes from http to https,
* but their activation still uses the original scheme.
* To send only the host, use a line like the one below:
*
* $this->domain = str_ireplace( array( 'http://', 'https://' ), '', home_url() ); // blog domain name
*/
$this->domain = \str_ireplace(['http://', 'https://'], '', \home_url());
// blog domain name
$this->software_version = $this->version;
// The software version
$this->plugin_or_theme = 'plugin';
// 'theme' or 'plugin'
// Performs activations and deactivations of API License Keys
require_once 'class-wc-key-api.php';
// Checks for software updatess
require_once 'class-wc-plugin-update.php';
// Admin menu with the license key and license email form
// require_once( 'class-wc-api-manager-menu.php' );
// new WPDesk_API_MENU( $this );
$options = \get_option($this->data_key);
/**
* Check for software updates
*/
if ($hook_to_updates) {
if (!empty($options) && $options !== \false) {
$this->update_check($this->upgrade_url, $this->plugin_name, $this->product_id, $this->options[$this->api_key], $this->options[$this->activation_email], $this->renew_license_url, $this->instance_id, $this->domain, $this->software_version, $this->plugin_or_theme, $this->text_domain);
}
$this->add_not_possible_update_message();
}
}
}
/**
* @return bool
*/
public function is_activated()
{
return \get_option($this->activated_key, '0') === self::ACTIVATED;
}
/**
* @return string
*/
public function get_myaccount_url()
{
return $this->upgrade_url . '/my-account/';
}
/**
* Adds message to plugins page when plugin is not activated with info about subscription.
*/
private function add_not_possible_update_message()
{
\add_action('in_plugin_update_message-' . $this->plugin_name, function (array $plugin_data, \stdClass $response) {
if (isset($response->changelog) && !empty($response->changelog)) {
$this->display_changelog($plugin_data['Version'], $response->changelog);
}
}, 10, 2);
}
public function create_instance_id()
{
$password_management = new \VendorDHL\WPDesk_API_Password_Management();
// Generate a unique installation $instance id
$instance = $password_management->generate_password(12, \false);
$this->instance_id = $instance;
\update_option($this->instance_key, $instance);
\update_option($this->activated_key, 'Deactivated');
$this->options = [];
$this->options[$this->api_key] = '';
$this->options[$this->activation_email] = '';
\update_option($this->data_key, $this->options);
}
/** Load Shared Classes as on-demand Instances **********************************************/
/**
* API Key Class.
*
* @return WPDesk_API_KEY
*/
public function key()
{
if ($this->key_insance == null) {
$this->key_insance = new \VendorDHL\WPDesk_API_KEY($this);
}
return $this->key_insance;
}
/**
* Update Check Class.
*
* @return WPDesk_Update_API_Check
*/
public function update_check($upgrade_url, $plugin_name, $product_id, $api_key, $activation_email, $renew_license_url, $instance, $domain, $software_version, $plugin_or_theme, $text_domain, $extra = '')
{
if ($this->update_check_insance == null) {
$this->update_check_insance = new \VendorDHL\WPDesk_Update_API_Check($this, $upgrade_url, $plugin_name, $product_id, $api_key, $activation_email, $renew_license_url, $instance, $domain, $software_version, $plugin_or_theme, $text_domain, $extra);
}
return $this->update_check_insance;
}
public function plugin_url()
{
if (isset($this->plugin_url)) {
return $this->plugin_url;
}
return $this->plugin_url = \plugins_url('/', __FILE__);
}
/**
* Generate the default data arrays
*/
public function activation()
{
$global_options = [$this->api_key => '', $this->activation_email => ''];
\update_option($this->data_key, $global_options);
require_once $this->plugin_dir . 'am/classes/class-wc-api-manager-passwords.php';
$password_management = new \VendorDHL\WPDesk_API_Password_Management();
// Generate a unique installation $instance id
$instance = $password_management->generate_password(12, \false);
$single_options = [$this->product_id_key => $this->software_product_id, $this->instance_key => $instance, $this->deactivate_checkbox_key => 'on', $this->activated_key => 'Deactivated'];
foreach ($single_options as $key => $value) {
\update_option($key, $value);
}
$curr_ver = \get_option($this->api_version_name);
// checks if the current plugin version is lower than the version being installed
if (\version_compare($this->version, $curr_ver, '>')) {
// update the version
\update_option($this->api_version_name, $this->version);
}
}
/**
* Deletes all data if plugin deactivated
* @return void
*/
public function uninstall()
{
global $blog_id;
$this->license_key_deactivation();
// Remove options
if (\is_multisite()) {
\switch_to_blog($blog_id);
foreach ([$this->data_key, $this->product_id_key, $this->instance_key, $this->deactivate_checkbox_key, $this->activated_key] as $option) {
\delete_option($option);
}
\restore_current_blog();
} else {
foreach ([$this->data_key, $this->product_id_key, $this->instance_key, $this->deactivate_checkbox_key, $this->activated_key] as $option) {
\delete_option($option);
}
}
}
/**
* Deactivates the license on the API server
* @return void
*/
public function license_key_deactivation()
{
$activation_status = \get_option($this->activated_key);
$api_email = $this->options[$this->activation_email];
$api_key = $this->options[$this->api_key];
$args = ['email' => $api_email, 'licence_key' => $api_key];
if ($activation_status == self::ACTIVATED && $api_key != '' && $api_email != '') {
$this->key()->deactivate($args);
// reset license key activation
}
}
/**
* Displays an inactive notice when the software is inactive.
*/
public function inactive_notice()
{
if (!\current_user_can('manage_options')) {
return;
}
if (\apply_filters('wpdesk_show_plugin_activation_notice', \true)) {
(new \VendorDHL\WPDesk\Notice\AjaxHandler())->hooks();
new \VendorDHL\WPDesk\Notice\PermanentDismissibleNotice(\sprintf(\__('The %1$s%2$s%3$s API Key has not been activated, so you won\'t be supported and your plugin won\'t be updated! %4$sClick here%5$s to activate the API key and the plugin.', $this->text_domain), '<strong>', $this->plugin_title, '</strong>', '<a href="' . \esc_url(\admin_url('plugins.php#' . $this->plugin_dir . '-wpdesk-license')) . '">', '</a>'), "notice-{$this->software_product_id}", \VendorDHL\WPDesk\Notice\PermanentDismissibleNotice::NOTICE_TYPE_WARNING);
}
}
/**
* Check for external blocking constants
* @return string
*/
public function check_external_blocking()
{
// show notice if external requests are blocked through the WP_HTTP_BLOCK_EXTERNAL constant
if (\defined('VendorDHL\\WP_HTTP_BLOCK_EXTERNAL') && \VendorDHL\WP_HTTP_BLOCK_EXTERNAL === \true) {
// check if our API endpoint is in the allowed hosts
$host = \parse_url($this->upgrade_url, \PHP_URL_HOST);
if (!\defined('VendorDHL\\WP_ACCESSIBLE_HOSTS') || \stristr(\VendorDHL\WP_ACCESSIBLE_HOSTS, $host) === \false) {
?>
<div class="error">
<p><?php
\printf(\__('<b>Warning!</b> You\'re blocking external requests which means you won\'t be able to get %s updates. Please add %s to %s.', $this->text_domain), $this->software_product_id, '<strong>' . $host . '</strong>', '<code>WP_ACCESSIBLE_HOSTS</code>');
?></p>
</div>
<?php
}
}
}
/**
* @param string $plugin_data
* @param string $response
*/
private function display_changelog($plugin_version, $changelog)
{
$parser = new \VendorDHL\WPDesk\License\Changelog\Parser($changelog);
$parser->parse();
$parsed_changelog = $parser->get_parsed_changelog()->getIterator();
$changes = new \VendorDHL\WPDesk\License\Changelog\Filter\ByVersion($parsed_changelog, $plugin_version);
if (\iterator_count($changes) > 0) {
$changelog = new \VendorDHL\WPDesk\License\Changelog\Formatter($changes);
$changelog->set_changelog_types($parser->get_types());
$formatted_changelog = $changelog->prepare_formatted_html();
if ($formatted_changelog) {
echo \wp_kses_post('<br /><br />' . $formatted_changelog);
}
}
}
}
// class Ilabs_API_Manager
}
// if (!class_exists('Ilabs_API_Manager')) {

View File

@@ -0,0 +1,111 @@
<?php
namespace VendorDHL;
/**
* WooCommerce API Manager API Key Class
*
* @package Update API Manager/Key Handler
* @author Todd Lahman LLC, WPDesk
* @copyright Copyright (c) Todd Lahman LLC
* @since 1.3
*
*/
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
if (!\class_exists('VendorDHL\\WPDesk_API_KEY')) {
class WPDesk_API_KEY
{
/**
* @var The single instance of the class
*/
protected static $_instance = null;
private $api_manager;
public function __construct($api_manager)
{
$this->api_manager = $api_manager;
}
// API Key URL
public function create_software_api_url($args)
{
$api_url = \add_query_arg('wc-api', 'am-software-api', $this->api_manager->upgrade_url);
return $api_url . '&' . \http_build_query($args);
}
public function activate($args)
{
$this->api_manager->create_instance_id();
$defaults = ['request' => 'activation', 'product_id' => $this->api_manager->product_id, 'instance' => $this->api_manager->instance_id, 'platform' => $this->api_manager->domain, 'software_version' => $this->api_manager->software_version];
$args = \wp_parse_args($defaults, $args);
$target_url = \esc_url_raw($this->create_software_api_url($args));
$target_url = \str_replace('&amp;', '&', $target_url);
$request = \wp_safe_remote_get($target_url, ['timeout' => 30, 'sslverify' => \false]);
if (\is_wp_error($request) || \wp_remote_retrieve_response_code($request) != 200) {
if (\class_exists('VendorDHL\\WPDesk_Logger_Factory')) {
// Request failed
if (\is_wp_error($request)) {
\VendorDHL\WPDesk_Logger_Factory::log_wp_error($request, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
} else {
\VendorDHL\WPDesk_Logger_Factory::log_message_backtrace('Response is invalid. Response: ' . \json_encode($request), \VendorDHL\WPDesk_Logger::ERROR, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
}
}
return \false;
}
$response = \wp_remote_retrieve_body($request);
return $response;
}
public function deactivate($args)
{
$defaults = ['request' => 'deactivation', 'product_id' => $this->api_manager->product_id, 'instance' => $this->api_manager->instance_id, 'platform' => $this->api_manager->domain];
$args = \wp_parse_args($defaults, $args);
$target_url = \esc_url_raw($this->create_software_api_url($args));
$target_url = \str_replace('&amp;', '&', $target_url);
$request = \wp_safe_remote_get($target_url, ['timeout' => 30, 'sslverify' => \false]);
if (\is_wp_error($request) || \wp_remote_retrieve_response_code($request) != 200) {
if (\class_exists('VendorDHL\\WPDesk_Logger_Factory')) {
if (\is_wp_error($request)) {
\VendorDHL\WPDesk_Logger_Factory::log_wp_error($request, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
} else {
\VendorDHL\WPDesk_Logger_Factory::log_message_backtrace('Response is invalid. Response: ' . \json_encode($request), \VendorDHL\WPDesk_Logger::ERROR, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
}
}
// Request failed
return \false;
}
$response = \wp_remote_retrieve_body($request);
return $response;
}
/**
* Checks if the software is activated or deactivated
*
* @param array $args
*
* @return array
*/
public function status($args)
{
$defaults = ['request' => 'status', 'product_id' => $this->api_manager->product_id, 'instance' => $this->api_manager->instance_id, 'platform' => $this->api_manager->domain];
$args = \wp_parse_args($defaults, $args);
$target_url = \esc_url_raw($this->create_software_api_url($args));
$target_url = \str_replace('&amp;', '&', $target_url);
$request = \wp_safe_remote_get($target_url, ['timeout' => 30, 'sslverify' => \false]);
// $request = wp_remote_post( $this->api_manager->upgrade_url . 'wc-api/am-software-api/', array( 'body' => $args ) );
if (\is_wp_error($request) || \wp_remote_retrieve_response_code($request) != 200) {
if (\class_exists('VendorDHL\\WPDesk_Logger_Factory')) {
if (\is_wp_error($request)) {
\VendorDHL\WPDesk_Logger_Factory::log_wp_error($request, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
} else {
\VendorDHL\WPDesk_Logger_Factory::log_message_backtrace('Response is invalid. Response: ' . \json_encode($request), \VendorDHL\WPDesk_Logger::ERROR, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
}
}
// Request failed
return \false;
}
$response = \wp_remote_retrieve_body($request);
return $response;
}
}
// class WPDesk_API_KEY
}
// if (!class_exists('WPDesk_API_KEY'))

View File

@@ -0,0 +1,462 @@
<?php
namespace VendorDHL;
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
/**
* Todd Lahman LLC Updater - Single Updater Class
*
* @package Update API Manager/Update Handler
* @author Todd Lahman LLC
* @copyright Copyright (c) Todd Lahman LLC
* @since 1.0.0
*
*/
if (!\class_exists('VendorDHL\\WPDesk_Update_API_Check')) {
class WPDesk_Update_API_Check
{
/**
* @var The single instance of the class
*/
protected static $_instance = null;
private $api_manager;
/**
*
* Ensures only one instance is loaded or can be loaded.
*
* @static
* @return class instance
*/
public static function instance($upgrade_url, $plugin_name, $product_id, $api_key, $activation_email, $renew_license_url, $instance, $domain, $software_version, $plugin_or_theme, $text_domain, $extra = '')
{
if (\is_null(self::$_instance)) {
self::$_instance = new self($upgrade_url, $plugin_name, $product_id, $api_key, $activation_email, $renew_license_url, $instance, $domain, $software_version, $plugin_or_theme, $text_domain, $extra);
}
return self::$_instance;
}
private $upgrade_url;
// URL to access the Update API Manager.
private $plugin_name;
private $plugin_file;
private $product_id;
// Software Title
private $api_key;
// API License Key
private $activation_email;
// License Email
private $renew_license_url;
// URL to renew a license
private $instance;
// Instance ID (unique to each blog activation)
private $domain;
// blog domain name
private $software_version;
private $plugin_or_theme;
// 'theme' or 'plugin'
private $text_domain;
// localization for translation
private $extra;
// Used to send any extra information.
/**
* Constructor.
*
* @access public
* @since 1.0.0
* @return void
*/
public function __construct($api_manager, $upgrade_url, $plugin_name, $product_id, $api_key, $activation_email, $renew_license_url, $instance, $domain, $software_version, $plugin_or_theme, $text_domain, $extra, $free = \false)
{
$this->api_manager = $api_manager;
// API data
$this->upgrade_url = $upgrade_url;
$this->plugin_name = $plugin_name;
$this->product_id = $product_id;
$this->api_key = $api_key;
$this->activation_email = $activation_email;
$this->renew_license_url = $renew_license_url;
$this->instance = $instance;
$this->domain = $domain;
$this->software_version = $software_version;
$this->text_domain = $text_domain;
$this->extra = $extra;
$this->free = $free;
// Slug should be the same as the plugin/theme directory name
if (\strpos($this->plugin_name, '.php') !== 0) {
$this->slug = \dirname($this->plugin_name);
} else {
$this->slug = $this->plugin_name;
}
/**
* Flag for plugin or theme updates
* @access public
* @since 1.0.0
*
* @param string, plugin or theme
*/
$this->plugin_or_theme = $plugin_or_theme;
// 'theme' or 'plugin'
/*********************************************************************
* The plugin and theme filters should not be active at the same time
*********************************************************************/
/**
* More info:
* function set_site_transient moved from wp-includes/functions.php
* to wp-includes/option.php in WordPress 3.4
*
* set_site_transient() contains the pre_set_site_transient_{$transient} filter
* {$transient} is either update_plugins or update_themes
*
* Transient data for plugins and themes exist in the Options table:
* _site_transient_update_themes
* _site_transient_update_plugins
*/
// uses the flag above to determine if this is a plugin or a theme update request
if ($this->plugin_or_theme == 'plugin') {
/**
* Plugin Updates
*/
// Check For Plugin Updates
\add_filter('pre_set_site_transient_update_plugins', [$this, 'update_check']);
// Check For Plugin Information to display on the update details page
\add_filter('plugins_api', [$this, 'request'], 10, 3);
} elseif ($this->plugin_or_theme == 'theme') {
/**
* Theme Updates
*/
// Check For Theme Updates
\add_filter('pre_set_site_transient_update_themes', [$this, 'update_check']);
// Check For Theme Information to display on the update details page
\add_filter('themes_api', [$this, 'request'], 10, 3);
}
}
// Upgrade API URL
private function create_upgrade_api_url($args)
{
if ($this->free) {
$upgrade_url = \add_query_arg('wc-api', 'wpdesk-upgrade-api', $this->upgrade_url);
} else {
$upgrade_url = \add_query_arg('wc-api', 'upgrade-api', $this->upgrade_url);
}
return $upgrade_url . '&' . \http_build_query($args);
}
/**
* Check for updates against the remote server.
*
* @access public
* @since 1.0.0
*
* @param object $transient
*
* @return object $transient
*/
public function update_check($transient)
{
if (!\is_object($transient)) {
$transient = new \stdClass();
}
if (!isset($transient->response) || !\is_array($transient->response)) {
$transient->response = [];
}
$args = ['request' => 'pluginupdatecheck', 'slug' => $this->slug, 'plugin_name' => $this->plugin_name, 'version' => $this->software_version, 'product_id' => $this->product_id, 'api_key' => $this->api_key, 'activation_email' => $this->activation_email, 'instance' => $this->instance, 'domain' => $this->domain, 'software_version' => $this->software_version, 'extra' => $this->extra];
// Check for a plugin update
$response = $this->plugin_information($args);
// Displays an admin error message in the WordPress dashboard
$this->check_response_for_errors($response);
// Set version variables
if (isset($response) && \is_object($response) && $response !== \false) {
// New plugin version from the API
$new_ver = (string) $response->new_version;
// Current installed plugin version
$curr_ver = (string) $this->software_version;
//$curr_ver = (string)$transient->checked[$this->plugin_name];
}
// If there is a new version, modify the transient to reflect an update is available
if (isset($new_ver) && isset($curr_ver)) {
if ($response !== \false && \version_compare($new_ver, $curr_ver, '>')) {
if ($this->plugin_or_theme == 'plugin') {
$transient->response[$this->plugin_name] = $response;
} elseif ($this->plugin_or_theme == 'theme') {
$transient->response[$this->plugin_name]['new_version'] = $response->new_version;
$transient->response[$this->plugin_name]['url'] = $response->url;
$transient->response[$this->plugin_name]['package'] = $response->package;
}
}
}
return $transient;
}
/**
* Sends and receives data to and from the server API
*
* @access public
* @since 1.0.0
* @return object|bool $response
*/
public function plugin_information($args)
{
$target_url = \esc_url_raw($this->create_upgrade_api_url($args));
$target_url = \str_replace('&amp;', '&', $target_url);
$request = \wp_safe_remote_get($target_url, ['timeout' => 30, 'sslverify' => \false]);
if (\is_wp_error($request) || \wp_remote_retrieve_response_code($request) != 200) {
if (\class_exists('VendorDHL\\WPDesk_Logger_Factory')) {
if (\is_wp_error($request)) {
\VendorDHL\WPDesk_Logger_Factory::log_wp_error($request, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
} else {
\VendorDHL\WPDesk_Logger_Factory::log_message_backtrace('Response is invalid. Response: ' . \json_encode($request), \VendorDHL\WPDesk_Logger::ERROR, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
}
}
return \false;
}
$raw_response = \wp_remote_retrieve_body($request);
$response = @\unserialize($raw_response);
if (\is_object($response)) {
if (isset($response->sections)) {
$response->sections['description'] = \apply_filters('the_content', isset($response->sections['description_base64']) ? \base64_decode($response->sections['description_base64']) : '');
if (isset($response->sections['installation'])) {
$response->sections['installation'] = \apply_filters('the_content', $response->sections['installation']);
}
if (isset($response->sections['faq'])) {
$response->sections['faq'] = \apply_filters('the_content', $response->sections['faq']);
}
if (isset($response->sections['screenshots'])) {
$response->sections['screenshots'] = \apply_filters('the_content', $response->sections['screenshots']);
}
if (isset($response->sections['changelog'])) {
$response->sections['changelog'] = \apply_filters('the_content', $response->sections['changelog']);
}
if (isset($response->sections['other_notes'])) {
$response->sections['other_notes'] = \apply_filters('the_content', $response->sections['other_notes']);
}
}
if (isset($response->author)) {
$response->author = "<a href='http://www.wpdesk.pl'>{$response->author}</a>";
}
unset($response->sections['description_base64']);
return $response;
} else {
if (\class_exists('VendorDHL\\WPDesk_Logger_Factory')) {
\VendorDHL\WPDesk_Logger_Factory::log_message_backtrace('Response is not an object', \VendorDHL\WPDesk_Logger::DEBUG, \debug_backtrace(\DEBUG_BACKTRACE_PROVIDE_OBJECT | \DEBUG_BACKTRACE_IGNORE_ARGS));
} else {
\error_log("Unserialize error. Please send this report to support@wpdesk.net. Request: {$request}. Raw Response: {$raw_response}");
}
return \false;
}
}
/**
* Generic request helper.
*
* @access public
* @since 1.0.0
*
* @param array $args
*
* @return object $response or boolean false
*/
public function request($false, $action, $args)
{
// Is this a plugin or a theme?
if ($this->plugin_or_theme == 'plugin') {
$version = \get_site_transient('update_plugins');
} elseif ($this->plugin_or_theme == 'theme') {
$version = \get_site_transient('update_themes');
}
// Check if this plugins API is about this plugin
if (isset($args->slug)) {
//if ( $args->slug != dirname($this->slug)) {
if ($args->slug != $this->slug) {
return $false;
}
} else {
return $false;
}
$args = ['request' => 'plugininformation', 'plugin_name' => $this->plugin_name, 'slug' => $this->slug, 'version' => $this->software_version, 'product_id' => $this->product_id, 'api_key' => $this->api_key, 'activation_email' => $this->activation_email, 'instance' => $this->instance, 'domain' => $this->domain, 'software_version' => $this->software_version, 'extra' => $this->extra];
$response = $this->plugin_information($args);
if ($response) {
$response->slug = $this->slug;
$response->product_id = $this->product_id;
// If everything is okay return the $response
if (isset($response) && \is_object($response) && $response !== \false) {
return $response;
}
} else {
return \false;
}
}
/**
* Displays an admin error message in the WordPress dashboard
*
* @param array $response
*
* @return string
*/
public function check_response_for_errors($response)
{
if (!empty($response)) {
if (isset($response->errors['no_key']) && $response->errors['no_key'] == 'no_key' && isset($response->errors['no_subscription']) && $response->errors['no_subscription'] == 'no_subscription') {
\add_action('admin_notices', [$this, 'no_key_error_notice']);
\add_action('admin_notices', [$this, 'no_subscription_error_notice']);
} elseif (isset($response->errors['exp_license']) && $response->errors['exp_license'] == 'exp_license') {
\add_action('admin_notices', [$this, 'expired_license_error_notice']);
} elseif (isset($response->errors['hold_subscription']) && $response->errors['hold_subscription'] == 'hold_subscription') {
\add_action('admin_notices', [$this, 'on_hold_subscription_error_notice']);
} elseif (isset($response->errors['cancelled_subscription']) && $response->errors['cancelled_subscription'] == 'cancelled_subscription') {
\add_action('admin_notices', [$this, 'cancelled_subscription_error_notice']);
} elseif (isset($response->errors['exp_subscription']) && $response->errors['exp_subscription'] == 'exp_subscription') {
\add_action('admin_notices', [$this, 'expired_subscription_error_notice']);
} elseif (isset($response->errors['suspended_subscription']) && $response->errors['suspended_subscription'] == 'suspended_subscription') {
\add_action('admin_notices', [$this, 'suspended_subscription_error_notice']);
} elseif (isset($response->errors['pending_subscription']) && $response->errors['pending_subscription'] == 'pending_subscription') {
\add_action('admin_notices', [$this, 'pending_subscription_error_notice']);
} elseif (isset($response->errors['trash_subscription']) && $response->errors['trash_subscription'] == 'trash_subscription') {
\add_action('admin_notices', [$this, 'trash_subscription_error_notice']);
} elseif (isset($response->errors['no_subscription']) && $response->errors['no_subscription'] == 'no_subscription') {
\add_action('admin_notices', [$this, 'no_subscription_error_notice']);
} elseif (isset($response->errors['no_activation']) && $response->errors['no_activation'] == 'no_activation') {
\add_action('admin_notices', [$this, 'no_activation_error_notice']);
} elseif (isset($response->errors['no_key']) && $response->errors['no_key'] == 'no_key') {
\add_action('admin_notices', [$this, 'no_key_error_notice']);
} elseif (isset($response->errors['download_revoked']) && $response->errors['download_revoked'] == 'download_revoked') {
\add_action('admin_notices', [$this, 'download_revoked_error_notice']);
} elseif (isset($response->errors['switched_subscription']) && $response->errors['switched_subscription'] == 'switched_subscription') {
\add_action('admin_notices', [$this, 'switched_subscription_error_notice']);
}
}
}
/**
* Display license expired error notice
*
* @param string $message
*
* @return void
*/
public function expired_license_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The API key for %s has expired. You can reactivate or purchase a API key from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription on-hold error notice
*
* @param string $message
*
* @return void
*/
public function on_hold_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s is on-hold. You can reactivate the subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription cancelled error notice
*
* @param string $message
*
* @return void
*/
public function cancelled_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s has been cancelled. You can renew the subscription from your account <a href="%s" target="_blank">dashboard</a>. A new API key will be emailed to you after your order has been completed.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription expired error notice
*
* @param string $message
*
* @return void
*/
public function expired_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s has expired. You can reactivate the subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription expired error notice
*
* @param string $message
*
* @return void
*/
public function suspended_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s has been suspended. You can reactivate the subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription expired error notice
*
* @param string $message
*
* @return void
*/
public function pending_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s is still pending. You can check on the status of the subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription expired error notice
*
* @param string $message
*
* @return void
*/
public function trash_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('The subscription for %s has been placed in the trash and will be deleted soon. You can purchase a new subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display subscription expired error notice
*
* @param string $message
*
* @return void
*/
public function no_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('A subscription for %s could not be found. You can purchase a subscription from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display missing key error notice
*
* @param string $message
*
* @return void
*/
public function no_key_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('A API key for %s could not be found. Maybe you forgot to enter a API key when setting up %s, or the key was deactivated in your account. You can reactivate or purchase a subscription key from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->product_id, $this->renew_license_url));
}
/**
* Display missing download permission revoked error notice
*
* @param string $message
*
* @return void
*/
public function download_revoked_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('Download permission for %s has been revoked possibly due to a API key or subscription expiring. You can reactivate or purchase a API key from your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
/**
* Display no activation error notice
*
* @param string $message
*
* @return void
*/
public function no_activation_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('%s has not been activated. Go to the settings page and enter the API key and subscription email to activate %s.', $this->text_domain) . '</p></div>', $this->product_id, $this->product_id));
}
/**
* Display switched activation error notice
*
* @param string $message
*
* @return void
*/
public function switched_subscription_error_notice($message)
{
echo \wp_kses_post(\sprintf('<div id="message" class="error"><p>' . \__('You changed the subscription for %s, so you will need to enter your new API Key in the settings page. The API Key should have arrived in your email inbox, if not you can get it by logging into your account <a href="%s" target="_blank">dashboard</a>.', $this->text_domain) . '</p></div>', $this->product_id, $this->renew_license_url));
}
}
// class WPDesk_Update_API_Check
}
// if (!class_exists('WPDesk_Update_API_Check')) {

View File

@@ -0,0 +1,34 @@
<?php
namespace VendorDHL\WPDesk\License\Changelog\Filter;
use FilterIterator;
use Iterator;
/**
* Filters items by version.
*
* @package WPDesk\License\Changelog
*/
class ByVersion extends \FilterIterator
{
/**
* @var string
*/
private $version;
/**
* Updates constructor.
*
* @param Iterator $changes
* @param string $version
*/
public function __construct(\Iterator $changes, string $version)
{
parent::__construct($changes);
$this->version = $version;
}
public function accept() : bool
{
$change = $this->getInnerIterator()->current();
return (bool) \version_compare($change['version'], $this->version, '>');
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace VendorDHL\WPDesk\License\Changelog;
use Iterator;
/**
* Can format changelog.
*
* @package WPDesk\License\Changelog
*/
class Formatter
{
/**
* @var Iterator
*/
private $changes;
/**
* @var array
*/
private $types;
/**
* Formatter constructor.
*
* @param Iterator $changes
*/
public function __construct(\Iterator $changes)
{
$this->changes = $changes;
}
/**
* @param array $types
*/
public function set_changelog_types(array $types)
{
$this->types = $types;
}
/**
* @return string
*/
public function prepare_formatted_html()
{
$output = '';
foreach ($this->get_changes_data() as $name => $changes) {
if (empty($changes)) {
continue;
}
$output .= \sprintf("\n\n<strong>%s</strong>: <br/>* %s", $name, \implode(' <br />* ', \array_map('esc_html', $changes)));
}
return \wp_kses_post(\nl2br(\trim($output)));
}
/**
* @return array
*/
private function get_changes_data()
{
$changes = [];
foreach ($this->types as $type) {
$changes[$type] = [];
}
foreach ($this->changes as $item) {
foreach ($item['changes'] as $type => $change) {
if (!isset($changes[$type])) {
$changes[$type] = [];
}
$changes[$type] = \array_merge($changes[$type], $change);
}
}
return \array_filter($changes);
}
}

View File

@@ -0,0 +1,93 @@
<?php
namespace VendorDHL\WPDesk\License\Changelog;
use ArrayObject;
use VendorDHL\WPDesk\License\Changelog\Parser\Line;
/**
* Can parse changelog.
*
* @package FSVendor\WPDesk\License\Changelog
*/
class Parser
{
/**
* @var string
*/
private $changelog;
/**
* @var string
*/
private $changelog_parsed_data;
/**
* @var array
*/
private $types = [];
/**
* Parser constructor.
*
* @param string $changelog
*/
public function __construct(string $changelog)
{
$this->changelog = $changelog;
}
/**
* @return ArrayObject
*/
public function get_parsed_changelog()
{
return new \ArrayObject($this->changelog_parsed_data);
}
/**
* @return Parser $this
*/
public function parse()
{
$this->changelog_parsed_data = [];
$version = $type = null;
foreach ($this->get_lines() as $line) {
if (!$this->types && ($types = $line->get_types())) {
$this->types = $types;
continue;
}
if ($release = $line->get_release_details()) {
$version = $release['version'];
$type = null;
continue;
}
if ($type_details = $line->get_type_details()) {
$type = $type_details;
continue;
}
if (!$version || !$type) {
continue;
}
if (!isset($this->changelog_parsed_data[$version])) {
$this->changelog_parsed_data[$version] = ['version' => $version, 'changes' => []];
}
$this->changelog_parsed_data[$version]['changes'][$type][] = $line->get_value();
}
return $this;
}
/**
* @return array
*/
public function get_types()
{
return $this->types;
}
/**
* @return Line[]
*/
private function get_lines()
{
$content = \base64_decode($this->changelog);
if (!$content) {
return [];
}
return \array_map(function ($line) {
return new \VendorDHL\WPDesk\License\Changelog\Parser\Line($line);
}, \array_filter(\preg_split("/\r\n|\n|\r/", \wp_kses_post($content))));
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace VendorDHL\WPDesk\License\Changelog\Parser;
/**
* Can parse single changelog line.
*
* @package WPDesk\License\Changelog\Parser
*/
class Line
{
/**
* @var string
*/
private $line;
/**
* Line constructor.
*
* @param string $line
*/
public function __construct(string $line)
{
$this->line = $line;
}
/**
* @return array
*/
public function get_release_details()
{
\preg_match('/## \\[(.*)\\] - (.*)/', $this->line, $output_array);
if (!isset($output_array[1], $output_array[2])) {
return [];
}
return ['version' => $output_array[1], 'date' => $output_array[2]];
}
/**
* @return string
*/
public function get_type_details()
{
\preg_match('/### (.*)/', $this->line, $output_array);
if (!isset($output_array[1])) {
return '';
}
return $output_array[1];
}
/**
* @return array
*/
public function get_types()
{
\preg_match('/##### (.*)/', $this->line, $output_array);
if (!isset($output_array[1])) {
return [];
}
return \wp_parse_list($output_array[1]);
}
/**
* @return string
*/
public function get_value()
{
return \ltrim($this->line, '- ');
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace VendorDHL\WPDesk\License;
use VendorDHL\WPDesk_API_Manager_With_Update_Flag;
/**
* Provides info about activation/update state and can refresh that state
*
* @depreacted Check LicenseServer namespace
*
* @package WPDesk\License
*/
class InstalledPlugins
{
const KEY_API_MANAGER = 'api_manager';
const KEY_ACTIVATION_STATUS = 'activation_status';
/**
* Refresh WP info about updates.
*
* @return void
*/
public function refresh_plugin_update_info()
{
$this->get_plugins_activation_info(\true);
}
/**
* Returns info about activation/update state of plugins.
*
* @param bool $hook_to_updates If updates api should be called. If not sure then no!
*
* @return array Info about plugins.
* Key is plugin name and values are plugin_info + KEY_API_MANAGER + KEY_ACTIVATION_STATUS
*/
public function get_plugins_activation_info($hook_to_updates = \false)
{
global $wpdesk_helper_plugins;
if (!isset($wpdesk_helper_plugins)) {
$wpdesk_helper_plugins = [];
}
$plugins = [];
foreach ($wpdesk_helper_plugins as $key => $wpdesk_helper_plugin) {
$config_uri = null;
if (isset($wpdesk_helper_plugin['config_uri'])) {
$config_uri = $wpdesk_helper_plugin['config_uri'];
}
$menu_title = $wpdesk_helper_plugin['product_id'];
if (isset($wpdesk_helper_plugin['title'])) {
$menu_title = $wpdesk_helper_plugin['title'];
}
$addressRepository = new \VendorDHL\WPDesk\License\ServerAddressRepository($wpdesk_helper_plugin['product_id']);
$plugins[$key] = $wpdesk_helper_plugin;
$plugins[$key][self::KEY_API_MANAGER] = new \VendorDHL\WPDesk_API_Manager_With_Update_Flag($upgrade_url = $addressRepository->get_default_update_url(), $version = $wpdesk_helper_plugin['version'], $name = $wpdesk_helper_plugin['plugin'], $product_id = $wpdesk_helper_plugin['product_id'], $menu_title, $title = $menu_title, $plugin_file = \basename($wpdesk_helper_plugin['plugin']), $plugin_dir = \dirname($wpdesk_helper_plugin['plugin']), $config_uri, $hook_to_updates);
$plugins[$key][self::KEY_ACTIVATION_STATUS] = \get_option($plugins[$key][self::KEY_API_MANAGER]->activated_key, 'Deactivated');
}
return $plugins;
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace VendorDHL\WPDesk\License;
use VendorDHL\WPDesk\License\ActivationForm\AjaxHandler;
use VendorDHL\WPDesk\License\ActivationForm\PluginsPageRenderer;
use VendorDHL\WPDesk\License\WpUpgrader\SubscriptionHandler;
use VendorDHL\WPDesk\PluginBuilder\Plugin\HookableCollection;
use VendorDHL\WPDesk\PluginBuilder\Plugin\HookableParent;
use VendorDHL\WPDesk_API_Manager_With_Update_Flag;
use VendorDHL\WPDesk_Plugin_Info;
/**
* @depreacted Check LicenseServer namespace
*/
class LicenseManager implements \VendorDHL\WPDesk\PluginBuilder\Plugin\HookableCollection
{
use HookableParent;
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @var PluginsPageRenderer
*/
private $plugins_page_renderer;
/**
* @var AjaxHandler
*/
private $ajax_handler;
/**
* @param WPDesk_Plugin_Info $plugin_info
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
$this->plugin_info = $plugin_info;
}
/**
* @param bool $hooks_to_updates
*
* @return WPDesk_API_Manager_With_Update_Flag
*/
public function create_api_manager(bool $hook_to_updates = \true) : \VendorDHL\WPDesk_API_Manager_With_Update_Flag
{
$address_repository = new \VendorDHL\WPDesk\License\ServerAddressRepository($this->plugin_info->get_product_id());
return new \VendorDHL\WPDesk_API_Manager_With_Update_Flag($address_repository->get_default_update_url(), $this->plugin_info->get_version(), $this->plugin_info->get_plugin_file_name(), $this->plugin_info->get_product_id(), $this->plugin_info->get_plugin_file_name(), $this->plugin_info->get_plugin_slug(), $hook_to_updates, $this->plugin_info->get_plugin_name());
}
/**
*
*/
public function init_activation_form()
{
$this->plugins_page_renderer = new \VendorDHL\WPDesk\License\ActivationForm\PluginsPageRenderer($this->plugin_info);
$this->add_hookable($this->plugins_page_renderer);
$this->ajax_handler = new \VendorDHL\WPDesk\License\ActivationForm\AjaxHandler($this->plugin_info);
$this->add_hookable($this->ajax_handler);
}
/**
* .
*/
public function init_wp_upgrader(bool $activated, $subscriptions_url)
{
$this->add_hookable(new \VendorDHL\WPDesk\License\WpUpgrader\SubscriptionHandler($this->plugin_info->get_plugin_file_name(), $activated, $subscriptions_url));
}
/**
* .
*/
public function hooks()
{
$this->hooks_on_hookable_objects();
}
/**
* @return PluginsPageRenderer
*/
public function get_plugins_page_renderer() : \VendorDHL\WPDesk\License\ActivationForm\PluginsPageRenderer
{
return $this->plugins_page_renderer;
}
/**
* @return AjaxHandler
*/
public function get_ajax_handler() : \VendorDHL\WPDesk\License\ActivationForm\AjaxHandler
{
return $this->ajax_handler;
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace VendorDHL\WPDesk\License\LicenseServer;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Idea is to have a class that will be responsible for checking if external requests are blocked.
* Can show a notice if external requests are blocked.
*
* @package WPDesk\License\LicenseServer
*/
class PluginExternalBlocking
{
/** @var \WPDesk_Plugin_Info */
private $plugin_info;
public function __construct($plugin_info, string $server, string $token)
{
$this->plugin_info = $plugin_info;
}
/**
* Check for external blocking constants
*/
public function display_info_when_external_blocking()
{
// show notice if external requests are blocked through the WP_HTTP_BLOCK_EXTERNAL constant
if (\defined('VendorDHL\\WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL === \true) {
// check if our API endpoint is in the allowed hosts
$host = \parse_url($this->server, \PHP_URL_HOST);
if (!\defined('VendorDHL\\WP_ACCESSIBLE_HOSTS') || \stristr(WP_ACCESSIBLE_HOSTS, $host) === \false) {
?>
<div class="error">
<p><?php
\printf(\__('<b>Warning!</b> You\'re blocking external requests which means you won\'t be able to get %s updates. Please add %s to %s.', 'woocommerce-dhl'), $this->plugin_info->get_plugin_name(), '<strong>' . $host . '</strong>', '<code>WP_ACCESSIBLE_HOSTS</code>');
?></p>
</div>
<?php
}
}
}
public function hooks()
{
\add_action('admin_notices', [$this, 'display_info_when_external_blocking']);
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace VendorDHL\WPDesk\License\LicenseServer;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Provides plugin license information and gives a change to modify it.
*/
class PluginLicense
{
const ACTIVATED_VALUE = 'Activated';
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @param WPDesk_Plugin_Info $info
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $info)
{
$this->plugin_info = $info;
}
public function is_active() : bool
{
return \get_option($this->prepare_option_is_active()) === self::ACTIVATED_VALUE;
}
public function set_active()
{
\update_option($this->prepare_option_is_active(), self::ACTIVATED_VALUE);
}
public function set_inactive()
{
\update_option($this->prepare_option_is_active(), 'Inactive');
}
private function prepare_option_is_active() : string
{
return $this->prepare_option_name('activated');
}
private function prepare_option_name(string $field) : string
{
return \sprintf('api_%1$s_%2$s', \basename($this->plugin_info->get_plugin_slug()), $field);
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace VendorDHL\WPDesk\License\LicenseServer;
use VendorDHL\WPDesk\License\PluginRegistratorInterface;
use VendorDHL\WPDesk_Plugin_Info;
/**
* New server license manager.
* Fields in this class can be replaced during build process and/or package preparation on the license server.
*
* @package WPDesk\License\LicenseServer
*/
class PluginRegistrator implements \VendorDHL\WPDesk\License\PluginRegistratorInterface
{
/** @var WPDesk_Plugin_Info */
private $plugin_info;
/**
* Field CAN be replaced during build process.
*
* @var string License server URL.
*/
private $server = 'https://license.wpdesk.dev';
/**
* Token WILL BE REPLACED during package preparation on the license server.
*
* @var string User token.
*/
private $token = 'be7ff4b9-f113-4ac9-8eca-7a7f4dafe840';
/**
* This field WILL BE REPLACED during package preparation on the license server.
* Thanks to this field we know whether a plugin has been downloaded from license server.
*
* @var bool Should use license server.
*/
private static $should_use_license_server = true;
public static function should_use_license_server() : bool
{
return self::$should_use_license_server;
}
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
$this->plugin_info = $plugin_info;
}
public function is_active() : bool
{
return (new \VendorDHL\WPDesk\License\LicenseServer\PluginLicense($this->plugin_info))->is_active();
}
public function initialize_license_manager()
{
(new \VendorDHL\WPDesk\License\LicenseServer\PluginUpgrade($this->plugin_info, $this->server, $this->token))->hooks();
(new \VendorDHL\WPDesk\License\LicenseServer\PluginExternalBlocking($this->plugin_info, $this->server, $this->token))->hooks();
(new \VendorDHL\WPDesk\License\LicenseServer\PluginViewVersionInfo($this->plugin_info, $this->server))->hooks();
}
}

View File

@@ -0,0 +1,175 @@
<?php
namespace VendorDHL\WPDesk\License\LicenseServer;
/**
* Retrieves updates from license server.
*
* @package WPDesk\License\LicenseServer
*/
class PluginUpgrade
{
private $server;
private $token;
/** @var \WPDesk_Plugin_Info */
private $plugin_info;
public function __construct($plugin_info, string $server, string $token)
{
$this->server = $server;
$this->token = $token;
$this->plugin_info = $plugin_info;
}
/**
* @param string|array|\WP_Error|\stdClass $value Any response from remote server or request routine.
*
* @return mixed|\stdClass
* @internal
*/
public function inject_info_about_plugin_update_from_remote($value)
{
// on info about upgrade
if ($value instanceof \stdClass) {
// every each time only timestamp mutex is saved and when it's not the stdClass is here
$plugin_filename = $this->plugin_info->get_plugin_file_name();
if (isset($value->response[$plugin_filename])) {
// pre_set_site_transient is used two times and we need only once
return $value;
}
$remote_response = $this->request_remote_plugin_info_plugin_update_check();
if ($remote_response instanceof \WP_Error) {
// WP Error while connecting to remote server
$value->response[$plugin_filename] = $this->react_to_wp_error_response($remote_response);
} else {
// there is a response
$parsed_response = \json_decode($remote_response['body'], \true);
if (!empty($parsed_response) && $parsed_response['code'] >= 200) {
// response makes sense and had been parsed
if ($parsed_response['code'] !== 503) {
$value->response[$plugin_filename] = $this->react_to_valid_remote_response($parsed_response);
}
if (empty($value->response[$plugin_filename]->message) && empty($value->response[$plugin_filename]->need_update)) {
unset($value->response[$plugin_filename]);
}
} else {
// there is a response, but it makes no sense and cannot be parsed
$value->response[$plugin_filename] = $this->react_to_nonsense_response($remote_response);
}
}
}
return $value;
}
/**
* @return array|\WP_Error The same typ of response as wp_remote_request
*/
private function request_remote_plugin_info_plugin_update_check()
{
global $wp_version;
$params = ["site_url" => \get_site_url(), "plugin_name" => $this->plugin_info->get_plugin_name(), "plugin_slug" => $this->plugin_info->get_plugin_slug(), "plugin_version" => $this->plugin_info->get_version(), "php_version" => \PHP_VERSION, "wc_version" => \class_exists('WooCommerce') ? \WooCommerce::instance()->version : '', "wp_version" => $wp_version, 'locale' => \str_replace('-', '_', \get_bloginfo('language'))];
$product_id = \urlencode($this->plugin_info->get_product_id());
return \wp_remote_request("{$this->server}/api/v1/cid/{$this->token}/plugin/{$product_id}", ['body' => \json_encode($params), 'method' => 'POST']);
}
/**
* React when there an error while retrieving data from remote server.
*
* @param \WP_Error $remote_response
*
* @return \stdClass
*/
private function react_to_wp_error_response(\WP_Error $remote_response) : \stdClass
{
$response = $this->prepare_transient_base();
$response->message = \wp_kses_post('<span style="color: red" class="error">' . \sprintf(\__('Error while connecting to remote server %s. Please contact your hosting provider or try again later. Errors: ', 'woocommerce-dhl'), $this->server) . \implode(', ', $remote_response->get_error_messages()) . '</span>');
return $response;
}
/**
* Prepares response object to store in WP transient to avoid code duplication.
*
* @return \stdClass
*/
private function prepare_transient_base() : \stdClass
{
$response = new \stdClass();
$response->id = $this->plugin_info->get_plugin_slug();
$response->slug = $this->plugin_info->get_plugin_slug();
$response->plugin = $this->plugin_info->get_plugin_file_name();
return $response;
}
/**
* We have a valid response from server so we can react to it: show upgrade possibility or not.
*
* @param array $parsed_response
*
* @return \stdClass
*/
private function react_to_valid_remote_response(array $parsed_response) : \stdClass
{
$response = $this->prepare_transient_base();
// Just setting these two fields below is enough to show upgrade possibility
$response->new_version = $parsed_response['version'] ?? null;
$response->package = $parsed_response['package'] ?? null;
$response->requires_php = $parsed_response['requires_php'] ?? null;
$response->need_update = $parsed_response['need_update'] ?? null;
$response->changelog = $parsed_response['changelog'] ?? null;
$response->message = $parsed_response['message'] ?? null;
// Set license status
if (empty($parsed_response['package'])) {
(new \VendorDHL\WPDesk\License\LicenseServer\PluginLicense($this->plugin_info))->set_inactive();
} else {
(new \VendorDHL\WPDesk\License\LicenseServer\PluginLicense($this->plugin_info))->set_active();
}
return $response;
}
private function render_changelog(string $plugin_version, string $changelog) : string
{
$parser = new \VendorDHL\WPDesk\License\Changelog\Parser($changelog);
$parser->parse();
$parsed_changelog = $parser->get_parsed_changelog()->getIterator();
$changes = new \VendorDHL\WPDesk\License\Changelog\Filter\ByVersion($parsed_changelog, $plugin_version);
if (\iterator_count($changes) > 0) {
$changelogFormatter = new \VendorDHL\WPDesk\License\Changelog\Formatter($changes);
$changelogFormatter->set_changelog_types($parser->get_types());
$formatted_changelog = $changelogFormatter->prepare_formatted_html();
if ($formatted_changelog) {
return \wp_kses_post('<br /><br />' . $formatted_changelog);
}
}
return '';
}
/**
* It was not possible to parse a response. Show some error message.
*
* @param $remote_response
*
* @return \stdClass
*/
private function react_to_nonsense_response($remote_response) : \stdClass
{
$response = $this->prepare_transient_base();
\error_log("Update for {$this->plugin_info->get_plugin_name()} cannot be retrieved. Remote response invalid: " . \json_encode($remote_response));
if (isset($remote_response['response']['code'])) {
$message = \sprintf(\__('Error while connecting to remote server %s. Please contact with your hosting provider. Cannot parse response. Response code: %s Message: %s', 'woocommerce-dhl'), $this->server, $remote_response['response']['code'], $remote_response['body']);
} else {
$message = \sprintf(\__('Error while connecting to remote server %s. Please contact with your hosting provider. Cannot parse response: %s', 'woocommerce-dhl'), $this->server, \json_encode($remote_response));
}
$response->message = \wp_kses_post("<span style='color: red' class='upgrade-error'>{$message}</span>");
return $response;
}
public function show_messages_from_transients(array $plugin_data, \stdClass $response)
{
$transient = \get_site_transient('update_plugins');
$message = $transient->response[$this->plugin_info->get_plugin_file_name()]->message ?? '';
$changelog = $transient->response[$this->plugin_info->get_plugin_file_name()]->changelog ?? '';
// Server could have sent as some message to show. Show it.
if (!empty($message)) {
echo \wp_kses_post('<br><br>' . $message);
}
if (!empty($changelog)) {
echo $this->render_changelog($plugin_data['Version'], $changelog);
}
}
public function hooks()
{
\add_filter('pre_set_site_transient_update_plugins', [$this, 'inject_info_about_plugin_update_from_remote'], 10);
\add_filter('in_plugin_update_message-' . $this->plugin_info->get_plugin_file_name(), [$this, 'show_messages_from_transients'], 10, 2);
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace VendorDHL\WPDesk\License\LicenseServer;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Attaches to WordPress hooks to display plugin version info.
*
* @package WPDesk\License\LicenseServer
*/
class PluginViewVersionInfo
{
private $server;
/** @var \WPDesk_Plugin_Info */
private $plugin_info;
public function __construct($plugin_info, string $server)
{
$this->plugin_info = $plugin_info;
$this->server = $server;
}
public function hooks()
{
\add_filter('plugins_api', function ($false, $action, $args) {
if ($action === 'plugin_information' && $args->slug === $this->plugin_info->get_plugin_slug()) {
$remote_response = \wp_remote_get("{$this->server}/api/v1/plugin/{$this->plugin_info->get_product_id()}");
if ($remote_response instanceof \WP_Error) {
\error_log("Error while trying to get plugin info: " . \json_encode($remote_response));
return $false;
}
$parsed_response = \json_decode($remote_response['body'], \true);
if ($parsed_response) {
$response = new \stdClass();
$response->name = $this->plugin_info->get_plugin_name();
$response->slug = $parsed_response['slug'];
$response->version = $parsed_response['version'];
$response->homepage = $parsed_response['homepage'];
$response->requires = $parsed_response['requires'];
$response->tested = $parsed_response['tested'];
$response->testedWC = $parsed_response['testedWC'];
$response->requiresWC = $parsed_response['requiresWC'];
$response->last_updated = \date_i18n('Y-n-d H:i:s', $parsed_response['last_updated']);
$response->requires_php = $parsed_response['requires_php'];
$response->sections = [];
$response->sections['description'] = $parsed_response['sections']['description'] ?? '';
$response->sections['changelog'] = \nl2br($parsed_response['sections']['changelog'] ?? '');
return $response;
}
\error_log("Response from license server cannot be parsed: " . \json_encode($remote_response));
}
return $false;
}, 10, 3);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace VendorDHL\WPDesk\License;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Replaces WPDesk_Helper_Plugin. Gets info from plugin and sends it to subscription/update integrations
*
* @depreacted Check LicenseServer namespace
* @package WPDesk\License
*/
class OldLicenseRegistrator implements \VendorDHL\WPDesk\License\PluginRegistratorInterface
{
/** @var WPDesk_Plugin_Info */
private $plugin_info;
/**
* @var PluginLicense
*/
private $plugin_license;
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
$this->plugin_info = $plugin_info;
$this->plugin_license = new \VendorDHL\WPDesk\License\PluginLicense($plugin_info);
}
public function is_active() : bool
{
return $this->plugin_license->is_active();
}
/**
* Initializes license manager.
*/
public function initialize_license_manager()
{
$license_manager = new \VendorDHL\WPDesk\License\LicenseManager($this->plugin_info);
$license_manager->init_activation_form();
$api_manager = $license_manager->create_api_manager();
$license_manager->init_wp_upgrader($api_manager->is_activated(), $api_manager->get_myaccount_url());
$license_manager->hooks();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace VendorDHL\WPDesk\License\Page;
/**
* Action that can be executed relative to plugin.
*
* @package WPDesk\License\Page
*/
interface Action
{
public function execute(array $plugin);
}

View File

@@ -0,0 +1,48 @@
<?php
namespace VendorDHL\WPDesk\License\Page\License\Action;
/**
* Abstract Action with error handling methods.
*/
abstract class AbstractAction
{
/**
* @var bool
*/
private $add_settings_error;
/**
* @var ActionError[]
*/
private $errors = [];
/**
* @param bool $add_settings_error .
*/
public function __construct(bool $add_settings_error)
{
$this->add_settings_error = $add_settings_error;
}
/**
* @return ActionError[]
*/
public function get_errors() : array
{
return $this->errors;
}
/**
* Adds error.
*
* @param string $setting .
* @param string $code .
* @param string $message .
* @param string $type .
*/
protected function add_error(string $setting, string $code, string $message, string $type = 'error')
{
if ($this->add_settings_error) {
\add_settings_error($setting, $code, $message, $type);
} else {
$this->errors[] = new \VendorDHL\WPDesk\License\Page\License\Action\ActionError($message, $type);
}
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace VendorDHL\WPDesk\License\Page\License\Action;
/**
* Action error.
*/
class ActionError implements \JsonSerializable
{
/**
* @var string
*/
private $message;
/**
* @var string
*/
private $type;
/**
* @param string $message .
* @param string $type .
*/
public function __construct(string $message, string $type)
{
$this->message = $message;
$this->type = $type;
}
/**
* @return string
*/
public function get_message() : string
{
return $this->message;
}
/**
* @return string
*/
public function get_type() : string
{
return $this->type;
}
/**
* @return array
*/
public function jsonSerialize() : array
{
return ['message' => $this->message, 'type' => $this->type];
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace VendorDHL\WPDesk\License\Page\License\Action;
use VendorDHL\WPDesk\License\Page\Action;
use VendorDHL\WPDesk\License\ServerAddressRepository;
use VendorDHL\WPDesk_API_Manager_With_Update_Flag;
/**
* Can activate plugin license.
*
* @package WPDesk\License\Page\License\Action
*/
class LicenseActivation extends \VendorDHL\WPDesk\License\Page\License\Action\AbstractAction implements \VendorDHL\WPDesk\License\Page\Action
{
/**
* Plugin data.
*
* @var array
*/
private $plugin_data;
/**
* Activate plugin license.
*
* @param $plugin array Info about plugin
*/
public function execute(array $plugin)
{
$activation_email = \sanitize_email(\trim($_POST['activation_email']));
$api_key = \sanitize_text_field(\trim($_POST['api_key']));
$product_id = $plugin['product_id'];
$this->plugin_data = $plugin;
$this->activate_license($activation_email, $api_key, new \VendorDHL\WPDesk\License\ServerAddressRepository($product_id));
}
/**
* Get api manager from plugin data.
*
* @return WPDesk_API_Manager_With_Update_Flag
*/
private function get_api_manager_from_plugin_data()
{
return $this->plugin_data['api_manager'];
}
/**
* Is activated?
*
* @param mixed $activate_results Activate result.
*
* @return bool
*/
private function is_activated($activate_results)
{
if (\is_array($activate_results)) {
if (isset($activate_results['activated']) && \true === $activate_results['activated']) {
return \true;
}
}
return \false;
}
/**
* Is json error?
*
* @return bool
*/
private function is_json_error()
{
if (\JSON_ERROR_NONE !== \json_last_error()) {
return \true;
}
return \false;
}
/**
* Is invalid api license key?
*
* @param mixed $activate_results Activate result.
*
* @return bool
*/
private function is_invalid_api_license_key($activate_results)
{
if (\is_array($activate_results)) {
if (isset($activate_results['code']) && '101' === $activate_results['code']) {
return \true;
}
}
return \false;
}
/**
* Activate and save data.
*
* @param WPDesk_API_Manager_With_Update_Flag $plugin_api_manager Api manager.
* @param string $activation_email Activation email.
* @param string $api_key Api key.
*/
private function activate_and_save_data($plugin_api_manager, $activation_email, $api_key)
{
$plugin_api_manager->options[$plugin_api_manager->api_key] = $api_key;
$plugin_api_manager->options[$plugin_api_manager->activation_email] = $activation_email;
\update_option($plugin_api_manager->data_key, $plugin_api_manager->options);
\update_option($plugin_api_manager->upgrade_url_key, $plugin_api_manager->upgrade_url);
\update_option($plugin_api_manager->activated_key, 'Activated');
}
/**
* Activate and save data.
*
* @param WPDesk_API_Manager_With_Update_Flag $plugin_api_manager Api manager.
*/
private function deactivate_and_save_data($plugin_api_manager)
{
$plugin_api_manager->options[$plugin_api_manager->api_key] = '';
$plugin_api_manager->options[$plugin_api_manager->activation_email] = '';
\update_option($plugin_api_manager->data_key, $plugin_api_manager->options);
\update_option($plugin_api_manager->activated_key, 'Deactivated');
}
/**
* Show error from reposne.
*
* @param array $activate_results Activate results.
*/
private function show_error(array $activate_results)
{
if (!isset($activate_results['additional info'])) {
$activate_results['additional info'] = '';
}
$message = "{$activate_results['error']} {$activate_results['additional info']}";
$this->add_error('api_manager_message', 'api_manager_error', $message, 'error');
}
/**
* Show unknown error.
*/
private function show_unknown_error()
{
$this->add_error('api_key_check_text', 'api_key_check_error', \__('Connection failed to the Subscription Key API server. Try again later.', 'woocommerce-dhl'), 'error');
}
/**
* Show activation message.
*
* @param array $activate_results Activation results.
*/
private function show_activation_message(array $activate_results)
{
$this->add_error('activate_text', 'activate_msg', \__('Plugin license activated. ', 'woocommerce-dhl') . "{$activate_results['message']}.", 'updated');
}
/**
* Activate license.
*
* @param string $activation_email Activation email.
* @param string $api_key Api key.
* @param ServerAddressRepository $address_repository Repository of server addresses to check for activation
*/
public function activate_license($activation_email, $api_key, \VendorDHL\WPDesk\License\ServerAddressRepository $address_repository)
{
$plugin_api_manager = $this->get_api_manager_from_plugin_data();
$activation_args = ['email' => $activation_email, 'licence_key' => $api_key];
$activate_results = ['activated' => \false];
foreach ($address_repository->get_server_urls() as $upgrade_url) {
$plugin_api_manager->upgrade_url = $upgrade_url;
$activate_raw_response = $plugin_api_manager->key()->activate($activation_args);
$activate_results = \json_decode($activate_raw_response, \true);
if ($this->is_json_error()) {
$activate_results = ['activated' => \false, 'error' => 'Invalid response from API Server', 'additional info' => $activate_raw_response, 'code' => '500'];
break;
}
if ($this->is_activated($activate_results) || !$this->is_invalid_api_license_key($activate_results)) {
break;
}
}
if (isset($activate_results['activated']) && \true === $activate_results['activated']) {
$this->activate_and_save_data($plugin_api_manager, $activation_email, $api_key);
$this->show_activation_message($activate_results);
} else {
$this->deactivate_and_save_data($plugin_api_manager);
if (isset($activate_results['code'])) {
$this->show_error($activate_results);
} else {
$this->show_unknown_error();
}
}
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace VendorDHL\WPDesk\License\Page\License\Action;
use VendorDHL\WPDesk\License\Page\Action;
/**
* Can deactivate plugin license.
*
* @package WPDesk\License\Page\License\Action
*/
class LicenseDeactivation extends \VendorDHL\WPDesk\License\Page\License\Action\AbstractAction implements \VendorDHL\WPDesk\License\Page\Action
{
/**
* Deactivate plugin subscription.
*
* @param $plugin array Info about plugin
*/
public function execute(array $plugin)
{
$args = ['email' => $plugin['api_manager']->options[$plugin['api_manager']->activation_email], 'licence_key' => $plugin['api_manager']->options[$plugin['api_manager']->api_key]];
$activate_results = \json_decode($plugin['api_manager']->key()->deactivate($args), \true);
// Used to display results for development
//print_r($activate_results); exit();
$deactivated = \false;
if ($activate_results['deactivated'] === \true) {
$update = [$plugin['api_manager']->api_key => '', $plugin['api_manager']->activation_email => ''];
$merge_options = \array_merge($plugin['api_manager']->options, $update);
\update_option($plugin['api_manager']->data_key, $merge_options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
\delete_option($plugin['api_manager']->upgrade_url_key);
$this->add_error('wc_am_deactivate_text', 'deactivate_msg', \__('Plugin license deactivated. ', 'woocommerce-dhl') . "{$activate_results['activations_remaining']}.", 'updated');
$deactivated = \true;
$plugin_wpdesk_name = $plugin['plugin'];
$plugin_product_id = $plugin['product_id'];
\do_action('wpdesk_subscription_deactivated', $plugin_wpdesk_name, $plugin_product_id);
}
if (!$deactivated && isset($activate_results['code'])) {
switch ($activate_results['code']) {
case '100':
$this->add_error('api_email_text', 'api_email_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->activation_email] = '';
$options[$plugin['api_manager']->api_key] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '101':
$this->add_error('api_key_text', 'api_key_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '102':
$this->add_error('api_key_purchase_incomplete_text', 'api_key_purchase_incomplete_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '103':
$this->add_error('api_key_exceeded_text', 'api_key_exceeded_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '104':
$this->add_error('api_key_not_activated_text', 'api_key_not_activated_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '105':
$this->add_error('api_key_invalid_text', 'api_key_invalid_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
case '106':
$this->add_error('sub_not_active_text', 'sub_not_active_error', "{$activate_results['error']}. {$activate_results['additional info']}", 'error');
$options[$plugin['api_manager']->api_key] = '';
$options[$plugin['api_manager']->activation_email] = '';
\update_option($plugin['api_manager']->data_key, $plugin['api_manager']->options);
\update_option($plugin['api_manager']->activated_key, 'Deactivated');
break;
}
}
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace VendorDHL\WPDesk\License\Page\License\Action;
use VendorDHL\WPDesk\License\Page\Action;
/**
* Do nothing.
*
* @package WPDesk\License\Page\License\Action
*/
class Nothing implements \VendorDHL\WPDesk\License\Page\Action
{
public function execute(array $plugin)
{
// NOOP
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace VendorDHL;
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
if (!\class_exists('WP_List_Table')) {
require_once \ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}
class WPDesk_Helper_List_Table extends \WP_List_Table
{
public $per_page = 100;
public $data;
public function __construct($args = [])
{
global $status, $page;
parent::__construct(['singular' => 'subscription', 'plural' => 'subscriptions', 'ajax' => \false]);
$status = 'all';
$page = $this->get_pagenum();
$this->data = [];
parent::__construct($args);
}
public function no_items()
{
echo \wpautop(\__('No WP Desk plugins found.', 'woocommerce-dhl'));
}
public function column_default($item, $column_name)
{
return $item[$column_name];
}
public function get_sortable_columns()
{
return [];
}
public function get_columns()
{
$columns = ['product_name' => \__('Plugin', 'woocommerce-dhl'), 'product_status' => \__('Subscription Status', 'woocommerce-dhl'), 'product_license' => \__('Subscription Data', 'woocommerce-dhl')];
return $columns;
}
public function column_plugin_data($item)
{
return '<pre>' . \print_r($item, \true) . '</pre>';
}
public function column_product_name($item)
{
return \wpautop('<strong>' . $item['api_manager']->product_id . '</strong>');
}
public function column_product_version($item)
{
return \wpautop($item['api_manager']->version);
}
public function column_product_status($item)
{
$status = \__('Deactivated', 'woocommerce-dhl');
if ($item['activation_status'] == 'Activated') {
$status = \__('Activated', 'woocommerce-dhl');
}
return $status;
}
public function column_product_license($item)
{
$disabled = 'disabled';
$api_key = '';
$activation_email = '';
if ($item['activation_status'] == 'Deactivated') {
$disabled = '';
} else {
$api_key = $item['api_manager']->options[$item['api_manager']->api_key];
$activation_email = $item['api_manager']->options[$item['api_manager']->activation_email];
}
$plugin = $item['plugin'];
$activation_status = $item['activation_status'];
\ob_start();
include 'license-actions.php';
$output = \ob_get_contents();
\ob_end_clean();
return $output;
}
public function get_bulk_actions()
{
$actions = [];
return $actions;
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = [];
$sortable = $this->get_sortable_columns();
$this->_column_headers = [$columns, $hidden, $sortable];
$total_items = \count($this->data);
$this->set_pagination_args(['total_items' => $total_items, 'per_page' => $total_items]);
$this->items = $this->data;
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace VendorDHL;
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
?>
<form method="POST">
<table class="wpdesk_helper_key_table">
<tr>
<td><?php
\esc_html(\__('Key:', 'woocommerce-dhl'));
?></td>
<td><input class="wpdesk_helper_input" name="api_key" type="text"
value="<?php
echo \esc_attr($api_key);
?>" <?php
echo \esc_attr($disabled);
?> /></td>
</tr>
<tr>
<td><?php
\esc_html(\__('Email:', 'woocommerce-dhl'));
?></td>
<td><input class="wpdesk_helper_input" name="activation_email" type="email"
value="<?php
echo \esc_attr($activation_email);
?>" <?php
echo \esc_attr($disabled);
?> /></td>
</tr>
<tr>
<td></td>
<td>
<?php
if ($activation_status == 'Deactivated') {
?>
<button class="wpdesk_helper_button button button-primary"><?php
echo \esc_html(\__('Activate', 'woocommerce-dhl'));
?></button>
<?php
} else {
?>
<button class="wpdesk_helper_button button"><?php
echo \esc_html(\__('Deactivate', 'woocommerce-dhl'));
?></button>
<?php
}
?>
</td>
</tr>
</table>
<input type="hidden" name="plugin" value="<?php
echo \esc_attr($plugin);
?>"/>
<?php
if ($activation_status == 'Deactivated') {
?>
<input type="hidden" name="action" value="activate"/>
<?php
} else {
?>
<input type="hidden" name="action" value="deactivate"/>
<?php
}
?>
</form>
<?php

View File

@@ -0,0 +1,53 @@
<?php
namespace VendorDHL;
if (!\defined('ABSPATH')) {
exit;
}
// Exit if accessed directly
?>
<style>
#product_license {
width: 500px;
}
.wpdesk_helper_key_table,
.wpdesk_helper_input {
width: 100%;
}
</style>
<div class="wrap">
<?php
/* screen_icon(); */
?>
<h1><?php
\esc_html_e('WP Desk Subscriptions', 'woocommerce-dhl');
?></h1>
<p class="mb0">
<?php
if (\get_locale() === 'pl_PL') {
$url = 'https://www.wpdesk.pl/moje-konto/';
} else {
$url = 'https://www.wpdesk.net/my-account/';
}
$link = \sprintf(\__('Get your subscription keys <a href="%s" target="_blank">here</a>. You can activate/deactivate API keys <strong>unlimited times on different domains</strong> as long as you have an active subscription.', 'woocommerce-dhl'), \esc_url($url));
echo \wp_kses_post($link);
?>
</p>
<?php
\settings_errors();
?>
<?php
$list_table = new \VendorDHL\WPDesk_Helper_List_Table();
$list_table->data = $plugins;
$list_table->prepare_items();
$list_table->display();
?>
</div> <!-- class="wrap" -->
<?php

View File

@@ -0,0 +1,128 @@
<?php
namespace VendorDHL\WPDesk\License\Page;
use VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable;
use VendorDHL\WPDesk\License\InstalledPlugins;
/**
* Can render and manage license page.
*
* @package WPDesk\License\Page\License
*/
class LicensePage implements \VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable
{
const PAGE_SLUG = 'wpdesk-licenses';
/** @var string Css/Js version */
private $scripts_version = '1';
/** @var InstalledPlugins */
private $plugin_database;
public function __construct(\VendorDHL\WPDesk\License\InstalledPlugins $plugin_database)
{
$this->plugin_database = $plugin_database;
}
/**
* Attach license page hooks.
*
* @return void
*/
public function hooks()
{
\add_action('wp_ajax_wpdesk_api_hide_message', [$this, 'handle_api_hide_message']);
\add_action('admin_enqueue_scripts', [$this, 'handle_css_scripts'], 100);
}
/**
* Adds license page submenu.
* Have to be called from admin_menu action.
*
* @return void
*/
public function handle_add_page_submenu_item()
{
\add_submenu_page('wpdesk-helper', \__('Subscriptions', 'woocommerce-dhl'), \__('Subscriptions', 'woocommerce-dhl'), 'manage_options', self::PAGE_SLUG, [$this, 'handle_render_wpdesk_licenses_page']);
}
/**
* Renders license page.
*
* @return void
*/
public function handle_render_wpdesk_licenses_page()
{
global $wpdesk_helper_plugins;
if (!isset($wpdesk_helper_plugins)) {
$wpdesk_helper_plugins = [];
}
if (isset($_POST['plugin']) && $_POST['action']) {
$this->execute_plugin_action(\sanitize_text_field($_POST['plugin']), \sanitize_key($_POST['action']));
}
$plugins = $this->plugin_database->get_plugins_activation_info();
/** @noinspection PhpUnusedLocalVariableInspection */
$plugins = $this->ensure_unique_product($plugins);
if (!\class_exists('VendorDHL\\WPDesk_Helper_List_Table')) {
require_once __DIR__ . '/License/views/class-wpdesk-helper-list-table.php';
}
include __DIR__ . '/License/views/licenses.php';
}
/**
* Ensures that no product are shown more than once
*
* @param array $plugins
*
* @return array
*/
private function ensure_unique_product(array $plugins)
{
$uniqueness = [];
return \array_filter($plugins, static function ($item) use(&$uniqueness) {
$key = $item['product_id'];
if (!isset($uniqueness[$key])) {
$uniqueness[$key] = \true;
return \true;
}
return \false;
});
}
/**
* Find plugin with given name and execute action with given name.
*
* @param $plugin string Plugin name
* @param $action string to execute
*/
private function execute_plugin_action($plugin, $action)
{
$plugins = $this->plugin_database->get_plugins_activation_info();
foreach ($plugins as $plugin_key => $wpdesk_helper_plugin) {
if ($wpdesk_helper_plugin['plugin'] === $plugin) {
$plugin_info = $wpdesk_helper_plugin;
}
}
if (isset($plugin_info)) {
(new \VendorDHL\WPDesk\License\Page\LicensePageActions())->create_action($action)->execute($plugin_info);
}
}
/**
* Remember that the given in request message should be closed.
* Have to be called from wp_ajax_wpdesk_api_hide_message action.
*/
public function handle_api_hide_message()
{
if (\wp_verify_nonce($_REQUEST['nonce'], 'wpdesk-api-ajax-notification-nonce')) {
if (\update_option('wpdesk_api_message_close', \sanitize_key($_REQUEST['value']))) {
die('1');
}
die('0');
}
}
/**
* Append license page css.
*
* Have to be called from admin_enqueue_scripts action.
*/
public function handle_css_scripts()
{
$screen = \get_current_screen();
if (isset($screen) && \in_array($screen->base, ['toplevel_page_wpdesk-helper', 'wp-desk_page_wpdesk-licenses', 'wp-desk-1_page_wpdesk-licenses'], \true)) {
\wp_register_style(self::PAGE_SLUG, \plugins_url('wpdesk-helper/assets/css/admin-settings.css'), [], $this->scripts_version);
\wp_enqueue_style(self::PAGE_SLUG);
}
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace VendorDHL\WPDesk\License\Page;
use VendorDHL\WPDesk\License\Page\License\Action\LicenseActivation;
use VendorDHL\WPDesk\License\Page\License\Action\LicenseDeactivation;
use VendorDHL\WPDesk\License\Page\License\Action\Nothing;
/**
* Action factory.
*
* @package WPDesk\License\Page\License
*/
class LicensePageActions
{
/**
* Creates action object according to given param
*
* @param string $action .
* @param bool $add_settings_error .
*
* @return Action
*/
public function create_action($action, $add_settings_error = \true)
{
if ('activate' === $action) {
return new \VendorDHL\WPDesk\License\Page\License\Action\LicenseActivation($add_settings_error);
}
if ('deactivate' === $action) {
return new \VendorDHL\WPDesk\License\Page\License\Action\LicenseDeactivation($add_settings_error);
}
return new \VendorDHL\WPDesk\License\Page\License\Action\Nothing();
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace VendorDHL\WPDesk\License;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Provides plugin license information.
* @depreacted Check LicenseServer namespace
*/
class PluginLicense
{
/**
* @var WPDesk_Plugin_Info
*/
private $plugin_info;
/**
* @param WPDesk_Plugin_Info $info
*/
public function __construct(\VendorDHL\WPDesk_Plugin_Info $info)
{
$this->plugin_info = $info;
}
/**
* @return bool
*/
public function is_active()
{
return \get_option($this->prepare_option_is_active()) === 'Activated';
}
/**
* @return string
*/
public function get_api_key()
{
$api_option = $this->get_api_option();
$field_key = $this->prepare_option_name('key');
return isset($api_option[$field_key]) ? $api_option[$field_key] : '';
}
/**
* @return string
*/
public function get_activation_email()
{
$api_option = $this->get_api_option();
$field_key = $this->prepare_option_name('activation_email');
return isset($api_option[$field_key]) ? $api_option[$field_key] : '';
}
/**
* @return string
*/
public function get_upgrade_url()
{
return (string) \get_option($this->prepare_option_name('upgrade_url', ''));
}
/**
* @return array
*/
private function get_api_option()
{
$option_value = \get_option(\sprintf('api_%1$s', \basename($this->plugin_info->get_plugin_dir())), []);
return \is_array($option_value) ? $option_value : [];
}
/**
* @return string
*/
private function prepare_option_is_active()
{
return $this->prepare_option_name('activated');
}
/**
* @param string $field .
*
* @return string
*/
private function prepare_option_name($field)
{
return \sprintf('api_%1$s_%2$s', \basename($this->plugin_info->get_plugin_slug()), $field);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace VendorDHL\WPDesk\License;
use VendorDHL\WPDesk_Plugin_Info;
/**
* Replaces WPDesk_Helper_Plugin. Gets info from plugin and sends it to subscription/update integrations
*
* @depreacted Check LicenseServer namespace
* @package WPDesk\License
*/
class PluginRegistrator implements \VendorDHL\WPDesk\License\PluginRegistratorInterface
{
/** @var PluginRegistratorInterface */
private $true_registrator;
public function __construct(\VendorDHL\WPDesk_Plugin_Info $plugin_info)
{
if (\VendorDHL\WPDesk\License\LicenseServer\PluginRegistrator::should_use_license_server()) {
$this->true_registrator = new \VendorDHL\WPDesk\License\LicenseServer\PluginRegistrator($plugin_info);
} else {
$this->true_registrator = new \VendorDHL\WPDesk\License\OldLicenseRegistrator($plugin_info);
}
}
public function is_active() : bool
{
return $this->true_registrator->is_active();
}
/**
* Initializes license manager.
*/
public function initialize_license_manager()
{
$this->true_registrator->initialize_license_manager();
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace VendorDHL\WPDesk\License;
/**
* @package WPDesk\License
*/
interface PluginRegistratorInterface
{
public function is_active() : bool;
/**
* Initializes license manager.
*/
public function initialize_license_manager();
}

View File

@@ -0,0 +1,95 @@
<?php
namespace VendorDHL\WPDesk\License;
/**
* Provides server urls to check for upgrade/activation
*
* @depreacted Check LicenseServer namespace
* @package WPDesk\License
*/
class ServerAddressRepository
{
/** @var string */
private $product_id;
/**
* @param string $product_id Product if of a plugin. Retrieve from plugin_info
*/
public function __construct($product_id)
{
$this->product_id = $product_id;
}
/**
* Returns default server to ping ie. when checking if upgrade is available but is not yet activated
*
* @return string
*/
public function get_default_update_url()
{
$urls = $this->get_server_urls();
return \reset($urls);
}
/**
* Return list of servers to check for update
*
* @return string[] Full URL with protocol. Without ending /
*/
public function get_server_urls()
{
// PL version should be default for most plugins
$servers = ['https://www.wpdesk.pl', 'https://www.wpdesk.net'];
$servers[] = 'https://octolize.com';
if ($this->is_shipping_plugin($this->product_id)) {
$servers = \array_reverse($servers);
// set fs server as first to check
}
$servers[] = 'https://flexibleinvoices.com';
if ($this->is_invoice_product($this->product_id)) {
$servers = \array_reverse($servers);
// set invoice server as first to check
}
$servers[] = 'https://shopmagic.app';
if ($this->is_magic_plugin($this->product_id)) {
$servers = \array_reverse($servers);
// set magic server as first to check
}
return $servers;
}
/**
* Is product id of a ShopMagic Plugin?
*
* @param string $product_id
*
* @return bool
*/
private function is_magic_plugin($product_id)
{
return \stripos($product_id, 'ShopMagic') !== \false;
}
/**
* Is product id of a ShopMagic Plugin?
*
* @param string $product_id
*
* @return bool
*/
private function is_invoice_product($product_id)
{
return \stripos($product_id, 'Invoices') !== \false;
}
/**
* Is product id of a Flexible Shipping plugin?
*
* @param string $product_id .
*
* @return bool
*/
private function is_shipping_plugin($product_id)
{
$plugins = ['Shipping', 'UPS', 'FedEx', 'DHL', 'Royal', 'Hermes', 'DPD', 'Australia Post', 'Canada Post', 'Cart Weight', 'Delivery Date', 'Flexible Printing', 'USPS'];
// if one of the $plugins phrase found in product_id
return \count(\array_filter($plugins, static function ($plugin) use($product_id) {
return \stripos($product_id, $plugin) !== \false;
})) > 0;
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace VendorDHL\WPDesk\License\WpUpgrader;
use VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable;
/**
* Can handle plugin update for expired subscription.
*/
class SubscriptionHandler implements \VendorDHL\WPDesk\PluginBuilder\Plugin\Hookable
{
const UNAVAILABLE = 'unavailable';
/**
* @var string
*/
private $plugin_file;
/**
* @var bool
*/
private $activated;
/**
* @var string
*/
private $my_account_subscription_link;
/**
* .
* @param string $plugin_file .
* @param bool $activated .
* @param string $my_account_subscription_link .
*/
public function __construct($plugin_file, $activated, $my_account_subscription_link)
{
$this->plugin_file = $plugin_file;
$this->activated = $activated;
$this->my_account_subscription_link = $my_account_subscription_link;
}
/**
* .
*/
public function hooks()
{
\add_filter('site_transient_update_plugins', [$this, 'add_fake_package_url_if_not_present']);
\add_filter('upgrader_pre_download', [$this, 'verify_package_url'], 1000, 3);
}
/**
* .
*
* @param \stdClass $value .
*
* @return \stdClass
*/
public function add_fake_package_url_if_not_present($value)
{
if (\function_exists('get_current_screen')) {
$current_screen = \get_current_screen();
if ($current_screen && 'update' === $current_screen->id && isset($value, $value->response, $value->response[$this->plugin_file]) && empty($value->response[$this->plugin_file]->package)) {
$value->response[$this->plugin_file]->package = self::UNAVAILABLE;
}
}
return $value;
}
/**
* @param bool $reply
* @param string $package
* @param \WP_Upgrader $upgrader
*
* @return \WP_Error|bool
*/
public function verify_package_url($reply, $package, $upgrader)
{
if (self::UNAVAILABLE === $package) {
if ($this->activated) {
return new \WP_Error('package_unavailable', \sprintf(\__('Your plugin subscription has expired. In order to update the plugin please %1$srenew your subscription%2$s', 'woocommerce-dhl'), '</strong><a href="' . $this->add_utms($this->my_account_subscription_link) . '" class="button-primary" target="_blank" style="text-decoration: none;">', '</a><strong>'));
}
return new \WP_Error('package_unavailable', \sprintf(\__('An active subscription API key is required to download the plugin updates. In order to update the plugin please %1$sactivate your API key%2$s', 'woocommerce-dhl'), '</strong><a href="' . \admin_url('plugins.php#flexible-shipping-import-export-activation-form') . '" class="button-primary" target="_blank" style="text-decoration: none;">', '</a><strong>'));
}
return $reply;
}
/**
* @param string $link .
*
* @return string
*/
private function add_utms($link)
{
return \trailingslashit($link) . '?utm_source=update&utm_medium=plugin-list&utm_campaign=subscriptions';
}
}