This commit is contained in:
Aleksei Tikhomirov 2022-06-14 23:55:12 +03:00
parent 0e549c5221
commit 16e6e28263
10 changed files with 617 additions and 412 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/.idea/

View file

@ -10,7 +10,7 @@ https://github.com/froger-me/wp-plugin-update-server
![Alt text](https://i.imgur.com/3lAIQq9.jpg)

#### Orders
![](https://i.imgur.com/zT7UbQN.jpg)
![](https://i.imgur.com/W24IqZz.jpeg)

#### Edit order
![](https://i.imgur.com/BRbMxYv.jpg)
#### Edit order. Manage licences.
![](https://i.imgur.com/o4bKYlX.jpeg)

View file

@ -1,12 +1,13 @@
<?php
/**
* Manager
*/


final class Lic_Manager
final class LicOrder
{
public const key = '_wc_slm_payment_licenses';

public function __construct(){
$this->add_actions();
}

public function add_actions(){
@ -28,7 +29,10 @@ final class Lic_Manager
{
$payment_meta = $licenses = [];
$order = wc_get_order($order_id);
if ( ! $order ) { return; }

if (empty($order)) {
return;
}

$user_id = $order->get_user_id();
$get_user_meta = get_user_meta($user_id);
@ -49,36 +53,36 @@ final class Lic_Manager
$product_id = $values['product_id'];
$product = new WC_Product($product_id);

if ( !Lic_Settings::get_licensing_enabled($product_id) || !$product->is_downloadable() ) {
if ( !LicProduct::get_licensing_enabled($product_id) || !$product->is_downloadable() ) {
continue; // Лицензии выключены или товар не имеет разрешения на загрузку
}

$download_quantity = absint($values['qty']);
for ($i = 1; $i <= $download_quantity; $i++) {

$renewal_period = Lic_Settings::get_renewal_period($product_id);
if ($renewal_period == 0) {
$renewal_period = '0000-00-00';
$renewal_period = LicProduct::get_renewal_period($product_id);
if (0 === $renewal_period) {
$renewal_period = date('Y-m-d', strtotime('+99 years'));
} else {
$renewal_period = date('Y-m-d', strtotime('+' . $renewal_period . ' years'));
}

// Sites allowed
$sites_allowed = Lic_Settings::get_sites_allowed($product_id);
if (!$sites_allowed) {
$sites_allowed = LicProduct::get_sites_allowed($product_id);
if ($sites_allowed <= 0 ) {
$sites_allowed_error = __('License could not be created: Invalid sites allowed number.', 'wc-pus');
$this->add_order_note($order_id, $sites_allowed_error);
break;
}

$product_slug = Lic_Settings::get_slug($product_id);
if (!$product_slug) {
$product_slug = LicProduct::get_slug($product_id);
if (empty($product_slug)) {
$this->add_order_note($order_id, __('License could not be created: Invalid product slug.', 'wc-pus'));
break;
}

$product_type = Lic_Settings::get_type($product_id);
if (!$product_type) {
$product_type = LicProduct::get_type($product_id);
if (empty($product_type)) {
$this->add_order_note($order_id, __('License could not be created: Invalid product type.', 'wc-pus'));
break;
}
@ -86,33 +90,33 @@ final class Lic_Manager
// Build item name
$item_name = $product->get_title();
$owner_name = (isset($payment_meta['user_info']['first_name'])) ? $payment_meta['user_info']['first_name'] : '';
$owner_name .= " " . (isset($payment_meta['user_info']['last_name'])) ? $payment_meta['user_info']['last_name'] : '';
$owner_name .= (isset($payment_meta['user_info']['last_name'])) ? ' ' . $payment_meta['user_info']['last_name'] : '';

// Build parameters
$api_params = [];
$api_params['linknonce'] = wp_create_nonce('linknonce');
$api_params['wppus_license_action'] = 'create';
$api_params['page'] = 'wppus-page-licenses';
$api_params['wppus_license_action'] = 'create';
$today = mysql2date('Y-m-d', current_time('mysql'), false);

$payload = [
// default data
'license_key' => bin2hex(openssl_random_pseudo_bytes(16)),
'date_created' => mysql2date('Y-m-d', current_time('mysql'), false),
'status' => 'pending',
'license_key' => bin2hex(openssl_random_pseudo_bytes(16)),
'date_created' => $today,
'status' => 'pending',
// setup
'max_allowed_domains' => $sites_allowed,
'email' => (isset($payment_meta['user_info']['email'])) ? $payment_meta['user_info']['email'] : '',
'date_renewed' => $renewal_period,
'date_expiry' => $renewal_period,
'package_slug' => $product_slug,
'package_type' => $product_type,
'owner_name' => $owner_name,
'company_name' => $payment_meta['user_info']['company'],
'txn_id' => (string)$order_id,
'email' => $payment_meta['user_info']['email'] ?? '',
'date_renewed' => $today,
'date_expiry' => $renewal_period,
'package_slug' => $product_slug,
'package_type' => $product_type,
'owner_name' => $owner_name,
'company_name' => $payment_meta['user_info']['company'],
'txn_id' => (string)$order_id,
// custom
'first_name' => (isset($payment_meta['user_info']['first_name'])) ? $payment_meta['user_info']['first_name'] : '',
'last_name' => (isset($payment_meta['user_info']['last_name'])) ? $payment_meta['user_info']['last_name'] : '',
'first_name' => $payment_meta['user_info']['first_name'] ?? '',
'last_name' => $payment_meta['user_info']['last_name'] ?? '',
];

$lic_manager = new WPPUS_License_Server();
@ -132,22 +136,27 @@ final class Lic_Manager


if (count($licenses) !== 0) {
update_post_meta($order_id, Lic_Manager::key, $licenses);
update_post_meta($order_id, LicOrder::key, $licenses);
}

if (count($licenses) !== 0) {
$message = __('License Key(s) generated', 'wc-slm');
$message = __('License Key(s) generated', 'wc-pus');
foreach ($licenses as $license) {
$message .= '<br />' . $license['item'] . ': ' . $license['key'];
}
} else {
$message = __('License Key(s) could not be created.', 'wc-slm');
$message = __('License Key(s) could not be created.', 'wc-pus');
if(!empty($result['errors'][0])){
$message .= $result['errors'][0];
}
}

self::add_order_note($order_id, $message);
}

/** Add note to order */
/**
* Add note to order
*/
public static function add_order_note( int $order_id, string $note){
$order = wc_get_order($order_id);
$order->add_order_note($note);
@ -159,7 +168,7 @@ final class Lic_Manager
* @param WC_Order $order
*/
public function print_order_meta(WC_Order $order){
$licenses = get_post_meta($order->get_id(), Lic_Manager::key, true);
$licenses = get_post_meta($order->get_id(), LicOrder::key, true);
if ($licenses && count($licenses) != 0) {
$output = '<h2>' . __('Your Licenses', 'wc-pus') . ':</h2>';
$output .= '<table class="shop_table shop_table_responsive"><tr><th class="td">' . __('Item', 'wc-pus') . '</th>
@ -193,7 +202,7 @@ final class Lic_Manager
$output = '';

// Check if licenses were generated
$licenses = get_post_meta($order->get_id(), Lic_Manager::key, true);
$licenses = get_post_meta($order->get_id(), LicOrder::key, true);

if ($licenses && count($licenses) != 0) {
$output = '<h3>' . __('Your Licenses', 'wc-pus') . ':</h3><table><tr><th class="td">' . __('Item', 'wc-pus') . '</th><th class="td">' . __('License', 'wc-pus') . '</th><th class="td">' . __('Expire Date', 'wc-pus') . '</th></tr>';
@ -226,6 +235,9 @@ final class Lic_Manager
}
}

/**
* @return array
*/
public static function get_types(){
return [
'plugin' => __('Plugin', 'wc-pus'),

View file

@ -0,0 +1,366 @@
<?php
/**
* Admin interface and actions
*/

final class LicOrderMetaBox
{

/**
* Add actions
*
* @return void
*/
public function add_actions()
{

add_action('add_meta_boxes', [$this, 'add_meta_boxes'], 30);

// Add licences data to Order preview
add_filter('woocommerce_admin_order_preview_get_order_details', [$this, 'order_preview_add_data'], 8, 2);

// Add licences data to Order table
// add_action( 'woocommerce_admin_order_data_after_billing_address', [$this, 'add_order_meta'], 10, 1 );

// Order save action. metabox handler
add_action('save_post', [$this, 'save'], 60, 2);
}

/**
* Add order metabox
*/
public function add_meta_boxes()
{
$screen = get_current_screen();
$screen_id = $screen ? $screen->id : '';
foreach (wc_get_order_types('order-meta-boxes') as $type) {
$order_type_object = get_post_type_object($type);
if ('shop_order' === $order_type_object->name) {
add_meta_box('licence', __('Manage licences', 'wc-pus'), [$this,'licence_meta_box'], $type, 'side', 'default');
}
}
}

/**
* Render meta-box on admin order page
*
* @param WP_Post $post
*/
public function licence_meta_box(WP_Post $post)
{
global $theorder;

if (!is_object($theorder)) {
$theorder = wc_get_order($post->ID);
}

$order = $theorder;
?>

<div class="lic_data_column_container">
<div class="lic_data_column">
<?php $this->add_order_meta($order); ?>
</div>

<div class="lic_data_column">
<?php $this->add_lic_content($order); ?>
</div>
</div>

<style>
.lic_data_column_container {
display: grid;
grid-template-columns: repeat(1, 1fr);
grid-template-rows: 1fr;
grid-column-gap: 0;
grid-row-gap: 0;
}
.lic_data_column{
border-bottom: 1px solid #f0f0f1;
}
.lic_data_column h4 {
font-size: 1.3em;
margin: 0 !important;
}
</style>
<?php

}


/**
* Save meta box data.
* @see LicOrderMetaBox::add_lic_content()
*
* @param int $post_id Post ID.
*/
public static function save(int $post_id, WP_Post $post)
{
$post_id = absint($post_id);

// $post_id and $post are required && Dont' save meta boxes for revisions or autosaves.
if (empty($post_id) || empty($post) || defined('DOING_AUTOSAVE') || is_int(wp_is_post_revision($post)) || is_int(wp_is_post_autosave($post))) {
return;
}
// Check the nonce.
if (empty($_POST['woocommerce_meta_nonce']) || !wp_verify_nonce(wp_unslash($_POST['woocommerce_meta_nonce']), 'woocommerce_save_data')) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
return;
}
// Check the post being saved == the $post_id to prevent triggering this call for other save_post events.
if (empty($_POST['post_ID']) || absint($_POST['post_ID']) !== $post_id) {
return;
}

// Check user has permission to edit. Check right button click
if (!current_user_can('edit_post', $post_id) || !isset($_POST['wc-pus_save'])) {
return;
}

/**
*
* [lic_name] => 0
* [lic_type] => plugin
* [lic_slug] => woo-to-iiko
* [lic_key] => 8bc3be6a-dfb7-489c-a229-5eeb1d4b8287
* [lic_sites_allowed] => 1
* [lic_renewal_period] => 1|''
*/
$data = [];
if (isset($_POST['lic_product_id'], $_POST['lic_type'], $_POST['lic_slug'], $_POST['lic_key'],
$_POST['lic_sites_allowed'], $_POST['lic_renewal_period']) && !empty($_POST['lic_product_id'])) {

$order = wc_get_order($post_id);
$name = '';
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$name = $product->get_name();
}

$data['item'] = $name;
$data['key'] = $_POST['lic_key'];

$renewal_period= intval($_POST['lic_renewal_period']);
if (0 >= $renewal_period) {
$renewal_period = date('Y-m-d', strtotime('+99 years'));
} else {
$renewal_period = date('Y-m-d', strtotime('+' . $renewal_period . ' years'));
}

if (0 !== intval($_POST['lic_renewal_period'])) {
$data['expires'] = date('Y-m-d', strtotime('+' . intval($_POST['lic_renewal_period']) . ' years'));
}

$meta = (array)get_post_meta($post_id, LicOrder::key, true);
$order_new_lic_data = $data;

$data['date_created'] = date('Y-m-d', strtotime(current_time('mysql')));
$data['date_renewed'] = $data['date_created'];
$data['date_expiry'] = $renewal_period;

$data['max_allowed_domains'] = intval($_POST['lic_sites_allowed']) > 0 ? intval($_POST['lic_sites_allowed']) : 1;
$data['email'] = $_POST['_billing_email'] ?? '';
$data['package_slug'] = $_POST['lic_slug'];
$data['package_type'] = $_POST['lic_type'];
$data['owner_name'] = $_POST['_billing_first_name'] . ' ' . $_POST['_billing_last_name'];
$data['company_name'] = $_POST['_billing_company'];
$data['txn_id'] = (string)$post_id;
$data['first_name'] = $_POST['_billing_first_name'];
$data['last_name'] = $_POST['_billing_last_name'];

$result = self::save_licence_to_WPPUS($data);
if ($result instanceof stdClass) {
$order_new_lic_data['lic_id'] = $result->id;
}

$meta[] = $order_new_lic_data;
update_post_meta($post_id, LicOrder::key, $meta);

if (!empty($order_new_lic_data['lic_id'])) {
$message = __('License Key(s) generated', 'wc-pus');
$message .= '<br />' . $order_new_lic_data['item'] . ': ' . $order_new_lic_data['key'];
} else {
$message = __('Error! License Key(s) could not be created.', 'wc-pus');
}

LicOrder::add_order_note($post_id, $message);
}
}

/**
* Save new licence
*
* @param array $payload
* @return array|array[]|bool[]|mixed|object
*/
public static function save_licence_to_WPPUS(array $payload)
{
$lic_manager = new WPPUS_License_Server();
$result = $lic_manager->add_license($payload);
if (is_array($result) && isset($result['errors'])) {
error_log(print_r($result, true));
}
return $result;
}


/**
* Showing licence keys on admin Order page
*
* @param WC_Order $order
*/
public function add_order_meta(WC_Order $order)
{
$order_id = $order->get_id();
$licenses = get_post_meta($order_id, LicOrder::key, true);
$licenses_enable = !empty($licenses);
if ($licenses_enable): ?>
<h4><?php _e('Licences', 'wc-pus')?>:</h4>
<!--<button id="lic-t-btn" href="#" class="button button-primary">Show licence list</button>-->
<div class="lic-list" style="<?php echo $licenses_enable ? '' : ' display:none;'; ?>">
<?php if (!empty($licenses)) {
foreach ($licenses as $k => $lic) {
if (!empty($lic['lic_id'])) {
$licence = self::get_license_by_id($lic['lic_id']);
woocommerce_wp_text_input([
'id' => LicOrder::key . '[' . $k . ']',
'label' => sprintf('%s %s. </br> %s to %s. ', $licence->package_type, $licence->package_slug, $licence->date_created, $licence->date_expiry),
'value' => $licence->license_key,
'custom_attributes' => ['readonly' => true],
'description' => __('You can change this data in WP PUS', 'wc-pus'),
'desc_tip' => true,
]);
}
}
} ?>
</div>
<?php
endif;
add_action('admin_footer', function () {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$("#lic-t-btn").on("click", function (e) {
e.preventDefault();
$(".lic-list").toggle('slow');
});
});
</script>
<?php
});
}

/**
* @see LicOrderMetaBox::save()
* @param $order
*
* @return void
*/
public function add_lic_content($order)
{
$items = [];
$line_items = $order->get_items(apply_filters('woocommerce_admin_order_item_types', 'line_item'));
foreach ($line_items as $item) {
$items[$item->get_id()] = $item->get_name();
}

if (!empty($items)) {
woocommerce_wp_select([
'id' => 'lic_product_id',
'label' => __('Product name', 'wc-pus'),
'options' => $items,
'value' => array_shift($line_items)->get_id(),
]);
}

woocommerce_wp_select([
'id' => 'lic_type',
'label' => __('Product type', 'wc-pus'),
'options' => LicOrder::get_types(),
'value' => 'plugin',
]);

woocommerce_wp_text_input([
'id' => 'lic_slug',
'label' => __('Product slug', 'wc-pus'),
'value' => apply_filters('lic_default_value', 'woo-to-iiko'),
]);

woocommerce_wp_text_input([
'id' => 'lic_key',
'label' => __('New Key', 'wc-pus'),
'value' => bin2hex(openssl_random_pseudo_bytes(16)),
]);

woocommerce_wp_text_input([
'id' => 'lic_sites_allowed',
'label' => __('Maximum domains', 'wc-pus'),
'type' => 'number',
'default' => '1'
]);

woocommerce_wp_text_input([
'id' => 'lic_renewal_period',
'label' => __('License renewal period. In years.', 'wc-pus'),
'type' => 'number',
'default' => '1'
]);

submit_button( __('Add new licence','wc-pus'), 'primary large', 'wc-pus_save', false, null);
}


/**
* Showing data in admin order Preview
*
* @param array $args
* @param WC_Order $order
* @return array
*/
public function order_preview_add_data(array $args, WC_Order $order)
{
$licenses = get_post_meta($order->get_id(), LicOrder::key, true);

if (!empty($licenses)) {
$string = '<h3>Licences:</h3>';
$string .= '<ul>';
foreach ($licenses as $lic) {
if (!empty($lic['lic_id'])) {
$licence = self::get_license_by_id($lic['lic_id']);
$string .= sprintf('<li><b>%s %s:</b> <pre><code>%s</code></pre></li>',
$licence->package_type, $licence->package_slug, $licence->license_key);
}
}
$string .= '</ul>';
$args['payment_via'] = $string;
}
return $args;
}

/**
* Get licence by ID
*
* [id] => 127
* [license_key] => df3b5f4d6b244b517260ed8dd1605ebf
* [max_allowed_domains] => 1
* [allowed_domains] => a:0:{}
* [status] => pending
* [owner_name] => testТихомиров
* [email] => tech@rwsite.ru
* [company_name] =>
* [txn_id] => 4783
* [date_created] => 2022-06-01
* [date_renewed] => 2022-06-01
* [date_expiry] => 2023-06-14
* [package_slug] => woo-to-iiko
* [package_type] => plugin
* @return stdClass{id: int, license_key: string, max_allowed_domains: int, date_expiry: string, package_slug:string, package_type: string}
*/
public static function get_license_by_id($id)
{
/** @var wpdb */
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}wppus_licenses WHERE `id` = '%d'", $id));
return $result[0] ?? null;
}
}

View file

@ -1,7 +1,6 @@
<?php
/**
* Settings.
*
* Product Settings.
*/

// Exit if accessed directly
@ -9,7 +8,7 @@ if (!defined('ABSPATH')) {
exit;
}

final class Lic_Settings
final class LicProduct
{
public static $section_id = 'products';

@ -20,10 +19,14 @@ final class Lic_Settings
public static $slug = '_wc_slm_slug';

public function __construct(){

}

public function add_actions(){
// Admin product settings
if(is_admin()) {
add_action('woocommerce_product_options_general_product_data', [$this, 'show_options']);
add_action('woocommerce_process_product_meta', [$this, 'save_options']);
add_action('woocommerce_process_product_meta', [$this, 'save_product_meta'], 10, 1);
}
}

@ -34,16 +37,13 @@ final class Lic_Settings
global $woocommerce, $post;

$post_id = $post->ID;
$licensing_enabled = get_post_meta($post_id, self::$licensing_enabled, true) ? true : false;
$licensing_enabled = (bool)get_post_meta($post_id, self::$licensing_enabled, true);
$sites_allowed = esc_attr(get_post_meta($post_id, self::$sites_allowed, true));
$licensing_renewal_period = esc_attr(get_post_meta($post_id, self::$renewal_period, true));
$product_type = esc_attr(get_post_meta($post_id, self::$type, true));
$product_slug = esc_attr(get_post_meta($post_id, self::$slug, true));

$display = $licensing_enabled ? '' : ' style="display:none;"';
if (trim($licensing_renewal_period) == '') {
$licensing_renewal_period = 0;
}
?>
<script type="text/javascript">
jQuery( document ).ready( function($) {
@ -51,37 +51,36 @@ final class Lic_Settings
$( ".variable-toggled-hide" ).toggle();
$( ".toggled-hide" ).toggle();
});

if( $('#licensing_enabled').is(':checked')){
// TODO: require: type and slug of product
}
});
</script>

<p class="form-field">
<input type="checkbox" name="licensing_enabled" id="licensing_enabled" value="1" <?php echo checked(true, $licensing_enabled, false); ?> />
<label for="licensing_enabled"><?php _e('Enable licensing for this download.', '');?></label>
<label for="licensing_enabled"><?php _e('Enable licensing for this download.', 'wc-pus');?></label>
</p>

<div <?php echo $display; ?> class="toggled-hide">
<p class="form-field">
<label for="licensing_renewal_period"><?php _e('license renewal period(yearly) , enter 0 for lifetime.', '');?></label>
<input type="number" name="licensing_renewal_period" id="licensing_renewal_period" value="<?php echo $licensing_renewal_period; ?>" />
<label for="licensing_renewal_period">
<?php _e('license renewal period(yearly). Enter 0 for lifetime.', 'wc-pus');?>
</label>
<input type="number" name="licensing_renewal_period" id="licensing_renewal_period" value="<?php echo (int)$licensing_renewal_period; ?>" />
</p>
<p class="form-field">
<label for="sites_allowed"><?php _e('How many sites can be activated trough a single license key?', '');?></label>
<input type="number" name="sites_allowed" class="small-text" value="<?php echo $sites_allowed; ?>" />
<label for="sites_allowed">
<?php _e('How many sites can be activated trough a single license key?', 'wc-pus');?>
</label>
<input type="number" name="sites_allowed" class="small-text" value="<?php echo (int)$sites_allowed; ?>" />
</p>
<p class="form-field">
<label for="type"><?php _e('Product type (plugin or theme).', '');?></label>
<!--<select size="3" name="type[]">
<option>plugin</option>
<option>theme</option>
</select>-->
<input type="text" name="type" class="small-text" value="<?php echo $product_type; ?>" />
<label for="type"><?php _e('Product type (plugin or theme).', 'wc-pus');?></label>
<select name="type">
<option <?php echo $product_type == 'plugin' ? 'selected': ''?> >plugin</option>
<option <?php echo $product_type == 'theme' ? 'selected': ''?> >theme</option>
</select>
</p>
<p class="form-field">
<label for="slug"><?php _e('Product slug.', '');?></label>
<label for="slug"><?php _e('Product slug.', 'wc-pus');?></label>
<input type="text" name="slug" class="small-text" value="<?php echo $product_slug; ?>" />
</p>
</div>
@ -93,21 +92,22 @@ final class Lic_Settings
*
* @param int $post_id
*/
public function save_options( int $post_id) {
if (!empty($_POST['licensing_enabled'])) {
update_post_meta($post_id, self::$licensing_enabled, esc_html($_POST['licensing_enabled']));
}
if (!empty($_POST['sites_allowed'])) {
update_post_meta($post_id, self::$sites_allowed, esc_html($_POST['sites_allowed']));
}
if (!empty($_POST['licensing_renewal_period'])) {
update_post_meta($post_id, self::$renewal_period, esc_html($_POST['licensing_renewal_period']));
}
if (!empty($_POST['type'])) {
update_post_meta($post_id, self::$type, esc_html($_POST['type']));
}
if (!empty($_POST['slug'])) {
update_post_meta($post_id, self::$slug, esc_html($_POST['slug']));
public function save_product_meta(int $post_id) {

$properties = [
'licensing_enabled' => self::$licensing_enabled,
'sites_allowed' => self::$sites_allowed,
'licensing_renewal_period' => self::$renewal_period,
'type' => self::$type,
'slug' => self::$slug
];


foreach ($properties as $key => $name) {
if (isset($_POST[$key])) {
$value = ($key === 'sites_allowed' && (int)$_POST[$key] <= 0) ? 1 : esc_html($_POST[$key]);
update_post_meta($post_id, $name, $value);
}
}
}

View file

@ -1,254 +0,0 @@
<?php
/**
* Admin interface and actions
*/

final class Lic_Admin
{
public function __construct()
{
add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ], 30 );

// Add licences data to Order preview
add_filter( 'woocommerce_admin_order_preview_get_order_details', [$this, 'order_preview_add_data'], 8, 2 );

// Add licences data to Order table
add_action( 'woocommerce_admin_order_data_after_billing_address', [$this, 'add_order_meta'], 10, 1 );

// Order save
add_action( 'save_post', [$this, 'save'], 60, 2 );
}

/**
* Add order metabox
*/
public function add_meta_boxes(){
$screen = get_current_screen(); $screen_id = $screen ? $screen->id : '';
foreach ( wc_get_order_types( 'order-meta-boxes' ) as $type ) {
$order_type_object = get_post_type_object( $type );
if('shop_order' === $order_type_object->name){
add_meta_box('licence', __('Add licence to order products', 'wc-pus'), [$this, 'licence_meta_box'], $type, 'side');
}
}
}

/**
* Render meta-box on admin order page
*
* @param WP_Post $post
*/
public function licence_meta_box( WP_Post $post){

global $theorder;

if ( ! is_object( $theorder ) ) {
$theorder = wc_get_order( $post->ID );
}

$order = $theorder;

$items = [];
$line_items = $order->get_items( apply_filters( 'woocommerce_admin_order_item_types', 'line_item' ) );
foreach ($line_items as $item){
$items[$item->get_id()] = $item->get_name();
}

if(!empty($items)) {
woocommerce_wp_select([
'id' => 'lic_product_id',
'label' => __('Product name', 'wc-pus'),
'options' => $items,
'value' => array_shift ($line_items)->get_id(),
]);
}

woocommerce_wp_select([
'id' => 'lic_type',
'label' => __( 'Product type', 'wc-pus'),
'options' => Lic_Manager::get_types(),
'value' => 'plugin',
]);

woocommerce_wp_text_input([
'id' => 'lic_slug',
'label' => __('Slug', 'wc-pus'),
'value' => apply_filters('lic_default_value', 'woo-to-iiko'),
]);

woocommerce_wp_text_input([
'id' => 'lic_key',
'label' => __('Key', 'wc-pus'),
'value' => bin2hex(openssl_random_pseudo_bytes(16)),
]);

woocommerce_wp_text_input([
'id' => 'lic_sites_allowed',
'label' => __('Maximum domains', 'wc-pus'),
'type' => 'number'
]);

woocommerce_wp_text_input([
'id' => 'lic_renewal_period',
'label' => __('License renewal period', 'wc-pus'),
'type' => 'number'
]);

submit_button( __( 'Add' ), 'primary large', 'wc-pus_save', false, null);

/* $licences = $order->get_meta(Lic_Manager::key, true);
foreach ($licences as $licence) {
woocommerce_wp_text_input([
'id' => Lic_Manager::key,
'label' => __('Lic manager', 'woocommerce'),
'value' => $licence['key'],
]);
}*/
}


/**
* Save meta box data.
*
* @param int $post_id Post ID.
*/
public static function save( int $post_id, WP_Post $post ) {
$post_id = absint( $post_id );

// $post_id and $post are required && Dont' save meta boxes for revisions or autosaves.
if ( empty( $post_id ) || empty( $post ) || defined('DOING_AUTOSAVE' ) || is_int( wp_is_post_revision( $post ) ) || is_int( wp_is_post_autosave( $post ) ) ) {
return;
}
// Check the nonce.
if ( empty( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( wp_unslash( $_POST['woocommerce_meta_nonce'] ), 'woocommerce_save_data' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
return;
}
// Check the post being saved == the $post_id to prevent triggering this call for other save_post events.
if ( empty( $_POST['post_ID'] ) || absint( $_POST['post_ID'] ) !== $post_id ) {
return;
}
// Check user has permission to edit. Check right button click
if ( ! current_user_can( 'edit_post', $post_id ) || !isset($_POST['wc-pus_save']) ) {
return;
}

/**
*
* [lic_name] => 0
* [lic_type] => plugin
* [lic_slug] => woo-to-iiko
* [lic_key] => 8bc3be6a-dfb7-489c-a229-5eeb1d4b8287
* [lic_sites_allowed] => 1
* [lic_renewal_period] => 1|''
*/
$data = [];
if( isset($_POST['lic_product_id'], $_POST['lic_type'], $_POST['lic_slug'], $_POST['lic_key'],
$_POST['lic_sites_allowed'], $_POST['lic_renewal_period']) && !empty($_POST['lic_product_id']) ){

$order = wc_get_order($post_id); $name = '';
foreach ( $order->get_items() as $item_id => $item ) {
$product = $item->get_product();
$name = $product->get_name();
}

$data['item'] = $name;
$data['key'] = $_POST['lic_key'];

$data['expires'] = date('Y-m-d', strtotime('0000-00-00'));
if ( 0 !== intval($_POST['lic_renewal_period']) ) {
$data['expires'] = date('Y-m-d', strtotime('+' . intval($_POST['lic_renewal_period']) . ' years'));
}

$meta = (array)get_post_meta($post_id, Lic_Manager::key, true);
$order_new_lic_data = $data;

$data['date_created'] = date('Y-m-d', strtotime(current_time('mysql')));
$data['date_renewed'] = $data['date_expiry'] ?? $data['expires'];
$data['sites_allowed'] = $data['max_allowed_domains'] = intval($_POST['lic_sites_allowed']);
$data['email'] = $_POST['_billing_email'] ?? '';
$data['package_slug'] = $_POST['lic_slug'];
$data['package_type'] = $_POST['lic_type'];
$data['owner_name'] = $_POST['_billing_first_name'] .' '. $_POST['_billing_last_name'];
$data['company_name'] = $_POST['_billing_company'];
$data['txn_id'] = (string)$post_id;
$data['first_name'] = $_POST['_billing_first_name'];
$data['last_name'] = $_POST['_billing_last_name'];

$result = self::save_licence_to_WPPUS($data);
if($result instanceof stdClass) {
$order_new_lic_data['lic_id'] = $result->id;
}

$meta[] = $order_new_lic_data;
update_post_meta($post_id, Lic_Manager::key, $meta);

if ( !empty($order_new_lic_data)) {
$message = __('License Key(s) generated', 'wc-slm');
$message .= '<br />' . $order_new_lic_data['item'] . ': ' . $order_new_lic_data['key'];
} else {
$message = __('License Key(s) could not be created.', 'wc-slm');
}

Lic_Manager::add_order_note($post_id, $message);
}
}

/**
* Save new licence
*
* @param array $payload
* @return array|array[]|bool[]|mixed|object
*/
public static function save_licence_to_WPPUS(array $payload){
$lic_manager = new WPPUS_License_Server();
$result = $lic_manager->add_license($payload);
if(is_array($result) && isset($result['errors'])) {
error_log(print_r($result, true));
}
return $result;
}


/**
* Showing licence keys on admin Order page
*
* @param WC_Order $order
*/
public function add_order_meta( WC_Order $order ) {
$order_id = $order->get_id();
$licenses = get_post_meta( $order_id, Lic_Manager::key, true );
$track_and_trace_string = '';
if (!empty($licenses)) {
foreach ($licenses as $license){
if(isset($license['key'])) {
$track_and_trace_string .= '<div class="licenses">';
$track_and_trace_string .= '<strong>' . __('Licence: ', 'wc-pus') . '</strong>';
$track_and_trace_string .= '<input type="text" value="' . $license['key'] . '" style="width: 260px" disabled>';
$track_and_trace_string .= '</div>';
}
}
$track_and_trace_string .= '<br />';
echo $track_and_trace_string;
}
}


/**
* Showing data in admin order Preview
*
* @param array $args
* @param WC_Order $order
* @return array
*/
public function order_preview_add_data( array $args, WC_Order $order ) {
$licenses = get_post_meta($order->get_id(), Lic_Manager::key, true);
if(!empty($licenses)) {
$string = '';
foreach ($licenses as $lic){
$string .= '<strong>' . __('License: ', 'wc-pus') . $lic['key'] . '</strong>';
$string .= '<br />';
}
$args['payment_via'] = $string;
}
return $args;
}
}

Binary file not shown.

View file

@ -3,9 +3,9 @@ msgstr ""
"Project-Id-Version: WC Plugin Update Server integration\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-02-06 12:22+0000\n"
"PO-Revision-Date: 2021-09-07 17:10+0000\n"
"PO-Revision-Date: 2022-06-14 20:54+0000\n"
"Last-Translator: \n"
"Language-Team: Русский\n"
"Language-Team: Russian\n"
"Language: ru_RU\n"
"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10 >= 2 && "
"n%10<=4 &&(n%100<10||n%100 >= 20)? 1 : 2);\n"
@ -16,89 +16,129 @@ msgstr ""
"X-Loco-Version: 2.5.0; wp-5.6.1\n"
"X-Domain: wc-pus"

#: includes/Lic_Admin.php:30
msgid "Add licence to order products"
msgstr "Добавить лицензию товару в заказе"
#: includes/LicOrderMetaBox.php:309
msgid "Add new licence"
msgstr "Добавить новую лицензию"

#. Author of the plugin
msgid "Aleksey Tikhomirov"
msgstr "Алексей Тихомиров"

#: includes/Lic_Manager.php:198
#: includes/LicProduct.php:59
msgid "Enable licensing for this download."
msgstr "Включить лицензии"

#: includes/LicOrderMetaBox.php:183
msgid "Error! License Key(s) could not be created."
msgstr "Ошибка! Не удалось создать лицензии."

#: includes/LicOrder.php:208
msgid "Expire Date"
msgstr "Дата истечения"

#: includes/LicProduct.php:71
msgid ""
"How many sites can be activated trough a single license key? Enter 0 for "
"lifetime."
msgstr ""

#. URI of the plugin
#. Author URI of the plugin
msgid "http://rwsite.ru"
msgstr "http://rwsite.ru"

#: includes/Lic_Manager.php:165 includes/Lic_Manager.php:198
#: includes/LicOrder.php:174 includes/LicOrder.php:208
msgid "Item"
msgstr "Позиция"

#: includes/Lic_Admin.php:80
msgid "Key"
msgstr "Ключ"
#: includes/LicOrderMetaBox.php:218
#| msgid "Licence: "
msgid "Licences"
msgstr "Лицензии:"

#: includes/Lic_Admin.php:226
msgid "Licence: "
msgstr "Лицензия:"

#: includes/Lic_Manager.php:165 includes/Lic_Manager.php:198
#: includes/LicOrder.php:175 includes/LicOrder.php:208
msgid "License"
msgstr "Лицензия"

#: includes/Lic_Manager.php:76
#: includes/LicOrder.php:80
msgid "License could not be created: Invalid product slug."
msgstr "Не удалось создать лицензию: недопустимый slug."

#: includes/Lic_Manager.php:82
#: includes/LicOrder.php:86
msgid "License could not be created: Invalid product type."
msgstr "Не удалось создать лицензию: неверный тип продукта."

#: includes/Lic_Manager.php:69
#: includes/LicOrder.php:73
msgid "License could not be created: Invalid sites allowed number."
msgstr ""
"Не удалось создать лицензию: недопустимое разрешенное количество сайтов."

#: includes/Lic_Admin.php:92
msgid "License renewal period"
msgstr "Срок продления лицензии"
#: includes/LicOrder.php:148
msgid "License Key(s) could not be created."
msgstr "Ошибка! Не удалось создать лицензии."

#: includes/Lic_Admin.php:249
msgid "License: "
msgstr "Лицензия:"
#: includes/LicOrder.php:143 includes/LicOrderMetaBox.php:180
msgid "License Key(s) generated"
msgstr "Лицензионный ключ создан"

#: includes/Lic_Admin.php:86
#: includes/LicProduct.php:65
msgid "license renewal period(yearly)."
msgstr "Период продления лицензии (ежегодно)."

#: includes/LicOrderMetaBox.php:304
msgid "License renewal period. In years."
msgstr "Срок продления лицензии. В годах."

#: includes/LicOrderMetaBox.php:39
msgid "Manage licences"
msgstr "Управление лицензиями"

#: includes/LicOrderMetaBox.php:297
msgid "Maximum domains"
msgstr "Максимальное количество доменов"

#: includes/Lic_Manager.php:172
#: includes/LicOrderMetaBox.php:291
msgid "New Key"
msgstr "Новый ключ"

#: includes/LicOrder.php:182
msgid "No item and key assigned"
msgstr "Элемент и ключ не назначены"

#: includes/Lic_Manager.php:230
#: includes/LicOrder.php:243
msgid "Plugin"
msgstr "Плагин"

#: includes/Lic_Admin.php:59
#: includes/LicOrderMetaBox.php:270
msgid "Product name"
msgstr "Наименование товара"

#: includes/Lic_Admin.php:67
#: includes/LicOrderMetaBox.php:285
msgid "Product slug"
msgstr "Product slug"

#: includes/LicProduct.php:83
msgid "Product slug."
msgstr "Product slug"

#: includes/LicOrderMetaBox.php:278
msgid "Product type"
msgstr "Тип продукта"

#: includes/Lic_Admin.php:74
msgid "Slug"
msgstr "Слаг"
#: includes/LicProduct.php:76
msgid "Product type (plugin or theme)."
msgstr "Тип продукта (плагин или тема)."

#: includes/Lic_Manager.php:231
#: includes/LicOrder.php:244
msgid "Theme"
msgstr "Тема"

#: wc-plugin-update-server.php:70
#. Name of the plugin
#| msgid "WooCommerce Plugin Update Server integration"
msgid "WooCommerce and Plugin Update Server integration"
msgstr "Интеграция WooCommerce и Сервера Обновлений Плагинов"

#: wc-plugin-update-server.php:88
#| msgid ""
#| "Woocommerce or WPPUS_License_Server is not activated. To work thi plugin, "
#| "you need to install and activate WooCommerce and WPPUS_License_Server "
@ -112,11 +152,10 @@ msgstr ""
"плагина необходимо установить и активировать плагины WooCommerce и "
"WPPUS_License_Server."

#. Name of the plugin
#| msgid "WC Plugin Update Server integration"
msgid "WooCommerce Plugin Update Server integration"
msgstr "WC Plugin Update Server интеграция"
#: includes/LicOrderMetaBox.php:230
msgid "You can change this data in WP PUS"
msgstr "Вы можете изменить эти данные в WP PUS"

#: includes/Lic_Manager.php:164 includes/Lic_Manager.php:198
#: includes/LicOrder.php:173 includes/LicOrder.php:208
msgid "Your Licenses"
msgstr "Ваши лицензии"

View file

@ -3,7 +3,7 @@ msgid ""
msgstr ""
"Project-Id-Version: WC Plugin Update Server integration\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-09-07 17:06+0000\n"
"POT-Creation-Date: 2022-06-14 20:50+0000\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: \n"
@ -16,98 +16,136 @@ msgstr ""
"X-Loco-Version: 2.5.0; wp-5.6.1\n"
"X-Domain: wc-pus"

#: includes/Lic_Admin.php:30
msgid "Add licence to order products"
#: includes/LicOrderMetaBox.php:309
msgid "Add new licence"
msgstr ""

#. Author of the plugin
msgid "Aleksey Tikhomirov"
msgstr ""

#: includes/Lic_Manager.php:198
#: includes/LicProduct.php:59
msgid "Enable licensing for this download."
msgstr ""

#: includes/LicOrderMetaBox.php:183
msgid "Error! License Key(s) could not be created."
msgstr ""

#: includes/LicOrder.php:208
msgid "Expire Date"
msgstr ""

#: includes/LicProduct.php:71
msgid ""
"How many sites can be activated trough a single license key? Enter 0 for "
"lifetime."
msgstr ""

#. URI of the plugin
#. Author URI of the plugin
msgid "http://rwsite.ru"
msgstr ""

#: includes/Lic_Manager.php:165 includes/Lic_Manager.php:198
#: includes/LicOrder.php:174 includes/LicOrder.php:208
msgid "Item"
msgstr ""

#: includes/Lic_Admin.php:80
msgid "Key"
#: includes/LicOrderMetaBox.php:218
msgid "Licences"
msgstr ""

#: includes/Lic_Admin.php:226
msgid "Licence: "
msgstr ""

#: includes/Lic_Manager.php:165 includes/Lic_Manager.php:198
#: includes/LicOrder.php:175 includes/LicOrder.php:208
msgid "License"
msgstr ""

#: includes/Lic_Manager.php:76
#: includes/LicOrder.php:80
msgid "License could not be created: Invalid product slug."
msgstr ""

#: includes/Lic_Manager.php:82
#: includes/LicOrder.php:86
msgid "License could not be created: Invalid product type."
msgstr ""

#: includes/Lic_Manager.php:69
#: includes/LicOrder.php:73
msgid "License could not be created: Invalid sites allowed number."
msgstr ""

#: includes/Lic_Admin.php:92
msgid "License renewal period"
#: includes/LicOrder.php:148
msgid "License Key(s) could not be created."
msgstr ""

#: includes/Lic_Admin.php:249
msgid "License: "
#: includes/LicOrder.php:143 includes/LicOrderMetaBox.php:180
msgid "License Key(s) generated"
msgstr ""

#: includes/Lic_Admin.php:86
#: includes/LicProduct.php:65
msgid "license renewal period(yearly)."
msgstr ""

#: includes/LicOrderMetaBox.php:304
msgid "License renewal period. In years."
msgstr ""

#: includes/LicOrderMetaBox.php:39
msgid "Manage licences"
msgstr ""

#: includes/LicOrderMetaBox.php:297
msgid "Maximum domains"
msgstr ""

#: includes/Lic_Manager.php:172
#: includes/LicOrderMetaBox.php:291
msgid "New Key"
msgstr ""

#: includes/LicOrder.php:182
msgid "No item and key assigned"
msgstr ""

#: includes/Lic_Manager.php:230
#: includes/LicOrder.php:243
msgid "Plugin"
msgstr ""

#: includes/Lic_Admin.php:59
#: includes/LicOrderMetaBox.php:270
msgid "Product name"
msgstr ""

#: includes/Lic_Admin.php:67
#: includes/LicOrderMetaBox.php:285
msgid "Product slug"
msgstr ""

#: includes/LicProduct.php:83
msgid "Product slug."
msgstr ""

#: includes/LicOrderMetaBox.php:278
msgid "Product type"
msgstr ""

#: includes/Lic_Admin.php:74
msgid "Slug"
#: includes/LicProduct.php:76
msgid "Product type (plugin or theme)."
msgstr ""

#: includes/Lic_Manager.php:231
#: includes/LicOrder.php:244
msgid "Theme"
msgstr ""

#: wc-plugin-update-server.php:70
#. Name of the plugin
msgid "WooCommerce and Plugin Update Server integration"
msgstr ""

#: wc-plugin-update-server.php:88
msgid ""
"Woocommerce or WPPUS_License_Server is not activated. To work this plugin, "
"you need to install and activate WooCommerce and WPPUS_License_Server "
"plugins."
msgstr ""

#. Name of the plugin
msgid "WooCommerce Plugin Update Server integration"
#: includes/LicOrderMetaBox.php:230
msgid "You can change this data in WP PUS"
msgstr ""

#: includes/Lic_Manager.php:164 includes/Lic_Manager.php:198
#: includes/LicOrder.php:173 includes/LicOrder.php:208
msgid "Your Licenses"
msgstr ""

View file

@ -1,14 +1,19 @@
<?php
/**
* Plugin Name: WooCommerce Plugin Update Server integration
* Plugin Name: WooCommerce and Plugin Update Server integration
* Plugin URI: http://rwsite.ru
* Description:
* Version: 1.0.3
* Version: 1.0.4
* Author: Aleksey Tikhomirov
* Author URI: http://rwsite.ru
* Text Domain: wc-pus
* Domain Path: /languages
*
* Requires at least: 5.6
* Requires PHP: 7.0
* WC requires at least: 6.0
* WC tested up to: 6.6.0
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License version 3, as published by the Free Software Foundation. You may NOT assume
* that you can use any other version of the GPL.
@ -33,7 +38,7 @@ class Lic_Manager_Plugin {
private static $instance;

/**
* @return Lic_Manager
* @return LicOrder
*/
public static function getInstance()
{
@ -86,20 +91,18 @@ class Lic_Manager_Plugin {
return;
}

require_once __DIR__ . '/includes/Lic_Settings.php';
require_once __DIR__ . '/includes/Lic_Manager.php';
require_once __DIR__ . '/includes/LicProduct.php';
require_once __DIR__ . '/includes/LicOrder.php';
require_once __DIR__ . '/includes/Software_Licence_Manager_integration.php';
require_once __DIR__ . '/includes/Lic_Admin.php';
require_once __DIR__ . '/includes/LicOrderMetaBox.php';

if (is_admin()) {
// new Software_Licence_Manager_integration();
}

new Lic_Admin();

new Lic_Settings();
new Lic_Manager();

(new LicOrderMetaBox())->add_actions();
(new LicProduct())->add_actions();
(new LicOrder())->add_actions();
}

/**